Procuremen.php 588 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenGuard;
  6. use app\common\library\ProcuremenOperLog;
  7. use app\common\library\ProcuremenSchema;
  8. use app\common\library\ProcuremenStatus;
  9. use app\common\library\ProcuremenSupplierScore;
  10. use app\common\library\ProcuremenTime;
  11. use PHPMailer\PHPMailer\PHPMailer;
  12. use think\Config;
  13. use think\Cache;
  14. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  15. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  16. use PhpOffice\PhpSpreadsheet\Style\Border;
  17. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  18. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  19. use think\Db;
  20. use think\Log;
  21. class Procuremen extends Backend
  22. {
  23. /**
  24. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  25. */
  26. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,b.czlyq,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  27. /**
  28. * Procuremen模型对象
  29. * @var \app\admin\model\Procuremen
  30. */
  31. protected $model = null;
  32. /**
  33. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  34. */
  35. protected $notifyDryRunPreview = [];
  36. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  37. protected $procuremenRedisCache = null;
  38. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  39. protected $pickHiddenScydgySetCache = null;
  40. /** 邮件发送日志表结构已就绪缓存键 */
  41. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  42. /**
  43. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  44. * @var array
  45. */
  46. protected $noNeedRight = [
  47. 'pickreview', 'review', 'reviewcompanies',
  48. // 方法内用 hasProcuremenPerm 校验(兼容 auditsubmit / auditissue)
  49. 'auditmanualpick',
  50. // 与 rfqlist 同权,方法内校验
  51. 'rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqissuesuppliers', 'rfqissue', 'rfqissuesendmail', 'rfqquotes',
  52. 'rfqappendsuppliers', 'rfqsupplieroptions', 'rfqsalesmanoptions', 'rfqappendsalesmen',
  53. 'deliverynotifymen', 'deliverynotify',
  54. ];
  55. public function _initialize()
  56. {
  57. parent::_initialize();
  58. $this->model = new \app\admin\model\Procuremen;
  59. $this->maybeMigrateLegacyWflowStatusText();
  60. $this->assignProcuremenAuthConfig();
  61. try {
  62. ProcuremenSchema::ensureAll();
  63. } catch (\Throwable $e) {
  64. }
  65. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  66. $this->ensurePurchaseEmailSendLogTableOnce();
  67. }
  68. }
  69. /**
  70. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  71. */
  72. protected function maybeMigrateLegacyWflowStatusText(): void
  73. {
  74. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  75. if (is_file($flagFile)) {
  76. return;
  77. }
  78. $map = [
  79. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  80. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  81. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  82. '3' => ProcuremenStatus::WFLOW_APPROVED,
  83. ];
  84. try {
  85. foreach ($map as $num => $text) {
  86. Db::table('purchase_order')
  87. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  88. ->update(['wflow_status' => $text]);
  89. }
  90. @file_put_contents($flagFile, date('c'));
  91. } catch (\Throwable $e) {
  92. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  93. }
  94. }
  95. /**
  96. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  97. *
  98. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  99. */
  100. protected function hasProcuremenPerm(array $actions): bool
  101. {
  102. foreach ($actions as $action) {
  103. $action = strtolower(trim((string)$action));
  104. if ($action === '') {
  105. continue;
  106. }
  107. if (strpos($action, 'procuremen/') !== 0) {
  108. $action = 'procuremen/' . $action;
  109. }
  110. if ($this->auth->check($action)) {
  111. return true;
  112. }
  113. }
  114. $suffixes = [];
  115. foreach ($actions as $action) {
  116. $action = strtolower(trim((string)$action));
  117. $action = preg_replace('#^procuremen/#', '', $action);
  118. if ($action !== '') {
  119. $suffixes[$action] = true;
  120. }
  121. }
  122. if ($suffixes === []) {
  123. return false;
  124. }
  125. try {
  126. foreach ($this->auth->getRuleList() as $rule) {
  127. $rule = strtolower((string)$rule);
  128. if (strpos($rule, 'procuremen/') !== 0) {
  129. continue;
  130. }
  131. foreach (array_keys($suffixes) as $suffix) {
  132. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  133. return true;
  134. }
  135. }
  136. }
  137. } catch (\Throwable $e) {
  138. }
  139. return false;
  140. }
  141. /**
  142. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  143. *
  144. * @param string[] $actions
  145. */
  146. protected function hasProcuremenPermStrict(array $actions): bool
  147. {
  148. foreach ($actions as $action) {
  149. $action = strtolower(trim((string)$action));
  150. if ($action === '') {
  151. continue;
  152. }
  153. if (strpos($action, 'procuremen/') !== 0) {
  154. $action = 'procuremen/' . $action;
  155. }
  156. if ($this->auth->check($action)) {
  157. return true;
  158. }
  159. }
  160. return false;
  161. }
  162. /**
  163. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  164. *
  165. * @param string[] $titles
  166. */
  167. protected function authHasAssignedRuleTitle(array $titles): bool
  168. {
  169. $titles = array_values(array_filter(array_map('trim', $titles)));
  170. if ($titles === []) {
  171. return false;
  172. }
  173. try {
  174. $ids = $this->auth->getRuleIds();
  175. if (in_array('*', $ids, true)) {
  176. return true;
  177. }
  178. if ($ids === []) {
  179. return false;
  180. }
  181. $rows = Db::name('auth_rule')
  182. ->where('status', 'normal')
  183. ->whereIn('id', $ids)
  184. ->column('title');
  185. foreach ($rows as $title) {
  186. $t = trim((string)$title);
  187. if ($t !== '' && in_array($t, $titles, true)) {
  188. return true;
  189. }
  190. }
  191. } catch (\Throwable $e) {
  192. }
  193. return false;
  194. }
  195. protected function procuremenCanPickDelete(): bool
  196. {
  197. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  198. return true;
  199. }
  200. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  201. }
  202. protected function procuremenCanComplete(): bool
  203. {
  204. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  205. return true;
  206. }
  207. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  208. }
  209. protected function procuremenCanDispatch(): bool
  210. {
  211. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  212. }
  213. /**
  214. * 前端按钮显隐(Config.procuremenAuth)
  215. */
  216. protected function assignProcuremenAuthConfig(): void
  217. {
  218. $authMap = [
  219. 'pickreview' => $this->procuremenCanDispatch(),
  220. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  221. 'pickdelete' => $this->procuremenCanPickDelete(),
  222. 'completedirectly' => $this->procuremenCanComplete(),
  223. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  224. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  225. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  226. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  227. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  228. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  229. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  230. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  231. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  232. 'details' => $this->hasProcuremenPerm(['details']),
  233. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  234. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  235. 'export_month_quote' => $this->hasProcuremenPerm(['export_month_quote', 'exportMonthQuote', 'export_month_outward', 'exportMonthOutward']),
  236. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  237. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  238. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  239. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  240. 'auditmanualpick' => $this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue']),
  241. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  242. 'add' => $this->hasProcuremenPerm(['add']),
  243. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  244. // 查询询价三个操作按钮:各自独立,不再因有 rfqlist 就全部放开
  245. 'rfqissue' => $this->hasProcuremenPerm(['rfqissue']),
  246. 'rfqquotes' => $this->hasProcuremenPerm(['rfqquotes']),
  247. 'rfqnotifysalesman' => $this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen']),
  248. 'rfqnotifysalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman']),
  249. // 询价附属接口:有「询价」按钮权限即可(无需再单独勾选)
  250. 'rfqissuesuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers']),
  251. 'rfqissuesendmail' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail']),
  252. 'rfqappendsuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers']),
  253. 'rfqsupplieroptions' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions']),
  254. 'rfqsalesmanoptions' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen']),
  255. 'rfqappendsalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen']),
  256. 'deliverynotify' => $this->hasProcuremenPerm(['deliverynotify', 'deliverynotifymen', 'outward_detail', 'outwarddetail', 'purchaseconfirmpick', 'details']),
  257. 'deliverynotifymen' => $this->hasProcuremenPerm(['deliverynotifymen', 'deliverynotify', 'outward_detail', 'outwarddetail', 'purchaseconfirmpick', 'details']),
  258. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  259. ];
  260. $this->assignconfig('procuremenAuth', $authMap);
  261. }
  262. /**
  263. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  264. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  265. * 列表 Tab 写入 hash(mproc_tab),避免邮件客户端拆坏多 query 参数;浏览器端再补全 tab=
  266. *
  267. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  268. * @param string $listTab rfq|draft|submitted|done|rfq_submitted,空则仅靠服务端按状态推断
  269. */
  270. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId, $listTab = '')
  271. {
  272. static $mprocCfgLoaded = false;
  273. if (!$mprocCfgLoaded) {
  274. $mprocCfgLoaded = true;
  275. if (is_file(APP_PATH . 'extra/mproc.php')) {
  276. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  277. }
  278. }
  279. $eid = (int)$purchaseOrderDetailId;
  280. $base = $this->resolveMprocMobilePublicBaseUrl();
  281. if ($base === '') {
  282. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  283. }
  284. $path = trim((string)Config::get('mproc.mobile_index_path'));
  285. if ($path === '') {
  286. $path = '/index.php/index/index/index';
  287. } else {
  288. $path = '/' . ltrim($path, '/');
  289. }
  290. $tab = trim((string)$listTab);
  291. if (!in_array($tab, ['rfq', 'rfq_submitted', 'draft', 'submitted', 'done'], true)) {
  292. $tab = '';
  293. }
  294. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份 Tab
  295. if ($eid > 0) {
  296. $hash = 'mproc_fe=' . $eid;
  297. if ($tab !== '') {
  298. $hash .= '&mproc_tab=' . $tab;
  299. }
  300. return $base . $path . '?focus_eid=' . $eid . '#' . $hash;
  301. }
  302. return $base . $path . '?main_tab=orders' . ($tab !== '' ? ('&tab=' . $tab) : '');
  303. }
  304. /**
  305. * 业务员手机端「订单询价」直达链接(默认待询价)
  306. *
  307. * @param int $scydgyId 手工询价 scydgy_id(负数)
  308. * @param string $status pending|quoted
  309. */
  310. protected function buildMprocMobileRfqAddUrl($scydgyId = 0, $status = 'pending')
  311. {
  312. static $mprocCfgLoaded = false;
  313. if (!$mprocCfgLoaded) {
  314. $mprocCfgLoaded = true;
  315. if (is_file(APP_PATH . 'extra/mproc.php')) {
  316. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  317. }
  318. }
  319. $base = $this->resolveMprocMobilePublicBaseUrl();
  320. if ($base === '') {
  321. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  322. }
  323. $indexPath = trim((string)Config::get('mproc.mobile_index_path'));
  324. if ($indexPath === '') {
  325. $indexPath = '/index.php/index/index/index';
  326. } else {
  327. $indexPath = '/' . ltrim($indexPath, '/');
  328. }
  329. $path = preg_replace('#/index$#', '/rfqadd', rtrim($indexPath, '/'));
  330. if ($path === null || $path === '' || substr($path, -6) === '/index') {
  331. $path = '/index.php/index/index/rfqadd';
  332. }
  333. $status = trim((string)$status) === 'quoted' ? 'quoted' : 'pending';
  334. $sid = (int)$scydgyId;
  335. $q = 'status=' . $status;
  336. $hash = '';
  337. if ($sid < 0) {
  338. $q .= '&focus_sid=' . $sid;
  339. $hash = '#mproc_fs=' . $sid;
  340. }
  341. return $base . $path . '?' . $q . $hash;
  342. }
  343. /**
  344. * 邮件/短信外链:须为带点的公网域名
  345. */
  346. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  347. {
  348. $u = trim((string)$baseUrl);
  349. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  350. return false;
  351. }
  352. $host = parse_url($u, PHP_URL_HOST);
  353. if (!is_string($host) || $host === '') {
  354. return false;
  355. }
  356. if (strcasecmp($host, 'localhost') === 0) {
  357. return false;
  358. }
  359. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  360. return false;
  361. }
  362. if (strpos($host, '.') === false) {
  363. return false;
  364. }
  365. return true;
  366. }
  367. /**
  368. * 解析用于协助邮件/短信的手机端站点根
  369. */
  370. protected function resolveMprocMobilePublicBaseUrl()
  371. {
  372. $candidates = [];
  373. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  374. $candidates[] = trim((string)Config::get('site.indexurl'));
  375. $cdn = trim((string)Config::get('site.cdnurl'));
  376. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  377. $candidates[] = rtrim($cdn, '/');
  378. }
  379. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  380. $candidates[] = $reqBase;
  381. foreach ($candidates as $c) {
  382. if ($c === '') {
  383. continue;
  384. }
  385. $c = rtrim($c, '/');
  386. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  387. return $c;
  388. }
  389. }
  390. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  391. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  392. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  393. return $reqBase;
  394. }
  395. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  396. return '';
  397. }
  398. /**
  399. * 获取 Redis 中 procuremen_redis
  400. */
  401. protected function ProcuremenRedis(): array
  402. {
  403. if ($this->procuremenRedisCache !== null) {
  404. return $this->procuremenRedisCache;
  405. }
  406. try {
  407. $redis = redis();
  408. $raw = $redis->get('procuremen_redis');
  409. if ($raw === false || $raw === '') {
  410. $this->procuremenRedisCache = [];
  411. return $this->procuremenRedisCache;
  412. }
  413. $decoded = json_decode($raw, true);
  414. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  415. $this->procuremenRedisCache = [];
  416. return $this->procuremenRedisCache;
  417. }
  418. $this->procuremenRedisCache = $decoded['data'];
  419. // 整包已解码时顺带补齐侧栏小键,避免下次首屏再扫库
  420. if ($this->loadProcuremenSidebarYmList() === []) {
  421. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($this->procuremenRedisCache));
  422. }
  423. return $this->procuremenRedisCache;
  424. } catch (\Throwable $e) {
  425. $this->procuremenRedisCache = [];
  426. return $this->procuremenRedisCache;
  427. }
  428. }
  429. /**
  430. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  431. *
  432. * @return array<int, array<string, mixed>>
  433. */
  434. protected function procuremenFetchErpPoolFromDb(): array
  435. {
  436. try {
  437. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  438. $endTime = date('Y-m-d 23:59:59');
  439. $list = Db::table('scydgy')
  440. ->alias('a')
  441. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  442. ->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, b.czlyq, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  443. ->where([
  444. 'a.bwjg' => 1,
  445. 'a.iEndBz' => 0,
  446. 'a.iType' => 0,
  447. 'a.iStatus' => 10,
  448. ])
  449. ->where('a.dStamp', '>=', $startTime)
  450. ->where('a.dStamp', '<=', $endTime)
  451. ->order('a.dStamp', 'desc')
  452. ->select();
  453. if (!is_array($list)) {
  454. return [];
  455. }
  456. try {
  457. $redis = redis();
  458. $payload = [
  459. 'code' => 200,
  460. 'msg' => 'success',
  461. 'data' => $list,
  462. ];
  463. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  464. $this->procuremenRedisCache = $list;
  465. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($list));
  466. $this->clearPickMonthPoolCaches();
  467. $this->warmPickMonthPoolCachesFromPool($list);
  468. } catch (\Throwable $e) {
  469. }
  470. return $list;
  471. } catch (\Throwable $e) {
  472. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  473. return [];
  474. }
  475. }
  476. /**
  477. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  478. *
  479. * @return array<int, array<string, mixed>>
  480. */
  481. protected function procuremenEnsureRedisPool(): array
  482. {
  483. $pool = $this->ProcuremenRedis();
  484. if (is_array($pool) && $pool !== []) {
  485. return $pool;
  486. }
  487. static $warmed = false;
  488. if ($warmed) {
  489. return is_array($pool) ? $pool : [];
  490. }
  491. $warmed = true;
  492. return $this->procuremenFetchErpPoolFromDb();
  493. }
  494. /**
  495. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  496. *
  497. * @param array<string, mixed> $row
  498. */
  499. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  500. {
  501. $t = $this->procuremenRowListSortTime($row, $primary);
  502. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  503. return null;
  504. }
  505. $mo = (int)$m[2];
  506. if ($mo < 1 || $mo > 12) {
  507. return null;
  508. }
  509. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  510. }
  511. /**
  512. * @param array<int, array{year:string, months:array}> $sidebar
  513. * @return array<int, array{year:string, months:array}>
  514. */
  515. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  516. {
  517. $ym = trim($ym);
  518. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  519. return $sidebar;
  520. }
  521. foreach ($sidebar as $block) {
  522. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  523. continue;
  524. }
  525. foreach ($block['months'] as $item) {
  526. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  527. return $sidebar;
  528. }
  529. }
  530. }
  531. $y = substr($ym, 0, 4);
  532. $mo = (int)substr($ym, 5, 2);
  533. $sidebar[] = [
  534. 'year' => $y,
  535. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  536. ];
  537. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  538. }
  539. /**
  540. * @param array<int, array{year:string, months:array}> $sidebar
  541. * @return string[]
  542. */
  543. protected function flattenProcuremenSidebarYms(array $sidebar): array
  544. {
  545. $yms = [];
  546. foreach ($sidebar as $block) {
  547. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  548. continue;
  549. }
  550. foreach ($block['months'] as $item) {
  551. if (!is_array($item)) {
  552. continue;
  553. }
  554. $ym = trim((string)($item['ym'] ?? ''));
  555. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  556. $yms[$ym] = true;
  557. }
  558. }
  559. }
  560. return array_keys($yms);
  561. }
  562. /**
  563. * 左侧菜单(协助初选)
  564. * 优先 Redis 月份小键;为空时用轻量 DISTINCT 查库补齐(避免只显示空当月、漏掉有数据的月份)。
  565. */
  566. protected function GetIndexYearMonths()
  567. {
  568. $ymList = $this->ensureProcuremenPickSidebarYmList();
  569. if ($ymList === []) {
  570. $def = date('Y-m');
  571. $ymList = [preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m')];
  572. }
  573. return $this->buildYearMonthSidebar($ymList);
  574. }
  575. /**
  576. * 初选侧栏月份:以轻量 DISTINCT 查库为准(有数据才显示),并写回 Redis 小键。
  577. *
  578. * @return string[]
  579. */
  580. protected function ensureProcuremenPickSidebarYmList(bool $forceRefresh = false): array
  581. {
  582. static $memo = null;
  583. if (!$forceRefresh && is_array($memo)) {
  584. return $memo;
  585. }
  586. $fromDb = $this->queryProcuremenPickSidebarYmListLight();
  587. if ($fromDb !== []) {
  588. $this->saveProcuremenSidebarYmList($fromDb);
  589. $memo = $fromDb;
  590. return $memo;
  591. }
  592. // 库侧暂无初选数据时,再回退 Redis / 当月,避免侧栏空白
  593. $cached = $this->loadProcuremenSidebarYmList();
  594. if ($cached !== []) {
  595. $memo = $cached;
  596. return $memo;
  597. }
  598. $memo = [date('Y-m')];
  599. return $memo;
  600. }
  601. /**
  602. * @return string[] 形如 2026-07
  603. */
  604. protected function loadProcuremenSidebarYmList(): array
  605. {
  606. try {
  607. $raw = redis()->get('procuremen_redis_yms');
  608. if ($raw === false || $raw === null || $raw === '') {
  609. return [];
  610. }
  611. $decoded = json_decode((string)$raw, true);
  612. if (!is_array($decoded)) {
  613. return [];
  614. }
  615. $out = [];
  616. foreach ($decoded as $ym) {
  617. $ym = trim((string)$ym);
  618. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  619. $out[$ym] = true;
  620. }
  621. }
  622. return array_keys($out);
  623. } catch (\Throwable $e) {
  624. return [];
  625. }
  626. }
  627. /**
  628. * @param string[] $ymList
  629. */
  630. protected function saveProcuremenSidebarYmList(array $ymList): void
  631. {
  632. $out = [];
  633. foreach ($ymList as $ym) {
  634. $ym = trim((string)$ym);
  635. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  636. $out[$ym] = true;
  637. }
  638. }
  639. if ($out === []) {
  640. return;
  641. }
  642. try {
  643. redis()->set('procuremen_redis_yms', json_encode(array_keys($out), JSON_UNESCAPED_UNICODE));
  644. } catch (\Throwable $e) {
  645. }
  646. }
  647. /**
  648. * @param array<int, array<string, mixed>> $pool
  649. * @return string[]
  650. */
  651. protected function extractYearMonthsFromPoolRows(array $pool): array
  652. {
  653. $ymSet = [];
  654. foreach ($pool as $r) {
  655. if (!is_array($r)) {
  656. continue;
  657. }
  658. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  659. continue;
  660. }
  661. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  662. if ($ym !== null) {
  663. $ymSet[$ym] = true;
  664. }
  665. }
  666. return array_keys($ymSet);
  667. }
  668. /**
  669. * 轻量查询初选侧栏月份(只取 DISTINCT 年月,不拉整包工序)
  670. *
  671. * @return string[]
  672. */
  673. protected function queryProcuremenPickSidebarYmListLight(): array
  674. {
  675. try {
  676. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  677. $endTime = date('Y-m-d 23:59:59');
  678. $sql = 'SELECT DISTINCT DATE_FORMAT('
  679. . 'IF(b.dputrecord IS NOT NULL AND TRIM(CAST(b.dputrecord AS CHAR(32))) <> \'\''
  680. . ' AND TRIM(CAST(b.dputrecord AS CHAR(32))) NOT LIKE \'0000-00-00%\','
  681. . ' b.dputrecord, a.dStamp), \'%Y-%m\') AS ym'
  682. . ' FROM scydgy a'
  683. . ' INNER JOIN mcyd b ON b.ICYDID = a.ICYDID AND b.iStatus >= 10'
  684. . ' WHERE a.bwjg = 1 AND a.iEndBz = 0 AND a.iType = 0 AND a.iStatus = 10'
  685. . ' AND a.dStamp >= ? AND a.dStamp <= ?';
  686. $rows = Db::query($sql, [$startTime, $endTime]);
  687. if (!is_array($rows)) {
  688. return [];
  689. }
  690. $out = [];
  691. foreach ($rows as $r) {
  692. $ym = trim((string)($r['ym'] ?? ''));
  693. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  694. $out[$ym] = true;
  695. }
  696. }
  697. return array_keys($out);
  698. } catch (\Throwable $e) {
  699. Log::write('初选侧栏月份轻量查询失败:' . $e->getMessage(), 'warning');
  700. return [];
  701. }
  702. }
  703. /**
  704. * @return string[] 含当月在内的近 N 个自然月
  705. */
  706. protected function buildRecentCalendarYmList(int $months = 12): array
  707. {
  708. $months = max(1, min(24, $months));
  709. $out = [];
  710. $base = strtotime(date('Y-m-01'));
  711. for ($i = 0; $i < $months; $i++) {
  712. $out[] = date('Y-m', strtotime('-' . $i . ' month', $base));
  713. }
  714. return $out;
  715. }
  716. /**
  717. * 初选按月工序池:优先月缓存;未命中则直接按月查 ERP。
  718. * 禁止为列表去解近一年整包 Redis(解包/连接异常会造成长时间转圈)。
  719. *
  720. * @return array<int, array<string, mixed>>
  721. */
  722. protected function loadPickPoolForYm(string $ym): array
  723. {
  724. $ym = trim($ym);
  725. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  726. return [];
  727. }
  728. $hit = $this->readPickMonthPoolCache($ym);
  729. if ($hit !== null) {
  730. return $hit;
  731. }
  732. return $this->queryPickPoolForYmFromDb($ym);
  733. }
  734. /**
  735. * @return array<int, array<string, mixed>>|null null=无有效缓存(含旧版空数组误缓存)
  736. */
  737. protected function readPickMonthPoolCache(string $ym): ?array
  738. {
  739. try {
  740. $raw = redis()->get('procuremen_pick_pool:' . $ym);
  741. if ($raw === false || $raw === null || $raw === '') {
  742. return null;
  743. }
  744. $decoded = json_decode((string)$raw, true);
  745. if (!is_array($decoded)) {
  746. return null;
  747. }
  748. // 新格式:{ok:1, rows:[...]},空月也算有效(已从整包确认)
  749. if (isset($decoded['ok']) && (int)$decoded['ok'] === 1 && isset($decoded['rows']) && is_array($decoded['rows'])) {
  750. return $decoded['rows'];
  751. }
  752. // 旧格式:仅非空行列表可命中;[] 多半是错误 SQL 写入,视为未命中
  753. if ($decoded === []) {
  754. try {
  755. redis()->del('procuremen_pick_pool:' . $ym);
  756. } catch (\Throwable $e) {
  757. }
  758. return null;
  759. }
  760. if (isset($decoded[0]) && is_array($decoded[0])) {
  761. return $decoded;
  762. }
  763. return null;
  764. } catch (\Throwable $e) {
  765. return null;
  766. }
  767. }
  768. /**
  769. * @param array<int, array<string, mixed>> $rows
  770. */
  771. protected function writePickMonthPoolCache(string $ym, array $rows): void
  772. {
  773. try {
  774. redis()->setex(
  775. 'procuremen_pick_pool:' . $ym,
  776. 600,
  777. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  778. );
  779. } catch (\Throwable $e) {
  780. }
  781. }
  782. /**
  783. * @param array<int, array<string, mixed>> $pool
  784. * @return array<int, array<string, mixed>>
  785. */
  786. protected function filterPoolRowsByYm(array $pool, string $ym): array
  787. {
  788. $out = [];
  789. foreach ($pool as $r) {
  790. if (!is_array($r)) {
  791. continue;
  792. }
  793. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  794. continue;
  795. }
  796. if ($this->procuremenRowYearMonth($r, 'dputrecord') === $ym) {
  797. $out[] = $r;
  798. }
  799. }
  800. return $out;
  801. }
  802. /**
  803. * 按 dStamp 取当月附近数据,再用列表规则(dputrecord 优先)精确到 ym
  804. *
  805. * @return array<int, array<string, mixed>>
  806. */
  807. protected function queryPickPoolForYmFromDb(string $ym): array
  808. {
  809. $monthStart = $ym . '-01 00:00:00';
  810. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  811. // 略放大窗口,避免 dStamp 与 dputrecord 跨月导致漏数;最终仍按 ym 精确过滤
  812. $queryStart = date('Y-m-d 00:00:00', strtotime($monthStart . ' -7 days'));
  813. $queryEnd = date('Y-m-d 23:59:59', strtotime($monthEnd . ' +7 days'));
  814. try {
  815. $list = Db::table('scydgy')
  816. ->alias('a')
  817. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  818. ->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, b.czlyq, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  819. ->where([
  820. 'a.bwjg' => 1,
  821. 'a.iEndBz' => 0,
  822. 'a.iType' => 0,
  823. 'a.iStatus' => 10,
  824. ])
  825. ->where('a.dStamp', '>=', $queryStart)
  826. ->where('a.dStamp', '<=', $queryEnd)
  827. ->order('a.dStamp', 'desc')
  828. ->select();
  829. } catch (\Throwable $e) {
  830. Log::write('初选按月取数失败 ym=' . $ym . ':' . $e->getMessage(), 'error');
  831. return [];
  832. }
  833. if (!is_array($list)) {
  834. $list = [];
  835. }
  836. $out = $this->filterPoolRowsByYm($list, $ym);
  837. // 新格式缓存(含空月),避免重复打库;读侧只认 ok=1
  838. $this->writePickMonthPoolCache($ym, $out);
  839. try {
  840. $yms = $this->loadProcuremenSidebarYmList();
  841. if ($out !== [] && ($yms === [] || !in_array($ym, $yms, true))) {
  842. $yms[] = $ym;
  843. $this->saveProcuremenSidebarYmList($yms);
  844. }
  845. } catch (\Throwable $e) {
  846. }
  847. return $out;
  848. }
  849. /**
  850. * 整包写入后拆成按月小缓存,供初选列表秒开
  851. *
  852. * @param array<int, array<string, mixed>> $pool
  853. */
  854. protected function warmPickMonthPoolCachesFromPool(array $pool): void
  855. {
  856. if ($pool === []) {
  857. return;
  858. }
  859. $byYm = [];
  860. foreach ($pool as $r) {
  861. if (!is_array($r)) {
  862. continue;
  863. }
  864. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  865. continue;
  866. }
  867. $rowYm = $this->procuremenRowYearMonth($r, 'dputrecord');
  868. if ($rowYm === null) {
  869. continue;
  870. }
  871. $byYm[$rowYm][] = $r;
  872. }
  873. if ($byYm === []) {
  874. return;
  875. }
  876. try {
  877. $redis = redis();
  878. foreach ($byYm as $rowYm => $rows) {
  879. $redis->setex(
  880. 'procuremen_pick_pool:' . $rowYm,
  881. 600,
  882. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  883. );
  884. }
  885. try {
  886. $redis->del('procuremen_pick_hidden_scydgy_v1');
  887. } catch (\Throwable $e) {
  888. }
  889. } catch (\Throwable $e) {
  890. }
  891. }
  892. /**
  893. * 刷新整包后清理近月缓存,避免脏读
  894. */
  895. protected function clearPickMonthPoolCaches(int $months = 24): void
  896. {
  897. try {
  898. $redis = redis();
  899. foreach ($this->buildRecentCalendarYmList($months) as $ym) {
  900. try {
  901. $redis->del('procuremen_pick_pool:' . $ym);
  902. } catch (\Throwable $e) {
  903. }
  904. }
  905. } catch (\Throwable $e) {
  906. }
  907. $this->invalidatePickHiddenScydgyCache();
  908. }
  909. /**
  910. * 下发/完结后清隐藏集缓存,避免初选列表最多 90 秒仍显示已下发行
  911. */
  912. protected function invalidatePickHiddenScydgyCache(): void
  913. {
  914. $this->pickHiddenScydgySetCache = null;
  915. try {
  916. redis()->del('procuremen_pick_hidden_scydgy_v1');
  917. } catch (\Throwable $e) {
  918. }
  919. }
  920. /** 列表/首屏读完鉴权后尽早释放 session,避免多 iframe 串行卡死 */
  921. protected function procuremenReleaseSessionLock(): void
  922. {
  923. if (session_status() === PHP_SESSION_ACTIVE) {
  924. @session_write_close();
  925. }
  926. }
  927. /**
  928. * @param string[] $ymList 形如 2026-06
  929. * @return array<int, array{year:string, months:array}>
  930. */
  931. protected function buildYearMonthSidebar(array $ymList): array
  932. {
  933. rsort($ymList, SORT_STRING);
  934. $byYear = [];
  935. foreach ($ymList as $ym) {
  936. $y = substr($ym, 0, 4);
  937. $mo = (int)substr($ym, 5, 2);
  938. if (!isset($byYear[$y])) {
  939. $byYear[$y] = [];
  940. }
  941. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  942. }
  943. krsort($byYear, SORT_NUMERIC);
  944. foreach ($byYear as $y => $items) {
  945. usort($byYear[$y], function ($a, $b) {
  946. return strcmp($b['ym'], $a['ym']);
  947. });
  948. }
  949. $sidebar = [];
  950. foreach ($byYear as $y => $months) {
  951. $sidebar[] = ['year' => $y, 'months' => $months];
  952. }
  953. return $sidebar;
  954. }
  955. /**
  956. * 已下发/审批/确认列表左侧月份:SQL DISTINCT,禁止把该阶段全部行拉进 PHP
  957. * 注意:MySQL8 严格模式下勿对 datetime 用 <> '',否则报 Incorrect DATETIME value 被吞掉后侧栏只剩默认月
  958. */
  959. protected function GetIssuedOrderYearMonths(string $stage): array
  960. {
  961. if ($stage !== 'audit' && $stage !== 'confirm') {
  962. return $this->GetIndexYearMonths();
  963. }
  964. $ymSet = [];
  965. $addYm = function ($raw) use (&$ymSet): void {
  966. $ym = trim((string)$raw);
  967. if (preg_match('/^([12]\d{3})-(\d{2})/', $ym, $m)) {
  968. $ymSet[$m[1] . '-' . $m[2]] = true;
  969. }
  970. };
  971. try {
  972. $query = Db::table('purchase_order')->field('pick_time,createtime,dStamp');
  973. $this->applyPurchaseOrderNotDeletedWhere($query);
  974. $this->applyPurchaseOrderConfirmAuditListWhere($query);
  975. $rows = $query->select();
  976. if (is_array($rows)) {
  977. foreach ($rows as $r) {
  978. if (!is_array($r)) {
  979. continue;
  980. }
  981. $pick = trim((string)($r['pick_time'] ?? ''));
  982. if ($pick !== '' && stripos($pick, '0000-00-00') !== 0) {
  983. $addYm($pick);
  984. continue;
  985. }
  986. $ct = $r['createtime'] ?? null;
  987. if (is_numeric($ct) && (int)$ct > 946684800) {
  988. $addYm(date('Y-m-d', (int)$ct));
  989. continue;
  990. }
  991. $ctStr = trim((string)$ct);
  992. if ($ctStr !== '' && stripos($ctStr, '0000-00-00') !== 0) {
  993. $addYm($ctStr);
  994. continue;
  995. }
  996. $ds = trim((string)($r['dStamp'] ?? ''));
  997. if ($ds !== '' && stripos($ds, '0000-00-00') !== 0) {
  998. $addYm($ds);
  999. }
  1000. }
  1001. }
  1002. } catch (\Throwable $e) {
  1003. Log::write('GetIssuedOrderYearMonths: ' . $e->getMessage(), 'error');
  1004. $ymSet = [];
  1005. }
  1006. $ymList = array_keys($ymSet);
  1007. if ($ymList === []) {
  1008. $def = $this->resolveProcuremenDefaultYm($stage);
  1009. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  1010. }
  1011. return $this->buildYearMonthSidebar($ymList);
  1012. }
  1013. /**
  1014. * 列表默认月份:已下发类取最近有数据的月份;初选也取最近有数据月份(避免跨月后落到空当月)
  1015. */
  1016. protected function resolveProcuremenDefaultYm(string $stage): string
  1017. {
  1018. if ($stage === 'pick') {
  1019. $yms = $this->ensureProcuremenPickSidebarYmList();
  1020. if ($yms !== []) {
  1021. rsort($yms, SORT_STRING);
  1022. return $yms[0];
  1023. }
  1024. return date('Y-m');
  1025. }
  1026. try {
  1027. $query = Db::table('purchase_order');
  1028. $this->applyPurchaseOrderNotDeletedWhere($query);
  1029. if ($stage === 'audit') {
  1030. $query->whereIn('wflow_status', ProcuremenStatus::wflowConfirmAndAuditListValues());
  1031. } elseif ($stage === 'confirm') {
  1032. $this->applyPurchaseOrderConfirmStageWhere($query);
  1033. } else {
  1034. return date('Y-m');
  1035. }
  1036. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  1037. if ($latest === null || $latest === '') {
  1038. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  1039. }
  1040. $t = $this->formatProcuremenDetailTime($latest);
  1041. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  1042. return $m[1] . '-' . $m[2];
  1043. }
  1044. } catch (\Throwable $e) {
  1045. }
  1046. return date('Y-m');
  1047. }
  1048. protected function applyPurchaseOrderNotDeletedWhere($query): void
  1049. {
  1050. $query->whereRaw("(mod_rq IS NULL OR mod_rq = '' OR mod_rq LIKE '0000-00-00%')");
  1051. }
  1052. /**
  1053. * 确认/审批列表共用:待确认 + 待审核(待审批) + 已审核
  1054. */
  1055. protected function applyPurchaseOrderConfirmAuditListWhere($query): void
  1056. {
  1057. $vals = ProcuremenStatus::wflowConfirmAndAuditListValues();
  1058. $quoted = [];
  1059. foreach ($vals as $v) {
  1060. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  1061. }
  1062. if ($quoted === []) {
  1063. $query->whereRaw('1 = 0');
  1064. return;
  1065. }
  1066. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  1067. }
  1068. /**
  1069. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  1070. * 完结判断必须走 CAST 文案比较:status 为 0/'0' 时,NOT IN ('已完结','1') 会被 MySQL 把「已完结」转成 0 而整表滤空
  1071. */
  1072. protected function applyPurchaseOrderConfirmStageWhere($query): void
  1073. {
  1074. // 与确认页共用数据范围(待确认/待审核/已审核)
  1075. $this->applyPurchaseOrderConfirmAuditListWhere($query);
  1076. }
  1077. /**
  1078. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  1079. *
  1080. * @param array<string, mixed> $row
  1081. * @return array<string, mixed>
  1082. */
  1083. protected function normalizePurchaseOrderListTimeRow(array $row): array
  1084. {
  1085. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  1086. $pick = trim((string)($row['pick_time'] ?? ''));
  1087. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  1088. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  1089. $t = trim((string)($row[$key] ?? ''));
  1090. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1091. $row['pick_time'] = $t;
  1092. break;
  1093. }
  1094. }
  1095. }
  1096. return $row;
  1097. }
  1098. /**
  1099. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  1100. */
  1101. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  1102. {
  1103. if (!in_array($stage, ['audit', 'confirm'], true)) {
  1104. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1105. }
  1106. if ($pool === []) {
  1107. $def = $this->resolveProcuremenDefaultYm($stage);
  1108. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  1109. }
  1110. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  1111. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1112. return false;
  1113. }
  1114. $monthStart = $ym . '-01 00:00:00';
  1115. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1116. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  1117. return $probe !== [];
  1118. };
  1119. if ($tryYm($requestedYm)) {
  1120. return $requestedYm;
  1121. }
  1122. $fallback = $this->resolveProcuremenDefaultYm($stage);
  1123. if ($tryYm($fallback)) {
  1124. return $fallback;
  1125. }
  1126. $bestYm = '';
  1127. $bestTime = '';
  1128. foreach ($pool as $row) {
  1129. if (!is_array($row)) {
  1130. continue;
  1131. }
  1132. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  1133. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  1134. continue;
  1135. }
  1136. $ymRow = $m[1];
  1137. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  1138. $bestTime = $t;
  1139. $bestYm = $ymRow;
  1140. }
  1141. }
  1142. if ($bestYm !== '') {
  1143. return $bestYm;
  1144. }
  1145. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1146. }
  1147. protected function isPurchaseOrderDetailVoid(array $row): bool
  1148. {
  1149. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  1150. return true;
  1151. }
  1152. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  1153. }
  1154. /**
  1155. * 仅当前有效下发明细(排除废弃归档)
  1156. */
  1157. protected function applyActivePurchaseOrderDetailWhere($query): void
  1158. {
  1159. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1160. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  1161. }
  1162. /**
  1163. * @param array<string, mixed> $detailRow
  1164. */
  1165. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  1166. {
  1167. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  1168. return false;
  1169. }
  1170. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  1171. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  1172. }
  1173. /**
  1174. * 废弃退回初选:下发明细标记归档,不物理删除
  1175. *
  1176. * @param array<int, int|string> $scydgyIds
  1177. */
  1178. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  1179. {
  1180. $ids = [];
  1181. foreach ($scydgyIds as $sid) {
  1182. $n = (int)$sid;
  1183. if ($this->isValidScydgyRowId($n) || $n < 0) {
  1184. $ids[$n] = true;
  1185. }
  1186. }
  1187. if ($ids === []) {
  1188. return;
  1189. }
  1190. $void = ProcuremenStatus::POD_VOID;
  1191. Db::table('purchase_order_detail')
  1192. ->where('scydgy_id', 'in', array_keys($ids))
  1193. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1194. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  1195. ->update([
  1196. 'status' => $void,
  1197. 'status_name' => $void,
  1198. ]);
  1199. }
  1200. /**
  1201. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  1202. */
  1203. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  1204. {
  1205. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  1206. $norm = function (string $col) use ($p): string {
  1207. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  1208. };
  1209. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  1210. $parts = [];
  1211. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  1212. if ($key === 'createtime') {
  1213. $parts[] = $createtime;
  1214. } else {
  1215. $parts[] = $norm($key);
  1216. }
  1217. }
  1218. return 'COALESCE(' . implode(', ', $parts) . ')';
  1219. }
  1220. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  1221. {
  1222. if (!preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $monthStart)
  1223. || !preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $monthEnd)) {
  1224. return;
  1225. }
  1226. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  1227. // 禁止 whereRaw 用 ? :与 whereIn 命名绑定混用时 PDO 会失败,列表被 catch 成空
  1228. $query->whereRaw("({$expr}) >= '{$monthStart}' AND ({$expr}) <= '{$monthEnd}'");
  1229. }
  1230. /**
  1231. * @return array<int, array<string, mixed>>
  1232. */
  1233. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  1234. {
  1235. $this->ensurePurchaseOrderCzlyqColumn();
  1236. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1237. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name,order_batch_no';
  1238. try {
  1239. $this->ensurePurchaseOrderOrderBatchNoColumn();
  1240. $query = Db::table('purchase_order')->field($fields);
  1241. $this->applyPurchaseOrderNotDeletedWhere($query);
  1242. if ($stage === 'audit') {
  1243. $query->whereIn('wflow_status', ProcuremenStatus::wflowConfirmAndAuditListValues());
  1244. } elseif ($stage === 'confirm') {
  1245. $this->applyPurchaseOrderConfirmStageWhere($query);
  1246. } else {
  1247. return [];
  1248. }
  1249. $query->order('pick_time', 'desc')->order('id', 'desc');
  1250. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1251. $monthStart = $ym . '-01 00:00:00';
  1252. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1253. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  1254. }
  1255. $rows = $query->select();
  1256. } catch (\Throwable $e) {
  1257. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  1258. $rows = [];
  1259. }
  1260. return is_array($rows) ? $rows : [];
  1261. }
  1262. /**
  1263. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  1264. */
  1265. protected function resolveProcuremenListStage(): string
  1266. {
  1267. $tab = trim((string)$this->request->request('wff_tab', ''));
  1268. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  1269. return $tab;
  1270. }
  1271. $action = strtolower((string)$this->request->action());
  1272. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  1273. return $action;
  1274. }
  1275. return 'pick';
  1276. }
  1277. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  1278. {
  1279. $this->procuremenReleaseSessionLock();
  1280. $rootTrue = rtrim((string)$this->request->root(true), '/');
  1281. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  1282. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  1283. $indexPhpRoot = $rootTrue . '/index.php';
  1284. }
  1285. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  1286. if ($stage === 'pick') {
  1287. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  1288. $sidebar = $this->GetIndexYearMonths();
  1289. } else {
  1290. $sidebar = $this->GetIssuedOrderYearMonths($stage);
  1291. $defaultYm = $this->latestYmFromSidebar($sidebar);
  1292. }
  1293. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  1294. $this->view->assign('defaultYm', $defaultYm);
  1295. $this->view->assign('sidebarYearMonths', $sidebar);
  1296. $this->view->assign('procuremenStage', $stage);
  1297. $this->view->assign('procuremenPageTitle', $pageTitle);
  1298. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  1299. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  1300. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  1301. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  1302. // 筛选项由列表 AJAX 带回,避免进页再扫 4 次 DISTINCT 白屏
  1303. $this->assignconfig('procuremenFilterOptions', [
  1304. 'czlyq' => [],
  1305. 'CCLBMMC' => [],
  1306. 'cywyxm' => [],
  1307. 'CGYMC' => [],
  1308. ]);
  1309. }
  1310. /**
  1311. * @param array<int, array{year?:string, months?:array}> $sidebar
  1312. */
  1313. protected function latestYmFromSidebar(array $sidebar): string
  1314. {
  1315. $best = '';
  1316. foreach ($sidebar as $block) {
  1317. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  1318. continue;
  1319. }
  1320. foreach ($block['months'] as $item) {
  1321. $ym = is_array($item) ? trim((string)($item['ym'] ?? '')) : '';
  1322. if (preg_match('/^\d{4}-\d{2}$/', $ym) && ($best === '' || strcmp($ym, $best) > 0)) {
  1323. $best = $ym;
  1324. }
  1325. }
  1326. }
  1327. return $best !== '' ? $best : date('Y-m');
  1328. }
  1329. /**
  1330. * 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
  1331. *
  1332. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1333. */
  1334. protected function buildProcuremenFilterOptions(string $stage): array
  1335. {
  1336. $buckets = [
  1337. 'czlyq' => [],
  1338. 'CCLBMMC' => [],
  1339. 'cywyxm' => [],
  1340. 'CGYMC' => [],
  1341. ];
  1342. $maxPerField = 300;
  1343. try {
  1344. if ($stage === 'pick') {
  1345. // 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
  1346. return $buckets;
  1347. }
  1348. if (in_array($stage, ['audit', 'confirm'], true)) {
  1349. $this->ensurePurchaseOrderCzlyqColumn();
  1350. foreach (array_keys($buckets) as $field) {
  1351. try {
  1352. $query = Db::table('purchase_order')->field($field);
  1353. $this->applyPurchaseOrderNotDeletedWhere($query);
  1354. if ($stage === 'audit') {
  1355. $query->whereIn('wflow_status', ProcuremenStatus::wflowConfirmAndAuditListValues());
  1356. } else {
  1357. $this->applyPurchaseOrderConfirmStageWhere($query);
  1358. }
  1359. $query->where($field, '<>', '')->whereNotNull($field);
  1360. $vals = $query->distinct(true)->limit($maxPerField)->column($field);
  1361. if (!is_array($vals)) {
  1362. continue;
  1363. }
  1364. foreach ($vals as $v) {
  1365. $v = trim((string)$v);
  1366. if ($v !== '') {
  1367. $buckets[$field][$v] = $v;
  1368. }
  1369. }
  1370. } catch (\Throwable $e) {
  1371. // 单字段失败不影响其它
  1372. }
  1373. }
  1374. }
  1375. } catch (\Throwable $e) {
  1376. Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
  1377. }
  1378. foreach ($buckets as &$set) {
  1379. if ($set !== []) {
  1380. ksort($set, SORT_STRING);
  1381. }
  1382. }
  1383. unset($set);
  1384. return $buckets;
  1385. }
  1386. /**
  1387. * filter JSON 是否含有效条件
  1388. *
  1389. * @param array<string, mixed> $filterArr
  1390. */
  1391. protected function procuremenFilterArrHasValue(array $filterArr): bool
  1392. {
  1393. foreach ($filterArr as $v) {
  1394. if (is_array($v)) {
  1395. if (array_filter($v, function ($x) {
  1396. return $x !== '' && $x !== null;
  1397. })) {
  1398. return true;
  1399. }
  1400. } elseif ($v !== '' && $v !== null) {
  1401. return true;
  1402. }
  1403. }
  1404. return false;
  1405. }
  1406. /**
  1407. * 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
  1408. *
  1409. * @param array<string, mixed> $filterArr
  1410. * @param array<string, mixed> $opArr
  1411. */
  1412. protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
  1413. {
  1414. if ($search !== '') {
  1415. return false;
  1416. }
  1417. foreach ($filterArr as $fk => $fv) {
  1418. if (is_array($fv)) {
  1419. continue;
  1420. }
  1421. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  1422. continue;
  1423. }
  1424. if ($fv === null) {
  1425. continue;
  1426. }
  1427. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  1428. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  1429. if ($sym === '' || $sym === '=') {
  1430. continue;
  1431. }
  1432. return false;
  1433. }
  1434. return true;
  1435. }
  1436. /**
  1437. * 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
  1438. *
  1439. * @param array<int, mixed> $rows
  1440. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1441. */
  1442. protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
  1443. {
  1444. $buckets = [
  1445. 'czlyq' => [],
  1446. 'CCLBMMC' => [],
  1447. 'cywyxm' => [],
  1448. 'CGYMC' => [],
  1449. ];
  1450. foreach ($rows as $r) {
  1451. if (!is_array($r)) {
  1452. continue;
  1453. }
  1454. foreach ($buckets as $field => &$set) {
  1455. if (count($set) >= $maxPerField) {
  1456. continue;
  1457. }
  1458. $v = trim((string)($r[$field] ?? ''));
  1459. if ($v !== '') {
  1460. $set[$v] = $v;
  1461. }
  1462. }
  1463. unset($set);
  1464. $full = true;
  1465. foreach ($buckets as $set) {
  1466. if (count($set) < $maxPerField) {
  1467. $full = false;
  1468. break;
  1469. }
  1470. }
  1471. if ($full) {
  1472. break;
  1473. }
  1474. }
  1475. foreach ($buckets as &$set) {
  1476. if ($set !== []) {
  1477. // 保证 json 编码为对象(避免 list 下标 0,1,2… 被前端当选项)
  1478. $normalized = [];
  1479. foreach ($set as $k => $v) {
  1480. $s = trim((string)(is_scalar($v) ? $v : $k));
  1481. if ($s === '') {
  1482. continue;
  1483. }
  1484. $normalized[$s] = $s;
  1485. }
  1486. ksort($normalized, SORT_STRING);
  1487. $set = $normalized;
  1488. }
  1489. }
  1490. unset($set);
  1491. return $buckets;
  1492. }
  1493. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  1494. public function pick()
  1495. {
  1496. $this->request->filter(['strip_tags', 'trim']);
  1497. if (!$this->request->isAjax()) {
  1498. $this->assignProcuremenListPage('pick', '协助下发');
  1499. return $this->view->fetch('procuremen/index');
  1500. }
  1501. return $this->index();
  1502. }
  1503. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  1504. public function audit()
  1505. {
  1506. $this->request->filter(['strip_tags', 'trim']);
  1507. if (!$this->request->isAjax()) {
  1508. $this->assignProcuremenListPage('audit', '确认供应商');
  1509. return $this->view->fetch('procuremen/index');
  1510. }
  1511. return $this->index();
  1512. }
  1513. /** 采购确认(定标) */
  1514. public function confirm()
  1515. {
  1516. $this->request->filter(['strip_tags', 'trim']);
  1517. if (!$this->request->isAjax()) {
  1518. $this->assignProcuremenListPage('confirm', '采购确认');
  1519. return $this->view->fetch('procuremen/index');
  1520. }
  1521. return $this->index();
  1522. }
  1523. /**
  1524. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  1525. */
  1526. public function index()
  1527. {
  1528. $this->request->filter(['strip_tags', 'trim']);
  1529. if (!$this->request->isAjax()) {
  1530. $this->assignProcuremenListPage('pick', '协助下发');
  1531. return $this->view->fetch('procuremen/index');
  1532. }
  1533. if ($this->request->request('keyField')) {
  1534. return $this->selectpage();
  1535. }
  1536. $this->procuremenReleaseSessionLock();
  1537. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  1538. $limit = max(10, min(500, (int)$limit));
  1539. $ym = $this->request->request('ym', '');
  1540. $ym = is_string($ym) ? trim($ym) : '';
  1541. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  1542. $wffTab = $this->resolveProcuremenListStage();
  1543. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1544. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  1545. ? $this->resolveProcuremenDefaultYm($wffTab)
  1546. : date('Y-m');
  1547. }
  1548. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1549. $ym = date('Y-m');
  1550. }
  1551. $monthStart = $ym . '-01 00:00:00';
  1552. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1553. $search = trim((string)$this->request->get('search', ''));
  1554. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  1555. $opArr = (array)json_decode($this->request->get('op', ''), true);
  1556. if (!is_array($filterArr)) {
  1557. $filterArr = [];
  1558. }
  1559. if (!is_array($opArr)) {
  1560. $opArr = [];
  1561. }
  1562. // 开标状态 / 订单状态为计算字段,不能进池内等值筛选;单独抽出后在合并后再滤
  1563. $bidOpenStatusFilter = '';
  1564. foreach (['bid_open_status_text', 'a.bid_open_status_text'] as $bidFk) {
  1565. if (!array_key_exists($bidFk, $filterArr)) {
  1566. continue;
  1567. }
  1568. $bidOpenStatusFilter = trim((string)$filterArr[$bidFk]);
  1569. unset($filterArr[$bidFk], $opArr[$bidFk]);
  1570. }
  1571. $orderStatusFilter = '';
  1572. foreach (['order_status_text', 'a.order_status_text'] as $osFk) {
  1573. if (!array_key_exists($osFk, $filterArr)) {
  1574. continue;
  1575. }
  1576. $orderStatusFilter = trim((string)$filterArr[$osFk]);
  1577. unset($filterArr[$osFk], $opArr[$osFk]);
  1578. }
  1579. // 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
  1580. $applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
  1581. $hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
  1582. try {
  1583. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  1584. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1585. $dbRows = $this->loadPurchaseOrderRowsForListStage($wffTab, $ym, $applyMonthRange);
  1586. if ($applyMonthRange && $dbRows === []) {
  1587. $fallbackYm = $this->resolveProcuremenDefaultYm($wffTab);
  1588. if ($fallbackYm !== $ym && preg_match('/^\d{4}-\d{2}$/', $fallbackYm)) {
  1589. $ym = $fallbackYm;
  1590. $monthStart = $ym . '-01 00:00:00';
  1591. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1592. $dbRows = $this->loadPurchaseOrderRowsForListStage($wffTab, $ym, true);
  1593. }
  1594. }
  1595. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(is_array($dbRows) ? $dbRows : []);
  1596. if ($wffTab === 'confirm' && $pool === []) {
  1597. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1598. }
  1599. } else {
  1600. // 初选:按月直查 ERP(不解整包 Redis,避免长时间转圈)
  1601. if ($applyMonthRange) {
  1602. $pool = $this->loadPickPoolForYm($ym);
  1603. } else {
  1604. $pool = $this->procuremenEnsureRedisPool();
  1605. }
  1606. if (!is_array($pool)) {
  1607. $pool = [];
  1608. }
  1609. // 只针对本页候选 ID 查隐藏集,避免全表扫 purchase_order_detail
  1610. $hideSet = $this->loadPickHiddenScydgySetForIds($this->extractScydgyIdsFromPool($pool));
  1611. if ($pool !== [] && $hideSet !== []) {
  1612. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1613. if (!is_array($r)) {
  1614. return false;
  1615. }
  1616. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1617. return $id <= 0 || !isset($hideSet[$id]);
  1618. }));
  1619. }
  1620. // 手工新增(YW / scydgy_id<0)只走「新增询价/查询询价」,不进初选表格
  1621. if ($pool === []) {
  1622. return json([
  1623. 'total' => 0,
  1624. 'rows' => [],
  1625. 'activeYm' => $ym,
  1626. 'filterOptions' => (
  1627. (int)$offset === 0
  1628. && !$hasActiveSearch
  1629. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1630. )
  1631. ? $this->extractProcuremenFilterOptionsFromRows([])
  1632. : new \stdClass(),
  1633. ]);
  1634. }
  1635. }
  1636. $filtered = $this->filterProcuremenIndexPool(
  1637. $pool,
  1638. $monthStart,
  1639. $monthEnd,
  1640. $applyMonthRange,
  1641. $search,
  1642. $filterArr,
  1643. $opArr,
  1644. $listTimePrimary
  1645. );
  1646. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1647. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1648. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1649. }
  1650. if (in_array($wffTab, ['audit', 'confirm'], true) && $bidOpenStatusFilter !== '') {
  1651. $filtered = $this->filterProcuremenPoolByBidOpenStatus($filtered, $bidOpenStatusFilter);
  1652. }
  1653. if (in_array($wffTab, ['audit', 'confirm'], true) && $orderStatusFilter !== '') {
  1654. $filtered = $this->filterProcuremenPoolByOrderStatus($filtered, $orderStatusFilter);
  1655. }
  1656. $sortField = 'ID';
  1657. if (is_string($sort) && $sort !== '') {
  1658. $parts = explode(',', $sort);
  1659. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1660. if ($sortField === '') {
  1661. $sortField = 'ID';
  1662. }
  1663. }
  1664. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1665. $nFiltered = count($filtered);
  1666. if ($nFiltered > 1) {
  1667. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1668. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1669. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1670. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1671. if ($ta === $tb) {
  1672. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1673. }
  1674. if ($ta === '') {
  1675. return 1;
  1676. }
  1677. if ($tb === '') {
  1678. return -1;
  1679. }
  1680. return strcmp($ta, $tb) * $ord;
  1681. });
  1682. } elseif ($sortField === 'ID') {
  1683. $sortKeys = [];
  1684. foreach ($filtered as $i => $row) {
  1685. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1686. }
  1687. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1688. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1689. } elseif ($sortField === 'CCYDH') {
  1690. usort($filtered, function ($a, $b) use ($ord) {
  1691. $sa = trim((string)($a['CCYDH'] ?? ''));
  1692. $sb = trim((string)($b['CCYDH'] ?? ''));
  1693. if ($sa === $sb) {
  1694. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1695. }
  1696. if ($sa === '') {
  1697. return 1;
  1698. }
  1699. if ($sb === '') {
  1700. return -1;
  1701. }
  1702. return strcmp($sa, $sb) * $ord;
  1703. });
  1704. } else {
  1705. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1706. $va = $a[$sortField] ?? null;
  1707. $vb = $b[$sortField] ?? null;
  1708. $sa = (string)$va;
  1709. $sb = (string)$vb;
  1710. if ($sa === $sb) {
  1711. return 0;
  1712. }
  1713. return strcmp($sa, $sb) * $ord;
  1714. });
  1715. }
  1716. }
  1717. // 确认/审批:订单状态优先(同状态内保留上面时间等排序)
  1718. if (in_array($wffTab, ['audit', 'confirm'], true) && count($filtered) > 1) {
  1719. $statusWeights = [];
  1720. foreach ($filtered as $i => $row) {
  1721. if (!is_array($row)) {
  1722. $statusWeights[$i] = 99;
  1723. continue;
  1724. }
  1725. $statusKey = $row['order_status_text'] ?? $row['wflow_status'] ?? '';
  1726. if (trim((string)$statusKey) === '') {
  1727. $statusKey = $row['wflow_status'] ?? '';
  1728. }
  1729. $statusWeights[$i] = ProcuremenStatus::orderStatusSortWeight($wffTab, $statusKey);
  1730. }
  1731. array_multisort($statusWeights, SORT_ASC, SORT_NUMERIC, $filtered);
  1732. }
  1733. $offset = max(0, (int)$offset);
  1734. $limit = max(1, (int)$limit);
  1735. $rows = array_slice($filtered, $offset, $limit);
  1736. foreach ($rows as &$rw) {
  1737. if (!is_array($rw)) {
  1738. continue;
  1739. }
  1740. $rid = (int)($rw['ID'] ?? 0);
  1741. $rw['_iss_out'] = ($wffTab !== 'pick');
  1742. }
  1743. unset($rw);
  1744. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1745. $idList = [];
  1746. foreach ($rows as $rw) {
  1747. if (!is_array($rw)) {
  1748. continue;
  1749. }
  1750. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1751. foreach ($rw['_order_merge_rows'] as $mr) {
  1752. $mid = (int)($mr['ID'] ?? 0);
  1753. if ($this->isValidScydgyRowId($mid)) {
  1754. $idList[$mid] = true;
  1755. }
  1756. }
  1757. }
  1758. $id = (int)($rw['ID'] ?? 0);
  1759. if ($this->isValidScydgyRowId($id)) {
  1760. $idList[$id] = true;
  1761. }
  1762. }
  1763. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1764. foreach ($rows as &$rw) {
  1765. if (!is_array($rw)) {
  1766. continue;
  1767. }
  1768. $mergeIds = [];
  1769. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1770. foreach ($rw['_order_merge_rows'] as $mr) {
  1771. $mid = (int)($mr['ID'] ?? 0);
  1772. if ($this->isValidScydgyRowId($mid)) {
  1773. $mergeIds[$mid] = true;
  1774. }
  1775. }
  1776. }
  1777. $rid = (int)($rw['ID'] ?? 0);
  1778. if ($this->isValidScydgyRowId($rid)) {
  1779. $mergeIds[$rid] = true;
  1780. }
  1781. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1782. $rw['po_detail_count'] = $s['cnt'];
  1783. $rw['po_amount_fill_cnt'] = $s['amt'];
  1784. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1785. }
  1786. unset($rw);
  1787. }
  1788. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1789. $idList = [];
  1790. foreach ($rows as $rw) {
  1791. if (!is_array($rw)) {
  1792. continue;
  1793. }
  1794. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1795. foreach ($rw['_order_merge_rows'] as $mr) {
  1796. $mid = (int)($mr['ID'] ?? 0);
  1797. if ($this->isValidScydgyRowId($mid)) {
  1798. $idList[$mid] = true;
  1799. }
  1800. }
  1801. }
  1802. $id = (int)($rw['ID'] ?? 0);
  1803. if ($this->isValidScydgyRowId($id)) {
  1804. $idList[$id] = true;
  1805. }
  1806. }
  1807. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1808. $bidOpenSet = [];
  1809. $manualPickSet = [];
  1810. $ccydhList = [];
  1811. foreach ($rows as $rw0) {
  1812. if (!is_array($rw0)) {
  1813. continue;
  1814. }
  1815. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1816. if ($c0 !== '') {
  1817. $ccydhList[] = $c0;
  1818. }
  1819. }
  1820. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1821. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  1822. foreach ($rows as &$rw) {
  1823. if (!is_array($rw)) {
  1824. continue;
  1825. }
  1826. $mergeIds = [];
  1827. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1828. foreach ($rw['_order_merge_rows'] as $mr) {
  1829. $mid = (int)($mr['ID'] ?? 0);
  1830. if ($this->isValidScydgyRowId($mid)) {
  1831. $mergeIds[$mid] = true;
  1832. }
  1833. }
  1834. }
  1835. $rid = (int)($rw['ID'] ?? 0);
  1836. if ($this->isValidScydgyRowId($rid)) {
  1837. $mergeIds[$rid] = true;
  1838. }
  1839. $buckets = [];
  1840. foreach (array_keys($mergeIds) as $mid) {
  1841. if (isset($quoteBucket[$mid])) {
  1842. $buckets[] = $quoteBucket[$mid];
  1843. }
  1844. }
  1845. $supplierText = $buckets !== []
  1846. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1847. : '';
  1848. $picked = trim((string)($rw['pick_company_name'] ?? $rw['picked_supplier_name'] ?? ''));
  1849. if ($picked === '') {
  1850. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1851. foreach ($rw['_order_merge_rows'] as $mr) {
  1852. if (!is_array($mr)) {
  1853. continue;
  1854. }
  1855. $pn = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  1856. if ($pn !== '') {
  1857. $picked = $pn;
  1858. break;
  1859. }
  1860. }
  1861. }
  1862. }
  1863. $rw['picked_supplier_name'] = $picked;
  1864. $rw['notify_supplier_text'] = $supplierText;
  1865. $wflowRaw = trim((string)($rw['wflow_status'] ?? ''));
  1866. if ($wflowRaw === '' && !empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1867. foreach ($rw['_order_merge_rows'] as $mr) {
  1868. if (!is_array($mr)) {
  1869. continue;
  1870. }
  1871. $wf = trim((string)($mr['wflow_status'] ?? ''));
  1872. if ($wf !== '') {
  1873. $wflowRaw = $wf;
  1874. break;
  1875. }
  1876. }
  1877. }
  1878. $rw['wflow_status'] = $wflowRaw;
  1879. $rw['order_status_text'] = ProcuremenStatus::orderStatusLabelForList($wflowRaw);
  1880. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1881. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1882. $manualPicked = ($ccydh !== '' && isset($manualPickSet[$ccydh]));
  1883. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1884. $rw['manual_picked'] = $manualPicked ? 1 : 0;
  1885. if ($verified) {
  1886. $rw['bid_open_status_text'] = '已开标';
  1887. } elseif ($manualPicked) {
  1888. $rw['bid_open_status_text'] = '已指定供应商';
  1889. } else {
  1890. $rw['bid_open_status_text'] = '待开标';
  1891. }
  1892. }
  1893. unset($rw);
  1894. }
  1895. if (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
  1896. $this->enrichProcuremenListMilestoneTimes($rows);
  1897. $this->syncCollapsedOrderQtyPriceForList($rows);
  1898. }
  1899. if ($wffTab === 'all' && count($rows) > 0) {
  1900. $this->mergePurchaseOrder($rows);
  1901. }
  1902. if ($wffTab === 'pick' && count($rows) > 0) {
  1903. $this->mergePurchaseOrder($rows);
  1904. }
  1905. foreach ($rows as &$rwClean) {
  1906. if (is_array($rwClean)) {
  1907. unset($rwClean['_order_merge_rows']);
  1908. if (array_key_exists('NGZL', $rwClean)) {
  1909. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1910. }
  1911. }
  1912. }
  1913. unset($rwClean);
  1914. return json([
  1915. 'total' => count($filtered),
  1916. 'rows' => $rows,
  1917. 'activeYm' => $ym,
  1918. // 初选:把有数据的月份带回,替换「空月份日历」侧栏
  1919. 'sidebarYms' => (in_array($wffTab, ['pick', 'audit', 'confirm'], true) && (int)$offset === 0)
  1920. ? (
  1921. $wffTab === 'pick'
  1922. ? $this->ensureProcuremenPickSidebarYmList()
  1923. : $this->flattenProcuremenSidebarYms($this->GetIssuedOrderYearMonths($wffTab))
  1924. )
  1925. : [],
  1926. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1927. 'filterOptions' => (
  1928. (int)$offset === 0
  1929. && !$hasActiveSearch
  1930. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1931. )
  1932. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1933. : new \stdClass(),
  1934. ]);
  1935. } catch (\Throwable $e) {
  1936. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1937. return json([
  1938. 'total' => 0,
  1939. 'rows' => [],
  1940. ]);
  1941. }
  1942. }
  1943. /**
  1944. * @param array<int, array<string, mixed>> $pool
  1945. * @return int[]
  1946. */
  1947. protected function extractScydgyIdsFromPool(array $pool): array
  1948. {
  1949. $ids = [];
  1950. foreach ($pool as $r) {
  1951. if (!is_array($r)) {
  1952. continue;
  1953. }
  1954. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1955. if ($id > 0) {
  1956. $ids[$id] = $id;
  1957. }
  1958. }
  1959. return array_values($ids);
  1960. }
  1961. /**
  1962. * 仅查询指定工序 ID 是否已下发/进入后续流程(初选列表加速)
  1963. *
  1964. * @param int[] $scydgyIds
  1965. * @return array<int, true>
  1966. */
  1967. protected function loadPickHiddenScydgySetForIds(array $scydgyIds): array
  1968. {
  1969. $hideSet = [];
  1970. $scydgyIds = array_values(array_filter(array_map('intval', $scydgyIds), function ($id) {
  1971. return $id > 0;
  1972. }));
  1973. if ($scydgyIds === []) {
  1974. return $hideSet;
  1975. }
  1976. // 分批,避免 whereIn 过长
  1977. foreach (array_chunk($scydgyIds, 500) as $chunk) {
  1978. try {
  1979. $poIds = Db::table('purchase_order')
  1980. ->where('scydgy_id', 'in', $chunk)
  1981. ->where(function ($q) {
  1982. $q->whereIn('wflow_status', array_merge(
  1983. ProcuremenStatus::wflowPendingConfirmValues(),
  1984. ProcuremenStatus::wflowPendingApprovalValues()
  1985. ))
  1986. ->whereOr(function ($q1) {
  1987. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1988. })
  1989. ->whereOr(function ($q2) {
  1990. $q2->whereNotNull('pick_time')
  1991. ->where('pick_time', '<>', '')
  1992. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1993. })
  1994. ->whereOr(function ($q3) {
  1995. $q3->whereNotNull('mod_rq')
  1996. ->where('mod_rq', '<>', '')
  1997. ->where('mod_rq', 'not like', '0000-00-00%');
  1998. });
  1999. })
  2000. ->column('scydgy_id');
  2001. if (is_array($poIds)) {
  2002. foreach ($poIds as $pid) {
  2003. $k = (int)$pid;
  2004. if ($k !== 0) {
  2005. $hideSet[$k] = true;
  2006. }
  2007. }
  2008. }
  2009. } catch (\Throwable $e) {
  2010. }
  2011. try {
  2012. $detIdsQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $chunk);
  2013. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  2014. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  2015. if (is_array($detIds)) {
  2016. foreach ($detIds as $pid) {
  2017. $k = (int)$pid;
  2018. if ($this->isValidScydgyRowId($k)) {
  2019. $hideSet[$k] = true;
  2020. }
  2021. }
  2022. }
  2023. } catch (\Throwable $e) {
  2024. }
  2025. }
  2026. return $hideSet;
  2027. }
  2028. /**
  2029. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  2030. *
  2031. * @return array<int, true>
  2032. */
  2033. protected function loadPickHiddenScydgySet(): array
  2034. {
  2035. if ($this->pickHiddenScydgySetCache !== null) {
  2036. return $this->pickHiddenScydgySetCache;
  2037. }
  2038. $cacheKey = 'procuremen_pick_hidden_scydgy_v1';
  2039. try {
  2040. $raw = redis()->get($cacheKey);
  2041. if ($raw !== false && $raw !== null && $raw !== '') {
  2042. $ids = json_decode((string)$raw, true);
  2043. if (is_array($ids)) {
  2044. $hideSet = [];
  2045. foreach ($ids as $pid) {
  2046. $k = (int)$pid;
  2047. if ($k !== 0) {
  2048. $hideSet[$k] = true;
  2049. }
  2050. }
  2051. $this->pickHiddenScydgySetCache = $hideSet;
  2052. return $hideSet;
  2053. }
  2054. }
  2055. } catch (\Throwable $e) {
  2056. }
  2057. $hideSet = [];
  2058. try {
  2059. $poIds = Db::table('purchase_order')
  2060. ->where(function ($q) {
  2061. $q->whereIn('wflow_status', array_merge(
  2062. ProcuremenStatus::wflowPendingConfirmValues(),
  2063. ProcuremenStatus::wflowPendingApprovalValues()
  2064. ))
  2065. ->whereOr(function ($q1) {
  2066. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  2067. })
  2068. ->whereOr(function ($q2) {
  2069. $q2->whereNotNull('pick_time')
  2070. ->where('pick_time', '<>', '')
  2071. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  2072. })
  2073. ->whereOr(function ($q3) {
  2074. $q3->whereNotNull('mod_rq')
  2075. ->where('mod_rq', '<>', '')
  2076. ->where('mod_rq', 'not like', '0000-00-00%');
  2077. });
  2078. })
  2079. ->column('scydgy_id');
  2080. if (is_array($poIds)) {
  2081. foreach ($poIds as $pid) {
  2082. $k = (int)$pid;
  2083. if ($k !== 0) {
  2084. $hideSet[$k] = true;
  2085. }
  2086. }
  2087. }
  2088. } catch (\Throwable $e) {
  2089. }
  2090. try {
  2091. $detIdsQuery = Db::table('purchase_order_detail');
  2092. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  2093. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  2094. if (is_array($detIds)) {
  2095. foreach ($detIds as $pid) {
  2096. $k = (int)$pid;
  2097. if ($this->isValidScydgyRowId($k)) {
  2098. $hideSet[$k] = true;
  2099. }
  2100. }
  2101. }
  2102. } catch (\Throwable $e) {
  2103. }
  2104. $this->pickHiddenScydgySetCache = $hideSet;
  2105. try {
  2106. redis()->setex($cacheKey, 90, json_encode(array_map('intval', array_keys($hideSet))));
  2107. } catch (\Throwable $e) {
  2108. }
  2109. return $hideSet;
  2110. }
  2111. /**
  2112. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  2113. *
  2114. * @return array<int, array<string, mixed>>
  2115. */
  2116. protected function loadPickManualOrderRows(): array
  2117. {
  2118. try {
  2119. $dbRows = Db::table('purchase_order')
  2120. ->where('scydgy_id', '<', 0)
  2121. ->whereRaw('(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')')
  2122. ->order('scydgy_id', 'asc')
  2123. ->select();
  2124. } catch (\Throwable $e) {
  2125. try {
  2126. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  2127. } catch (\Throwable $e2) {
  2128. return [];
  2129. }
  2130. }
  2131. if (!is_array($dbRows) || $dbRows === []) {
  2132. return [];
  2133. }
  2134. $detailSidSet = [];
  2135. try {
  2136. $negIds = [];
  2137. foreach ($dbRows as $dbRow) {
  2138. if (!is_array($dbRow)) {
  2139. continue;
  2140. }
  2141. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2142. if ($sid < 0) {
  2143. $negIds[$sid] = true;
  2144. }
  2145. }
  2146. if ($negIds !== []) {
  2147. $detQuery = Db::table('purchase_order_detail')
  2148. ->where('scydgy_id', 'in', array_keys($negIds));
  2149. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  2150. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  2151. if (is_array($detRows)) {
  2152. foreach ($detRows as $did) {
  2153. $detailSidSet[(int)$did] = true;
  2154. }
  2155. }
  2156. }
  2157. } catch (\Throwable $e) {
  2158. }
  2159. $pool = [];
  2160. foreach ($dbRows as $dbRow) {
  2161. if (!is_array($dbRow)) {
  2162. continue;
  2163. }
  2164. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2165. if ($sid >= 0) {
  2166. continue;
  2167. }
  2168. // 已进入确认/审批的不进初选;仅废弃明细残留的仍算可下发
  2169. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  2170. continue;
  2171. }
  2172. // 仅排除已完结;空 status / 「进行中」/ 0 均保留(新建手工单)
  2173. if (ProcuremenStatus::isPoCompleted($dbRow['status'] ?? '')) {
  2174. continue;
  2175. }
  2176. if (isset($detailSidSet[$sid])) {
  2177. continue;
  2178. }
  2179. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  2180. $r['_is_manual'] = 1;
  2181. $pool[] = $r;
  2182. }
  2183. return $pool;
  2184. }
  2185. /**
  2186. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  2187. */
  2188. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  2189. {
  2190. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  2191. foreach ($keys as $k) {
  2192. $t = trim((string)($row[$k] ?? ''));
  2193. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2194. return $t;
  2195. }
  2196. }
  2197. return '';
  2198. }
  2199. /**
  2200. * 分配手工新增工序行 ID(负数递减)
  2201. * 调用方须在命名锁内执行,避免并发重复
  2202. */
  2203. protected function allocateManualScydgyId(): int
  2204. {
  2205. try {
  2206. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  2207. $min = (int)$min;
  2208. return $min < 0 ? $min - 1 : -1;
  2209. } catch (\Throwable $e) {
  2210. return -1;
  2211. }
  2212. }
  2213. /**
  2214. * 手工新增订单号:YW + 年月日 + 当日序号(如 YW20260618001)
  2215. * 调用方须在命名锁内执行,避免并发重复
  2216. */
  2217. protected function allocateManualOrderCcydh(): string
  2218. {
  2219. $prefix = 'YW' . date('Ymd');
  2220. $maxSeq = 0;
  2221. try {
  2222. $rows = Db::table('purchase_order')
  2223. ->where('CCYDH', 'like', $prefix . '%')
  2224. ->column('CCYDH');
  2225. if (is_array($rows)) {
  2226. foreach ($rows as $ccydh) {
  2227. $ccydh = trim((string)$ccydh);
  2228. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3,})$/', $ccydh, $m)) {
  2229. $maxSeq = max($maxSeq, (int)$m[1]);
  2230. }
  2231. }
  2232. }
  2233. } catch (\Throwable $e) {
  2234. }
  2235. $next = $maxSeq + 1;
  2236. $width = $next > 999 ? strlen((string)$next) : 3;
  2237. return $prefix . str_pad((string)$next, $width, '0', STR_PAD_LEFT);
  2238. }
  2239. /**
  2240. * MySQL 命名锁(跨连接防并发撞号)
  2241. */
  2242. protected function acquireProcuremenNamedLock(string $name, int $timeoutSec = 10): bool
  2243. {
  2244. $name = trim($name);
  2245. if ($name === '') {
  2246. return false;
  2247. }
  2248. try {
  2249. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2250. $rows = Db::query('SELECT GET_LOCK(\'' . $nameSql . '\', ' . max(1, $timeoutSec) . ') AS locked');
  2251. if (!is_array($rows) || $rows === []) {
  2252. return false;
  2253. }
  2254. $v = $rows[0]['locked'] ?? $rows[0]['LOCKED'] ?? null;
  2255. return (int)$v === 1;
  2256. } catch (\Throwable $e) {
  2257. return false;
  2258. }
  2259. }
  2260. protected function releaseProcuremenNamedLock(string $name): void
  2261. {
  2262. $name = trim($name);
  2263. if ($name === '') {
  2264. return;
  2265. }
  2266. try {
  2267. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2268. Db::query('SELECT RELEASE_LOCK(\'' . $nameSql . '\')');
  2269. } catch (\Throwable $e) {
  2270. }
  2271. }
  2272. /**
  2273. * purchase_order.mod_rq 是否有有效软删除时间
  2274. */
  2275. protected function isPurchaseOrderSoftDeleted($modRq): bool
  2276. {
  2277. $t = trim((string)$modRq);
  2278. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  2279. }
  2280. /**
  2281. * 列表行 → purchase_order 写入字段
  2282. *
  2283. * @return array<string, mixed>
  2284. */
  2285. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  2286. {
  2287. return $this->normalizePurchaseOrderWritePayload([
  2288. 'scydgy_id' => $scydgyId,
  2289. 'CCYDH' => $row['CCYDH'] ?? null,
  2290. 'CYJMC' => $row['CYJMC'] ?? null,
  2291. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2292. 'CDXMC' => $row['CDXMC'] ?? null,
  2293. 'CGYBH' => $row['CGYBH'] ?? null,
  2294. 'CGYMC' => $row['CGYMC'] ?? null,
  2295. 'CDW' => $row['CDW'] ?? null,
  2296. 'czlyq' => $row['czlyq'] ?? null,
  2297. 'NGZL' => $row['NGZL'] ?? null,
  2298. 'CDF' => $row['CDF'] ?? null,
  2299. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2300. 'MBZ' => $row['MBZ'] ?? null,
  2301. 'bwjg' => $row['bwjg'] ?? null,
  2302. 'iStatus' => $row['iStatus'] ?? null,
  2303. 'dStamp' => $row['dStamp'] ?? null,
  2304. 'dputrecord' => $row['dputrecord'] ?? null,
  2305. 'cywyxm' => $row['cywyxm'] ?? null,
  2306. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2307. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2308. ], $row);
  2309. }
  2310. /**
  2311. * purchase_order 写入前规范化:NOT NULL 列勿显式传 null(会绕过 DEFAULT 触发 1048)
  2312. *
  2313. * @param array<string, mixed> $data
  2314. * @param array<string, mixed> $row 原始列表行(可用于补齐 czlyq)
  2315. * @return array<string, mixed>
  2316. */
  2317. protected function normalizePurchaseOrderWritePayload(array $data, array $row = []): array
  2318. {
  2319. $this->ensurePurchaseOrderCzlyqColumn();
  2320. $cz = '';
  2321. foreach (['czlyq', 'CZLYQ'] as $k) {
  2322. if (isset($data[$k]) && trim((string)$data[$k]) !== '') {
  2323. $cz = trim((string)$data[$k]);
  2324. break;
  2325. }
  2326. if (isset($row[$k]) && trim((string)$row[$k]) !== '') {
  2327. $cz = trim((string)$row[$k]);
  2328. break;
  2329. }
  2330. }
  2331. if ($cz === '') {
  2332. $ccydh = trim((string)($data['CCYDH'] ?? $row['CCYDH'] ?? ''));
  2333. if ($ccydh !== '') {
  2334. try {
  2335. $fromMcyd = Db::table('mcyd')->where('CCYDH', $ccydh)->value('czlyq');
  2336. $cz = trim((string)$fromMcyd);
  2337. } catch (\Throwable $e) {
  2338. $cz = '';
  2339. }
  2340. }
  2341. }
  2342. $data['czlyq'] = $cz;
  2343. // 显式 NULL 的字符串 NOT NULL 列改为空串
  2344. foreach (['czlyq', 'notify_salesman', 'manual_pick_reason', 'score_rule_name'] as $col) {
  2345. if (!array_key_exists($col, $data)) {
  2346. continue;
  2347. }
  2348. if ($data[$col] === null || !is_scalar($data[$col])) {
  2349. $data[$col] = '';
  2350. } else {
  2351. $data[$col] = (string)$data[$col];
  2352. }
  2353. }
  2354. foreach (['rfq_salesman_notified', 'manual_pick', 'score_rule_id', 'score_quality_weight', 'score_price_weight', 'score_lead_weight'] as $col) {
  2355. if (array_key_exists($col, $data) && $data[$col] === null) {
  2356. $data[$col] = 0;
  2357. }
  2358. }
  2359. return $data;
  2360. }
  2361. /**
  2362. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  2363. *
  2364. * @return array{po:?array<string,mixed>, hidden:bool}
  2365. */
  2366. protected function resolvePickRowPoContext(int $sid): array
  2367. {
  2368. $po = null;
  2369. try {
  2370. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2371. if (is_array($found)) {
  2372. $po = $found;
  2373. }
  2374. } catch (\Throwable $e) {
  2375. }
  2376. $hideSet = $this->loadPickHiddenScydgySet();
  2377. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  2378. }
  2379. /**
  2380. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  2381. */
  2382. protected function assertPickRowCanDelete(int $sid, array $row): void
  2383. {
  2384. $ctx = $this->resolvePickRowPoContext($sid);
  2385. $po = $ctx['po'];
  2386. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2387. return;
  2388. }
  2389. if (is_array($po)) {
  2390. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2391. throw new \InvalidArgumentException('该工序已完结,无法删除');
  2392. }
  2393. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2394. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  2395. }
  2396. }
  2397. if ($ctx['hidden']) {
  2398. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2399. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  2400. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  2401. }
  2402. }
  2403. /**
  2404. * 初选直接完结前校验
  2405. */
  2406. protected function assertPickRowCanComplete(int $sid, array $row): void
  2407. {
  2408. $ctx = $this->resolvePickRowPoContext($sid);
  2409. $po = $ctx['po'];
  2410. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2411. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  2412. }
  2413. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2414. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  2415. }
  2416. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  2417. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  2418. }
  2419. }
  2420. /**
  2421. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  2422. */
  2423. protected function softDeleteProcuremenPickRow(array $row): void
  2424. {
  2425. $sid = $this->extractScydgyRowId($row);
  2426. if (!$this->isValidScydgyRowId($sid)) {
  2427. throw new \InvalidArgumentException('无效的行主键');
  2428. }
  2429. $this->assertPickRowCanDelete($sid, $row);
  2430. $po = $this->resolvePickRowPoContext($sid)['po'];
  2431. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2432. return;
  2433. }
  2434. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2435. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  2436. }
  2437. $now = date('Y-m-d H:i:s');
  2438. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2439. if (is_array($exists)) {
  2440. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  2441. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  2442. } else {
  2443. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  2444. $data['mod_rq'] = $now;
  2445. $data['createtime'] = $now;
  2446. Db::table('purchase_order')->insert($data);
  2447. $poIdLog = (int)Db::getLastInsID();
  2448. }
  2449. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  2450. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  2451. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  2452. if ($gymcLog !== '') {
  2453. $logTail .= ' / ' . $gymcLog;
  2454. }
  2455. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  2456. }
  2457. /**
  2458. * 手工新增协助工序(写入 purchase_order)
  2459. *
  2460. * @param array<string, mixed> $params
  2461. * @return int scydgy_id
  2462. */
  2463. protected function saveManualPickOrder(array $params): int
  2464. {
  2465. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  2466. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  2467. $ccydhIn = trim((string)($params['CCYDH'] ?? ''));
  2468. $lockName = 'procuremen_manual_order_alloc';
  2469. if (!$this->acquireProcuremenNamedLock($lockName, 10)) {
  2470. throw new \RuntimeException('系统繁忙,请稍后重试');
  2471. }
  2472. try {
  2473. $ccydh = $ccydhIn !== '' ? $ccydhIn : $this->allocateManualOrderCcydh();
  2474. $now = date('Y-m-d H:i:s');
  2475. $sid = $this->allocateManualScydgyId();
  2476. $this->ensurePurchaseOrderNotifySalesmanColumn();
  2477. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  2478. // 选择供应商 / 通知业务员:支持多选,落库用顿号拼接
  2479. $supplierName = $this->joinRfqMultiSelectValues($params['cGzzxMc'] ?? ($params['pick_company_name'] ?? ''));
  2480. $notifySalesman = $this->joinRfqMultiSelectValues($params['notify_salesman'] ?? '');
  2481. $data = [
  2482. 'scydgy_id' => $sid,
  2483. 'CCYDH' => $ccydh,
  2484. 'CYJMC' => $cyjmc,
  2485. 'CGYMC' => $cgymc,
  2486. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  2487. 'CDW' => trim((string)($params['CDW'] ?? '')),
  2488. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  2489. 'CDF' => trim((string)($params['CDF'] ?? '')),
  2490. 'cGzzxMc' => $supplierName,
  2491. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  2492. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  2493. 'notify_salesman' => $notifySalesman,
  2494. 'rfq_salesman_notified' => 0,
  2495. 'rfq_salesman_notify_time' => null,
  2496. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  2497. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  2498. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  2499. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  2500. 'createtime' => $now,
  2501. 'dStamp' => $now,
  2502. 'dputrecord' => $now,
  2503. ];
  2504. Db::table('purchase_order')->insert($data);
  2505. $poId = (int)Db::getLastInsID();
  2506. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  2507. return $sid;
  2508. } finally {
  2509. $this->releaseProcuremenNamedLock($lockName);
  2510. }
  2511. }
  2512. protected function formatProcuremenRowLabel(array $row): string
  2513. {
  2514. $dh = trim((string)($row['CCYDH'] ?? ''));
  2515. $gymc = trim((string)($row['CGYMC'] ?? ''));
  2516. if ($dh !== '' && $gymc !== '') {
  2517. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  2518. }
  2519. if ($dh !== '') {
  2520. return '订单「' . $dh . '」';
  2521. }
  2522. if ($gymc !== '') {
  2523. return '工序「' . $gymc . '」';
  2524. }
  2525. $id = $this->extractScydgyRowId($row);
  2526. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  2527. }
  2528. /**
  2529. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  2530. */
  2531. protected function extractScydgyRowId(array $row): int
  2532. {
  2533. // 优先 scydgy_id,避免明细行 ID(自增主键)被误当成工序主键;手工单为负数
  2534. if (array_key_exists('scydgy_id', $row) && $row['scydgy_id'] !== null && $row['scydgy_id'] !== '') {
  2535. return (int)$row['scydgy_id'];
  2536. }
  2537. if (array_key_exists('SCYDGY_ID', $row) && $row['SCYDGY_ID'] !== null && $row['SCYDGY_ID'] !== '') {
  2538. return (int)$row['SCYDGY_ID'];
  2539. }
  2540. return (int)($row['ID'] ?? $row['id'] ?? 0);
  2541. }
  2542. protected function isValidScydgyRowId(int $id): bool
  2543. {
  2544. return ProcuremenGuard::isValidScydgyId($id);
  2545. }
  2546. protected function isManualScydgyRowId(int $id): bool
  2547. {
  2548. return $id < 0;
  2549. }
  2550. /**
  2551. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  2552. *
  2553. * @param int[] $scydgyIds
  2554. * @return array<int, string[]>
  2555. */
  2556. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  2557. {
  2558. $out = [];
  2559. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2560. if ($scydgyIds === []) {
  2561. return $out;
  2562. }
  2563. try {
  2564. $rows = Db::table('purchase_order_detail')
  2565. ->where('scydgy_id', 'in', $scydgyIds)
  2566. ->field('scydgy_id,company_name')
  2567. ->order('company_name', 'asc')
  2568. ->select();
  2569. } catch (\Throwable $e) {
  2570. $rows = [];
  2571. }
  2572. if (!is_array($rows)) {
  2573. return $out;
  2574. }
  2575. foreach ($rows as $r) {
  2576. if (!is_array($r)) {
  2577. continue;
  2578. }
  2579. $sid = (int)($r['scydgy_id'] ?? 0);
  2580. $cn = trim((string)($r['company_name'] ?? ''));
  2581. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2582. continue;
  2583. }
  2584. if (!isset($out[$sid])) {
  2585. $out[$sid] = [];
  2586. }
  2587. if (!in_array($cn, $out[$sid], true)) {
  2588. $out[$sid][] = $cn;
  2589. }
  2590. }
  2591. return $out;
  2592. }
  2593. /**
  2594. * 列表展示通知供应商(完整列表,前端单行省略展开)
  2595. *
  2596. * @param string[] $names
  2597. */
  2598. protected function formatNotifySupplierDisplay(array $names): string
  2599. {
  2600. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  2601. return trim((string)$n);
  2602. }, $names))));
  2603. if ($names === []) {
  2604. return '';
  2605. }
  2606. sort($names, SORT_STRING);
  2607. return implode("\n", $names);
  2608. }
  2609. /**
  2610. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  2611. *
  2612. * @param int[] $scydgyIds
  2613. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  2614. */
  2615. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  2616. {
  2617. $out = [];
  2618. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2619. if ($scydgyIds === []) {
  2620. return $out;
  2621. }
  2622. try {
  2623. $rows = Db::table('purchase_order_detail')
  2624. ->where('scydgy_id', 'in', $scydgyIds)
  2625. ->field('scydgy_id,company_name,amount')
  2626. ->select();
  2627. } catch (\Throwable $e) {
  2628. $rows = [];
  2629. }
  2630. if (!is_array($rows)) {
  2631. return $out;
  2632. }
  2633. foreach ($rows as $r) {
  2634. if (!is_array($r)) {
  2635. continue;
  2636. }
  2637. $sid = (int)($r['scydgy_id'] ?? 0);
  2638. $cn = trim((string)($r['company_name'] ?? ''));
  2639. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2640. continue;
  2641. }
  2642. if (!isset($out[$sid])) {
  2643. $out[$sid] = ['all' => [], 'quoted' => []];
  2644. }
  2645. $out[$sid]['all'][$cn] = true;
  2646. $am = trim((string)($r['amount'] ?? ''));
  2647. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2648. $out[$sid]['quoted'][$cn] = true;
  2649. }
  2650. }
  2651. return $out;
  2652. }
  2653. /**
  2654. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  2655. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  2656. */
  2657. protected function mergeQuotedSupplierBuckets(array $buckets): array
  2658. {
  2659. $merged = ['all' => [], 'quoted' => []];
  2660. foreach ($buckets as $b) {
  2661. if (!is_array($b)) {
  2662. continue;
  2663. }
  2664. foreach ($b['all'] ?? [] as $cn => $_) {
  2665. $merged['all'][$cn] = true;
  2666. }
  2667. foreach ($b['quoted'] ?? [] as $cn => $_) {
  2668. $merged['quoted'][$cn] = true;
  2669. }
  2670. }
  2671. return $merged;
  2672. }
  2673. /**
  2674. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  2675. */
  2676. protected function formatQuotedSupplierLines(array $bucket): string
  2677. {
  2678. $all = array_keys($bucket['all'] ?? []);
  2679. if ($all === []) {
  2680. return '';
  2681. }
  2682. sort($all, SORT_STRING);
  2683. $lines = [];
  2684. foreach ($all as $cn) {
  2685. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  2686. $lines[] = $cn . '(' . $status . ')';
  2687. }
  2688. return implode("\n", $lines);
  2689. }
  2690. /**
  2691. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  2692. */
  2693. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  2694. {
  2695. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2696. $this->view->engine->layout(false);
  2697. try {
  2698. $bodyHtml = $this->view->fetch($view);
  2699. $this->view->assign('dialogBody', $bodyHtml);
  2700. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  2701. return $this->view->fetch('procuremen/dialog_lite_shell');
  2702. } finally {
  2703. if ($restoreLayout) {
  2704. $this->view->engine->layout($restoreLayout);
  2705. }
  2706. }
  2707. }
  2708. /**
  2709. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  2710. */
  2711. protected function resolveBundleSysRq(array $bundle): string
  2712. {
  2713. foreach ($bundle['pos'] ?? [] as $po) {
  2714. if (!is_array($po)) {
  2715. continue;
  2716. }
  2717. $sr = trim((string)($po['sys_rq'] ?? ''));
  2718. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  2719. return $sr;
  2720. }
  2721. }
  2722. return '';
  2723. }
  2724. /**
  2725. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  2726. */
  2727. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  2728. {
  2729. $raw = trim((string)$sysRq);
  2730. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  2731. return true;
  2732. }
  2733. $ts = strtotime(str_replace('T', ' ', $raw));
  2734. if ($ts === false || $ts <= 0) {
  2735. return true;
  2736. }
  2737. return time() >= $ts;
  2738. }
  2739. /**
  2740. * 开标前校验:必须已过报价截止时间
  2741. *
  2742. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2743. */
  2744. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  2745. {
  2746. $sysRq = $this->resolveBundleSysRq($bundle);
  2747. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  2748. $this->error('未到招标截止日期');
  2749. }
  2750. }
  2751. /**
  2752. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  2753. *
  2754. * @param array<string, mixed> $d
  2755. * @param string $deliveryYmd
  2756. */
  2757. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  2758. {
  2759. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  2760. return max(0, (int)$d['lead_days']);
  2761. }
  2762. if ($deliveryYmd === '') {
  2763. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  2764. }
  2765. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  2766. return null;
  2767. }
  2768. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2769. $t2 = strtotime($m[1] . ' 00:00:00');
  2770. if ($t1 === false || $t2 === false) {
  2771. return null;
  2772. }
  2773. return max(0, (int)round(($t2 - $t1) / 86400));
  2774. }
  2775. /**
  2776. * @param int|null $days
  2777. */
  2778. protected function formatProcuremenLeadDaysText($days): string
  2779. {
  2780. if ($days === null || $days === '') {
  2781. return '未填写';
  2782. }
  2783. if (!is_numeric($days)) {
  2784. return '未填写';
  2785. }
  2786. return ((int)$days) . '天';
  2787. }
  2788. /**
  2789. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2790. *
  2791. * @param array<string, mixed> $line
  2792. */
  2793. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2794. {
  2795. $amountFilled = !empty($line['amount_filled']);
  2796. $deliveryFilled = !empty($line['delivery_filled']);
  2797. $leadFilled = !empty($line['lead_days_filled']);
  2798. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2799. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2800. $line['amount_show'] = '';
  2801. if (array_key_exists('amount_text', $line)) {
  2802. $line['amount_text'] = $line['unit_price_text'];
  2803. }
  2804. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2805. $line['delivery_show'] = $deliveryText;
  2806. if (array_key_exists('delivery_text', $line)) {
  2807. $line['delivery_text'] = $deliveryText;
  2808. }
  2809. $line['delivery_ymd'] = '';
  2810. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2811. $line['lead_days_show'] = $leadText;
  2812. $line['lead_days_text'] = $leadText;
  2813. $line['lead_days'] = '';
  2814. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2815. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2816. $line['subtotal_num'] = null;
  2817. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2818. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2819. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2820. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2821. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2822. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2823. $line['amount_filled'] = false;
  2824. $line['delivery_filled'] = false;
  2825. $line['lead_days_filled'] = false;
  2826. $line['is_quoted'] = false;
  2827. if (array_key_exists('quote_label', $line)) {
  2828. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2829. }
  2830. }
  2831. protected function ensurePurchaseOrderBidOpenTable(): void
  2832. {
  2833. static $ready = false;
  2834. if ($ready) {
  2835. return;
  2836. }
  2837. $cacheKey = 'procuremen_bid_open_table_ok_v1';
  2838. try {
  2839. if (Cache::get($cacheKey)) {
  2840. $ready = true;
  2841. return;
  2842. }
  2843. } catch (\Throwable $e) {
  2844. }
  2845. try {
  2846. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2847. $ready = true;
  2848. try {
  2849. Cache::set($cacheKey, 1, 86400);
  2850. } catch (\Throwable $e) {
  2851. }
  2852. } catch (\Throwable $e) {
  2853. Db::execute(
  2854. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2855. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2856. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2857. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2858. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2859. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2860. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2861. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2862. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2863. `createtime` datetime DEFAULT NULL,
  2864. PRIMARY KEY (`id`),
  2865. UNIQUE KEY `uk_ccydh` (`ccydh`)
  2866. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2867. );
  2868. $ready = true;
  2869. try {
  2870. Cache::set($cacheKey, 1, 86400);
  2871. } catch (\Throwable $e2) {
  2872. }
  2873. }
  2874. }
  2875. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  2876. {
  2877. $ccydh = trim($ccydh);
  2878. if ($ccydh === '') {
  2879. return false;
  2880. }
  2881. $this->ensurePurchaseOrderBidOpenTable();
  2882. try {
  2883. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2884. return is_array($row);
  2885. } catch (\Throwable $e) {
  2886. return false;
  2887. }
  2888. }
  2889. /**
  2890. * 批量查询订单是否已开标验证
  2891. *
  2892. * @param array<int, string> $ccydhs
  2893. * @return array<string, bool> ccydh => true
  2894. */
  2895. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  2896. {
  2897. $set = [];
  2898. $list = [];
  2899. foreach ($ccydhs as $c) {
  2900. $c = trim((string)$c);
  2901. if ($c !== '') {
  2902. $list[$c] = true;
  2903. }
  2904. }
  2905. if ($list === []) {
  2906. return $set;
  2907. }
  2908. $this->ensurePurchaseOrderBidOpenTable();
  2909. try {
  2910. $rows = Db::table('purchase_order_bid_open')
  2911. ->where('ccydh', 'in', array_keys($list))
  2912. ->field('ccydh')
  2913. ->select();
  2914. foreach ($rows as $row) {
  2915. if (!is_array($row)) {
  2916. continue;
  2917. }
  2918. $c = trim((string)($row['ccydh'] ?? ''));
  2919. if ($c !== '') {
  2920. $set[$c] = true;
  2921. }
  2922. }
  2923. } catch (\Throwable $e) {
  2924. return [];
  2925. }
  2926. return $set;
  2927. }
  2928. /**
  2929. * 批量查询订单是否已指定供应商(免开标)
  2930. *
  2931. * @param array<int, string> $ccydhs
  2932. * @return array<string, bool> ccydh => true
  2933. */
  2934. protected function loadProcuremenManualPickedCcydhSet(array $ccydhs): array
  2935. {
  2936. $set = [];
  2937. $list = [];
  2938. foreach ($ccydhs as $c) {
  2939. $c = trim((string)$c);
  2940. if ($c !== '') {
  2941. $list[$c] = true;
  2942. }
  2943. }
  2944. if ($list === []) {
  2945. return $set;
  2946. }
  2947. $this->ensurePurchaseOrderManualPickColumns();
  2948. try {
  2949. $rows = Db::table('purchase_order')
  2950. ->where('CCYDH', 'in', array_keys($list))
  2951. ->where('manual_pick', 1)
  2952. ->field('CCYDH')
  2953. ->select();
  2954. foreach ($rows as $row) {
  2955. if (!is_array($row)) {
  2956. continue;
  2957. }
  2958. $c = trim((string)($row['CCYDH'] ?? ''));
  2959. if ($c !== '') {
  2960. $set[$c] = true;
  2961. }
  2962. }
  2963. } catch (\Throwable $e) {
  2964. return [];
  2965. }
  2966. return $set;
  2967. }
  2968. /**
  2969. * 确认供应商列表:按开标状态筛选(已开标 / 已指定供应商 / 待开标)
  2970. *
  2971. * @param array<int, array<string, mixed>> $pool
  2972. * @return array<int, array<string, mixed>>
  2973. */
  2974. protected function filterProcuremenPoolByBidOpenStatus(array $pool, string $status): array
  2975. {
  2976. $status = trim($status);
  2977. if ($status === '' || !in_array($status, ['待开标', '已开标', '已指定供应商'], true)) {
  2978. return $pool;
  2979. }
  2980. $ccydhList = [];
  2981. foreach ($pool as $rw) {
  2982. if (!is_array($rw)) {
  2983. continue;
  2984. }
  2985. $c = trim((string)($rw['CCYDH'] ?? ''));
  2986. if ($c !== '') {
  2987. $ccydhList[] = $c;
  2988. }
  2989. }
  2990. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  2991. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  2992. $out = [];
  2993. foreach ($pool as $rw) {
  2994. if (!is_array($rw)) {
  2995. continue;
  2996. }
  2997. $c = trim((string)($rw['CCYDH'] ?? ''));
  2998. if ($c !== '' && isset($bidOpenSet[$c])) {
  2999. $t = '已开标';
  3000. } elseif ($c !== '' && isset($manualPickSet[$c])) {
  3001. $t = '已指定供应商';
  3002. } else {
  3003. $t = '待开标';
  3004. }
  3005. if ($t === $status) {
  3006. $out[] = $rw;
  3007. }
  3008. }
  3009. return $out;
  3010. }
  3011. /**
  3012. * 按订单状态筛选(待确认 / 待审核 / 已审核)
  3013. *
  3014. * @param array<int, array<string, mixed>> $pool
  3015. * @return array<int, array<string, mixed>>
  3016. */
  3017. protected function filterProcuremenPoolByOrderStatus(array $pool, string $status): array
  3018. {
  3019. $status = trim($status);
  3020. if ($status === '' || !in_array($status, ['待确认', '待审核', '已审核'], true)) {
  3021. return $pool;
  3022. }
  3023. $out = [];
  3024. foreach ($pool as $rw) {
  3025. if (!is_array($rw)) {
  3026. continue;
  3027. }
  3028. $label = trim((string)($rw['order_status_text'] ?? ''));
  3029. if ($label === '') {
  3030. $label = ProcuremenStatus::orderStatusLabelForList($rw['wflow_status'] ?? '');
  3031. }
  3032. if ($label === $status) {
  3033. $out[] = $rw;
  3034. }
  3035. }
  3036. return $out;
  3037. }
  3038. /**
  3039. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  3040. *
  3041. * @param array<string, mixed> $group
  3042. */
  3043. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  3044. {
  3045. if ($quoteVisible) {
  3046. $group['remark_quote_pending'] = 0;
  3047. return;
  3048. }
  3049. $group['remark'] = '';
  3050. $group['remark_quote_pending'] = 0;
  3051. }
  3052. /**
  3053. * 下发订单备注 MBZ(印件规格),不是供应商填写
  3054. *
  3055. * @param array{pos?:array, merge_rows?:array} $bundle
  3056. */
  3057. protected function resolveBundleOrderMbz(array $bundle): string
  3058. {
  3059. foreach (['pos', 'merge_rows'] as $key) {
  3060. foreach ($bundle[$key] ?? [] as $row) {
  3061. if (!is_array($row)) {
  3062. continue;
  3063. }
  3064. $mbz = trim((string)($row['MBZ'] ?? $row['mbz'] ?? ''));
  3065. if ($mbz !== '') {
  3066. return $mbz;
  3067. }
  3068. }
  3069. }
  3070. return '';
  3071. }
  3072. /**
  3073. * 供应商自己填的备注;与订单 MBZ 相同视为未填(历史误把规格写入明细)
  3074. */
  3075. protected function resolveSupplierOwnRemark($detailRemark, $orderMbz = ''): string
  3076. {
  3077. $own = trim((string)$detailRemark);
  3078. $mbz = trim((string)$orderMbz);
  3079. if ($own === '' || ($mbz !== '' && $own === $mbz)) {
  3080. return '';
  3081. }
  3082. return $own;
  3083. }
  3084. /**
  3085. * 供应商备注展示:仅自己填写的;有工序行时始终占一行「投标备注」(空也显示标签)
  3086. *
  3087. * @param array<string, mixed> $group
  3088. */
  3089. protected function finalizeSupplierRemarkDisplay(array &$group, string $orderMbz, bool $quoteVisible): void
  3090. {
  3091. $group['remark'] = $this->resolveSupplierOwnRemark($group['remark'] ?? '', $orderMbz);
  3092. $this->maskSupplierRemarkBeforeBidOpen($group, $quoteVisible);
  3093. $lineCount = (int)($group['line_count'] ?? 0);
  3094. if ($lineCount <= 0) {
  3095. $lines = $group['lines'] ?? $group['pick_lines'] ?? [];
  3096. $lineCount = is_array($lines) ? count($lines) : 0;
  3097. }
  3098. // 与手机端一致:有供应商工序行就显示投标备注行,内容可为空
  3099. $group['has_remark'] = $lineCount > 0;
  3100. $extra = (!empty($group['has_remark']) ? 1 : 0) + (!empty($group['has_total']) ? 1 : 0);
  3101. $group['display_rowspan'] = $lineCount > 0 ? ($lineCount + $extra) : 0;
  3102. }
  3103. /**
  3104. * @param array{ccydh?:string,pos?:array} $bundle
  3105. */
  3106. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  3107. {
  3108. $list = [];
  3109. foreach ($bundle['pos'] ?? [] as $po) {
  3110. if (!is_array($po)) {
  3111. continue;
  3112. }
  3113. $dh = trim((string)($po['CCYDH'] ?? ''));
  3114. if ($dh !== '') {
  3115. $list[$dh] = true;
  3116. }
  3117. }
  3118. $primary = trim((string)($bundle['ccydh'] ?? ''));
  3119. if ($primary !== '') {
  3120. $list[$primary] = true;
  3121. }
  3122. if ($list === []) {
  3123. return false;
  3124. }
  3125. foreach (array_keys($list) as $ccydh) {
  3126. if (!$this->isProcuremenBidOpenVerified($ccydh)) {
  3127. return false;
  3128. }
  3129. }
  3130. return true;
  3131. }
  3132. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  3133. {
  3134. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  3135. return true;
  3136. }
  3137. return $this->isProcuremenManualPickedForBundle($bundle);
  3138. }
  3139. /**
  3140. * 确保 purchase_order 自选供应商字段
  3141. */
  3142. protected function ensurePurchaseOrderManualPickColumns(): void
  3143. {
  3144. static $done = false;
  3145. if ($done) {
  3146. return;
  3147. }
  3148. $done = true;
  3149. $adds = [
  3150. 'manual_pick' => "ADD COLUMN `manual_pick` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=自选供应商(免开标)' AFTER `pick_company_name`",
  3151. 'manual_pick_reason' => "ADD COLUMN `manual_pick_reason` varchar(500) NOT NULL DEFAULT '' COMMENT '自选供应商选择说明' AFTER `manual_pick`",
  3152. ];
  3153. foreach ($adds as $col => $ddl) {
  3154. try {
  3155. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  3156. if (!is_array($cols) || $cols === []) {
  3157. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  3158. }
  3159. } catch (\Throwable $e) {
  3160. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  3161. }
  3162. }
  3163. }
  3164. /**
  3165. * 是否已自选供应商(免开标查看报价)
  3166. *
  3167. * @param array{pos?:array} $bundle
  3168. */
  3169. protected function isProcuremenManualPickedForBundle(array $bundle): bool
  3170. {
  3171. $this->ensurePurchaseOrderManualPickColumns();
  3172. foreach ($bundle['pos'] ?? [] as $poRow) {
  3173. if (!is_array($poRow)) {
  3174. continue;
  3175. }
  3176. if ((int)($poRow['manual_pick'] ?? 0) === 1) {
  3177. return true;
  3178. }
  3179. }
  3180. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3181. if ($ccydh === '') {
  3182. return false;
  3183. }
  3184. try {
  3185. $v = Db::table('purchase_order')->where('CCYDH', $ccydh)->where('manual_pick', 1)->value('id');
  3186. return $v !== null && $v !== false && (int)$v > 0;
  3187. } catch (\Throwable $e) {
  3188. return false;
  3189. }
  3190. }
  3191. /**
  3192. * @param array{pos?:array} $bundle
  3193. * @return array{company:string,reason:string}
  3194. */
  3195. protected function resolveProcuremenManualPickInfo(array $bundle): array
  3196. {
  3197. $this->ensurePurchaseOrderManualPickColumns();
  3198. foreach ($bundle['pos'] ?? [] as $poRow) {
  3199. if (!is_array($poRow)) {
  3200. continue;
  3201. }
  3202. if ((int)($poRow['manual_pick'] ?? 0) !== 1) {
  3203. continue;
  3204. }
  3205. $cn = trim((string)($poRow['pick_company_name'] ?? ''));
  3206. $reason = trim((string)($poRow['manual_pick_reason'] ?? ''));
  3207. return ['company' => $cn, 'reason' => $reason];
  3208. }
  3209. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3210. if ($ccydh === '') {
  3211. return ['company' => '', 'reason' => ''];
  3212. }
  3213. try {
  3214. $row = Db::table('purchase_order')
  3215. ->where('CCYDH', $ccydh)
  3216. ->where('manual_pick', 1)
  3217. ->field('pick_company_name,manual_pick_reason')
  3218. ->order('id', 'asc')
  3219. ->find();
  3220. } catch (\Throwable $e) {
  3221. $row = null;
  3222. }
  3223. if (!is_array($row)) {
  3224. return ['company' => '', 'reason' => ''];
  3225. }
  3226. return [
  3227. 'company' => trim((string)($row['pick_company_name'] ?? '')),
  3228. 'reason' => trim((string)($row['manual_pick_reason'] ?? '')),
  3229. ];
  3230. }
  3231. protected function loadBidOpenAdminUser(int $adminId): ?array
  3232. {
  3233. if ($adminId <= 0) {
  3234. return null;
  3235. }
  3236. try {
  3237. $row = Db::name('admin')->where('id', $adminId)->find();
  3238. } catch (\Throwable $e) {
  3239. return null;
  3240. }
  3241. if (!is_array($row)) {
  3242. return null;
  3243. }
  3244. $status = strtolower(trim((string)($row['status'] ?? '')));
  3245. if ($status !== '' && $status !== 'normal') {
  3246. return null;
  3247. }
  3248. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  3249. return null;
  3250. }
  3251. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  3252. if (!preg_match('/^1\d{10}$/', $phone)) {
  3253. return null;
  3254. }
  3255. $name = trim((string)($row['nickname'] ?? ''));
  3256. if ($name === '') {
  3257. $name = trim((string)($row['username'] ?? ''));
  3258. }
  3259. return [
  3260. 'id' => (int)$row['id'],
  3261. 'username' => trim((string)($row['username'] ?? '')),
  3262. 'nickname' => $name,
  3263. 'mobile' => $phone,
  3264. ];
  3265. }
  3266. /**
  3267. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  3268. */
  3269. protected function bidOpenVerifierAuthGroupRootId(): int
  3270. {
  3271. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  3272. return $id > 0 ? $id : 10;
  3273. }
  3274. /**
  3275. * @return int[]
  3276. */
  3277. protected function loadBidOpenVerifierAuthGroupIds(): array
  3278. {
  3279. static $memo = [];
  3280. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  3281. if (isset($memo[$rootId])) {
  3282. return $memo[$rootId];
  3283. }
  3284. try {
  3285. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  3286. } catch (\Throwable $e) {
  3287. $memo[$rootId] = [$rootId];
  3288. return $memo[$rootId];
  3289. }
  3290. if (!is_array($groups) || $groups === []) {
  3291. $memo[$rootId] = [$rootId];
  3292. return $memo[$rootId];
  3293. }
  3294. $groupList = [];
  3295. foreach ($groups as $g) {
  3296. if (is_array($g)) {
  3297. $groupList[] = $g;
  3298. }
  3299. }
  3300. if ($groupList === []) {
  3301. $memo[$rootId] = [$rootId];
  3302. return $memo[$rootId];
  3303. }
  3304. $tree = \fast\Tree::instance();
  3305. $tree->init($groupList);
  3306. $ids = $tree->getChildrenIds($rootId, true);
  3307. if (!is_array($ids) || $ids === []) {
  3308. $memo[$rootId] = [$rootId];
  3309. return $memo[$rootId];
  3310. }
  3311. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  3312. return $memo[$rootId];
  3313. }
  3314. protected function isBidOpenVerifierAdmin(int $adminId): bool
  3315. {
  3316. if ($adminId <= 0) {
  3317. return false;
  3318. }
  3319. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3320. if ($groupIds === []) {
  3321. return false;
  3322. }
  3323. try {
  3324. return (bool)Db::name('auth_group_access')
  3325. ->where('uid', $adminId)
  3326. ->where('group_id', 'in', $groupIds)
  3327. ->count();
  3328. } catch (\Throwable $e) {
  3329. return false;
  3330. }
  3331. }
  3332. /**
  3333. * @return array<int, array<string, mixed>>
  3334. */
  3335. protected function listBidOpenVerifierCandidates(): array
  3336. {
  3337. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3338. if ($groupIds === []) {
  3339. return [];
  3340. }
  3341. try {
  3342. $adminIds = Db::name('auth_group_access')
  3343. ->where('group_id', 'in', $groupIds)
  3344. ->column('uid');
  3345. } catch (\Throwable $e) {
  3346. $adminIds = [];
  3347. }
  3348. $adminIds = is_array($adminIds)
  3349. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  3350. : [];
  3351. if ($adminIds === []) {
  3352. return [];
  3353. }
  3354. try {
  3355. $rows = Db::name('admin')
  3356. ->where('status', 'normal')
  3357. ->where('id', 'in', $adminIds)
  3358. ->where('mobile', '<>', '')
  3359. ->order('id', 'asc')
  3360. ->select();
  3361. } catch (\Throwable $e) {
  3362. return [];
  3363. }
  3364. if (!is_array($rows)) {
  3365. return [];
  3366. }
  3367. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  3368. $out = [];
  3369. foreach ($rows as $row) {
  3370. if (!is_array($row)) {
  3371. continue;
  3372. }
  3373. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  3374. if ($one === null) {
  3375. continue;
  3376. }
  3377. $out[] = [
  3378. 'id' => $one['id'],
  3379. 'username' => $one['username'],
  3380. 'nickname' => $one['nickname'],
  3381. 'group_name' => $groupNameMap[$one['id']] ?? '',
  3382. 'mobile' => mask_phone($one['mobile']),
  3383. 'mobile_plain' => (string)$one['mobile'],
  3384. ];
  3385. }
  3386. return $out;
  3387. }
  3388. /**
  3389. * @param int[] $adminIds
  3390. * @return array<int, string>
  3391. */
  3392. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  3393. {
  3394. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  3395. if ($adminIds === []) {
  3396. return [];
  3397. }
  3398. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3399. try {
  3400. $rows = Db::name('auth_group_access')
  3401. ->alias('aga')
  3402. ->join('auth_group ag', 'aga.group_id = ag.id')
  3403. ->where('aga.uid', 'in', $adminIds)
  3404. ->where('aga.group_id', 'in', $groupIds)
  3405. ->field('aga.uid,ag.name')
  3406. ->order('aga.uid', 'asc')
  3407. ->order('aga.group_id', 'asc')
  3408. ->select();
  3409. } catch (\Throwable $e) {
  3410. return [];
  3411. }
  3412. if (!is_array($rows)) {
  3413. return [];
  3414. }
  3415. $out = [];
  3416. foreach ($rows as $row) {
  3417. if (!is_array($row)) {
  3418. continue;
  3419. }
  3420. $uid = (int)($row['uid'] ?? 0);
  3421. $name = trim((string)($row['name'] ?? ''));
  3422. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  3423. continue;
  3424. }
  3425. $out[$uid] = $name;
  3426. }
  3427. return $out;
  3428. }
  3429. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  3430. {
  3431. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  3432. }
  3433. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  3434. {
  3435. return 'procuremen_bidopen_wait_' . $adminId;
  3436. }
  3437. protected function renderBidOpenVerifySms(string $code): string
  3438. {
  3439. $tpl = '';
  3440. try {
  3441. $row = $this->loadNotifyTemplateRow('bid_open');
  3442. if (is_array($row)) {
  3443. $tpl = trim((string)($row['content'] ?? ''));
  3444. }
  3445. } catch (\Throwable $e) {
  3446. $tpl = '';
  3447. }
  3448. if ($tpl === '') {
  3449. $tpl = '【可集达】您的短信验证码是{code}';
  3450. }
  3451. return str_replace('{code}', $code, $tpl);
  3452. }
  3453. protected function sendBidOpenVerifySms(string $phone, string $code): void
  3454. {
  3455. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  3456. }
  3457. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  3458. {
  3459. $code = trim($code);
  3460. if (!preg_match('/^\d{6}$/', $code)) {
  3461. return false;
  3462. }
  3463. $mock = Config::get('mproc.mock_sms_code');
  3464. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3465. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3466. return true;
  3467. }
  3468. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3469. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3470. return false;
  3471. }
  3472. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3473. return true;
  3474. }
  3475. /**
  3476. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3477. */
  3478. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  3479. {
  3480. $ccydhList = [];
  3481. foreach ($bundle['pos'] ?? [] as $poRow) {
  3482. if (!is_array($poRow)) {
  3483. continue;
  3484. }
  3485. $dh = trim((string)($poRow['CCYDH'] ?? ''));
  3486. if ($dh !== '') {
  3487. $ccydhList[$dh] = true;
  3488. }
  3489. }
  3490. $primaryCcydh = trim((string)($bundle['ccydh'] ?? ''));
  3491. if ($primaryCcydh !== '') {
  3492. $ccydhList[$primaryCcydh] = true;
  3493. }
  3494. if ($ccydhList === []) {
  3495. throw new \InvalidArgumentException('订单号无效');
  3496. }
  3497. $this->ensurePurchaseOrderBidOpenTable();
  3498. list($operatorId, $operatorName) = $this->GetUseName();
  3499. $now = date('Y-m-d H:i:s');
  3500. $payloadBase = [
  3501. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  3502. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  3503. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  3504. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  3505. 'operator_id' => (int)$operatorId,
  3506. 'operator_name' => trim((string)$operatorName),
  3507. 'createtime' => $now,
  3508. ];
  3509. foreach (array_keys($ccydhList) as $ccydh) {
  3510. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3511. $payload = $payloadBase;
  3512. $payload['ccydh'] = $ccydh;
  3513. if (is_array($exists)) {
  3514. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  3515. } else {
  3516. Db::table('purchase_order_bid_open')->insert($payload);
  3517. }
  3518. }
  3519. $name1 = $payloadBase['verifier1_name'] !== '' ? $payloadBase['verifier1_name'] : ('ID' . $payloadBase['verifier1_id']);
  3520. $name2 = $payloadBase['verifier2_name'] !== '' ? $payloadBase['verifier2_name'] : ('ID' . $payloadBase['verifier2_id']);
  3521. $labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
  3522. (int)$payloadBase['verifier1_id'],
  3523. (int)$payloadBase['verifier2_id'],
  3524. ]);
  3525. if (isset($labelMap[(int)$payloadBase['verifier1_id']]) && (int)$payloadBase['verifier1_id'] > 0) {
  3526. $name1 = $labelMap[(int)$payloadBase['verifier1_id']];
  3527. }
  3528. if (isset($labelMap[(int)$payloadBase['verifier2_id']]) && (int)$payloadBase['verifier2_id'] > 0) {
  3529. $name2 = $labelMap[(int)$payloadBase['verifier2_id']];
  3530. }
  3531. $logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
  3532. $seenSid = [];
  3533. foreach ($bundle['pos'] ?? [] as $poRow) {
  3534. if (!is_array($poRow)) {
  3535. continue;
  3536. }
  3537. $sid = (int)($poRow['scydgy_id'] ?? 0);
  3538. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  3539. continue;
  3540. }
  3541. $seenSid[$sid] = true;
  3542. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  3543. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  3544. }
  3545. if ($seenSid === []) {
  3546. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  3547. if ($this->isValidScydgyRowId($anchor)) {
  3548. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  3549. }
  3550. }
  3551. // 开标通过后:按订单号分别计算并写入供应商服务评分(避免多订单串分)
  3552. try {
  3553. $ym = date('Y-m', strtotime($now) ?: time());
  3554. $this->saveProcuremenSupplierScoresForBundle($bundle, $ym);
  3555. } catch (\Throwable $e) {
  3556. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  3557. }
  3558. }
  3559. /**
  3560. * 按 bundle 内各订单分别计分落库(价格分不跨订单混算)
  3561. *
  3562. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3563. */
  3564. protected function saveProcuremenSupplierScoresForBundle(array $bundle, ?string $ym = null): void
  3565. {
  3566. $posByCcydh = [];
  3567. foreach ($bundle['pos'] ?? [] as $po) {
  3568. if (!is_array($po)) {
  3569. continue;
  3570. }
  3571. $dh = trim((string)($po['CCYDH'] ?? ''));
  3572. if ($dh === '') {
  3573. continue;
  3574. }
  3575. if (!isset($posByCcydh[$dh])) {
  3576. $posByCcydh[$dh] = [];
  3577. }
  3578. $posByCcydh[$dh][] = $po;
  3579. }
  3580. if ($posByCcydh === []) {
  3581. $fallback = trim((string)($bundle['ccydh'] ?? ''));
  3582. if ($fallback === '') {
  3583. return;
  3584. }
  3585. $groups = $this->loadAuditSupplierQuoteGroups($bundle);
  3586. ProcuremenSupplierScore::saveForOrder($fallback, $groups, $ym);
  3587. return;
  3588. }
  3589. $mergeAll = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  3590. foreach ($posByCcydh as $ccydh => $posList) {
  3591. $sidSet = [];
  3592. foreach ($posList as $po) {
  3593. $sid = (int)($po['scydgy_id'] ?? 0);
  3594. if ($this->isValidScydgyRowId($sid)) {
  3595. $sidSet[$sid] = true;
  3596. }
  3597. }
  3598. $mergeRows = [];
  3599. foreach ($mergeAll as $mr) {
  3600. if (!is_array($mr)) {
  3601. continue;
  3602. }
  3603. $gid = $this->extractScydgyRowId($mr);
  3604. if ($this->isValidScydgyRowId($gid) && isset($sidSet[$gid])) {
  3605. $mergeRows[] = $mr;
  3606. }
  3607. }
  3608. $subBundle = [
  3609. 'ccydh' => $ccydh,
  3610. 'pos' => $posList,
  3611. 'merge_rows' => $mergeRows !== [] ? $mergeRows : $this->scydgyRowsForPurchaseOrders($posList),
  3612. ];
  3613. $groups = $this->loadAuditSupplierQuoteGroups($subBundle);
  3614. ProcuremenSupplierScore::saveForOrder($ccydh, $groups, $ym);
  3615. }
  3616. }
  3617. /**
  3618. * 报价行展示字段默认值(模板安全访问)
  3619. *
  3620. * @param array<string, mixed> $line
  3621. * @return array<string, mixed>
  3622. */
  3623. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  3624. {
  3625. if (!array_key_exists('amount_quote_pending', $line)) {
  3626. $line['amount_quote_pending'] = 0;
  3627. }
  3628. if (!array_key_exists('delivery_quote_pending', $line)) {
  3629. $line['delivery_quote_pending'] = 0;
  3630. }
  3631. if (!array_key_exists('quote_before_deadline', $line)) {
  3632. $line['quote_before_deadline'] = 0;
  3633. }
  3634. if (!array_key_exists('amount_filled', $line)) {
  3635. $line['amount_filled'] = 0;
  3636. }
  3637. if (!array_key_exists('delivery_filled', $line)) {
  3638. $line['delivery_filled'] = 0;
  3639. }
  3640. if (!array_key_exists('lead_days_filled', $line)) {
  3641. $line['lead_days_filled'] = 0;
  3642. }
  3643. if (!array_key_exists('lead_days_quote_pending', $line)) {
  3644. $line['lead_days_quote_pending'] = 0;
  3645. }
  3646. if (!array_key_exists('lead_days_show', $line)) {
  3647. $line['lead_days_show'] = '未填写';
  3648. }
  3649. if (!array_key_exists('lead_days_text', $line)) {
  3650. $line['lead_days_text'] = $line['lead_days_show'];
  3651. }
  3652. if (!array_key_exists('ccydh', $line)) {
  3653. $line['ccydh'] = '';
  3654. }
  3655. if (!array_key_exists('cgymc', $line)) {
  3656. $line['cgymc'] = '';
  3657. }
  3658. // 工序列展示文案:上行订单号、下行工序(无括号;兼容旧模板)
  3659. if (!array_key_exists('cgymc_display', $line) || trim((string)$line['cgymc_display']) === '') {
  3660. $dh = trim((string)$line['ccydh']);
  3661. $gy = trim((string)$line['cgymc']);
  3662. $line['cgymc_display'] = $dh !== '' ? ($dh . "\n" . $gy) : $gy;
  3663. }
  3664. return $line;
  3665. }
  3666. /**
  3667. * 供应商报价表「工序名称」列:订单号 + 工序名(不加 [])
  3668. *
  3669. * @return array{ccydh:string,cgymc:string,cgymc_display:string}
  3670. */
  3671. protected function buildSupplierProcessNameFields(string $ccydh, string $cgymc): array
  3672. {
  3673. $ccydh = trim($ccydh);
  3674. $cgymc = trim($cgymc);
  3675. if ($cgymc === '') {
  3676. $cgymc = '工序';
  3677. }
  3678. return [
  3679. 'ccydh' => $ccydh,
  3680. 'cgymc' => $cgymc,
  3681. 'cgymc_display' => $ccydh !== '' ? ($ccydh . "\n" . $cgymc) : $cgymc,
  3682. ];
  3683. }
  3684. /**
  3685. * 审核弹窗:按供应商汇总报价明细
  3686. *
  3687. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3688. * @return array<int, array<string, mixed>>
  3689. */
  3690. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  3691. {
  3692. $sids = [];
  3693. foreach ($bundle['pos'] ?? [] as $po) {
  3694. if (!is_array($po)) {
  3695. continue;
  3696. }
  3697. $sid = (int)($po['scydgy_id'] ?? 0);
  3698. if ($this->isValidScydgyRowId($sid)) {
  3699. $sids[$sid] = true;
  3700. }
  3701. }
  3702. if ($sids === []) {
  3703. return [];
  3704. }
  3705. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3706. $orderMbz = $this->resolveBundleOrderMbz($bundle);
  3707. $gymcMap = [];
  3708. $ccydhBySid = [];
  3709. $qtyBySid = [];
  3710. $orderedSids = [];
  3711. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3712. if (!is_array($mr)) {
  3713. continue;
  3714. }
  3715. $gid = $this->extractScydgyRowId($mr);
  3716. if ($this->isValidScydgyRowId($gid)) {
  3717. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3718. $dh = trim((string)($mr['CCYDH'] ?? ''));
  3719. if ($dh !== '') {
  3720. $ccydhBySid[$gid] = $dh;
  3721. }
  3722. $orderedSids[] = $gid;
  3723. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3724. if ($qty === '') {
  3725. $qty = trim((string)($mr['NGZL'] ?? ''));
  3726. }
  3727. $qtyBySid[$gid] = $qty;
  3728. }
  3729. }
  3730. foreach ($bundle['pos'] ?? [] as $po) {
  3731. if (!is_array($po)) {
  3732. continue;
  3733. }
  3734. $gid = (int)($po['scydgy_id'] ?? 0);
  3735. if ($this->isValidScydgyRowId($gid)) {
  3736. $nm = trim((string)($po['CGYMC'] ?? ''));
  3737. if ($nm !== '') {
  3738. $gymcMap[$gid] = $nm;
  3739. }
  3740. $dh = trim((string)($po['CCYDH'] ?? ''));
  3741. if ($dh !== '' && empty($ccydhBySid[$gid])) {
  3742. $ccydhBySid[$gid] = $dh;
  3743. }
  3744. if (!in_array($gid, $orderedSids, true)) {
  3745. $orderedSids[] = $gid;
  3746. }
  3747. }
  3748. }
  3749. try {
  3750. $detailsQuery = Db::table('purchase_order_detail')
  3751. ->where('scydgy_id', 'in', array_keys($sids));
  3752. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3753. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  3754. } catch (\Throwable $e) {
  3755. try {
  3756. $detailsQuery = Db::table('purchase_order_detail')
  3757. ->where('scydgy_id', 'in', array_keys($sids));
  3758. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3759. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  3760. } catch (\Throwable $e2) {
  3761. $details = [];
  3762. }
  3763. }
  3764. if (!is_array($details)) {
  3765. $details = [];
  3766. }
  3767. $byCompany = [];
  3768. foreach ($details as $d) {
  3769. if (!is_array($d)) {
  3770. continue;
  3771. }
  3772. $cn = trim((string)($d['company_name'] ?? ''));
  3773. if ($cn === '') {
  3774. continue;
  3775. }
  3776. if (!isset($byCompany[$cn])) {
  3777. $ph = trim((string)($d['phone'] ?? ''));
  3778. $username = trim((string)($d['username'] ?? ''));
  3779. if ($username === '') {
  3780. $username = $this->resolveCustomerContactName($ph, $cn);
  3781. }
  3782. $byCompany[$cn] = [
  3783. 'name' => $cn,
  3784. 'email' => trim((string)($d['email'] ?? '')),
  3785. 'phone' => $ph,
  3786. 'username' => $username,
  3787. 'remark' => '',
  3788. 'has_quote' => false,
  3789. 'lines_map' => [],
  3790. ];
  3791. }
  3792. if ($byCompany[$cn]['remark'] === '') {
  3793. $rm = '';
  3794. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3795. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3796. $rm = trim((string)$d[$rk]);
  3797. break;
  3798. }
  3799. }
  3800. if ($rm !== '') {
  3801. $byCompany[$cn]['remark'] = $rm;
  3802. }
  3803. }
  3804. $sid = (int)($d['scydgy_id'] ?? 0);
  3805. $am = trim((string)($d['amount'] ?? ''));
  3806. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3807. $ccydhLine = trim((string)($ccydhBySid[$sid] ?? ''));
  3808. $processName = $this->buildSupplierProcessNameFields($ccydhLine, $gymc);
  3809. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3810. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3811. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3812. $deliveryShow = $deliveryRaw;
  3813. }
  3814. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3815. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3816. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3817. $subtotal = null;
  3818. if ($amountNum !== null) {
  3819. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3820. }
  3821. $unitPriceText = $amountFilled
  3822. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3823. : '未填写';
  3824. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3825. $leadFilled = ($leadDays !== null);
  3826. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3827. $lineRow = array_merge($processName, [
  3828. 'amount' => $am,
  3829. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  3830. 'amount_filled' => $amountFilled,
  3831. 'unit_price_text' => $unitPriceText,
  3832. 'delivery' => $deliveryRaw,
  3833. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  3834. 'delivery_filled' => $deliveryFilled,
  3835. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  3836. 'lead_days' => $leadFilled ? $leadDays : '',
  3837. 'lead_days_filled'=> $leadFilled,
  3838. 'lead_days_show' => $leadText,
  3839. 'lead_days_text' => $leadText,
  3840. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3841. 'subtotal_num' => $subtotal,
  3842. 'status_name' => trim((string)($d['status_name'] ?? '')),
  3843. 'is_quoted' => $amountFilled,
  3844. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  3845. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3846. ]);
  3847. if (!$quoteVisible) {
  3848. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  3849. }
  3850. // 按工序 id 暂存,下面再按上方工序表顺序输出
  3851. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  3852. }
  3853. foreach ($byCompany as $cn => $g) {
  3854. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  3855. $lines = [];
  3856. $usedSids = [];
  3857. foreach ($orderedSids as $sid) {
  3858. if (!isset($linesMap[$sid])) {
  3859. continue;
  3860. }
  3861. $lines[] = $linesMap[$sid];
  3862. $usedSids[$sid] = true;
  3863. }
  3864. foreach ($linesMap as $sid => $ln) {
  3865. if (isset($usedSids[$sid])) {
  3866. continue;
  3867. }
  3868. $lines[] = $ln;
  3869. }
  3870. $total = count($lines);
  3871. $quoted = 0;
  3872. $groupTotal = 0.0;
  3873. $groupHasTotal = false;
  3874. if ($quoteVisible) {
  3875. foreach ($lines as $ln) {
  3876. $am = trim((string)($ln['amount'] ?? ''));
  3877. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  3878. $quoted++;
  3879. }
  3880. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3881. $groupTotal += (float)$ln['subtotal_num'];
  3882. $groupHasTotal = true;
  3883. }
  3884. }
  3885. }
  3886. unset($byCompany[$cn]['lines_map']);
  3887. $byCompany[$cn]['lines'] = $lines;
  3888. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  3889. $byCompany[$cn]['line_count'] = $total;
  3890. $byCompany[$cn]['has_total'] = $total > 0;
  3891. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3892. $this->finalizeSupplierRemarkDisplay($byCompany[$cn], $orderMbz, $quoteVisible);
  3893. }
  3894. $groups = array_values($byCompany);
  3895. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3896. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  3897. }
  3898. /**
  3899. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  3900. *
  3901. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3902. * @return array<int, array<string, mixed>>
  3903. */
  3904. protected function loadConfirmSupplierPickGroups(array $bundle): array
  3905. {
  3906. $sids = [];
  3907. $poIdMap = [];
  3908. foreach ($bundle['pos'] ?? [] as $po) {
  3909. if (!is_array($po)) {
  3910. continue;
  3911. }
  3912. $sid = (int)($po['scydgy_id'] ?? 0);
  3913. if ($this->isValidScydgyRowId($sid)) {
  3914. $sids[$sid] = true;
  3915. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  3916. }
  3917. }
  3918. if ($sids === []) {
  3919. return [];
  3920. }
  3921. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3922. $orderMbz = $this->resolveBundleOrderMbz($bundle);
  3923. $gymcMap = [];
  3924. $ccydhBySid = [];
  3925. $qtyBySid = [];
  3926. $orderedSids = [];
  3927. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3928. if (!is_array($mr)) {
  3929. continue;
  3930. }
  3931. $gid = $this->extractScydgyRowId($mr);
  3932. if ($this->isValidScydgyRowId($gid)) {
  3933. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3934. $dh = trim((string)($mr['CCYDH'] ?? ''));
  3935. if ($dh !== '') {
  3936. $ccydhBySid[$gid] = $dh;
  3937. }
  3938. $orderedSids[] = $gid;
  3939. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3940. if ($qty === '') {
  3941. $qty = trim((string)($mr['NGZL'] ?? ''));
  3942. }
  3943. $qtyBySid[$gid] = $qty;
  3944. }
  3945. }
  3946. foreach ($bundle['pos'] ?? [] as $po) {
  3947. if (!is_array($po)) {
  3948. continue;
  3949. }
  3950. $gid = (int)($po['scydgy_id'] ?? 0);
  3951. if ($this->isValidScydgyRowId($gid)) {
  3952. $nm = trim((string)($po['CGYMC'] ?? ''));
  3953. if ($nm !== '') {
  3954. $gymcMap[$gid] = $nm;
  3955. }
  3956. $dh = trim((string)($po['CCYDH'] ?? ''));
  3957. if ($dh !== '' && empty($ccydhBySid[$gid])) {
  3958. $ccydhBySid[$gid] = $dh;
  3959. }
  3960. }
  3961. }
  3962. try {
  3963. $details = Db::table('purchase_order_detail')
  3964. ->where('scydgy_id', 'in', array_keys($sids))
  3965. ->order('company_name', 'asc')
  3966. ->order('id', 'asc')
  3967. ->select();
  3968. } catch (\Throwable $e) {
  3969. try {
  3970. $details = Db::table('purchase_order_detail')
  3971. ->where('scydgy_id', 'in', array_keys($sids))
  3972. ->order('company_name', 'asc')
  3973. ->order('ID', 'asc')
  3974. ->select();
  3975. } catch (\Throwable $e2) {
  3976. $details = [];
  3977. }
  3978. }
  3979. if (!is_array($details)) {
  3980. $details = [];
  3981. }
  3982. $byCompany = [];
  3983. foreach ($details as $d) {
  3984. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3985. continue;
  3986. }
  3987. $cn = trim((string)($d['company_name'] ?? ''));
  3988. if ($cn === '') {
  3989. continue;
  3990. }
  3991. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  3992. $sid = (int)($d['scydgy_id'] ?? 0);
  3993. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  3994. continue;
  3995. }
  3996. if (!isset($byCompany[$cn])) {
  3997. $ph = trim((string)($d['phone'] ?? ''));
  3998. $username = trim((string)($d['username'] ?? ''));
  3999. if ($username === '') {
  4000. $username = $this->resolveCustomerContactName($ph, $cn);
  4001. }
  4002. $byCompany[$cn] = [
  4003. 'name' => $cn,
  4004. 'email' => trim((string)($d['email'] ?? '')),
  4005. 'phone' => $ph,
  4006. 'username' => $username,
  4007. 'remark' => '',
  4008. 'pick_lines' => [],
  4009. 'detail_picks' => [],
  4010. ];
  4011. }
  4012. if ($byCompany[$cn]['remark'] === '') {
  4013. $rm = '';
  4014. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  4015. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  4016. $rm = trim((string)$d[$rk]);
  4017. break;
  4018. }
  4019. }
  4020. if ($rm !== '') {
  4021. $byCompany[$cn]['remark'] = $rm;
  4022. }
  4023. }
  4024. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  4025. $ccydhLine = trim((string)($ccydhBySid[$sid] ?? ''));
  4026. $processName = $this->buildSupplierProcessNameFields($ccydhLine, $gymc);
  4027. $am = trim((string)($d['amount'] ?? ''));
  4028. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  4029. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  4030. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  4031. if ($deliveryShow === '' && $deliveryRaw !== '') {
  4032. $deliveryShow = $deliveryRaw;
  4033. }
  4034. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  4035. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  4036. $subtotal = null;
  4037. if ($amountNum !== null) {
  4038. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  4039. }
  4040. $unitPriceText = $amountFilled
  4041. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  4042. : '未填写';
  4043. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  4044. $leadFilled = ($leadDays !== null);
  4045. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  4046. $pickLine = array_merge($processName, [
  4047. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  4048. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  4049. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  4050. 'amount_filled' => $amountFilled,
  4051. 'delivery_filled' => $deliveryFilled,
  4052. 'unit_price_text' => $unitPriceText,
  4053. 'lead_days' => $leadFilled ? $leadDays : '',
  4054. 'lead_days_filled'=> $leadFilled,
  4055. 'lead_days_show' => $leadText,
  4056. 'lead_days_text' => $leadText,
  4057. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  4058. 'subtotal_num' => $subtotal,
  4059. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  4060. 'is_quoted' => $amountFilled,
  4061. ]);
  4062. if (!$quoteVisible) {
  4063. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  4064. }
  4065. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  4066. $byCompany[$cn]['detail_picks'][$sid] = [
  4067. 'scydgy_id' => $sid,
  4068. 'detail_id' => $detailId,
  4069. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  4070. 'cgymc' => $processName['cgymc'],
  4071. 'ccydh' => $processName['ccydh'],
  4072. ];
  4073. }
  4074. $out = [];
  4075. foreach ($byCompany as $g) {
  4076. $pickLinesMap = $g['pick_lines'] ?? [];
  4077. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  4078. continue;
  4079. }
  4080. $pickLines = [];
  4081. $usedLineSids = [];
  4082. foreach ($orderedSids as $sid) {
  4083. if (!isset($pickLinesMap[$sid])) {
  4084. continue;
  4085. }
  4086. $pickLines[] = $pickLinesMap[$sid];
  4087. $usedLineSids[$sid] = true;
  4088. }
  4089. foreach ($pickLinesMap as $sid => $ln) {
  4090. if (isset($usedLineSids[$sid])) {
  4091. continue;
  4092. }
  4093. $pickLines[] = $ln;
  4094. }
  4095. $groupTotal = 0.0;
  4096. $groupHasTotal = false;
  4097. if ($quoteVisible) {
  4098. foreach ($pickLines as $ln) {
  4099. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  4100. $groupTotal += (float)$ln['subtotal_num'];
  4101. $groupHasTotal = true;
  4102. }
  4103. }
  4104. }
  4105. $lineCount = count($pickLines);
  4106. $g['pick_lines'] = $pickLines;
  4107. $g['line_count'] = $lineCount;
  4108. $g['has_total'] = $lineCount > 0;
  4109. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  4110. $this->finalizeSupplierRemarkDisplay($g, $orderMbz, $quoteVisible);
  4111. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  4112. $detailPicks = [];
  4113. $usedPickSids = [];
  4114. foreach ($orderedSids as $sid) {
  4115. if (!isset($detailPicksMap[$sid])) {
  4116. continue;
  4117. }
  4118. $detailPicks[] = $detailPicksMap[$sid];
  4119. $usedPickSids[$sid] = true;
  4120. }
  4121. foreach ($detailPicksMap as $sid => $dp) {
  4122. if (isset($usedPickSids[$sid])) {
  4123. continue;
  4124. }
  4125. $detailPicks[] = $dp;
  4126. }
  4127. $g['detail_picks'] = $detailPicks;
  4128. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  4129. unset($g['detail_picks']);
  4130. $out[] = $g;
  4131. }
  4132. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  4133. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  4134. }
  4135. /**
  4136. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  4137. * @return array<int, int[]> scydgy_id => detail_id[]
  4138. */
  4139. protected function mapDetailIdsByScydgyId(array $details): array
  4140. {
  4141. $out = [];
  4142. foreach ($details as $d) {
  4143. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  4144. continue;
  4145. }
  4146. $sid = (int)($d['scydgy_id'] ?? 0);
  4147. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  4148. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  4149. continue;
  4150. }
  4151. if (!isset($out[$sid])) {
  4152. $out[$sid] = [];
  4153. }
  4154. $out[$sid][] = $pk;
  4155. }
  4156. foreach ($out as $sid => $ids) {
  4157. $out[$sid] = array_values(array_unique($ids));
  4158. }
  4159. return $out;
  4160. }
  4161. /**
  4162. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  4163. *
  4164. * @param array<string, mixed> $dbRow
  4165. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  4166. */
  4167. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  4168. {
  4169. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  4170. $r = [
  4171. 'ID' => $sid,
  4172. 'scydgy_id' => $sid,
  4173. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  4174. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  4175. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  4176. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  4177. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  4178. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  4179. 'CDW' => $dbRow['CDW'] ?? '',
  4180. 'czlyq' => $dbRow['czlyq'] ?? '',
  4181. 'NGZL' => $dbRow['NGZL'] ?? '',
  4182. 'CDF' => $dbRow['CDF'] ?? '',
  4183. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  4184. 'MBZ' => $dbRow['MBZ'] ?? '',
  4185. 'bwjg' => $dbRow['bwjg'] ?? '',
  4186. 'iStatus' => $dbRow['iStatus'] ?? '',
  4187. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  4188. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  4189. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  4190. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  4191. 'dStamp' => $dbRow['dStamp'] ?? '',
  4192. 'pick_time' => $dbRow['pick_time'] ?? '',
  4193. 'order_batch_no' => $this->resolveProcuremenOrderBatchNo($dbRow),
  4194. ];
  4195. $r['This_quantity'] = $this->resolveProcuremenThisQuantity($r);
  4196. $r['ceilingPrice'] = $this->resolveProcuremenCeilingPrice($r);
  4197. if ($sid > 0 && isset($dStampMap[$sid])) {
  4198. $t = trim((string)$dStampMap[$sid]);
  4199. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  4200. $r['dStamp'] = $dStampMap[$sid];
  4201. }
  4202. }
  4203. $dsOut = trim((string)($r['dStamp'] ?? ''));
  4204. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  4205. $ct = $dbRow['createtime'];
  4206. if (is_numeric($ct) && (int)$ct > 946684800) {
  4207. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  4208. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  4209. $r['dStamp'] = trim($ct);
  4210. }
  4211. }
  4212. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  4213. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  4214. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  4215. $fallback = trim((string)($r['dStamp'] ?? ''));
  4216. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  4217. $r['dputrecord'] = $fallback;
  4218. }
  4219. }
  4220. if (array_key_exists('id', $dbRow)) {
  4221. $r['purchase_order_id'] = (int)$dbRow['id'];
  4222. }
  4223. if ($sid < 0) {
  4224. $r['_is_manual'] = 1;
  4225. }
  4226. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  4227. $pickOut = trim((string)($r['pick_time'] ?? ''));
  4228. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  4229. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  4230. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  4231. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  4232. $r['pick_time'] = $pickFallback;
  4233. break;
  4234. }
  4235. }
  4236. }
  4237. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  4238. if ($pickNm !== '') {
  4239. $r['pick_company_name'] = $pickNm;
  4240. $r['picked_supplier_name'] = $pickNm;
  4241. }
  4242. $r['wflow_status'] = trim((string)($dbRow['wflow_status'] ?? ''));
  4243. $r['order_status_text'] = ProcuremenStatus::orderStatusLabelForList($r['wflow_status']);
  4244. if (array_key_exists('status', $dbRow)) {
  4245. $r['status'] = $dbRow['status'];
  4246. }
  4247. return $r;
  4248. }
  4249. /**
  4250. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  4251. *
  4252. * @return array<int, array<string, mixed>>
  4253. */
  4254. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  4255. {
  4256. $pool = [];
  4257. if (!is_array($dbRows) || $dbRows === []) {
  4258. return $pool;
  4259. }
  4260. $dStampMap = [];
  4261. $sidList = [];
  4262. foreach ($dbRows as $tmpRow) {
  4263. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  4264. $sid = (int)$tmpRow['scydgy_id'];
  4265. if ($sid > 0) {
  4266. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  4267. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  4268. $sidList[$sid] = true;
  4269. }
  4270. }
  4271. }
  4272. }
  4273. if ($sidList !== []) {
  4274. try {
  4275. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  4276. } catch (\Throwable $e) {
  4277. $dStampMap = [];
  4278. }
  4279. }
  4280. foreach ($dbRows as $dbRow) {
  4281. if (!is_array($dbRow)) {
  4282. continue;
  4283. }
  4284. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  4285. }
  4286. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  4287. $needCcydh = [];
  4288. foreach ($pool as $row) {
  4289. if (!is_array($row)) {
  4290. continue;
  4291. }
  4292. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  4293. continue;
  4294. }
  4295. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  4296. if ($ccydh !== '') {
  4297. $needCcydh[$ccydh] = true;
  4298. }
  4299. }
  4300. if ($needCcydh !== []) {
  4301. $czMap = [];
  4302. try {
  4303. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  4304. } catch (\Throwable $e) {
  4305. $czMap = [];
  4306. }
  4307. if (is_array($czMap) && $czMap !== []) {
  4308. foreach ($pool as &$row) {
  4309. if (!is_array($row)) {
  4310. continue;
  4311. }
  4312. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  4313. continue;
  4314. }
  4315. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  4316. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  4317. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  4318. }
  4319. }
  4320. unset($row);
  4321. }
  4322. }
  4323. return $pool;
  4324. }
  4325. /**
  4326. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  4327. *
  4328. * @param int[] $scydgyIds
  4329. * @return array<int, array<string, mixed>>
  4330. */
  4331. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  4332. {
  4333. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4334. if ($scydgyIds === []) {
  4335. return [];
  4336. }
  4337. try {
  4338. $list = Db::table('purchase_order_detail')
  4339. ->where('scydgy_id', 'in', $scydgyIds)
  4340. ->field('scydgy_id,company_name,amount,delivery')
  4341. ->select();
  4342. } catch (\Throwable $e) {
  4343. $list = [];
  4344. }
  4345. return is_array($list) ? $list : [];
  4346. }
  4347. /**
  4348. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  4349. *
  4350. * @param int[] $scydgyIds
  4351. * @param array<int, array<string, mixed>> $allRows
  4352. * @return array{cnt:int, amt:int, deliv:int}
  4353. */
  4354. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  4355. {
  4356. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4357. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4358. if ($scydgyIds === [] || $allRows === []) {
  4359. return $out;
  4360. }
  4361. $idSet = array_flip($scydgyIds);
  4362. $all = [];
  4363. $withAmt = [];
  4364. $withDeliv = [];
  4365. foreach ($allRows as $r) {
  4366. if (!is_array($r)) {
  4367. continue;
  4368. }
  4369. $sid = (int)($r['scydgy_id'] ?? 0);
  4370. if (!isset($idSet[$sid])) {
  4371. continue;
  4372. }
  4373. $cn = trim((string)($r['company_name'] ?? ''));
  4374. if ($cn === '') {
  4375. continue;
  4376. }
  4377. $all[$cn] = true;
  4378. $am = $r['amount'] ?? null;
  4379. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  4380. $withAmt[$cn] = true;
  4381. }
  4382. $dv = $r['delivery'] ?? null;
  4383. if ($dv !== null && trim((string)$dv) !== '') {
  4384. $withDeliv[$cn] = true;
  4385. }
  4386. }
  4387. return [
  4388. 'cnt' => count($all),
  4389. 'amt' => count($withAmt),
  4390. 'deliv' => count($withDeliv),
  4391. ];
  4392. }
  4393. /**
  4394. * 本次数量:优先 This_quantity,空则回退工作量 NGZL(与下发/确认/审批弹窗一致)
  4395. *
  4396. * @param array<string, mixed> $row
  4397. */
  4398. protected function resolveProcuremenThisQuantity(array $row): string
  4399. {
  4400. $q = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  4401. if ($q !== '') {
  4402. return $q;
  4403. }
  4404. $ngzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  4405. if (!is_scalar($ngzl)) {
  4406. return '';
  4407. }
  4408. $s = trim((string)$ngzl);
  4409. if ($s === '') {
  4410. return '';
  4411. }
  4412. if (is_numeric($s) && (float)$s === 0.0) {
  4413. return '';
  4414. }
  4415. return $s;
  4416. }
  4417. /**
  4418. * @param array<string, mixed> $row
  4419. */
  4420. protected function resolveProcuremenCeilingPrice(array $row): string
  4421. {
  4422. return trim((string)($row['ceilingPrice'] ?? $row['ceiling_price'] ?? ''));
  4423. }
  4424. /**
  4425. * 多工序数量/限价拼接:跳过空值,避免出现「、10」「304、」
  4426. *
  4427. * @param array<int, mixed> $parts
  4428. */
  4429. protected function joinProcuremenNonEmpty(array $parts, string $sep = '、'): string
  4430. {
  4431. $out = [];
  4432. foreach ($parts as $p) {
  4433. $s = trim((string)$p);
  4434. if ($s !== '') {
  4435. $out[] = $s;
  4436. }
  4437. }
  4438. return $out === [] ? '' : implode($sep, $out);
  4439. }
  4440. /**
  4441. * 确认/审批列表:合并行按各工序同步本次数量、最高限价(顿号间隔)
  4442. *
  4443. * @param array<int, array<string, mixed>> $rows
  4444. */
  4445. protected function syncCollapsedOrderQtyPriceForList(array &$rows): void
  4446. {
  4447. if ($rows === []) {
  4448. return;
  4449. }
  4450. $idList = [];
  4451. foreach ($rows as $rw) {
  4452. if (!is_array($rw)) {
  4453. continue;
  4454. }
  4455. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4456. foreach ($rw['_order_merge_rows'] as $mr) {
  4457. if (!is_array($mr)) {
  4458. continue;
  4459. }
  4460. $mid = (int)($mr['ID'] ?? 0);
  4461. if ($this->isValidScydgyRowId($mid)) {
  4462. $idList[$mid] = true;
  4463. }
  4464. }
  4465. }
  4466. $id = (int)($rw['ID'] ?? 0);
  4467. if ($this->isValidScydgyRowId($id)) {
  4468. $idList[$id] = true;
  4469. }
  4470. }
  4471. if ($idList === []) {
  4472. return;
  4473. }
  4474. try {
  4475. $list = Db::table('purchase_order')
  4476. ->where('scydgy_id', 'in', array_keys($idList))
  4477. ->field('scydgy_id,This_quantity,ceilingPrice,NGZL,pick_company_name')
  4478. ->select();
  4479. } catch (\Throwable $e) {
  4480. return;
  4481. }
  4482. if (!is_array($list)) {
  4483. return;
  4484. }
  4485. $byId = [];
  4486. foreach ($list as $dbRow) {
  4487. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4488. continue;
  4489. }
  4490. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4491. }
  4492. foreach ($rows as &$rw) {
  4493. if (!is_array($rw)) {
  4494. continue;
  4495. }
  4496. $mergeRows = [];
  4497. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4498. $mergeRows = $rw['_order_merge_rows'];
  4499. } else {
  4500. $mergeRows = [$rw];
  4501. }
  4502. $qtyList = [];
  4503. $priceList = [];
  4504. $picked = '';
  4505. foreach ($mergeRows as $mr) {
  4506. if (!is_array($mr)) {
  4507. continue;
  4508. }
  4509. $sid = (int)($mr['ID'] ?? 0);
  4510. $db = ($sid !== 0 && isset($byId[$sid])) ? $byId[$sid] : null;
  4511. $src = $mr;
  4512. if (is_array($db)) {
  4513. $qDb = trim((string)($db['This_quantity'] ?? $db['this_quantity'] ?? ''));
  4514. $pDb = trim((string)($db['ceilingPrice'] ?? $db['ceiling_price'] ?? ''));
  4515. $ngzlDb = $db['NGZL'] ?? $db['ngzl'] ?? null;
  4516. if ($qDb !== '') {
  4517. $src['This_quantity'] = $qDb;
  4518. }
  4519. if ($pDb !== '') {
  4520. $src['ceilingPrice'] = $pDb;
  4521. }
  4522. if ($ngzlDb !== null && trim((string)$ngzlDb) !== '') {
  4523. $src['NGZL'] = $ngzlDb;
  4524. }
  4525. if ($picked === '') {
  4526. $picked = trim((string)($db['pick_company_name'] ?? ''));
  4527. }
  4528. }
  4529. if ($picked === '') {
  4530. $picked = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  4531. }
  4532. $qtyList[] = $this->resolveProcuremenThisQuantity($src);
  4533. $priceList[] = $this->resolveProcuremenCeilingPrice($src);
  4534. }
  4535. $rw['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  4536. $rw['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  4537. if ($picked !== '') {
  4538. $rw['pick_company_name'] = $picked;
  4539. $rw['picked_supplier_name'] = $picked;
  4540. }
  4541. }
  4542. unset($rw);
  4543. }
  4544. /**
  4545. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  4546. *
  4547. * @param int[] $scydgyIds
  4548. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  4549. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  4550. */
  4551. protected function OrderDetailSummary(array $scydgyIds)
  4552. {
  4553. $out = [];
  4554. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4555. if ($scydgyIds === []) {
  4556. return $out;
  4557. }
  4558. $list = [];
  4559. try {
  4560. $list = Db::table('purchase_order_detail')
  4561. ->where('scydgy_id', 'in', $scydgyIds)
  4562. ->field('id,scydgy_id,amount,delivery')
  4563. ->select();
  4564. } catch (\Throwable $e) {
  4565. $list = [];
  4566. }
  4567. if (!is_array($list)) {
  4568. return $out;
  4569. }
  4570. foreach ($list as $r) {
  4571. if (!is_array($r)) {
  4572. continue;
  4573. }
  4574. $ids = (int)($r['scydgy_id'] ?? 0);
  4575. if (!$this->isValidScydgyRowId($ids)) {
  4576. continue;
  4577. }
  4578. if (!isset($out[$ids])) {
  4579. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4580. }
  4581. $out[$ids]['cnt']++;
  4582. $am = $r['amount'] ?? null;
  4583. if ($am !== null && $am !== '') {
  4584. if (!(is_string($am) && trim($am) === '')) {
  4585. $out[$ids]['amt']++;
  4586. }
  4587. }
  4588. $dv = $r['delivery'] ?? null;
  4589. if ($dv !== null && trim((string)$dv) !== '') {
  4590. $out[$ids]['deliv']++;
  4591. }
  4592. }
  4593. return $out;
  4594. }
  4595. /**
  4596. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  4597. *
  4598. * @return array
  4599. */
  4600. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  4601. {
  4602. $strContains = function ($haystack, $needle) {
  4603. if ($needle === '') {
  4604. return false;
  4605. }
  4606. $haystack = (string)$haystack;
  4607. if (function_exists('mb_stripos')) {
  4608. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  4609. }
  4610. return stripos($haystack, $needle) !== false;
  4611. };
  4612. $stripAlias = function ($f) {
  4613. return preg_replace('/^[ab]\./i', '', (string)$f);
  4614. };
  4615. $searchColNames = [];
  4616. foreach (explode(',', $this->searchFields) as $colRaw) {
  4617. $c = $stripAlias(trim($colRaw));
  4618. if ($c !== '') {
  4619. $searchColNames[] = $c;
  4620. }
  4621. }
  4622. // 等值条件先行(表头下拉),减少后续日期解析量
  4623. $eqFilters = [];
  4624. $otherFilters = [];
  4625. foreach ($filterArr as $fk => $fv) {
  4626. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  4627. continue;
  4628. }
  4629. if (is_array($fv)) {
  4630. continue;
  4631. }
  4632. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  4633. continue;
  4634. }
  4635. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  4636. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  4637. $field = $stripAlias($fk);
  4638. if ($sym === '=' || $sym === '') {
  4639. $eqFilters[$field] = trim((string)$fv);
  4640. } else {
  4641. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  4642. }
  4643. }
  4644. $ymTarget = '';
  4645. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  4646. $ymTarget = $ymM[1];
  4647. }
  4648. $filtered = [];
  4649. foreach ($pool as $r) {
  4650. if (!is_array($r)) {
  4651. continue;
  4652. }
  4653. foreach ($eqFilters as $field => $fv) {
  4654. if (trim((string)($r[$field] ?? '')) !== $fv) {
  4655. continue 2;
  4656. }
  4657. }
  4658. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  4659. // 初选池不应含手工单;若混入则直接剔除
  4660. if ($isManual) {
  4661. continue;
  4662. }
  4663. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  4664. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  4665. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  4666. continue;
  4667. }
  4668. if ($applyMonthRange) {
  4669. $mo = (int)$m[2];
  4670. if ($mo < 1 || $mo > 12) {
  4671. continue;
  4672. }
  4673. if ($ymTarget !== '') {
  4674. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4675. if ($ymRow !== $ymTarget) {
  4676. continue;
  4677. }
  4678. } else {
  4679. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4680. $rowMonthStart = $ymRow . '-01 00:00:00';
  4681. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  4682. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  4683. continue;
  4684. }
  4685. }
  4686. }
  4687. if ($search !== '') {
  4688. $hitSearch = false;
  4689. foreach ($searchColNames as $c) {
  4690. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  4691. if ($cell !== '' && $strContains($cell, $search)) {
  4692. $hitSearch = true;
  4693. break;
  4694. }
  4695. }
  4696. if (!$hitSearch) {
  4697. continue;
  4698. }
  4699. }
  4700. foreach ($otherFilters as $item) {
  4701. $fv = $item['fv'];
  4702. $sym = $item['sym'];
  4703. $field = $item['field'];
  4704. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  4705. $cellStr = trim((string)$cell);
  4706. switch ($sym) {
  4707. case '<>':
  4708. if ((string)$cell === (string)$fv) {
  4709. continue 3;
  4710. }
  4711. break;
  4712. case 'LIKE':
  4713. case 'NOT LIKE':
  4714. $needle = trim((string)$fv);
  4715. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  4716. if ($sym === 'LIKE' && !$hit) {
  4717. continue 3;
  4718. }
  4719. if ($sym === 'NOT LIKE' && $hit) {
  4720. continue 3;
  4721. }
  4722. break;
  4723. case 'BETWEEN':
  4724. case 'RANGE':
  4725. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  4726. if (count($parts) < 2) {
  4727. $parts = is_string($fv) ? explode(',', $fv) : [];
  4728. }
  4729. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  4730. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  4731. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  4732. continue 3;
  4733. }
  4734. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  4735. continue 3;
  4736. }
  4737. break;
  4738. case '>':
  4739. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  4740. continue 3;
  4741. }
  4742. break;
  4743. case '>=':
  4744. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  4745. continue 3;
  4746. }
  4747. break;
  4748. case '<':
  4749. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  4750. continue 3;
  4751. }
  4752. break;
  4753. case '<=':
  4754. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  4755. continue 3;
  4756. }
  4757. break;
  4758. default:
  4759. if ((string)$cell !== (string)$fv) {
  4760. continue 3;
  4761. }
  4762. break;
  4763. }
  4764. }
  4765. $filtered[] = $r;
  4766. }
  4767. return $filtered;
  4768. }
  4769. /**
  4770. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  4771. */
  4772. public function snapshotToProcure()
  4773. {
  4774. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4775. $this->error(__('Invalid parameters'));
  4776. }
  4777. $row = json_decode($this->request->post('row_json', ''), true);
  4778. if (!is_array($row)) {
  4779. $this->error(__('Invalid parameters'));
  4780. }
  4781. try {
  4782. $ids = $this->extractScydgyRowId($row);
  4783. if (!$this->isValidScydgyRowId($ids)) {
  4784. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4785. }
  4786. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4787. $data = $this->normalizePurchaseOrderWritePayload([
  4788. 'scydgy_id' => $ids,
  4789. 'CCYDH' => $row['CCYDH'] ?? null,
  4790. 'CYJMC' => $row['CYJMC'] ?? null,
  4791. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4792. 'CDXMC' => $row['CDXMC'] ?? null,
  4793. 'CGYBH' => $row['CGYBH'] ?? null,
  4794. 'CGYMC' => $row['CGYMC'] ?? null,
  4795. 'CDW' => $row['CDW'] ?? null,
  4796. 'czlyq' => $row['czlyq'] ?? null,
  4797. 'NGZL' => $row['NGZL'] ?? null,
  4798. 'CDF' => $row['CDF'] ?? null,
  4799. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4800. 'MBZ' => $row['MBZ'] ?? null,
  4801. 'bwjg' => $row['bwjg'] ?? null,
  4802. 'iStatus' => $row['iStatus'] ?? null,
  4803. 'dStamp' => $row['dStamp'] ?? null,
  4804. 'dputrecord' => $row['dputrecord'] ?? null,
  4805. 'cywyxm' => $row['cywyxm'] ?? null,
  4806. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4807. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4808. ], $row);
  4809. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  4810. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  4811. $mbzSnap = trim((string)($data['MBZ'] ?? ''));
  4812. if (!$exists && $qtySnap === '' && $priceSnap === '' && $mbzSnap === '') {
  4813. $this->success('操作成功');
  4814. return;
  4815. }
  4816. if ($exists) {
  4817. $upd = $data;
  4818. unset($upd['scydgy_id'], $upd['status']);
  4819. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4820. } else {
  4821. // 新增:不写 status(空/走库默认);仅写创建时间
  4822. $data['createtime'] = date('Y-m-d H:i:s');
  4823. Db::table('purchase_order')->insert($data);
  4824. }
  4825. } catch (\Throwable $e) {
  4826. $this->error($e->getMessage());
  4827. }
  4828. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  4829. $this->success('操作成功');
  4830. }
  4831. /**
  4832. * 未发列表
  4833. * 「完结」或「仅保存本次数量/最高限价/备注」:有则改、无则插
  4834. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  4835. */
  4836. public function completeDirectly()
  4837. {
  4838. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4839. $this->error(__('参数错误'));
  4840. }
  4841. if (!$this->procuremenCanComplete()) {
  4842. $this->error(__('You have no permission'));
  4843. }
  4844. $row = json_decode($this->request->post('row_json', ''), true);
  4845. if (!is_array($row)) {
  4846. $this->error(__('Invalid parameters'));
  4847. }
  4848. $finishRaw = $this->request->post('finish', '1');
  4849. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  4850. $poIdLog = null;
  4851. try {
  4852. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  4853. $ids = $this->extractScydgyRowId($row);
  4854. if (!$this->isValidScydgyRowId($ids)) {
  4855. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4856. }
  4857. if ($asComplete) {
  4858. $this->assertPickRowCanComplete($ids, $row);
  4859. }
  4860. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4861. $data = $this->normalizePurchaseOrderWritePayload([
  4862. 'scydgy_id' => $ids,
  4863. 'CCYDH' => $row['CCYDH'] ?? null,
  4864. 'CYJMC' => $row['CYJMC'] ?? null,
  4865. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4866. 'CDXMC' => $row['CDXMC'] ?? null,
  4867. 'CGYBH' => $row['CGYBH'] ?? null,
  4868. 'CGYMC' => $row['CGYMC'] ?? null,
  4869. 'CDW' => $row['CDW'] ?? null,
  4870. 'czlyq' => $row['czlyq'] ?? null,
  4871. 'NGZL' => $row['NGZL'] ?? null,
  4872. 'CDF' => $row['CDF'] ?? null,
  4873. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4874. 'MBZ' => $row['MBZ'] ?? null,
  4875. 'bwjg' => $row['bwjg'] ?? null,
  4876. 'iStatus' => $row['iStatus'] ?? null,
  4877. 'dStamp' => $row['dStamp'] ?? null,
  4878. 'dputrecord' => $row['dputrecord'] ?? null,
  4879. 'cywyxm' => $row['cywyxm'] ?? null,
  4880. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4881. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4882. ], $row);
  4883. if ($asComplete) {
  4884. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  4885. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  4886. }
  4887. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  4888. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  4889. $mbzCd = trim((string)($data['MBZ'] ?? ''));
  4890. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '' && $mbzCd === '') {
  4891. $this->success('操作成功');
  4892. return;
  4893. }
  4894. if ($exists) {
  4895. $upd = $data;
  4896. unset($upd['scydgy_id']);
  4897. if (!$asComplete) {
  4898. unset($upd['status']);
  4899. }
  4900. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4901. } else {
  4902. // 新增:不写 status;完结时 $data 已含 status=1
  4903. $data['createtime'] = date('Y-m-d H:i:s');
  4904. Db::table('purchase_order')->insert($data);
  4905. }
  4906. } catch (\Throwable $e) {
  4907. $this->error($e->getMessage());
  4908. }
  4909. try {
  4910. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4911. if (is_array($rpo)) {
  4912. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4913. $poIdLog = $tid > 0 ? $tid : null;
  4914. }
  4915. } catch (\Throwable $e) {
  4916. $poIdLog = null;
  4917. }
  4918. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  4919. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  4920. if ($asComplete) {
  4921. $this->addOrderLog(
  4922. $ids,
  4923. 'mark_complete',
  4924. '点击「完结」,已标记为已完结',
  4925. $poIdLog
  4926. );
  4927. try {
  4928. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  4929. if ($pdfPublicPath === '') {
  4930. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  4931. }
  4932. } catch (\Throwable $e) {
  4933. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  4934. }
  4935. } else {
  4936. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  4937. $mbz = isset($data['MBZ']) ? trim((string)$data['MBZ']) : '';
  4938. $parts = [];
  4939. if ($q !== '') {
  4940. $parts[] = ($gymc !== '' ? ($gymc . '本次数量') : '本次数量') . '「' . $q . '」';
  4941. } elseif ($gymc !== '') {
  4942. // 仅改限价/备注时仍带工序名便于辨认
  4943. $parts[] = $gymc;
  4944. }
  4945. if ($p !== '') {
  4946. $parts[] = '最高限价「' . $p . '」';
  4947. }
  4948. if ($mbz !== '') {
  4949. $parts[] = '招标备注「' . $mbz . '」';
  4950. }
  4951. $detail = $parts !== [] ? implode(',', $parts) : '(未改数量/限价/招标备注)';
  4952. $this->addOrderLog(
  4953. $ids,
  4954. 'save_qty_price',
  4955. '保存本次数量、最高限价、招标备注:' . $detail,
  4956. $poIdLog
  4957. );
  4958. }
  4959. $this->pickHiddenScydgySetCache = null;
  4960. $this->success("操作成功");
  4961. }
  4962. /**
  4963. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价、备注(若表中有对应列)
  4964. *
  4965. * @param array<int, array> $rows 引用传递当前页行
  4966. */
  4967. protected function mergePurchaseOrder(array &$rows)
  4968. {
  4969. if ($rows === []) {
  4970. return;
  4971. }
  4972. $ids = [];
  4973. foreach ($rows as $rw) {
  4974. if (!is_array($rw)) {
  4975. continue;
  4976. }
  4977. $id = (int)($rw['ID'] ?? 0);
  4978. // 含手工新增负数 scydgy_id,避免限价/数量不同步
  4979. if ($this->isValidScydgyRowId($id)) {
  4980. $ids[$id] = true;
  4981. }
  4982. }
  4983. $idList = array_keys($ids);
  4984. if ($idList === []) {
  4985. return;
  4986. }
  4987. try {
  4988. $list = Db::table('purchase_order')
  4989. ->where('scydgy_id', 'in', $idList)
  4990. ->field('scydgy_id,This_quantity,ceilingPrice,MBZ')
  4991. ->select();
  4992. } catch (\Throwable $e) {
  4993. return;
  4994. }
  4995. if (!is_array($list)) {
  4996. return;
  4997. }
  4998. $byId = [];
  4999. foreach ($list as $dbRow) {
  5000. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  5001. continue;
  5002. }
  5003. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  5004. }
  5005. foreach ($rows as &$rw) {
  5006. if (!is_array($rw)) {
  5007. continue;
  5008. }
  5009. $sid = (int)($rw['ID'] ?? 0);
  5010. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  5011. continue;
  5012. }
  5013. $db = $byId[$sid];
  5014. // 有 purchase_order 记录时同步数量/限价/备注(含清空后的空串,避免刷新后又冒出来)
  5015. if (array_key_exists('This_quantity', $db)) {
  5016. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  5017. }
  5018. if (array_key_exists('ceilingPrice', $db)) {
  5019. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  5020. } elseif (array_key_exists('ceiling_price', $db)) {
  5021. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  5022. }
  5023. if (array_key_exists('MBZ', $db)) {
  5024. $poMbz = $db['MBZ'] === null ? '' : trim((string)$db['MBZ']);
  5025. if ($poMbz !== '') {
  5026. $rw['MBZ'] = $poMbz;
  5027. }
  5028. }
  5029. }
  5030. unset($rw);
  5031. }
  5032. /**
  5033. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  5034. */
  5035. public function purchaseConfirmPick()
  5036. {
  5037. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5038. $this->error(__('Invalid parameters'));
  5039. }
  5040. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  5041. $this->error(__('You have no permission'));
  5042. }
  5043. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  5044. if ($batchRaw !== '') {
  5045. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  5046. return;
  5047. }
  5048. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5049. $sid = (int)$scydgyId;
  5050. if (!$this->isValidScydgyRowId($sid)) {
  5051. $this->error('参数无效');
  5052. }
  5053. $parseIdList = function ($raw) {
  5054. if (is_array($raw)) {
  5055. $arr = $raw;
  5056. } else {
  5057. $decoded = json_decode((string)$raw, true);
  5058. $arr = is_array($decoded) ? $decoded : [];
  5059. }
  5060. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  5061. };
  5062. $selectedRaw = $this->request->post('selected_ids', null);
  5063. if ($selectedRaw === null || $selectedRaw === '') {
  5064. $legacy = (int)$this->request->post('selected_id', 0);
  5065. $selectedIds = $legacy > 0 ? [$legacy] : [];
  5066. } else {
  5067. $selectedIds = $parseIdList($selectedRaw);
  5068. }
  5069. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  5070. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  5071. try {
  5072. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  5073. } catch (\InvalidArgumentException $e) {
  5074. $this->error($e->getMessage());
  5075. } catch (\Throwable $e) {
  5076. $this->error($e->getMessage());
  5077. }
  5078. $this->pickHiddenScydgySetCache = null;
  5079. $this->success('操作成功', '', $result);
  5080. }
  5081. /**
  5082. * 整单采购确认(多道工序一次提交)
  5083. */
  5084. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  5085. {
  5086. $decoded = json_decode($batchRaw, true);
  5087. if (!is_array($decoded) || $decoded === []) {
  5088. $this->error('提交数据无效');
  5089. }
  5090. $picks = [];
  5091. foreach ($decoded as $item) {
  5092. if (!is_array($item)) {
  5093. continue;
  5094. }
  5095. $sid = (int)($item['scydgy_id'] ?? 0);
  5096. if (!$this->isValidScydgyRowId($sid)) {
  5097. continue;
  5098. }
  5099. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  5100. if (!is_array($sel)) {
  5101. $sel = [(int)$sel];
  5102. }
  5103. $unsel = $item['unselected_ids'] ?? [];
  5104. if (!is_array($unsel)) {
  5105. $unsel = json_decode((string)$unsel, true);
  5106. $unsel = is_array($unsel) ? $unsel : [];
  5107. }
  5108. $picks[] = [
  5109. 'scydgy_id' => $sid,
  5110. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  5111. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  5112. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  5113. ];
  5114. }
  5115. if ($picks === []) {
  5116. $this->error('提交数据无效');
  5117. }
  5118. Db::startTrans();
  5119. $results = [];
  5120. try {
  5121. foreach ($picks as $pick) {
  5122. $results[] = $this->runPurchaseConfirmPick(
  5123. (int)$pick['scydgy_id'],
  5124. $pick['selected_ids'],
  5125. $pick['unselected_ids'],
  5126. (int)$pick['purchase_order_id'],
  5127. false,
  5128. false
  5129. );
  5130. }
  5131. Db::commit();
  5132. } catch (\Throwable $e) {
  5133. Db::rollback();
  5134. $msg = $e->getMessage();
  5135. $this->error($msg !== '' ? $msg : '提交失败');
  5136. }
  5137. try {
  5138. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  5139. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  5140. } catch (\Throwable $e) {
  5141. Log::write('采购确认通知批量发送异常: ' . $e->getMessage(), 'error');
  5142. }
  5143. $this->pickHiddenScydgySetCache = null;
  5144. $this->success('操作成功', '', ['batch' => $results]);
  5145. }
  5146. /**
  5147. * @return array<string, mixed>
  5148. */
  5149. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  5150. {
  5151. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  5152. ProcuremenGuard::assertWflowPendingApproval($poRow);
  5153. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  5154. $scydgyId = (string)$sid;
  5155. if ($selectedIds === []) {
  5156. throw new \InvalidArgumentException('请至少勾选一条明细');
  5157. }
  5158. $inter = array_intersect($selectedIds, $unselectedIds);
  5159. if ($inter !== []) {
  5160. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  5161. }
  5162. $allIds = $this->purchaseOrderDetail($sid);
  5163. if ($allIds === []) {
  5164. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  5165. }
  5166. foreach ($selectedIds as $id) {
  5167. if (!in_array($id, $allIds, true)) {
  5168. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  5169. }
  5170. }
  5171. foreach ($unselectedIds as $id) {
  5172. if (!in_array($id, $allIds, true)) {
  5173. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  5174. }
  5175. }
  5176. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  5177. sort($union, SORT_NUMERIC);
  5178. $expect = $allIds;
  5179. sort($expect, SORT_NUMERIC);
  5180. if ($union !== $expect) {
  5181. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  5182. }
  5183. if ($manageTransaction) {
  5184. Db::startTrans();
  5185. }
  5186. try {
  5187. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  5188. $aff = 0;
  5189. try {
  5190. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  5191. } catch (\Throwable $e) {
  5192. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  5193. }
  5194. if ($aff < 1) {
  5195. throw new \Exception('更新选中状态失败');
  5196. }
  5197. $poPayload = [
  5198. // 审核通过后进入「待入库评分」;合格/不合格后才置已完结
  5199. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5200. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  5201. ];
  5202. if ($purchaseOrderId > 0) {
  5203. $poAff = (int)Db::table('purchase_order')
  5204. ->where('id', $purchaseOrderId)
  5205. ->where('scydgy_id', $sid)
  5206. ->update($poPayload);
  5207. if ($poAff < 1) {
  5208. throw new \Exception('主表订单不存在或与工序行不匹配');
  5209. }
  5210. } else {
  5211. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  5212. if ($poAff < 1) {
  5213. throw new \Exception('未找到');
  5214. }
  5215. }
  5216. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  5217. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  5218. if ($manageTransaction) {
  5219. Db::commit();
  5220. }
  5221. } catch (\Throwable $e) {
  5222. if ($manageTransaction) {
  5223. Db::rollback();
  5224. }
  5225. throw $e;
  5226. }
  5227. $poIdFinal = $purchaseOrderId;
  5228. if ($poIdFinal <= 0) {
  5229. try {
  5230. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  5231. if (is_array($rpo)) {
  5232. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  5233. }
  5234. } catch (\Throwable $e) {
  5235. $poIdFinal = 0;
  5236. }
  5237. }
  5238. $pickNames = [];
  5239. foreach ($selectedIds as $pid) {
  5240. $dr = $this->purchaseOrderDetai($sid, $pid);
  5241. $nm = trim((string)($dr['company_name'] ?? ''));
  5242. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  5243. }
  5244. $this->addOrderLog(
  5245. $sid,
  5246. 'purchase_confirm',
  5247. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  5248. $poIdFinal > 0 ? $poIdFinal : null
  5249. );
  5250. if ($sendNotifications) {
  5251. try {
  5252. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  5253. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  5254. 'scydgy_id' => $sid,
  5255. 'selected_ids' => $selectedIds,
  5256. 'unselected_ids' => $unselectedIds,
  5257. 'purchase_order_id' => $purchaseOrderId,
  5258. ]]);
  5259. } catch (\Throwable $e) {
  5260. Log::write('采购确认通知发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  5261. }
  5262. }
  5263. Log::write(sprintf(
  5264. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  5265. $scydgyId,
  5266. $purchaseOrderId,
  5267. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  5268. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  5269. ), 'notice');
  5270. $pdfPublicPath = '';
  5271. try {
  5272. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  5273. } catch (\Throwable $e) {
  5274. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  5275. }
  5276. return [
  5277. 'scydgy_id' => $scydgyId,
  5278. 'purchase_order_id' => $purchaseOrderId,
  5279. 'selected_ids' => $selectedIds,
  5280. 'unselected_ids' => $unselectedIds,
  5281. 'purchase_confirm_pdf' => $pdfPublicPath,
  5282. ];
  5283. }
  5284. /**
  5285. * 审批通过短信:按本次涉及的工序汇总 process_lines
  5286. *
  5287. * @param int[]|string[] $scydgyIds
  5288. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  5289. */
  5290. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  5291. {
  5292. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  5293. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  5294. if ($scydgyIds === []) {
  5295. return $empty;
  5296. }
  5297. $pos = [];
  5298. try {
  5299. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  5300. } catch (\Throwable $e) {
  5301. $rows = [];
  5302. }
  5303. if (is_array($rows)) {
  5304. foreach ($rows as $po) {
  5305. if (is_array($po)) {
  5306. $pos[] = $po;
  5307. }
  5308. }
  5309. }
  5310. if ($pos === []) {
  5311. return $empty;
  5312. }
  5313. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  5314. return [
  5315. 'ccydh' => $ccydh,
  5316. 'pos' => $pos,
  5317. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  5318. ];
  5319. }
  5320. /**
  5321. * 审批通过/未通过:短信 + 邮件(同一供应商只发一条;邮件含平台链接)
  5322. *
  5323. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  5324. * @param array<int, array<string, mixed>> $picks
  5325. */
  5326. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  5327. {
  5328. if ($picks === []) {
  5329. return;
  5330. }
  5331. $this->ensureConfirmResultEmailTemplates();
  5332. $fallbackDetailId = 0;
  5333. $winners = [];
  5334. $losers = [];
  5335. foreach ($picks as $pick) {
  5336. if (!is_array($pick)) {
  5337. continue;
  5338. }
  5339. $sid = (int)($pick['scydgy_id'] ?? 0);
  5340. if (!$this->isValidScydgyRowId($sid)) {
  5341. continue;
  5342. }
  5343. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  5344. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  5345. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  5346. $fallbackDetailId = (int)$selectedIds[0];
  5347. }
  5348. foreach ($selectedIds as $pid) {
  5349. $dr = $this->purchaseOrderDetai($sid, $pid);
  5350. if (!is_array($dr)) {
  5351. continue;
  5352. }
  5353. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  5354. }
  5355. foreach ($unselectedIds as $pid) {
  5356. $dr = $this->purchaseOrderDetai($sid, $pid);
  5357. if (!is_array($dr)) {
  5358. continue;
  5359. }
  5360. $key = $this->notifySupplierDedupeKey($dr);
  5361. if (!isset($winners[$key])) {
  5362. $losers[$key] = $dr;
  5363. }
  5364. }
  5365. }
  5366. if ($winners === [] && $losers === []) {
  5367. return;
  5368. }
  5369. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  5370. $poIdLog = 0;
  5371. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5372. if (isset($pos[0]) && is_array($pos[0])) {
  5373. $poIdLog = (int)($pos[0]['id'] ?? 0);
  5374. }
  5375. $sendSmsSafe = function ($phone, $content) {
  5376. $phone = trim((string)$phone);
  5377. if ($phone === '') {
  5378. return;
  5379. }
  5380. try {
  5381. $this->smsbao($phone, $content);
  5382. } catch (\Throwable $e) {
  5383. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  5384. }
  5385. };
  5386. $sendConfirmEmailSafe = function (array $dr, string $emailScene) use ($confirmNotifyVars, $poIdLog) {
  5387. $cname = trim((string)($dr['company_name'] ?? ''));
  5388. $ph = trim((string)($dr['phone'] ?? ''));
  5389. $toEmail = trim((string)($dr['email'] ?? ''));
  5390. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5391. Log::write('采购确认邮件跳过:无有效邮箱 company=' . $cname, 'error');
  5392. return;
  5393. }
  5394. $detailId = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5395. if ($detailId <= 0) {
  5396. $detailId = (int)($confirmNotifyVars['_fallback_detail_id'] ?? 0);
  5397. }
  5398. try {
  5399. $platformUrl = $this->buildMprocMobileOrderUrl($detailId);
  5400. } catch (\Throwable $e) {
  5401. Log::write('采购确认邮件链接失败: ' . $e->getMessage(), 'error');
  5402. $platformUrl = '';
  5403. }
  5404. $vars = array_merge($confirmNotifyVars, [
  5405. 'company_name' => $cname,
  5406. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5407. 'phone' => $ph,
  5408. 'email' => $toEmail,
  5409. 'platform_url' => $platformUrl,
  5410. ]);
  5411. unset($vars['_fallback_detail_id']);
  5412. try {
  5413. $mailPlain = $this->renderNotifyTemplate($emailScene, $vars);
  5414. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  5415. $mailSubject = $this->resolveProcuremenEmailSubject($emailScene);
  5416. $mailConfig = $this->loadMailerConfig();
  5417. $this->issueSendSupplierEmail([
  5418. 'company_name' => $cname,
  5419. 'email' => $toEmail,
  5420. 'mail_plain' => $mailPlain,
  5421. 'mail_body' => $mailBody,
  5422. 'notify_vars' => $vars,
  5423. 'sms_content' => '',
  5424. 'detail_links' => $platformUrl !== '' ? [['url' => $platformUrl, 'cgymc' => '']] : [],
  5425. 'email_log_scene' => (strpos((string)$emailScene, 'confirm_ok') !== false) ? 'confirm_ok' : 'confirm_fail',
  5426. 'email_log_scydgy_id' => (int)($dr['scydgy_id'] ?? 0),
  5427. 'email_log_purchase_order_id' => $poIdLog,
  5428. ], $mailConfig, $mailSubject);
  5429. } catch (\Throwable $e) {
  5430. Log::write('采购确认邮件失败 company=' . $cname . ' email=' . $toEmail . ' ' . $e->getMessage(), 'error');
  5431. }
  5432. };
  5433. $confirmNotifyVars['_fallback_detail_id'] = $fallbackDetailId;
  5434. foreach ($winners as $dr) {
  5435. $cname = trim((string)($dr['company_name'] ?? ''));
  5436. $ph = trim((string)($dr['phone'] ?? ''));
  5437. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  5438. 'company_name' => $cname,
  5439. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5440. 'phone' => $ph,
  5441. ]));
  5442. $sendSmsSafe($ph, $sms);
  5443. $sendConfirmEmailSafe($dr, 'confirm_ok_email');
  5444. }
  5445. foreach ($losers as $dr) {
  5446. $cname = trim((string)($dr['company_name'] ?? ''));
  5447. $ph = trim((string)($dr['phone'] ?? ''));
  5448. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  5449. 'company_name' => $cname,
  5450. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5451. 'phone' => $ph,
  5452. ]));
  5453. $sendSmsSafe($ph, $sms);
  5454. $sendConfirmEmailSafe($dr, 'confirm_fail_email');
  5455. }
  5456. }
  5457. /**
  5458. * 短信去重键:优先手机号,否则公司名
  5459. */
  5460. protected function notifySupplierDedupeKey(array $detailRow): string
  5461. {
  5462. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  5463. if ($ph !== '') {
  5464. return 'p:' . $ph;
  5465. }
  5466. $cn = trim((string)($detailRow['company_name'] ?? ''));
  5467. return 'c:' . $cn;
  5468. }
  5469. /**
  5470. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  5471. *
  5472. * @param int[] $detailIds
  5473. */
  5474. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  5475. {
  5476. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  5477. if ($detailIds === []) {
  5478. return;
  5479. }
  5480. $payload = ['status_name' => $statusName];
  5481. try {
  5482. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  5483. } catch (\Throwable $e) {
  5484. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  5485. }
  5486. }
  5487. /**
  5488. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  5489. */
  5490. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  5491. {
  5492. try {
  5493. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  5494. } catch (\Throwable $e) {
  5495. return;
  5496. }
  5497. if (!is_array($rows)) {
  5498. return;
  5499. }
  5500. foreach ($rows as $dr) {
  5501. if (!is_array($dr)) {
  5502. continue;
  5503. }
  5504. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5505. if ($id <= 0) {
  5506. continue;
  5507. }
  5508. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  5509. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  5510. try {
  5511. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  5512. } catch (\Throwable $e) {
  5513. }
  5514. }
  5515. }
  5516. /**
  5517. * @param array<string, mixed> $detailRow
  5518. */
  5519. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  5520. {
  5521. $am = $detailRow['amount'] ?? null;
  5522. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  5523. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  5524. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  5525. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  5526. }
  5527. /**
  5528. * @return int[]
  5529. */
  5530. protected function purchaseOrderDetail(int $scydgyId): array
  5531. {
  5532. if (!$this->isValidScydgyRowId($scydgyId)) {
  5533. return [];
  5534. }
  5535. try {
  5536. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  5537. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  5538. $list = $listQuery->select();
  5539. } catch (\Throwable $e) {
  5540. return [];
  5541. }
  5542. if (!is_array($list)) {
  5543. return [];
  5544. }
  5545. $ids = [];
  5546. foreach ($list as $r) {
  5547. if (!is_array($r)) {
  5548. continue;
  5549. }
  5550. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  5551. if ($pk > 0) {
  5552. $ids[] = $pk;
  5553. }
  5554. }
  5555. return array_values(array_unique($ids));
  5556. }
  5557. /**
  5558. * 获取当前登录用户信息 [id, 展示名]
  5559. * admin_name 一律记「名称」(昵称),无昵称再回退账号
  5560. */
  5561. protected function GetUseName(): array
  5562. {
  5563. $id = 0;
  5564. $name = '';
  5565. try {
  5566. if ($this->auth && $this->auth->isLogin()) {
  5567. $u = $this->auth->getUserInfo();
  5568. if (is_array($u)) {
  5569. $id = (int)($u['id'] ?? 0);
  5570. $name = trim((string)($u['nickname'] ?? ''));
  5571. // 会话昵称缺失或等于登录账号时,再查库取正式昵称
  5572. $sessionUser = trim((string)($u['username'] ?? ''));
  5573. if ($id > 0 && ($name === '' || ($sessionUser !== '' && strcasecmp($name, $sessionUser) === 0))) {
  5574. try {
  5575. $row = Db::name('admin')->where('id', $id)->field('nickname,username')->find();
  5576. if (is_array($row)) {
  5577. $nick = trim((string)($row['nickname'] ?? ''));
  5578. if ($nick !== '') {
  5579. $name = $nick;
  5580. } elseif ($name === '') {
  5581. $name = trim((string)($row['username'] ?? ''));
  5582. }
  5583. }
  5584. } catch (\Throwable $e) {
  5585. }
  5586. }
  5587. if ($name === '') {
  5588. $name = $sessionUser;
  5589. }
  5590. }
  5591. }
  5592. } catch (\Throwable $e) {
  5593. }
  5594. if ($name === '') {
  5595. $name = '未知用户';
  5596. }
  5597. return [$id, $name];
  5598. }
  5599. /**
  5600. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  5601. */
  5602. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  5603. {
  5604. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  5605. }
  5606. /**
  5607. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  5608. *
  5609. * @param array<int, array<string, mixed>> $rows
  5610. */
  5611. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  5612. {
  5613. $sidList = [];
  5614. foreach ($rows as $rw) {
  5615. if (!is_array($rw)) {
  5616. continue;
  5617. }
  5618. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5619. foreach ($rw['_order_merge_rows'] as $mr) {
  5620. $mid = (int)($mr['ID'] ?? 0);
  5621. if ($this->isValidScydgyRowId($mid)) {
  5622. $sidList[$mid] = true;
  5623. }
  5624. }
  5625. }
  5626. $id = (int)($rw['ID'] ?? 0);
  5627. if ($this->isValidScydgyRowId($id)) {
  5628. $sidList[$id] = true;
  5629. }
  5630. }
  5631. $sids = array_keys($sidList);
  5632. $issueBySid = [];
  5633. $confirmBySid = [];
  5634. $approveBySid = [];
  5635. if ($sids !== []) {
  5636. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  5637. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  5638. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  5639. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  5640. try {
  5641. $logs = Db::table('purchase_order_oper_log')
  5642. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  5643. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  5644. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  5645. ->order('id', 'asc')
  5646. ->select();
  5647. } catch (\Throwable $e) {
  5648. $logs = [];
  5649. }
  5650. if (is_array($logs)) {
  5651. $issueSet = array_fill_keys($issueActs, true);
  5652. $confirmSet = array_fill_keys($confirmActs, true);
  5653. $approveSet = array_fill_keys($approveActs, true);
  5654. foreach ($logs as $lg) {
  5655. if (!is_array($lg)) {
  5656. continue;
  5657. }
  5658. $lg = ProcuremenOperLog::normalizeRow($lg);
  5659. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  5660. if ($sid === 0) {
  5661. continue;
  5662. }
  5663. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  5664. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  5665. if ($t === '') {
  5666. continue;
  5667. }
  5668. if (isset($issueSet[$action])) {
  5669. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  5670. $issueBySid[$sid] = $t;
  5671. }
  5672. }
  5673. if (isset($confirmSet[$action])) {
  5674. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  5675. $confirmBySid[$sid] = $t;
  5676. }
  5677. }
  5678. if (isset($approveSet[$action])) {
  5679. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  5680. $approveBySid[$sid] = $t;
  5681. }
  5682. }
  5683. }
  5684. }
  5685. }
  5686. foreach ($rows as &$rw) {
  5687. if (!is_array($rw)) {
  5688. continue;
  5689. }
  5690. $mergeSids = [];
  5691. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5692. foreach ($rw['_order_merge_rows'] as $mr) {
  5693. $mid = (int)($mr['ID'] ?? 0);
  5694. if ($this->isValidScydgyRowId($mid)) {
  5695. $mergeSids[] = $mid;
  5696. }
  5697. }
  5698. }
  5699. $rid = (int)($rw['ID'] ?? 0);
  5700. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  5701. $mergeSids[] = $rid;
  5702. }
  5703. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  5704. $issue = $pick;
  5705. $confirm = '';
  5706. $approve = '';
  5707. foreach ($mergeSids as $sid) {
  5708. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  5709. $issue = $issueBySid[$sid];
  5710. }
  5711. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  5712. $confirm = $confirmBySid[$sid];
  5713. }
  5714. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  5715. $approve = $approveBySid[$sid];
  5716. }
  5717. }
  5718. if ($issue === '' && $pick !== '') {
  5719. $issue = $pick;
  5720. }
  5721. $rw['issue_time'] = $issue;
  5722. $rw['confirm_time'] = $confirm;
  5723. $rw['approve_time'] = $approve;
  5724. }
  5725. unset($rw);
  5726. }
  5727. /**
  5728. * 按主键取一条
  5729. */
  5730. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  5731. {
  5732. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  5733. return [];
  5734. }
  5735. try {
  5736. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  5737. if (is_array($one)) {
  5738. return $one;
  5739. }
  5740. } catch (\Throwable $e) {
  5741. }
  5742. try {
  5743. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  5744. if (is_array($one)) {
  5745. return $one;
  5746. }
  5747. } catch (\Throwable $e) {
  5748. }
  5749. return [];
  5750. }
  5751. /**
  5752. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  5753. */
  5754. protected function formatProcuremenDetailTime($v): string
  5755. {
  5756. if ($v === null || $v === '') {
  5757. return '';
  5758. }
  5759. if (is_numeric($v) && (int)$v > 946684800) {
  5760. return date('Y-m-d H:i:s', (int)$v);
  5761. }
  5762. return ProcuremenTime::formatDisplayDateTime($v);
  5763. }
  5764. /**
  5765. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  5766. */
  5767. protected function formatDeliveryYmd($v): string
  5768. {
  5769. if ($v === null || $v === '') {
  5770. return '';
  5771. }
  5772. $s = trim((string)$v);
  5773. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  5774. return '';
  5775. }
  5776. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5777. return $m[1];
  5778. }
  5779. $ts = strtotime($s);
  5780. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  5781. }
  5782. /**
  5783. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  5784. */
  5785. protected function detailRowSupplierOperated(array $r): bool
  5786. {
  5787. $am = $r['amount'] ?? null;
  5788. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5789. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5790. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5791. return $okAmt || $okDel;
  5792. }
  5793. /**
  5794. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  5795. */
  5796. protected function resolveDetailSupplierOperTime(array $r): string
  5797. {
  5798. if (!$this->detailRowSupplierOperated($r)) {
  5799. return '';
  5800. }
  5801. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  5802. if ($t !== '') {
  5803. return $t;
  5804. }
  5805. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  5806. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  5807. continue;
  5808. }
  5809. $t = $this->formatProcuremenDetailTime($r[$col]);
  5810. if ($t !== '') {
  5811. return $t;
  5812. }
  5813. }
  5814. return '';
  5815. }
  5816. /**
  5817. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  5818. */
  5819. protected function detailRowSupplierAccepted(array $r): bool
  5820. {
  5821. $am = $r['amount'] ?? null;
  5822. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5823. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5824. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5825. return $okAmt && $okDel;
  5826. }
  5827. /**
  5828. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  5829. */
  5830. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  5831. {
  5832. if ($detailCount > 0) {
  5833. return true;
  5834. }
  5835. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  5836. return true;
  5837. }
  5838. $pickTime = trim((string)($main['pick_time'] ?? ''));
  5839. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  5840. return true;
  5841. }
  5842. return false;
  5843. }
  5844. /**
  5845. * 下发时间:优先 pick_time,其次首条下发明细时间
  5846. */
  5847. protected function resolveProcuremenIssueTime(array $main, array $details): string
  5848. {
  5849. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  5850. if ($issueTime !== '') {
  5851. return $issueTime;
  5852. }
  5853. foreach ($details as $dr) {
  5854. if (!is_array($dr)) {
  5855. continue;
  5856. }
  5857. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5858. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  5859. $issueTime = $t;
  5860. }
  5861. }
  5862. if ($issueTime !== '') {
  5863. return $issueTime;
  5864. }
  5865. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5866. }
  5867. /**
  5868. * 直接点「完结」时间:优先操作记录 mark_complete
  5869. */
  5870. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  5871. {
  5872. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  5873. }
  5874. /**
  5875. * 操作记录时间(取指定 action 最近一条)
  5876. *
  5877. * @param string|array<int, string> $actions
  5878. */
  5879. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  5880. {
  5881. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  5882. }
  5883. /**
  5884. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  5885. *
  5886. * @param array $main purchase_order 一行
  5887. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  5888. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  5889. */
  5890. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  5891. {
  5892. $issueCnt = count($details);
  5893. $acceptCnt = 0;
  5894. $pickedName = '';
  5895. $pickedTime = '';
  5896. foreach ($details as $dr) {
  5897. if (!is_array($dr)) {
  5898. continue;
  5899. }
  5900. if ($this->detailRowSupplierAccepted($dr)) {
  5901. $acceptCnt++;
  5902. }
  5903. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5904. if ($pickedName === '') {
  5905. $pickedName = trim((string)($dr['company_name'] ?? ''));
  5906. }
  5907. if ($pickedTime === '') {
  5908. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  5909. if ($pickedTime === '') {
  5910. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5911. }
  5912. }
  5913. }
  5914. }
  5915. $hasMain = $main !== [];
  5916. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  5917. if ($poTime === '') {
  5918. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  5919. }
  5920. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  5921. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  5922. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  5923. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  5924. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  5925. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  5926. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  5927. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  5928. $inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
  5929. $inboundResult = '';
  5930. if ($scydgyId > 0) {
  5931. try {
  5932. $inRow = Db::table('purchase_order_inbound_score')
  5933. ->where('scydgy_id', $scydgyId)
  5934. ->field('result,updatetime,createtime')
  5935. ->find();
  5936. } catch (\Throwable $e) {
  5937. $inRow = null;
  5938. }
  5939. if (is_array($inRow) && $inRow !== []) {
  5940. $inboundResult = trim((string)($inRow['result'] ?? ''));
  5941. if ($inboundScoreTime === '') {
  5942. $inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
  5943. }
  5944. }
  5945. }
  5946. $inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
  5947. $supplierTime = '';
  5948. if ($acceptCnt > 0) {
  5949. foreach ($details as $dr) {
  5950. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  5951. continue;
  5952. }
  5953. $t = $this->resolveDetailSupplierOperTime($dr);
  5954. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  5955. $supplierTime = $t;
  5956. }
  5957. }
  5958. }
  5959. $directComplete = ($mainCompleted && !$issued);
  5960. $doneTime = '';
  5961. if ($mainCompleted) {
  5962. if ($directComplete) {
  5963. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  5964. }
  5965. if ($doneTime === '' && $inboundScoreTime !== '') {
  5966. $doneTime = $inboundScoreTime;
  5967. }
  5968. if ($doneTime === '') {
  5969. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5970. }
  5971. if ($doneTime === '') {
  5972. foreach ($details as $dr) {
  5973. if (!is_array($dr)) {
  5974. continue;
  5975. }
  5976. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  5977. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  5978. $doneTime = $t;
  5979. }
  5980. }
  5981. }
  5982. if ($doneTime === '') {
  5983. $doneTime = $poTime;
  5984. }
  5985. // 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
  5986. if ($doneTime === '' && $confirmApproveTime !== '') {
  5987. $doneTime = $confirmApproveTime;
  5988. }
  5989. }
  5990. if ($directComplete) {
  5991. // 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
  5992. $step1Done = $hasMain;
  5993. $step2Done = false;
  5994. $step3Done = false;
  5995. $step4Done = false;
  5996. $step5Done = false;
  5997. $stepInboundDone = $inboundScored;
  5998. $step6Done = $mainCompleted && $inboundScored;
  5999. } else {
  6000. $step1Done = $issued;
  6001. $step2Done = $issued;
  6002. $step3Done = $acceptCnt > 0;
  6003. $step4Done = $wflowPendingApproval;
  6004. if (!$step4Done) {
  6005. foreach ($details as $dr) {
  6006. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  6007. $step4Done = true;
  6008. break;
  6009. }
  6010. }
  6011. }
  6012. $step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
  6013. $stepInboundDone = $inboundScored;
  6014. // 未确认合格/不合格时,「已完结」保持未点亮(灰色)
  6015. $step6Done = $mainCompleted && $inboundScored;
  6016. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  6017. if ($mainCompleted && $issued) {
  6018. $step3Done = true;
  6019. $step4Done = true;
  6020. $step5Done = true;
  6021. // 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
  6022. if ($supplierTime === '') {
  6023. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6024. if ($fillT !== '') {
  6025. $supplierTime = $fillT;
  6026. }
  6027. }
  6028. if ($pickedTime === '') {
  6029. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6030. if ($fillT !== '') {
  6031. $pickedTime = $fillT;
  6032. }
  6033. }
  6034. if ($auditSelectTime === '') {
  6035. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6036. if ($fillT !== '') {
  6037. $auditSelectTime = $fillT;
  6038. }
  6039. }
  6040. if ($confirmApproveTime === '') {
  6041. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6042. if ($fillT !== '') {
  6043. $confirmApproveTime = $fillT;
  6044. }
  6045. }
  6046. }
  6047. }
  6048. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  6049. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  6050. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  6051. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  6052. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  6053. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  6054. $inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
  6055. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  6056. $deadlineLines = [];
  6057. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  6058. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  6059. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  6060. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  6061. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  6062. }
  6063. }
  6064. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  6065. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  6066. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  6067. if ($deliveryDisp === '') {
  6068. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  6069. }
  6070. if ($deliveryDisp !== '') {
  6071. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  6072. }
  6073. }
  6074. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  6075. $deadlineText = implode("\n", $deadlineLines);
  6076. $prefixOperTime = static function (string $t): string {
  6077. $t = trim($t);
  6078. if ($t === '' || $t === '—') {
  6079. return $t;
  6080. }
  6081. if (strpos($t, '操作时间') === 0) {
  6082. return $t;
  6083. }
  6084. return '操作时间:' . $t;
  6085. };
  6086. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  6087. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  6088. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
  6089. $stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  6090. $step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  6091. $steps = [
  6092. [
  6093. 'title' => '未发',
  6094. 'subtitle' => '',
  6095. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  6096. 'done' => $step1Done,
  6097. ],
  6098. [
  6099. 'title' => '下发',
  6100. 'subtitle' => $deadlineText,
  6101. 'time' => $prefixOperTime($step2Time),
  6102. 'done' => $step2Done,
  6103. ],
  6104. [
  6105. 'title' => '供应商接单',
  6106. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  6107. 'time' => '',
  6108. 'done' => $step3Done,
  6109. ],
  6110. [
  6111. 'title' => '待确认',
  6112. 'subtitle' => $step4Done
  6113. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  6114. : ($issued ? '待选供应商' : ''),
  6115. 'time' => $prefixOperTime($step4Time),
  6116. 'done' => $step4Done,
  6117. ],
  6118. [
  6119. 'title' => '待审批',
  6120. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  6121. 'time' => $prefixOperTime($step5Time),
  6122. 'done' => $step5Done,
  6123. ],
  6124. [
  6125. 'title' => '是否合格',
  6126. 'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
  6127. 'time' => $prefixOperTime($stepInboundTime),
  6128. 'done' => $stepInboundDone,
  6129. ],
  6130. [
  6131. 'title' => '已完结',
  6132. 'subtitle' => '',
  6133. 'time' => $prefixOperTime($step6Time),
  6134. 'done' => $step6Done,
  6135. ],
  6136. ];
  6137. $currentIdx = count($steps) - 1;
  6138. if ($directComplete) {
  6139. // 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
  6140. if (!$step6Done) {
  6141. foreach ($steps as $i => $s) {
  6142. if (($s['title'] ?? '') === '是否合格') {
  6143. $currentIdx = $i;
  6144. break;
  6145. }
  6146. }
  6147. }
  6148. } else {
  6149. foreach ($steps as $i => $s) {
  6150. if (!$s['done']) {
  6151. $currentIdx = $i;
  6152. break;
  6153. }
  6154. }
  6155. }
  6156. $nSteps = count($steps);
  6157. foreach ($steps as $idx => &$s) {
  6158. $s['current'] = ($idx === $currentIdx);
  6159. if ($idx === 0) {
  6160. $s['pdf_left_bg'] = '';
  6161. } else {
  6162. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  6163. }
  6164. if ($idx >= $nSteps - 1) {
  6165. $s['pdf_right_bg'] = '';
  6166. } else {
  6167. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  6168. }
  6169. }
  6170. unset($s);
  6171. $labelMap = [
  6172. 'CCYDH' => '订单号',
  6173. 'CYJMC' => '印件名称',
  6174. 'CCLBMMC' => '承揽部门',
  6175. 'CGYMC' => '工序名称',
  6176. 'CDW' => '单位',
  6177. 'czlyq' => '类型',
  6178. 'NGZL' => '工作量',
  6179. 'CDF' => '单价',
  6180. 'cGzzxMc' => '工作中心',
  6181. 'MBZ' => '招标备注',
  6182. 'This_quantity' => '本次数量',
  6183. 'ceilingPrice' => '最高限价',
  6184. ];
  6185. $orderSummary = [];
  6186. foreach ($labelMap as $key => $lab) {
  6187. if (!array_key_exists($key, $main)) {
  6188. continue;
  6189. }
  6190. $val = $main[$key];
  6191. if ($val === null) {
  6192. $val = '';
  6193. } elseif (!is_scalar($val)) {
  6194. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  6195. } else {
  6196. $val = (string)$val;
  6197. }
  6198. $orderSummary[] = ['label' => $lab, 'value' => $val];
  6199. }
  6200. $orderSummary[] = [
  6201. 'label' => '是否合格',
  6202. 'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
  6203. ];
  6204. $orderSummaryGrid = [];
  6205. $n = count($orderSummary);
  6206. for ($i = 0; $i < $n; $i += 2) {
  6207. $left = $orderSummary[$i];
  6208. $hasRight = ($i + 1) < $n;
  6209. $orderSummaryGrid[] = [
  6210. 'l1' => $left['label'],
  6211. 'v1' => $left['value'],
  6212. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  6213. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  6214. ];
  6215. }
  6216. return [
  6217. 'steps' => $steps,
  6218. 'orderSummary' => $orderSummary,
  6219. 'orderSummaryGrid' => $orderSummaryGrid,
  6220. 'inbound_result' => $inboundResult,
  6221. 'inbound_score_time'=> $inboundScoreTime,
  6222. 'detailRows' => $details,
  6223. ];
  6224. }
  6225. /**
  6226. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  6227. *
  6228. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  6229. */
  6230. protected function prepareProcuremenDetailsView(string $ids): array
  6231. {
  6232. $main = [];
  6233. try {
  6234. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  6235. $main = is_array($one) ? $one : [];
  6236. } catch (\Throwable $e) {
  6237. $main = [];
  6238. }
  6239. $details = [];
  6240. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  6241. if ($mergeRows === []) {
  6242. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  6243. if ($mergeRows === [] && $main !== []) {
  6244. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  6245. }
  6246. }
  6247. $detailSidList = [];
  6248. $anchorSid = (int)$ids;
  6249. if ($anchorSid !== 0) {
  6250. $detailSidList[$anchorSid] = true;
  6251. }
  6252. foreach ($mergeRows as $mr) {
  6253. if (!is_array($mr)) {
  6254. continue;
  6255. }
  6256. $sid = $this->extractScydgyRowId($mr);
  6257. if ($sid !== 0) {
  6258. $detailSidList[$sid] = true;
  6259. }
  6260. }
  6261. try {
  6262. if ($detailSidList !== []) {
  6263. $details = Db::table('purchase_order_detail')
  6264. ->where('scydgy_id', 'in', array_keys($detailSidList))
  6265. ->order('id', 'asc')
  6266. ->select();
  6267. }
  6268. } catch (\Throwable $e) {
  6269. $details = [];
  6270. }
  6271. if (!is_array($details)) {
  6272. $details = [];
  6273. }
  6274. foreach ($details as &$r) {
  6275. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  6276. $r['id'] = $r['ID'];
  6277. }
  6278. if (isset($r['createtime'])) {
  6279. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  6280. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  6281. } else {
  6282. $r['createtime_text'] = (string)$r['createtime'];
  6283. }
  6284. } else {
  6285. $r['createtime_text'] = '';
  6286. }
  6287. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  6288. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  6289. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  6290. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  6291. if (is_array($r)) {
  6292. $r = $this->maskSupplierContactFields($r);
  6293. }
  6294. }
  6295. unset($r);
  6296. $activeDetails = [];
  6297. foreach ($details as $r) {
  6298. if (is_array($r) && empty($r['is_void'])) {
  6299. $activeDetails[] = $r;
  6300. }
  6301. }
  6302. $operLogs = [];
  6303. try {
  6304. $operSidList = array_keys($detailSidList);
  6305. if ($operSidList === [] && (int)$ids !== 0) {
  6306. $operSidList = [(int)$ids];
  6307. }
  6308. if ($operSidList !== []) {
  6309. $operLogs = Db::table('purchase_order_oper_log')
  6310. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  6311. ->order('id', 'asc')
  6312. ->select();
  6313. }
  6314. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  6315. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  6316. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  6317. if ($poId > 0) {
  6318. $operLogs = Db::table('purchase_order_oper_log')
  6319. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  6320. ->order('id', 'asc')
  6321. ->select();
  6322. }
  6323. }
  6324. } catch (\Throwable $e) {
  6325. $operLogs = [];
  6326. }
  6327. if (!is_array($operLogs)) {
  6328. $operLogs = [];
  6329. }
  6330. $operLogsRaw = $operLogs;
  6331. $processNameBySid = [];
  6332. foreach ($mergeRows as $mr) {
  6333. if (!is_array($mr)) {
  6334. continue;
  6335. }
  6336. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  6337. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  6338. if ($psid !== 0 && $gymc !== '') {
  6339. $processNameBySid[$psid] = $gymc;
  6340. }
  6341. }
  6342. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  6343. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
  6344. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  6345. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  6346. if ($ccydh === '') {
  6347. foreach ($details as $r) {
  6348. if (!is_array($r)) {
  6349. continue;
  6350. }
  6351. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  6352. if ($ccydh !== '') {
  6353. break;
  6354. }
  6355. }
  6356. }
  6357. $this->view->assign('ccydh', $ccydh);
  6358. $this->view->assign('steps', $bundle['steps']);
  6359. $this->view->assign('orderSummary', $bundle['orderSummary']);
  6360. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  6361. $this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
  6362. $this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
  6363. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  6364. $this->view->assign('processCount', count($mergeRows));
  6365. $this->view->assign('detailRows', $details);
  6366. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  6367. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  6368. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  6369. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  6370. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  6371. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  6372. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  6373. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  6374. $this->view->assign('operLogs', $operLogs);
  6375. $sg = $quoteView['supplier_groups'] ?? [];
  6376. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
  6377. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  6378. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
  6379. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
  6380. return [
  6381. 'ok' => $main !== [] || $details !== [],
  6382. 'ccydh' => $ccydh,
  6383. 'steps' => $bundle['steps'],
  6384. ];
  6385. }
  6386. /**
  6387. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  6388. */
  6389. public function details()
  6390. {
  6391. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6392. if (is_array($ids)) {
  6393. $ids = isset($ids[0]) ? $ids[0] : '';
  6394. }
  6395. $ids = trim((string)$ids);
  6396. if ($ids === '') {
  6397. $this->error(__('Invalid parameters'));
  6398. }
  6399. $this->assertManualOrderDetailsViewable((int)$ids);
  6400. // 已完结:打开详情时按最新进度/操作记录重存存证 PDF(含质量/交货评分)
  6401. $sid = (int)$ids;
  6402. if ($this->isValidScydgyRowId($sid)) {
  6403. try {
  6404. $poCheck = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  6405. if (is_array($poCheck) && ProcuremenStatus::isPoCompleted($poCheck['status'] ?? '')) {
  6406. $this->refreshCompletedOrderArchivePdf($sid, true);
  6407. }
  6408. } catch (\Throwable $e) {
  6409. Log::write('详情页刷新完结存证PDF失败 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'notice');
  6410. }
  6411. }
  6412. $this->prepareProcuremenDetailsView($ids);
  6413. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  6414. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  6415. $this->view->engine->layout(false);
  6416. try {
  6417. return $this->view->fetch('procuremen/details_dialog_shell');
  6418. } finally {
  6419. if ($restoreLayout) {
  6420. $this->view->engine->layout($restoreLayout);
  6421. }
  6422. }
  6423. }
  6424. /**
  6425. * 已完结订单重生成存证 PDF(与详情页一致,含质量/交货评分与「已完结」节点)
  6426. *
  6427. * @param bool $requireCompleted true 时仅已完结才重生成;false 强制按当前详情重存
  6428. * @return string 本地 web 路径或 OSS URL,失败为空串
  6429. */
  6430. protected function refreshCompletedOrderArchivePdf(int $scydgyId, bool $requireCompleted = true): string
  6431. {
  6432. if (!$this->isValidScydgyRowId($scydgyId)) {
  6433. return '';
  6434. }
  6435. try {
  6436. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6437. } catch (\Throwable $e) {
  6438. $po = null;
  6439. }
  6440. if (!is_array($po) || $po === []) {
  6441. return '';
  6442. }
  6443. if ($requireCompleted && !ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6444. return trim((string)($po['pdf_url'] ?? ''));
  6445. }
  6446. $poId = (int)($po['id'] ?? 0);
  6447. return $this->savePurchaseConfirmDetailPdf($scydgyId, $poId);
  6448. }
  6449. /**
  6450. * CLI / 手机端评分完结后调用:无后台登录态重生成存证 PDF
  6451. */
  6452. public static function regenerateArchivePdfWithoutAuth(int $scydgyId, bool $requireCompleted = true): string
  6453. {
  6454. if ((int)$scydgyId === 0) {
  6455. return '';
  6456. }
  6457. try {
  6458. $ctl = new class extends Procuremen {
  6459. public function _initialize()
  6460. {
  6461. $this->request = \think\Request::instance();
  6462. $tpl = \think\Config::get('template');
  6463. if (!is_array($tpl)) {
  6464. $tpl = [];
  6465. }
  6466. // CLI / 跨模块调用时无 admin 视图目录
  6467. $tpl['view_path'] = APP_PATH . 'admin' . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR;
  6468. $this->view = new \think\View($tpl, \think\Config::get('view_replace_str'));
  6469. $this->model = new \app\admin\model\Procuremen();
  6470. try {
  6471. ProcuremenSchema::ensureAll();
  6472. } catch (\Throwable $e) {
  6473. }
  6474. }
  6475. public function runRegen(int $sid, bool $requireCompleted): string
  6476. {
  6477. return $this->refreshCompletedOrderArchivePdf($sid, $requireCompleted);
  6478. }
  6479. };
  6480. return $ctl->runRegen($scydgyId, $requireCompleted);
  6481. } catch (\Throwable $e) {
  6482. Log::write('regenerateArchivePdfWithoutAuth 失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'error');
  6483. return '';
  6484. }
  6485. }
  6486. /**
  6487. * 解析合并下发工序行(可跨订单,且均未协助)
  6488. *
  6489. * @return array<int, array<string, mixed>>
  6490. */
  6491. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  6492. {
  6493. $primary = json_decode($rowJson, true);
  6494. if (!is_array($primary)) {
  6495. $this->error(__('Invalid parameters'));
  6496. }
  6497. $merge = json_decode($mergeRowsJson, true);
  6498. if (!is_array($merge) || $merge === []) {
  6499. $merge = [$primary];
  6500. }
  6501. $seen = [];
  6502. $out = [];
  6503. foreach ($merge as $r) {
  6504. if (!is_array($r)) {
  6505. continue;
  6506. }
  6507. $id = $this->extractScydgyRowId($r);
  6508. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  6509. continue;
  6510. }
  6511. $seen[$id] = true;
  6512. $out[] = $r;
  6513. }
  6514. if ($out === []) {
  6515. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  6516. }
  6517. // 允许多订单同批下发:不再校验订单号一致
  6518. $ids = [];
  6519. foreach ($out as $r) {
  6520. $id = $this->extractScydgyRowId($r);
  6521. if ($this->isValidScydgyRowId($id)) {
  6522. $ids[$id] = true;
  6523. }
  6524. }
  6525. $poBySid = [];
  6526. $detCntBySid = [];
  6527. if ($ids !== []) {
  6528. $idList = array_keys($ids);
  6529. try {
  6530. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  6531. if (is_array($poList)) {
  6532. foreach ($poList as $po) {
  6533. if (!is_array($po)) {
  6534. continue;
  6535. }
  6536. $sid = (int)($po['scydgy_id'] ?? 0);
  6537. if ($this->isValidScydgyRowId($sid)) {
  6538. $poBySid[$sid] = $po;
  6539. }
  6540. }
  6541. }
  6542. } catch (\Throwable $e) {
  6543. }
  6544. try {
  6545. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  6546. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  6547. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  6548. if (is_array($detRows)) {
  6549. foreach ($detRows as $dr) {
  6550. if (!is_array($dr)) {
  6551. continue;
  6552. }
  6553. $sid = (int)($dr['scydgy_id'] ?? 0);
  6554. if ($this->isValidScydgyRowId($sid)) {
  6555. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  6556. }
  6557. }
  6558. }
  6559. } catch (\Throwable $e) {
  6560. }
  6561. }
  6562. foreach ($out as $r) {
  6563. $id = $this->extractScydgyRowId($r);
  6564. if (!$this->isValidScydgyRowId($id)) {
  6565. continue;
  6566. }
  6567. $po = $poBySid[$id] ?? null;
  6568. if (!is_array($po)) {
  6569. continue;
  6570. }
  6571. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6572. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6573. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  6574. }
  6575. $detCnt = (int)($detCntBySid[$id] ?? 0);
  6576. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  6577. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6578. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  6579. }
  6580. }
  6581. return $out;
  6582. }
  6583. /**
  6584. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  6585. */
  6586. protected function maskSupplierContactFields(array $item): array
  6587. {
  6588. if (array_key_exists('email', $item)) {
  6589. $item['email'] = mask_email((string)$item['email']);
  6590. }
  6591. if (array_key_exists('phone', $item)) {
  6592. $item['phone'] = mask_phone((string)$item['phone']);
  6593. }
  6594. return $item;
  6595. }
  6596. /**
  6597. * @param array<int, array<string, mixed>> $list
  6598. * @return array<int, array<string, mixed>>
  6599. */
  6600. protected function maskSupplierContactList(array $list): array
  6601. {
  6602. $out = [];
  6603. foreach ($list as $item) {
  6604. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  6605. }
  6606. return $out;
  6607. }
  6608. /**
  6609. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  6610. *
  6611. * @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
  6612. * @return array<string, string>|null
  6613. */
  6614. protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
  6615. {
  6616. if (!is_array($row)) {
  6617. return null;
  6618. }
  6619. $norm = [];
  6620. foreach ($row as $k => $v) {
  6621. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  6622. }
  6623. $row = $norm;
  6624. $st = $row['status'] ?? '';
  6625. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  6626. return null;
  6627. }
  6628. $companyName = '';
  6629. foreach (['company_name', 'name'] as $nk) {
  6630. if (!empty($row[$nk])) {
  6631. $companyName = trim((string)$row[$nk]);
  6632. break;
  6633. }
  6634. }
  6635. if ($companyName === '') {
  6636. return null;
  6637. }
  6638. $username = '';
  6639. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  6640. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  6641. $username = trim((string)$row[$uk]);
  6642. break;
  6643. }
  6644. }
  6645. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  6646. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  6647. if ($phone === '' && isset($row['account'])) {
  6648. $phone = trim((string)$row['account']);
  6649. }
  6650. if ($phone === '' && isset($row['mobile'])) {
  6651. $phone = trim((string)$row['mobile']);
  6652. }
  6653. if ($requireContactChannels && $email === '' && $phone === '') {
  6654. return null;
  6655. }
  6656. $category = '';
  6657. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6658. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6659. $category = trim((string)$row[$ck]);
  6660. break;
  6661. }
  6662. }
  6663. return [
  6664. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  6665. 'name' => $companyName,
  6666. 'company_name' => $companyName,
  6667. 'username' => $username,
  6668. 'email' => $email,
  6669. 'phone' => $phone,
  6670. 'category' => $category,
  6671. 'company_type' => $category,
  6672. 'can_select' => ($email !== '' && $phone !== '') ? 1 : 0,
  6673. ];
  6674. }
  6675. /**
  6676. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  6677. */
  6678. protected function resolveCustomerContactById(string $id): ?array
  6679. {
  6680. $id = trim($id);
  6681. if ($id === '' || !ctype_digit($id)) {
  6682. return null;
  6683. }
  6684. try {
  6685. $row = Db::table('customer')->where('id', (int)$id)->find();
  6686. } catch (\Throwable $e) {
  6687. return null;
  6688. }
  6689. return $this->buildCustomerContactPayloadFromRow($row);
  6690. }
  6691. /**
  6692. * 按供应商名称解析联系信息(兼容旧提交数据)
  6693. *
  6694. * @param bool $requireContactChannels true 时须有邮箱或手机
  6695. */
  6696. protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
  6697. {
  6698. $name = trim($name);
  6699. if ($name === '') {
  6700. return null;
  6701. }
  6702. try {
  6703. // customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
  6704. $row = Db::table('customer')
  6705. ->where('company_name', $name)
  6706. ->order('id', 'desc')
  6707. ->find();
  6708. } catch (\Throwable $e) {
  6709. return null;
  6710. }
  6711. return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
  6712. }
  6713. /**
  6714. * 规范化下发/确认时勾选的供应商
  6715. *
  6716. * @param array<int, mixed> $companies
  6717. * @return array<int, array<string, string>>
  6718. */
  6719. protected function normalizePickCompanies(array $companies): array
  6720. {
  6721. $out = [];
  6722. foreach ($companies as $c) {
  6723. if (!is_array($c)) {
  6724. continue;
  6725. }
  6726. $resolved = null;
  6727. $cid = trim((string)($c['id'] ?? ''));
  6728. if ($cid !== '') {
  6729. $resolved = $this->resolveCustomerContactById($cid);
  6730. }
  6731. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  6732. if ($resolved === null && $name !== '') {
  6733. $resolved = $this->resolveCustomerContactByCompanyName($name);
  6734. }
  6735. if ($resolved === null) {
  6736. continue;
  6737. }
  6738. $email = trim((string)($resolved['email'] ?? ''));
  6739. $phone = trim((string)($resolved['phone'] ?? ''));
  6740. // 下发须同时有邮箱和手机号(与初选弹窗可选规则一致)
  6741. if ($email === '' || $phone === '') {
  6742. continue;
  6743. }
  6744. $out[] = $resolved;
  6745. }
  6746. return $out;
  6747. }
  6748. /**
  6749. * 同一次下发批次的时间(优先 pick_time,空则 createtime)
  6750. */
  6751. protected function procuremenIssueBatchTime(array $row): string
  6752. {
  6753. $t = $this->procuremenRowListSortTime($row, 'pick_time');
  6754. if ($t !== '') {
  6755. return $t;
  6756. }
  6757. $t = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  6758. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  6759. return $t;
  6760. }
  6761. return '';
  6762. }
  6763. /**
  6764. * 读取下发批次号(兼容旧字段 issue_batch_no)
  6765. *
  6766. * @param array<string, mixed> $row
  6767. */
  6768. protected function resolveProcuremenOrderBatchNo(array $row): string
  6769. {
  6770. foreach (['order_batch_no', 'issue_batch_no'] as $k) {
  6771. $v = trim((string)($row[$k] ?? ''));
  6772. if ($v !== '') {
  6773. return $v;
  6774. }
  6775. }
  6776. return '';
  6777. }
  6778. /**
  6779. * @param int[] $sidList
  6780. * @return array<int, string> scydgy_id => MBZ
  6781. */
  6782. protected function loadScydgyMbzByIds(array $sidList): array
  6783. {
  6784. $ids = [];
  6785. foreach ($sidList as $sid) {
  6786. $sid = (int)$sid;
  6787. if ($this->isValidScydgyRowId($sid)) {
  6788. $ids[$sid] = true;
  6789. }
  6790. }
  6791. if ($ids === []) {
  6792. return [];
  6793. }
  6794. try {
  6795. $map = Db::table('scydgy')->where('ID', 'in', array_keys($ids))->column('MBZ', 'ID');
  6796. } catch (\Throwable $e) {
  6797. return [];
  6798. }
  6799. return is_array($map) ? $map : [];
  6800. }
  6801. /**
  6802. * purchase_order / 列表行 MBZ 为空时,回退 ERP 工序表 scydgy.MBZ
  6803. *
  6804. * @param array<int, array<string, mixed>> $rows
  6805. */
  6806. protected function enrichProcuremenRowsMbz(array &$rows): void
  6807. {
  6808. if ($rows === []) {
  6809. return;
  6810. }
  6811. $need = [];
  6812. foreach ($rows as $r) {
  6813. if (!is_array($r)) {
  6814. continue;
  6815. }
  6816. if (trim((string)($r['MBZ'] ?? $r['mbz'] ?? '')) !== '') {
  6817. continue;
  6818. }
  6819. $sid = $this->extractScydgyRowId($r);
  6820. if ($this->isValidScydgyRowId($sid)) {
  6821. $need[$sid] = true;
  6822. }
  6823. }
  6824. if ($need === []) {
  6825. return;
  6826. }
  6827. $mbzMap = $this->loadScydgyMbzByIds(array_keys($need));
  6828. if ($mbzMap === []) {
  6829. return;
  6830. }
  6831. foreach ($rows as &$r) {
  6832. if (!is_array($r)) {
  6833. continue;
  6834. }
  6835. if (trim((string)($r['MBZ'] ?? $r['mbz'] ?? '')) !== '') {
  6836. continue;
  6837. }
  6838. $sid = $this->extractScydgyRowId($r);
  6839. if (!$this->isValidScydgyRowId($sid) || !isset($mbzMap[$sid])) {
  6840. continue;
  6841. }
  6842. $mbz = trim((string)$mbzMap[$sid]);
  6843. if ($mbz !== '') {
  6844. $r['MBZ'] = $mbz;
  6845. }
  6846. }
  6847. unset($r);
  6848. }
  6849. /**
  6850. * 列表/弹窗合并键:优先正式批次号 order_batch_no;
  6851. * 旧数据无批次号时回退为「同一订单号 + 同一次下发时间」。
  6852. */
  6853. protected function procuremenIssueBatchGroupKey(array $row): string
  6854. {
  6855. $batchNo = $this->resolveProcuremenOrderBatchNo($row);
  6856. if ($batchNo !== '') {
  6857. return 'bn:' . $batchNo;
  6858. }
  6859. $dh = trim((string)($row['CCYDH'] ?? ''));
  6860. $sid = (int)($row['scydgy_id'] ?? $row['ID'] ?? $row['id'] ?? 0);
  6861. if ($dh === '') {
  6862. return '_id_' . $sid;
  6863. }
  6864. $batch = $this->procuremenIssueBatchTime($row);
  6865. return $batch !== '' ? ($dh . '|' . $batch) : ($dh . '|sid:' . $sid);
  6866. }
  6867. /**
  6868. * 是否同一次下发(同批次号,或旧数据同订单号且下发时间一致)
  6869. */
  6870. protected function isSameProcuremenIssueBatch(array $anchor, array $po): bool
  6871. {
  6872. return $this->procuremenIssueBatchGroupKey($anchor) === $this->procuremenIssueBatchGroupKey($po);
  6873. }
  6874. /**
  6875. * @param array<int, mixed> $pos
  6876. * @return array<int, array<string, mixed>>
  6877. */
  6878. protected function filterPurchaseOrdersSameIssueBatch(array $pos, array $anchor): array
  6879. {
  6880. $out = [];
  6881. foreach ($pos as $po) {
  6882. if (is_array($po) && $this->isSameProcuremenIssueBatch($anchor, $po)) {
  6883. $out[] = $po;
  6884. }
  6885. }
  6886. return $out !== [] ? $out : [$anchor];
  6887. }
  6888. /**
  6889. * 确认供应商列表:同一订单号且同一次下发才合并为一行
  6890. *
  6891. * @param array<int, array<string, mixed>> $pool
  6892. * @return array<int, array<string, mixed>>
  6893. */
  6894. protected function collapseProcuremenPoolByOrder(array $pool): array
  6895. {
  6896. if ($pool === []) {
  6897. return [];
  6898. }
  6899. $groups = [];
  6900. foreach ($pool as $row) {
  6901. if (!is_array($row)) {
  6902. continue;
  6903. }
  6904. $key = $this->procuremenIssueBatchGroupKey($row);
  6905. if (!isset($groups[$key])) {
  6906. $groups[$key] = [];
  6907. }
  6908. $groups[$key][] = $row;
  6909. }
  6910. $out = [];
  6911. foreach ($groups as $ccydh => $rows) {
  6912. if ($rows === []) {
  6913. continue;
  6914. }
  6915. usort($rows, function ($a, $b) {
  6916. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  6917. });
  6918. $head = $rows[0];
  6919. $gymcList = [];
  6920. foreach ($rows as $r) {
  6921. $g = trim((string)($r['CGYMC'] ?? ''));
  6922. if ($g !== '' && !in_array($g, $gymcList, true)) {
  6923. $gymcList[] = $g;
  6924. }
  6925. }
  6926. $merged = $head;
  6927. $orderDhList = [];
  6928. $nameList = [];
  6929. foreach ($rows as $r) {
  6930. if (!is_array($r)) {
  6931. continue;
  6932. }
  6933. $odh = trim((string)($r['CCYDH'] ?? ''));
  6934. if ($odh !== '' && !in_array($odh, $orderDhList, true)) {
  6935. $orderDhList[] = $odh;
  6936. }
  6937. $onm = trim((string)($r['CYJMC'] ?? ''));
  6938. if ($onm !== '' && !in_array($onm, $nameList, true)) {
  6939. $nameList[] = $onm;
  6940. }
  6941. }
  6942. $orderDh = $orderDhList !== [] ? implode('、', $orderDhList) : trim((string)($head['CCYDH'] ?? ''));
  6943. $merged['CCYDH'] = $orderDh;
  6944. $merged['order_key'] = $orderDh;
  6945. if ($nameList !== []) {
  6946. $merged['CYJMC'] = implode('、', $nameList);
  6947. }
  6948. $merged['order_batch_no'] = $this->resolveProcuremenOrderBatchNo($head);
  6949. $merged['process_count'] = count($rows);
  6950. $merged['_order_merge_rows'] = $rows;
  6951. $qtyList = [];
  6952. $priceList = [];
  6953. foreach ($rows as $r) {
  6954. if (!is_array($r)) {
  6955. continue;
  6956. }
  6957. $qtyList[] = $this->resolveProcuremenThisQuantity($r);
  6958. $priceList[] = $this->resolveProcuremenCeilingPrice($r);
  6959. }
  6960. if (count($rows) > 1) {
  6961. $merged['CGYMC'] = implode('、', $gymcList);
  6962. // 多工序:数量/限价按有值项顿号间隔(空值不占位)
  6963. $merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  6964. $merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  6965. } else {
  6966. $merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
  6967. $merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
  6968. }
  6969. // 已选供应商:取合并行中首个非空 pick_company_name
  6970. $pickedName = '';
  6971. foreach ($rows as $r) {
  6972. if (!is_array($r)) {
  6973. continue;
  6974. }
  6975. $pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
  6976. if ($pn !== '') {
  6977. $pickedName = $pn;
  6978. break;
  6979. }
  6980. }
  6981. if ($pickedName !== '') {
  6982. $merged['pick_company_name'] = $pickedName;
  6983. $merged['picked_supplier_name'] = $pickedName;
  6984. }
  6985. $mergedPickTime = '';
  6986. foreach ($rows as $r) {
  6987. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  6988. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  6989. $mergedPickTime = $t;
  6990. }
  6991. }
  6992. if ($mergedPickTime !== '') {
  6993. $merged['pick_time'] = $mergedPickTime;
  6994. }
  6995. $out[] = $merged;
  6996. }
  6997. usort($out, function ($a, $b) {
  6998. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  6999. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  7000. if ($ta === $tb) {
  7001. $ida = (int)($a['purchase_order_id'] ?? 0);
  7002. $idb = (int)($b['purchase_order_id'] ?? 0);
  7003. if ($ida !== $idb) {
  7004. return $idb <=> $ida;
  7005. }
  7006. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  7007. }
  7008. if ($ta === '') {
  7009. return 1;
  7010. }
  7011. if ($tb === '') {
  7012. return -1;
  7013. }
  7014. return strcmp($tb, $ta);
  7015. });
  7016. return $out;
  7017. }
  7018. /**
  7019. * 待确认供应商:同一次下发批次的工序(优先 order_batch_no;旧数据回退同订单+同下发时间)
  7020. *
  7021. * @return array{ccydh:string, order_batch_no?:string, pos:array<int,array>, merge_rows:array<int,array>}
  7022. */
  7023. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  7024. {
  7025. $scydgyId = trim($scydgyId);
  7026. $empty = ['ccydh' => '', 'order_batch_no' => '', 'pos' => [], 'merge_rows' => []];
  7027. if ($scydgyId === '') {
  7028. return $empty;
  7029. }
  7030. try {
  7031. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7032. } catch (\Throwable $e) {
  7033. $anchor = null;
  7034. }
  7035. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  7036. return $empty;
  7037. }
  7038. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7039. $batchNo = $this->resolveProcuremenOrderBatchNo($anchor);
  7040. try {
  7041. if ($batchNo !== '') {
  7042. $pos = Db::table('purchase_order')
  7043. ->where('order_batch_no', $batchNo)
  7044. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())
  7045. ->order('scydgy_id', 'asc')
  7046. ->select();
  7047. } elseif ($ccydh !== '') {
  7048. $pos = Db::table('purchase_order')
  7049. ->where('CCYDH', $ccydh)
  7050. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())
  7051. ->order('scydgy_id', 'asc')
  7052. ->select();
  7053. } else {
  7054. $pos = [$anchor];
  7055. }
  7056. } catch (\Throwable $e) {
  7057. $pos = [$anchor];
  7058. }
  7059. if (!is_array($pos) || $pos === []) {
  7060. $pos = [$anchor];
  7061. }
  7062. $pos = $this->filterPurchaseOrdersSameIssueBatch($pos, $anchor);
  7063. return [
  7064. 'ccydh' => $ccydh,
  7065. 'order_batch_no' => $batchNo,
  7066. 'pos' => $pos,
  7067. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  7068. ];
  7069. }
  7070. /**
  7071. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  7072. */
  7073. protected function purchaseOrderRowInConfirmStage(array $po): bool
  7074. {
  7075. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  7076. return false;
  7077. }
  7078. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  7079. return false;
  7080. }
  7081. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  7082. return true;
  7083. }
  7084. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  7085. $sid = (int)($po['scydgy_id'] ?? 0);
  7086. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  7087. }
  7088. return false;
  7089. }
  7090. /**
  7091. * 采购确认:同一次下发批次的待审批工序(优先 order_batch_no)
  7092. *
  7093. * @return array{ccydh:string, order_batch_no?:string, pos:array<int,array>, merge_rows:array<int,array>}
  7094. */
  7095. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  7096. {
  7097. $scydgyId = trim($scydgyId);
  7098. $empty = ['ccydh' => '', 'order_batch_no' => '', 'pos' => [], 'merge_rows' => []];
  7099. if ($scydgyId === '') {
  7100. return $empty;
  7101. }
  7102. try {
  7103. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7104. } catch (\Throwable $e) {
  7105. $anchor = null;
  7106. }
  7107. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  7108. return $empty;
  7109. }
  7110. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7111. $batchNo = $this->resolveProcuremenOrderBatchNo($anchor);
  7112. try {
  7113. if ($batchNo !== '') {
  7114. $posQuery = Db::table('purchase_order')->where('order_batch_no', $batchNo);
  7115. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  7116. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  7117. } elseif ($ccydh !== '') {
  7118. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  7119. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  7120. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  7121. } else {
  7122. $pos = [$anchor];
  7123. }
  7124. } catch (\Throwable $e) {
  7125. $pos = [$anchor];
  7126. }
  7127. if (!is_array($pos) || $pos === []) {
  7128. $pos = [$anchor];
  7129. }
  7130. $pos = array_values(array_filter($pos, function ($po) {
  7131. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  7132. }));
  7133. if ($pos === []) {
  7134. $pos = [$anchor];
  7135. }
  7136. $pos = $this->filterPurchaseOrdersSameIssueBatch($pos, $anchor);
  7137. return [
  7138. 'ccydh' => $ccydh,
  7139. 'order_batch_no' => $batchNo,
  7140. 'pos' => $pos,
  7141. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  7142. ];
  7143. }
  7144. /**
  7145. * @param array<int, array<string, mixed>> $purchaseOrders
  7146. * @return array<int, array<string, mixed>>
  7147. */
  7148. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  7149. {
  7150. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  7151. $byId = [];
  7152. foreach ($pool as $r) {
  7153. if (!is_array($r)) {
  7154. continue;
  7155. }
  7156. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  7157. if ($this->isValidScydgyRowId($sid)) {
  7158. $byId[$sid] = $r;
  7159. }
  7160. }
  7161. $out = [];
  7162. foreach ($purchaseOrders as $po) {
  7163. if (!is_array($po)) {
  7164. continue;
  7165. }
  7166. $sid = (int)($po['scydgy_id'] ?? 0);
  7167. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  7168. $out[] = $byId[$sid];
  7169. }
  7170. }
  7171. $this->enrichProcuremenRowsMbz($out);
  7172. return $out;
  7173. }
  7174. /**
  7175. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  7176. *
  7177. * @return array<int, array<string, mixed>>
  7178. */
  7179. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  7180. {
  7181. $scydgyId = trim($scydgyId);
  7182. if ($scydgyId === '') {
  7183. return [];
  7184. }
  7185. try {
  7186. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7187. } catch (\Throwable $e) {
  7188. $anchor = null;
  7189. }
  7190. if (!is_array($anchor)) {
  7191. return [];
  7192. }
  7193. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  7194. return [];
  7195. }
  7196. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7197. $batchNo = $this->resolveProcuremenOrderBatchNo($anchor);
  7198. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  7199. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  7200. try {
  7201. $q = Db::table('purchase_order');
  7202. if ($batchNo !== '') {
  7203. $q->where('order_batch_no', $batchNo);
  7204. } elseif ($ccydh !== '' && $isValidPick) {
  7205. $q->where('CCYDH', $ccydh)->where('pick_time', $pickTime);
  7206. } else {
  7207. $q->where('scydgy_id', $scydgyId);
  7208. }
  7209. $pos = $q->order('scydgy_id', 'asc')->select();
  7210. } catch (\Throwable $e) {
  7211. $pos = [$anchor];
  7212. }
  7213. if (!is_array($pos) || $pos === []) {
  7214. $pos = [$anchor];
  7215. }
  7216. $pos = array_values(array_filter($pos, function ($po) {
  7217. if (!is_array($po)) {
  7218. return false;
  7219. }
  7220. $mr = $po['mod_rq'] ?? null;
  7221. if ($mr === null || $mr === '') {
  7222. return true;
  7223. }
  7224. $mrs = trim((string)$mr);
  7225. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  7226. }));
  7227. if ($pos === []) {
  7228. $pos = [$anchor];
  7229. }
  7230. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  7231. if ($rows === []) {
  7232. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  7233. }
  7234. return $rows;
  7235. }
  7236. /**
  7237. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  7238. *
  7239. * @param array<int, array<string, mixed>> $mergeRows
  7240. * @return array<int, array<string, mixed>>
  7241. */
  7242. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  7243. {
  7244. $list = array_values($mergeRows);
  7245. $n = count($list);
  7246. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  7247. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  7248. $mergeSame = $n > 1 && $orderKey0 !== '';
  7249. if ($mergeSame) {
  7250. foreach ($list as $rr) {
  7251. if (!is_array($rr)) {
  7252. $mergeSame = false;
  7253. break;
  7254. }
  7255. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  7256. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  7257. $mergeSame = false;
  7258. break;
  7259. }
  7260. }
  7261. }
  7262. $out = [];
  7263. foreach ($list as $idx => $r) {
  7264. if (!is_array($r)) {
  7265. continue;
  7266. }
  7267. $qty = $this->resolveProcuremenThisQuantity($r);
  7268. $price = $this->resolveProcuremenCeilingPrice($r);
  7269. $sid = $this->extractScydgyRowId($r);
  7270. $out[] = [
  7271. 'seq' => $idx + 1,
  7272. 'scydgy_id' => $sid,
  7273. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  7274. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  7275. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  7276. 'CDW' => trim((string)($r['CDW'] ?? '')),
  7277. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  7278. 'NGZL' => $r['NGZL'] ?? '',
  7279. 'This_quantity' => $qty,
  7280. 'ceilingPrice' => $price,
  7281. 'CDF' => trim((string)($r['CDF'] ?? '')),
  7282. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  7283. 'show_order_cells' => !$mergeSame || $idx === 0,
  7284. 'order_rowspan' => $mergeSame ? $n : 1,
  7285. ];
  7286. }
  7287. return $out;
  7288. }
  7289. /**
  7290. * 解析金额/数量(去千分位等非数字字符)
  7291. */
  7292. protected function parseProcuremenMoneyNumber($value): ?float
  7293. {
  7294. if ($value === null || $value === '') {
  7295. return null;
  7296. }
  7297. if (is_numeric($value)) {
  7298. return (float)$value;
  7299. }
  7300. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  7301. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  7302. }
  7303. protected function formatProcuremenMoneyDisplay(?float $amount): string
  7304. {
  7305. if ($amount === null) {
  7306. return '';
  7307. }
  7308. // 保留小数(最多 5 位),去掉末尾无意义的 0,避免 0.25 被显示成 0
  7309. $s = rtrim(rtrim(sprintf('%.5F', (float)$amount), '0'), '.');
  7310. return $s === '' ? '0' : $s;
  7311. }
  7312. /**
  7313. * 列表/详情展示:工作量为 0 时显示空
  7314. */
  7315. protected function formatProcuremenWorkloadDisplay($value): string
  7316. {
  7317. if ($value === null || $value === '') {
  7318. return '';
  7319. }
  7320. $s = trim((string)$value);
  7321. if ($s === '') {
  7322. return '';
  7323. }
  7324. if (is_numeric($s) && (float)$s == 0) {
  7325. return '';
  7326. }
  7327. return $s;
  7328. }
  7329. /**
  7330. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  7331. */
  7332. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  7333. {
  7334. foreach ($details as $d) {
  7335. if (!is_array($d)) {
  7336. continue;
  7337. }
  7338. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  7339. $cn = trim((string)($d['company_name'] ?? ''));
  7340. if ($cn !== '') {
  7341. return $cn;
  7342. }
  7343. }
  7344. }
  7345. return trim((string)($main['pick_company_name'] ?? ''));
  7346. }
  7347. /**
  7348. * 详情报价小计:单价 × 本工序本次数量
  7349. */
  7350. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  7351. {
  7352. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  7353. if ($unit === null) {
  7354. return null;
  7355. }
  7356. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  7357. if ($qty === null || $qty <= 0) {
  7358. return null;
  7359. }
  7360. return $unit * $qty;
  7361. }
  7362. /**
  7363. * 详情页:工序小计 + 供应商分组报价与总计
  7364. *
  7365. * @param array<int, array<string, mixed>> $mergeRows
  7366. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  7367. * @return array{
  7368. * process_rows: array,
  7369. * supplier_groups: array,
  7370. * order_total_text: string,
  7371. * order_total_has: bool,
  7372. * selected_company: string
  7373. * }
  7374. */
  7375. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  7376. {
  7377. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  7378. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  7379. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
  7380. || ((int)($main['manual_pick'] ?? 0) === 1);
  7381. $orderMbz = trim((string)($main['MBZ'] ?? $main['mbz'] ?? ''));
  7382. if ($orderMbz === '') {
  7383. $orderMbz = $this->resolveBundleOrderMbz(['pos' => [$main], 'merge_rows' => $mergeRows]);
  7384. }
  7385. $qtyBySid = [];
  7386. $gymcBySid = [];
  7387. $ccydhBySid = [];
  7388. $orderedSids = [];
  7389. foreach ($mergeRows as $mr) {
  7390. if (!is_array($mr)) {
  7391. continue;
  7392. }
  7393. $sid = $this->extractScydgyRowId($mr);
  7394. if ($this->isValidScydgyRowId($sid)) {
  7395. $orderedSids[] = $sid;
  7396. }
  7397. $qty = trim((string)($mr['This_quantity'] ?? ''));
  7398. if ($qty === '') {
  7399. $qty = trim((string)($mr['NGZL'] ?? ''));
  7400. }
  7401. $qtyBySid[$sid] = $qty;
  7402. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  7403. $dh = trim((string)($mr['CCYDH'] ?? ''));
  7404. if ($dh !== '') {
  7405. $ccydhBySid[$sid] = $dh;
  7406. }
  7407. }
  7408. $mainCcydh = trim((string)($main['CCYDH'] ?? $ccydh));
  7409. if ($mainCcydh !== '') {
  7410. foreach ($orderedSids as $sid) {
  7411. if (empty($ccydhBySid[$sid])) {
  7412. $ccydhBySid[$sid] = $mainCcydh;
  7413. }
  7414. }
  7415. }
  7416. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  7417. $detailByCompanySid = [];
  7418. foreach ($details as $d) {
  7419. if (!is_array($d)) {
  7420. continue;
  7421. }
  7422. $cn = trim((string)($d['company_name'] ?? ''));
  7423. $sid = (int)($d['scydgy_id'] ?? 0);
  7424. if ($cn === '' || $sid === 0) {
  7425. continue;
  7426. }
  7427. if (!isset($detailByCompanySid[$cn])) {
  7428. $detailByCompanySid[$cn] = [];
  7429. }
  7430. $detailByCompanySid[$cn][$sid] = $d;
  7431. }
  7432. $supplierGroups = [];
  7433. foreach ($detailByCompanySid as $cn => $bySid) {
  7434. $lines = [];
  7435. $groupTotal = 0.0;
  7436. $groupHas = false;
  7437. $groupVoid = true;
  7438. $usedSids = [];
  7439. $appendLine = function (int $sid, array $d) use (
  7440. &$lines,
  7441. &$groupTotal,
  7442. &$groupHas,
  7443. &$groupVoid,
  7444. $qtyBySid,
  7445. $gymcBySid,
  7446. $ccydhBySid,
  7447. $quoteVisible
  7448. ) {
  7449. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  7450. if (!$isVoid) {
  7451. $groupVoid = false;
  7452. }
  7453. $qtyStr = $qtyBySid[$sid] ?? '';
  7454. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  7455. $am = trim((string)($d['amount'] ?? ''));
  7456. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  7457. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  7458. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  7459. $sub = null;
  7460. if (!$isVoid && $amountNum !== null) {
  7461. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  7462. }
  7463. $ct = $this->resolveDetailSupplierOperTime($d);
  7464. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  7465. $leadFilled = ($leadDays !== null);
  7466. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  7467. $processName = $this->buildSupplierProcessNameFields(
  7468. (string)($ccydhBySid[$sid] ?? ''),
  7469. (string)($gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')))
  7470. );
  7471. $line = array_merge($processName, [
  7472. 'amount' => $am,
  7473. 'unit_price_text' => $amountFilled
  7474. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  7475. : '未填写',
  7476. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  7477. 'delivery_ymd' => $deliveryYmd,
  7478. 'amount_filled' => $amountFilled,
  7479. 'delivery_filled' => $deliveryFilled,
  7480. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  7481. 'lead_days' => $leadFilled ? $leadDays : '',
  7482. 'lead_days_filled'=> $leadFilled,
  7483. 'lead_days_show' => $leadText,
  7484. 'lead_days_text' => $leadText,
  7485. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  7486. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  7487. 'is_void' => $isVoid,
  7488. 'oper_time_text' => $ct,
  7489. ]);
  7490. if (!$quoteVisible && !$isVoid) {
  7491. $this->maskSupplierQuoteLineBeforeDeadline($line);
  7492. } elseif ($sub !== null) {
  7493. $groupTotal += $sub;
  7494. $groupHas = true;
  7495. }
  7496. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  7497. };
  7498. foreach ($orderedSids as $sid) {
  7499. if (!isset($bySid[$sid])) {
  7500. continue;
  7501. }
  7502. $usedSids[$sid] = true;
  7503. $appendLine($sid, $bySid[$sid]);
  7504. }
  7505. foreach ($bySid as $sid => $d) {
  7506. if (isset($usedSids[$sid])) {
  7507. continue;
  7508. }
  7509. $appendLine((int)$sid, $d);
  7510. }
  7511. $firstDetail = null;
  7512. foreach ($bySid as $d) {
  7513. if (is_array($d)) {
  7514. $firstDetail = $d;
  7515. break;
  7516. }
  7517. }
  7518. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  7519. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  7520. if ($username === '' && $ph !== '') {
  7521. $username = $this->resolveCustomerContactName($ph, $cn);
  7522. }
  7523. $remark = '';
  7524. foreach ($bySid as $d) {
  7525. if (!is_array($d)) {
  7526. continue;
  7527. }
  7528. $rm = '';
  7529. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  7530. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  7531. $rm = trim((string)$d[$rk]);
  7532. break;
  7533. }
  7534. }
  7535. if ($rm !== '') {
  7536. $remark = $rm;
  7537. break;
  7538. }
  7539. }
  7540. $lineCount = count($lines);
  7541. $supplierGroup = [
  7542. 'company_name' => $cn,
  7543. 'username' => $username,
  7544. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  7545. 'phone' => $ph,
  7546. 'remark' => $remark,
  7547. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  7548. 'is_void' => $groupVoid,
  7549. 'lines' => $lines,
  7550. 'line_count' => $lineCount,
  7551. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  7552. 'has_total' => $lineCount > 0,
  7553. ];
  7554. $this->finalizeSupplierRemarkDisplay($supplierGroup, $orderMbz, $quoteVisible);
  7555. $supplierGroups[] = $supplierGroup;
  7556. }
  7557. usort($supplierGroups, function ($a, $b) {
  7558. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  7559. return ($a['is_void'] ?? false) ? 1 : -1;
  7560. }
  7561. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  7562. return ($a['is_selected'] ?? false) ? -1 : 1;
  7563. }
  7564. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  7565. });
  7566. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  7567. return [
  7568. 'process_rows' => $processRows,
  7569. 'supplier_groups' => $supplierGroups,
  7570. 'order_total_text' => '',
  7571. 'order_total_has' => false,
  7572. 'selected_company' => $selectedCompany,
  7573. ];
  7574. }
  7575. /**
  7576. * 短信用工序明细。
  7577. * 单订单:仅工序行(订单号/印件名称由模版 {ccydh}{cyjmc} 排版);
  7578. * 多订单同批:每个订单各自输出「订单号 + 印件名称 + 工序列表」,组间空行。
  7579. */
  7580. protected function buildProcessLinesPlain(array $mergeRows): string
  7581. {
  7582. $groups = [];
  7583. foreach ($mergeRows as $r) {
  7584. if (!is_array($r)) {
  7585. continue;
  7586. }
  7587. $dh = trim((string)($r['CCYDH'] ?? ''));
  7588. $key = $dh !== '' ? $dh : ('__sid_' . (int)($r['ID'] ?? $r['id'] ?? $r['scydgy_id'] ?? 0));
  7589. if (!isset($groups[$key])) {
  7590. $groups[$key] = [
  7591. 'ccydh' => $dh,
  7592. 'cyjmc' => trim((string)($r['CYJMC'] ?? '')),
  7593. 'rows' => [],
  7594. ];
  7595. } elseif ($groups[$key]['cyjmc'] === '') {
  7596. $groups[$key]['cyjmc'] = trim((string)($r['CYJMC'] ?? ''));
  7597. }
  7598. $groups[$key]['rows'][] = $r;
  7599. }
  7600. if ($groups === []) {
  7601. return '';
  7602. }
  7603. $multiOrder = count($groups) > 1;
  7604. $blocks = [];
  7605. foreach ($groups as $g) {
  7606. $lines = [];
  7607. if ($multiOrder) {
  7608. if ($g['ccydh'] !== '') {
  7609. $lines[] = '订单号:' . $g['ccydh'];
  7610. }
  7611. if ($g['cyjmc'] !== '') {
  7612. $lines[] = '印件名称:' . $g['cyjmc'];
  7613. }
  7614. }
  7615. $parsed = [];
  7616. $maxNameW = 0;
  7617. foreach ($g['rows'] as $r) {
  7618. $gymc = trim((string)($r['CGYMC'] ?? ''));
  7619. if ($gymc === '') {
  7620. $gymc = '—';
  7621. }
  7622. $w = $this->mbDisplayWidth($gymc);
  7623. if ($w > $maxNameW) {
  7624. $maxNameW = $w;
  7625. }
  7626. $parsed[] = [
  7627. 'gymc' => $gymc,
  7628. 'dw' => trim((string)($r['CDW'] ?? '')),
  7629. 'gzl' => trim((string)($r['NGZL'] ?? '')),
  7630. 'qty' => trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')),
  7631. ];
  7632. }
  7633. $i = 1;
  7634. foreach ($parsed as $p) {
  7635. $namePad = $this->mbPadRight($p['gymc'], $maxNameW);
  7636. $parts = [$i . '.工序名称:' . $namePad];
  7637. if ($p['dw'] !== '') {
  7638. $parts[] = '单位:' . $p['dw'];
  7639. }
  7640. if ($p['gzl'] !== '') {
  7641. $parts[] = '工作量:' . $p['gzl'];
  7642. } elseif ($p['qty'] !== '') {
  7643. $parts[] = '工作量:' . $p['qty'];
  7644. }
  7645. if ($p['qty'] !== '' && $p['gzl'] !== '' && $p['qty'] !== $p['gzl']) {
  7646. $parts[] = '本次数量:' . $p['qty'];
  7647. }
  7648. $lines[] = implode(' ', $parts);
  7649. $i++;
  7650. }
  7651. if ($lines !== []) {
  7652. $blocks[] = implode("\n", $lines);
  7653. }
  7654. }
  7655. return implode("\n\n", $blocks);
  7656. }
  7657. /** 中文友好显示宽度(全角约 2,半角 1) */
  7658. protected function mbDisplayWidth(string $s): int
  7659. {
  7660. if ($s === '') {
  7661. return 0;
  7662. }
  7663. if (function_exists('mb_strwidth')) {
  7664. return (int)mb_strwidth($s, 'UTF-8');
  7665. }
  7666. if (function_exists('mb_strlen')) {
  7667. return (int)mb_strlen($s, 'UTF-8');
  7668. }
  7669. return strlen($s);
  7670. }
  7671. /** 按显示宽度右侧补空格,便于短信/邮件工序行对齐 */
  7672. protected function mbPadRight(string $s, int $width): string
  7673. {
  7674. $cur = $this->mbDisplayWidth($s);
  7675. if ($cur >= $width) {
  7676. return $s;
  7677. }
  7678. return $s . str_repeat(' ', $width - $cur);
  7679. }
  7680. /**
  7681. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  7682. *
  7683. * @return array<string, string>
  7684. */
  7685. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  7686. {
  7687. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  7688. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  7689. }
  7690. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  7691. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  7692. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7693. $cyjmc = '';
  7694. foreach ($mergeRows as $mr) {
  7695. if (!is_array($mr)) {
  7696. continue;
  7697. }
  7698. if ($ccydh === '') {
  7699. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  7700. }
  7701. if ($cyjmc === '') {
  7702. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  7703. }
  7704. }
  7705. if ($pos !== []) {
  7706. $firstPo = $pos[0];
  7707. if (is_array($firstPo)) {
  7708. if ($ccydh === '') {
  7709. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  7710. }
  7711. if ($cyjmc === '') {
  7712. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  7713. }
  7714. }
  7715. }
  7716. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  7717. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  7718. if (is_array($any)) {
  7719. if ($ccydh === '') {
  7720. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  7721. }
  7722. if ($cyjmc === '') {
  7723. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  7724. }
  7725. }
  7726. }
  7727. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  7728. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  7729. $cgymc = '';
  7730. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  7731. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  7732. }
  7733. return [
  7734. 'ccydh' => $ccydh,
  7735. 'cyjmc' => $cyjmc,
  7736. 'cgymc' => $cgymc,
  7737. 'process_lines' => $processLines,
  7738. 'process_lines_html' => '',
  7739. ];
  7740. }
  7741. /**
  7742. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  7743. * 多订单时 processPlain 已含各订单头,不再重复拼订单号/印件名称。
  7744. */
  7745. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  7746. {
  7747. $processPlain = trim($processPlain);
  7748. if ($processPlain !== '' && preg_match('/^订单号:/u', $processPlain)) {
  7749. return $processPlain;
  7750. }
  7751. $lines = [];
  7752. if ($ccydh !== '') {
  7753. $lines[] = '订单号:' . $ccydh;
  7754. }
  7755. if ($cyjmc !== '') {
  7756. $lines[] = '印件名称:' . $cyjmc;
  7757. }
  7758. if ($processPlain !== '') {
  7759. $lines[] = $processPlain;
  7760. }
  7761. return implode("\n", $lines);
  7762. }
  7763. /**
  7764. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  7765. *
  7766. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  7767. */
  7768. protected function buildPlatformLinksPlain(array $detailLinks): string
  7769. {
  7770. $lines = [];
  7771. $i = 1;
  7772. foreach ($detailLinks as $lk) {
  7773. if (!is_array($lk)) {
  7774. continue;
  7775. }
  7776. $url = trim((string)($lk['url'] ?? ''));
  7777. if ($url === '') {
  7778. continue;
  7779. }
  7780. $label = trim((string)($lk['cgymc'] ?? ''));
  7781. if ($label === '') {
  7782. $label = '工序' . $i;
  7783. }
  7784. $lines[] = $label . ':' . $url;
  7785. $i++;
  7786. }
  7787. return implode("\n", $lines);
  7788. }
  7789. /**
  7790. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  7791. *
  7792. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  7793. */
  7794. protected function buildPlatformLinksHtml(array $detailLinks): string
  7795. {
  7796. $parts = [];
  7797. $i = 1;
  7798. foreach ($detailLinks as $lk) {
  7799. if (!is_array($lk)) {
  7800. continue;
  7801. }
  7802. $url = trim((string)($lk['url'] ?? ''));
  7803. if ($url === '') {
  7804. continue;
  7805. }
  7806. $label = trim((string)($lk['cgymc'] ?? ''));
  7807. if ($label === '') {
  7808. $label = '工序' . $i;
  7809. }
  7810. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  7811. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  7812. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  7813. $i++;
  7814. }
  7815. return implode("<br>\n", $parts);
  7816. }
  7817. /**
  7818. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  7819. *
  7820. * @return array<string, mixed>
  7821. */
  7822. protected function loadMailerConfig(): array
  7823. {
  7824. try {
  7825. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  7826. } catch (\Throwable $e) {
  7827. $cfg = [];
  7828. }
  7829. return is_array($cfg) ? $cfg : [];
  7830. }
  7831. protected function loadNotifyTemplateRow(string $scene): ?array
  7832. {
  7833. try {
  7834. $row = Db::table('purchase_sms_template')
  7835. ->where('scene', $scene)
  7836. ->where(function ($q) {
  7837. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  7838. })
  7839. ->order('id', 'asc')
  7840. ->find();
  7841. } catch (\Throwable $e) {
  7842. return null;
  7843. }
  7844. if (!is_array($row) || $row === []) {
  7845. return null;
  7846. }
  7847. return [
  7848. 'title' => trim((string)($row['title'] ?? '')),
  7849. 'content' => trim((string)($row['content'] ?? '')),
  7850. ];
  7851. }
  7852. /**
  7853. * 邮件用工序明细 HTML。
  7854. * 多订单同批时按订单分组;单订单保持原表格/单行样式。
  7855. */
  7856. protected function buildProcessLinesHtml(array $mergeRows): string
  7857. {
  7858. $groups = [];
  7859. foreach ($mergeRows as $r) {
  7860. if (!is_array($r)) {
  7861. continue;
  7862. }
  7863. $dh = trim((string)($r['CCYDH'] ?? ''));
  7864. $key = $dh !== '' ? $dh : ('__sid_' . (int)($r['ID'] ?? $r['id'] ?? $r['scydgy_id'] ?? 0));
  7865. if (!isset($groups[$key])) {
  7866. $groups[$key] = [
  7867. 'ccydh' => $dh,
  7868. 'cyjmc' => trim((string)($r['CYJMC'] ?? '')),
  7869. 'rows' => [],
  7870. ];
  7871. } elseif ($groups[$key]['cyjmc'] === '') {
  7872. $groups[$key]['cyjmc'] = trim((string)($r['CYJMC'] ?? ''));
  7873. }
  7874. $groups[$key]['rows'][] = $r;
  7875. }
  7876. if ($groups === []) {
  7877. return '';
  7878. }
  7879. $multiOrder = count($groups) > 1;
  7880. $flatRows = [];
  7881. foreach ($groups as $g) {
  7882. foreach ($g['rows'] as $r) {
  7883. $flatRows[] = $r;
  7884. }
  7885. }
  7886. if (!$multiOrder && count($flatRows) <= 1) {
  7887. $r = $flatRows[0] ?? [];
  7888. if (!is_array($r)) {
  7889. return '';
  7890. }
  7891. $gymc = trim((string)($r['CGYMC'] ?? ''));
  7892. $dw = trim((string)($r['CDW'] ?? ''));
  7893. $gzl = trim((string)($r['NGZL'] ?? ''));
  7894. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  7895. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  7896. if ($dw !== '') {
  7897. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  7898. }
  7899. if ($gzl !== '') {
  7900. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  7901. }
  7902. if ($qty !== '') {
  7903. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  7904. }
  7905. return $html;
  7906. }
  7907. $blocks = [];
  7908. foreach ($groups as $g) {
  7909. $head = '';
  7910. if ($multiOrder) {
  7911. if ($g['ccydh'] !== '') {
  7912. $head .= '<div style="margin:10px 0 4px;font-weight:700;">订单号:'
  7913. . htmlspecialchars($g['ccydh'], ENT_QUOTES, 'UTF-8') . '</div>';
  7914. }
  7915. if ($g['cyjmc'] !== '') {
  7916. $head .= '<div style="margin:0 0 6px;color:#333;">印件名称:'
  7917. . htmlspecialchars($g['cyjmc'], ENT_QUOTES, 'UTF-8') . '</div>';
  7918. }
  7919. }
  7920. $rows = '';
  7921. $i = 1;
  7922. foreach ($g['rows'] as $r) {
  7923. if (!is_array($r)) {
  7924. continue;
  7925. }
  7926. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  7927. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  7928. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  7929. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  7930. $workload = $gzl !== '' ? $gzl : $qty;
  7931. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  7932. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  7933. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  7934. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($workload !== '' ? $workload : '—') . '</td></tr>';
  7935. $i++;
  7936. }
  7937. if ($rows === '') {
  7938. continue;
  7939. }
  7940. $table = '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:4px 0 12px;font-size:14px;width:100%;max-width:560px;">'
  7941. . '<thead><tr style="background:#f5f5f5;">'
  7942. . '<th style="padding:6px 8px;border:1px solid #ddd;width:48px;">序号</th>'
  7943. . '<th style="padding:6px 8px;border:1px solid #ddd;text-align:left;">工序名称</th>'
  7944. . '<th style="padding:6px 8px;border:1px solid #ddd;width:64px;">单位</th>'
  7945. . '<th style="padding:6px 8px;border:1px solid #ddd;width:88px;">工作量</th>'
  7946. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  7947. $blocks[] = $head . $table;
  7948. }
  7949. return implode('', $blocks);
  7950. }
  7951. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  7952. {
  7953. $sysRq = trim($sysRq);
  7954. if ($sysRq === '') {
  7955. if ($required) {
  7956. $this->error('请选择招标截止日期');
  7957. }
  7958. return '';
  7959. }
  7960. $ts = strtotime($sysRq);
  7961. if ($ts === false || $ts <= 0) {
  7962. $this->error('招标截止日期格式无效');
  7963. }
  7964. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  7965. if (!$allowPast) {
  7966. $ymd = date('Y-m-d', $ts);
  7967. if ($ymd < date('Y-m-d')) {
  7968. $this->error('招标截止日期不能早于今天');
  7969. }
  7970. if ($ts <= time()) {
  7971. $this->error('招标截止时间不能早于当前时间');
  7972. }
  7973. }
  7974. return date('Y-m-d H:i:s', $ts);
  7975. }
  7976. /**
  7977. * 确保 purchase_order.czlyq(类型)存在
  7978. */
  7979. protected function ensurePurchaseOrderCzlyqColumn(): void
  7980. {
  7981. static $done = false;
  7982. if ($done) {
  7983. return;
  7984. }
  7985. $done = true;
  7986. try {
  7987. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  7988. if (empty($cols)) {
  7989. Db::execute(
  7990. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  7991. );
  7992. }
  7993. } catch (\Throwable $e) {
  7994. // ignore
  7995. }
  7996. }
  7997. /**
  7998. * 确保 purchase_order.delivery_deadline 存在
  7999. */
  8000. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  8001. {
  8002. static $done = false;
  8003. if ($done) {
  8004. return;
  8005. }
  8006. $done = true;
  8007. try {
  8008. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  8009. if (empty($cols)) {
  8010. Db::execute(
  8011. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  8012. );
  8013. }
  8014. } catch (\Throwable $e) {
  8015. // ignore
  8016. }
  8017. }
  8018. /**
  8019. * 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
  8020. */
  8021. protected function ensurePurchaseOrderScoreRuleIdColumn(): void
  8022. {
  8023. static $done = false;
  8024. if ($done) {
  8025. return;
  8026. }
  8027. $done = true;
  8028. // 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
  8029. $adds = [
  8030. 'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
  8031. 'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
  8032. 'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
  8033. 'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
  8034. 'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
  8035. ];
  8036. $changed = false;
  8037. foreach ($adds as $col => $ddl) {
  8038. try {
  8039. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  8040. if (!is_array($cols) || $cols === []) {
  8041. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  8042. $changed = true;
  8043. }
  8044. } catch (\Throwable $e) {
  8045. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  8046. }
  8047. }
  8048. if ($changed) {
  8049. $this->clearPurchaseOrderTableFieldsCache();
  8050. }
  8051. }
  8052. /**
  8053. * 确保 purchase_order.order_batch_no(下发批次号)存在
  8054. */
  8055. protected function ensurePurchaseOrderOrderBatchNoColumn(): void
  8056. {
  8057. static $done = false;
  8058. if ($done) {
  8059. return;
  8060. }
  8061. $done = true;
  8062. try {
  8063. $hasNew = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'order_batch_no'");
  8064. if (is_array($hasNew) && $hasNew !== []) {
  8065. return;
  8066. }
  8067. $hasOld = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'issue_batch_no'");
  8068. if (is_array($hasOld) && $hasOld !== []) {
  8069. Db::execute(
  8070. "ALTER TABLE `purchase_order` CHANGE COLUMN `issue_batch_no` `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号(如XH202608240001)'"
  8071. );
  8072. try {
  8073. Db::execute('ALTER TABLE `purchase_order` DROP INDEX `idx_issue_batch_no`');
  8074. } catch (\Throwable $eDrop) {
  8075. }
  8076. try {
  8077. Db::execute('ALTER TABLE `purchase_order` ADD INDEX `idx_order_batch_no` (`order_batch_no`)');
  8078. } catch (\Throwable $eIdx) {
  8079. }
  8080. } else {
  8081. Db::execute(
  8082. "ALTER TABLE `purchase_order` ADD COLUMN `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号(如XH202608240001)'"
  8083. );
  8084. try {
  8085. Db::execute('ALTER TABLE `purchase_order` ADD INDEX `idx_order_batch_no` (`order_batch_no`)');
  8086. } catch (\Throwable $eIdx) {
  8087. }
  8088. }
  8089. $this->clearPurchaseOrderTableFieldsCache();
  8090. } catch (\Throwable $e) {
  8091. Log::write('purchase_order.order_batch_no: ' . $e->getMessage(), 'error');
  8092. }
  8093. }
  8094. /** @deprecated 兼容旧调用 */
  8095. protected function ensurePurchaseOrderIssueBatchNoColumn(): void
  8096. {
  8097. $this->ensurePurchaseOrderOrderBatchNoColumn();
  8098. }
  8099. /**
  8100. * 批次号日流水表:取号时立刻落库递增,避免并发下发撞号
  8101. */
  8102. protected function ensurePurchaseIssueBatchSeqTable(): void
  8103. {
  8104. static $done = false;
  8105. if ($done) {
  8106. return;
  8107. }
  8108. $done = true;
  8109. try {
  8110. Db::execute(
  8111. "CREATE TABLE IF NOT EXISTS `purchase_issue_batch_seq` (
  8112. `ymd` char(8) NOT NULL COMMENT '日期Ymd',
  8113. `last_no` int unsigned NOT NULL DEFAULT 0 COMMENT '当日已分配最大流水',
  8114. `updatetime` datetime DEFAULT NULL,
  8115. PRIMARY KEY (`ymd`)
  8116. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助下发批次号日流水'"
  8117. );
  8118. } catch (\Throwable $e) {
  8119. Log::write('purchase_issue_batch_seq: ' . $e->getMessage(), 'error');
  8120. }
  8121. }
  8122. /**
  8123. * 生成下发批次号:XH + Ymd + 当日4位流水(如 XH202608240001)
  8124. * 必须拿到日锁后先递增流水表再返回,避免两笔下发同时取到同一号。
  8125. *
  8126. * @throws \RuntimeException
  8127. */
  8128. protected function allocateProcuremenIssueBatchNo(): string
  8129. {
  8130. $this->ensurePurchaseOrderOrderBatchNoColumn();
  8131. $this->ensurePurchaseIssueBatchSeqTable();
  8132. $ymd = date('Ymd');
  8133. $prefix = 'XH' . $ymd;
  8134. $lockName = 'procuremen_issue_batch_' . $ymd;
  8135. if (!$this->acquireProcuremenNamedLock($lockName, 15)) {
  8136. throw new \RuntimeException('批次号生成繁忙,请稍后重试');
  8137. }
  8138. try {
  8139. $last = 0;
  8140. $hasSeqRow = false;
  8141. try {
  8142. $row = Db::table('purchase_issue_batch_seq')->where('ymd', $ymd)->find();
  8143. if (is_array($row) && $row !== []) {
  8144. $hasSeqRow = true;
  8145. $last = (int)($row['last_no'] ?? 0);
  8146. }
  8147. } catch (\Throwable $e) {
  8148. $last = 0;
  8149. }
  8150. // 兼容:流水表为空时,用已有 purchase_order.order_batch_no 最大值对齐
  8151. try {
  8152. $maxPo = Db::table('purchase_order')
  8153. ->where('order_batch_no', 'like', $prefix . '%')
  8154. ->order('order_batch_no', 'desc')
  8155. ->value('order_batch_no');
  8156. if (is_string($maxPo) && preg_match('/^XH\d{8}(\d{4})$/', $maxPo, $m)) {
  8157. $last = max($last, (int)$m[1]);
  8158. }
  8159. } catch (\Throwable $e) {
  8160. }
  8161. $seq = $last + 1;
  8162. if ($seq < 1) {
  8163. $seq = 1;
  8164. }
  8165. if ($seq > 9999) {
  8166. throw new \RuntimeException('当日批次号已用尽,请联系管理员');
  8167. }
  8168. $now = date('Y-m-d H:i:s');
  8169. try {
  8170. if ($hasSeqRow) {
  8171. Db::table('purchase_issue_batch_seq')->where('ymd', $ymd)->update([
  8172. 'last_no' => $seq,
  8173. 'updatetime' => $now,
  8174. ]);
  8175. } else {
  8176. try {
  8177. Db::table('purchase_issue_batch_seq')->insert([
  8178. 'ymd' => $ymd,
  8179. 'last_no' => $seq,
  8180. 'updatetime' => $now,
  8181. ]);
  8182. } catch (\Throwable $eIns) {
  8183. Db::table('purchase_issue_batch_seq')->where('ymd', $ymd)->update([
  8184. 'last_no' => $seq,
  8185. 'updatetime' => $now,
  8186. ]);
  8187. }
  8188. }
  8189. } catch (\Throwable $e) {
  8190. throw new \RuntimeException('批次号写入失败,请重试');
  8191. }
  8192. return $prefix . str_pad((string)$seq, 4, '0', STR_PAD_LEFT);
  8193. } finally {
  8194. $this->releaseProcuremenNamedLock($lockName);
  8195. }
  8196. }
  8197. /**
  8198. * ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
  8199. */
  8200. protected function clearPurchaseOrderTableFieldsCache(): void
  8201. {
  8202. try {
  8203. $db = (string)Config::get('database.database');
  8204. $key = $db . '.purchase_order';
  8205. $ref = new \ReflectionProperty(\think\db\Query::class, 'info');
  8206. $ref->setAccessible(true);
  8207. $info = $ref->getValue();
  8208. if (is_array($info) && isset($info[$key])) {
  8209. unset($info[$key]);
  8210. $ref->setValue(null, $info);
  8211. }
  8212. } catch (\Throwable $e) {
  8213. }
  8214. try {
  8215. $db = (string)Config::get('database.database');
  8216. $schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
  8217. if (is_file($schemaFile)) {
  8218. @unlink($schemaFile);
  8219. }
  8220. } catch (\Throwable $e) {
  8221. }
  8222. }
  8223. /**
  8224. * @return array<string, bool>
  8225. */
  8226. protected function loadPurchaseOrderColumnSet(): array
  8227. {
  8228. static $set = null;
  8229. if (is_array($set)) {
  8230. return $set;
  8231. }
  8232. $set = [];
  8233. try {
  8234. $cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
  8235. } catch (\Throwable $e) {
  8236. return $set;
  8237. }
  8238. if (!is_array($cols)) {
  8239. return $set;
  8240. }
  8241. foreach ($cols as $c) {
  8242. if (!is_array($c)) {
  8243. continue;
  8244. }
  8245. $f = (string)($c['Field'] ?? $c['field'] ?? '');
  8246. if ($f !== '') {
  8247. $set[$f] = true;
  8248. }
  8249. }
  8250. return $set;
  8251. }
  8252. /**
  8253. * 解析交货截止日期(仅年月日)
  8254. */
  8255. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  8256. {
  8257. $raw = trim($raw);
  8258. if ($raw === '') {
  8259. if ($required) {
  8260. $this->error('请选择交货截止日期');
  8261. }
  8262. return '';
  8263. }
  8264. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  8265. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  8266. } else {
  8267. $ts = strtotime(str_replace('/', '-', $raw));
  8268. if ($ts === false || $ts <= 0) {
  8269. $this->error('交货截止日期格式无效');
  8270. }
  8271. $ymd = date('Y-m-d', $ts);
  8272. }
  8273. if ($ymd < date('Y-m-d')) {
  8274. $this->error('交货截止日期不能早于今天');
  8275. }
  8276. return $ymd;
  8277. }
  8278. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  8279. {
  8280. $s = trim((string)$value);
  8281. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  8282. return '';
  8283. }
  8284. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  8285. return $m[1];
  8286. }
  8287. $ts = strtotime(str_replace('/', '-', $s));
  8288. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  8289. }
  8290. /**
  8291. * @param array{pos?:array} $bundle
  8292. */
  8293. protected function resolveBundleDeliveryDeadline(array $bundle): string
  8294. {
  8295. foreach ($bundle['pos'] ?? [] as $po) {
  8296. if (!is_array($po)) {
  8297. continue;
  8298. }
  8299. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  8300. if ($d !== '') {
  8301. return $d;
  8302. }
  8303. }
  8304. return '';
  8305. }
  8306. protected function formatProcuremenSysRqForInput($sysRq): string
  8307. {
  8308. $sr = trim((string)$sysRq);
  8309. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  8310. return '';
  8311. }
  8312. $ts = strtotime($sr);
  8313. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  8314. }
  8315. protected function formatProcuremenSysRqForDisplay($sysRq): string
  8316. {
  8317. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  8318. if ($sr === '') {
  8319. return '—';
  8320. }
  8321. $ts = strtotime($sr);
  8322. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  8323. }
  8324. /**
  8325. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  8326. *
  8327. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  8328. * @return array{ccydh?:string,pos:array,merge_rows:array}
  8329. */
  8330. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  8331. {
  8332. return $bundle;
  8333. }
  8334. /**
  8335. * 写入/更新 purchase_order(单道工序行)
  8336. *
  8337. * @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
  8338. */
  8339. protected function upsertPurchaseOrderFromRow(
  8340. array $row,
  8341. string $sysRqDb,
  8342. $wflowStatus = null,
  8343. ?string $pickTime = null,
  8344. ?array $exists = null,
  8345. ?string $deliveryDeadline = null,
  8346. $scoreRuleId = null,
  8347. ?string $issueBatchNo = null
  8348. ): void {
  8349. $ids = $this->extractScydgyRowId($row);
  8350. if (!$this->isValidScydgyRowId($ids)) {
  8351. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  8352. }
  8353. if ($exists === null) {
  8354. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  8355. }
  8356. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  8357. $this->ensurePurchaseOrderScoreRuleIdColumn();
  8358. $this->ensurePurchaseOrderOrderBatchNoColumn();
  8359. $this->ensurePurchaseOrderCzlyqColumn();
  8360. $data = $this->normalizePurchaseOrderWritePayload([
  8361. 'scydgy_id' => $ids,
  8362. 'CCYDH' => $row['CCYDH'] ?? null,
  8363. 'CYJMC' => $row['CYJMC'] ?? null,
  8364. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  8365. 'CDXMC' => $row['CDXMC'] ?? null,
  8366. 'CGYBH' => $row['CGYBH'] ?? null,
  8367. 'CGYMC' => $row['CGYMC'] ?? null,
  8368. 'CDW' => $row['CDW'] ?? null,
  8369. 'czlyq' => $row['czlyq'] ?? null,
  8370. 'NGZL' => $row['NGZL'] ?? null,
  8371. 'CDF' => $row['CDF'] ?? null,
  8372. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  8373. 'MBZ' => trim((string)($row['MBZ'] ?? $row['mbz'] ?? '')),
  8374. 'bwjg' => $row['bwjg'] ?? null,
  8375. 'iStatus' => $row['iStatus'] ?? null,
  8376. 'dStamp' => $row['dStamp'] ?? null,
  8377. 'dputrecord' => $row['dputrecord'] ?? null,
  8378. 'cywyxm' => $row['cywyxm'] ?? null,
  8379. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  8380. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  8381. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  8382. 'sys_rq' => $sysRqDb,
  8383. ], $row);
  8384. // 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
  8385. $qtyUp = trim((string)($data['This_quantity'] ?? ''));
  8386. if ($qtyUp === '') {
  8387. $qtyFallback = $this->resolveProcuremenThisQuantity([
  8388. 'This_quantity' => '',
  8389. 'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
  8390. ]);
  8391. if ($qtyFallback !== '') {
  8392. $data['This_quantity'] = $qtyFallback;
  8393. }
  8394. }
  8395. if ($deliveryDeadline !== null) {
  8396. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  8397. }
  8398. // 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
  8399. $scoreRule = null;
  8400. if (is_array($scoreRuleId)) {
  8401. $scoreRule = $scoreRuleId;
  8402. $scoreRuleId = (int)($scoreRule['id'] ?? 0);
  8403. } else {
  8404. $scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
  8405. }
  8406. if ($scoreRuleId !== null && $scoreRuleId > 0) {
  8407. $poCols = $this->loadPurchaseOrderColumnSet();
  8408. if (!empty($poCols['score_rule_id'])) {
  8409. $data['score_rule_id'] = $scoreRuleId;
  8410. if (is_array($scoreRule)) {
  8411. if (!empty($poCols['score_rule_name'])) {
  8412. $data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
  8413. }
  8414. if (!empty($poCols['score_quality_weight'])) {
  8415. $data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
  8416. }
  8417. if (!empty($poCols['score_price_weight'])) {
  8418. $data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
  8419. }
  8420. if (!empty($poCols['score_lead_weight'])) {
  8421. $data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
  8422. }
  8423. }
  8424. }
  8425. }
  8426. if ($wflowStatus !== null && $wflowStatus !== '') {
  8427. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  8428. }
  8429. if ($pickTime !== null && $pickTime !== '') {
  8430. $data['pick_time'] = $pickTime;
  8431. $data['pick_company_name'] = '';
  8432. }
  8433. if ($issueBatchNo !== null) {
  8434. $batchNo = trim($issueBatchNo);
  8435. $poCols = $this->loadPurchaseOrderColumnSet();
  8436. if (!empty($poCols['order_batch_no'])) {
  8437. $data['order_batch_no'] = $batchNo;
  8438. }
  8439. }
  8440. if ($exists) {
  8441. $upd = $data;
  8442. unset($upd['scydgy_id']);
  8443. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  8444. } else {
  8445. $data['createtime'] = date('Y-m-d H:i:s');
  8446. Db::table('purchase_order')->insert($data);
  8447. }
  8448. }
  8449. /**
  8450. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  8451. *
  8452. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  8453. */
  8454. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
  8455. {
  8456. $toDb = function ($value) {
  8457. if ($value === null) {
  8458. return null;
  8459. }
  8460. if (is_scalar($value)) {
  8461. return $value;
  8462. }
  8463. return json_encode($value, JSON_UNESCAPED_UNICODE);
  8464. };
  8465. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  8466. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  8467. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  8468. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  8469. if ($username === '') {
  8470. $username = $this->resolveCustomerContactName($phone, $companyName);
  8471. }
  8472. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  8473. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  8474. }
  8475. if ($requirePhone && $phone === '') {
  8476. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  8477. }
  8478. $detailLinks = [];
  8479. foreach ($mergeRows as $row) {
  8480. if (!is_array($row)) {
  8481. continue;
  8482. }
  8483. $sid = $this->extractScydgyRowId($row);
  8484. $detailId = 0;
  8485. if ($skipExisting) {
  8486. try {
  8487. $existsQuery = Db::table('purchase_order_detail')
  8488. ->where('scydgy_id', $sid)
  8489. ->where('company_name', $companyName);
  8490. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  8491. $exists = $existsQuery->find();
  8492. } catch (\Throwable $e) {
  8493. $exists = null;
  8494. }
  8495. if (is_array($exists)) {
  8496. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  8497. }
  8498. }
  8499. if ($detailId <= 0) {
  8500. $one = [
  8501. 'scydgy_id' => $toDb($sid),
  8502. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  8503. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  8504. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  8505. 'username' => $username !== '' ? $username : null,
  8506. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  8507. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  8508. 'createtime' => date('Y-m-d H:i:s'),
  8509. 'status' => ProcuremenStatus::POD_UNPICKED,
  8510. 'status_name' => '未提交',
  8511. ];
  8512. // 重新下发:继承该供应商同一工序最近一次有效报价,避免手机端又变「未填写」
  8513. $prevQuote = $this->loadPreviousSupplierQuoteForReissue($sid, $companyName);
  8514. if ($prevQuote !== []) {
  8515. if (isset($prevQuote['amount'])) {
  8516. $one['amount'] = $prevQuote['amount'];
  8517. }
  8518. if (array_key_exists('delivery', $prevQuote)) {
  8519. $one['delivery'] = $prevQuote['delivery'];
  8520. }
  8521. if (array_key_exists('lead_days', $prevQuote)) {
  8522. $one['lead_days'] = $prevQuote['lead_days'];
  8523. }
  8524. if (!empty($prevQuote['has_quote'])) {
  8525. $one['status_name'] = '已提交';
  8526. }
  8527. }
  8528. Db::table('purchase_order_detail')->insert($one);
  8529. $detailId = (int)Db::getLastInsID();
  8530. }
  8531. $mprocUrl = '';
  8532. if ($buildMobileLinks && $detailId > 0) {
  8533. // 手工询价 → 待报价;协助下发 → 未提交
  8534. $listTab = ($sid < 0) ? 'rfq' : 'draft';
  8535. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId, $listTab);
  8536. }
  8537. $detailLinks[] = [
  8538. 'detail_id' => $detailId,
  8539. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  8540. 'url' => $mprocUrl,
  8541. ];
  8542. }
  8543. $this->invalidatePickHiddenScydgyCache();
  8544. return $detailLinks;
  8545. }
  8546. /**
  8547. * 重新下发新建明细时:取该供应商同一工序最近一次非空报价
  8548. *
  8549. * @return array{amount?:mixed,delivery?:mixed,lead_days?:mixed,has_quote?:int}
  8550. */
  8551. protected function loadPreviousSupplierQuoteForReissue(int $sid, string $companyName): array
  8552. {
  8553. $companyName = trim($companyName);
  8554. if ($sid === 0 || $companyName === '') {
  8555. return [];
  8556. }
  8557. try {
  8558. $prevRows = Db::table('purchase_order_detail')
  8559. ->where('scydgy_id', $sid)
  8560. ->where('company_name', $companyName)
  8561. ->order('id', 'desc')
  8562. ->limit(20)
  8563. ->select();
  8564. } catch (\Throwable $e) {
  8565. return [];
  8566. }
  8567. if (!is_array($prevRows) || $prevRows === []) {
  8568. return [];
  8569. }
  8570. $out = [];
  8571. $hasAmt = false;
  8572. $hasDel = false;
  8573. $hasLead = false;
  8574. foreach ($prevRows as $prev) {
  8575. if (!is_array($prev)) {
  8576. continue;
  8577. }
  8578. if (!$hasAmt) {
  8579. $am = $prev['amount'] ?? null;
  8580. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  8581. $out['amount'] = is_scalar($am) ? $am : (string)$am;
  8582. $hasAmt = true;
  8583. }
  8584. }
  8585. if (!$hasDel) {
  8586. $dv = isset($prev['delivery']) ? trim((string)$prev['delivery']) : '';
  8587. if ($dv !== '' && !preg_match('/^0000-00-00/i', $dv)) {
  8588. $out['delivery'] = $prev['delivery'];
  8589. $hasDel = true;
  8590. }
  8591. }
  8592. if (!$hasLead) {
  8593. $ld = $prev['lead_days'] ?? null;
  8594. if ($ld !== null && $ld !== '' && is_numeric($ld)) {
  8595. $out['lead_days'] = (int)$ld;
  8596. $hasLead = true;
  8597. }
  8598. }
  8599. if ($hasAmt && $hasDel && $hasLead) {
  8600. break;
  8601. }
  8602. }
  8603. if ($out === []) {
  8604. return [];
  8605. }
  8606. $out['has_quote'] = ($hasAmt || $hasDel) ? 1 : 0;
  8607. return $out;
  8608. }
  8609. /**
  8610. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  8611. * @return array<string, mixed>
  8612. */
  8613. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks, string $emailTplScene = 'review_email'): array
  8614. {
  8615. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  8616. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  8617. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  8618. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  8619. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  8620. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  8621. $isMerge = !empty($ctx['is_merge']);
  8622. $contactName = trim((string)($c['username'] ?? ''));
  8623. if ($contactName === '') {
  8624. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  8625. }
  8626. $notifyVars = [
  8627. 'company_name' => $companyName,
  8628. 'contact_name' => $contactName,
  8629. 'phone' => $phone,
  8630. 'email' => $toEmail,
  8631. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  8632. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  8633. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  8634. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  8635. 'deadline' => (string)($ctx['deadline'] ?? ''),
  8636. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  8637. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  8638. 'order_type' => (string)($ctx['order_type'] ?? ''),
  8639. 'score_weights' => (string)($ctx['score_weights'] ?? ''),
  8640. 'platform_url' => $platformUrl,
  8641. 'platform_links' => $platformLinksPlain,
  8642. 'platform_links_html' => $platformLinksHtml,
  8643. ];
  8644. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  8645. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  8646. $mailPlain = $this->renderNotifyTemplate($emailTplScene, $notifyVars);
  8647. if (!empty($ctx['multi_order'])) {
  8648. $smsContent = $this->stripEmptyOrderHeaderLines($smsContent);
  8649. $mailPlain = $this->stripEmptyOrderHeaderLines($mailPlain);
  8650. }
  8651. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  8652. // 邮件:用表格替换纯文本工序块,列对齐更整齐
  8653. $processHtml = trim((string)($ctx['process_html'] ?? ''));
  8654. $processPlain = trim((string)($ctx['process_plain'] ?? ''));
  8655. if ($processHtml !== '' && $processPlain !== '') {
  8656. $plainBlockHtml = $this->plainTextToHtmlEmailBody($processPlain);
  8657. if ($plainBlockHtml !== '' && strpos($mailBody, $plainBlockHtml) !== false) {
  8658. $mailBody = str_replace($plainBlockHtml, $processHtml, $mailBody);
  8659. }
  8660. }
  8661. return [
  8662. 'company_name' => $companyName,
  8663. 'phone' => $phone,
  8664. 'email' => $toEmail,
  8665. 'sms_content' => $smsContent,
  8666. 'mail_plain' => $mailPlain,
  8667. 'mail_body' => $mailBody,
  8668. 'notify_vars' => $notifyVars,
  8669. 'detail_links' => $detailLinks,
  8670. ];
  8671. }
  8672. /**
  8673. * 多订单下发时模版里「订单号:{ccydh}」可能变成空行,去掉以免重复
  8674. */
  8675. protected function stripEmptyOrderHeaderLines(string $text): string
  8676. {
  8677. $text = str_replace(["\r\n", "\r"], "\n", $text);
  8678. $text = preg_replace('/^订单号:\s*\n/mu', '', $text);
  8679. $text = preg_replace('/^印件名称:\s*\n/mu', '', $text);
  8680. $text = preg_replace("/\n{3,}/", "\n\n", (string)$text);
  8681. return (string)$text;
  8682. }
  8683. /**
  8684. * @param array<string, mixed> $chosen
  8685. * @param array<int, array<string, mixed>> $mergeRows
  8686. * @param array{ccydh:string, pos:array} $bundle
  8687. */
  8688. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue', string $emailTplScene = 'review_email'): void
  8689. {
  8690. if (!$sendSms && !$sendEmail) {
  8691. return;
  8692. }
  8693. $companyName = trim((string)($chosen['name'] ?? ''));
  8694. $phone = trim((string)($chosen['phone'] ?? ''));
  8695. $toEmail = trim((string)($chosen['email'] ?? ''));
  8696. if ($companyName === '') {
  8697. throw new \Exception('供应商名称无效');
  8698. }
  8699. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  8700. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  8701. }
  8702. if ($sendSms && $phone === '') {
  8703. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  8704. }
  8705. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  8706. $linkListTab = (strpos($emailTplScene, 'rfq_') === 0) ? 'rfq' : 'draft';
  8707. $sids = [];
  8708. foreach ($mergeRows as $mr) {
  8709. if (!is_array($mr)) {
  8710. continue;
  8711. }
  8712. $sid = $this->extractScydgyRowId($mr);
  8713. if ($this->isValidScydgyRowId($sid)) {
  8714. $sids[$sid] = true;
  8715. }
  8716. }
  8717. if ($sids === []) {
  8718. throw new \Exception('未找到工序行,无法发送通知');
  8719. }
  8720. $sysRqNotify = '';
  8721. $pos = $bundle['pos'] ?? [];
  8722. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  8723. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  8724. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  8725. $ts = strtotime($sr);
  8726. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  8727. }
  8728. }
  8729. try {
  8730. $detailsQuery = Db::table('purchase_order_detail')
  8731. ->where('scydgy_id', 'in', array_keys($sids))
  8732. ->where('company_name', $companyName);
  8733. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  8734. $details = $detailsQuery->order('id', 'asc')->select();
  8735. } catch (\Throwable $e) {
  8736. $details = [];
  8737. }
  8738. if (!is_array($details) || $details === []) {
  8739. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  8740. try {
  8741. $detailsQuery = Db::table('purchase_order_detail')
  8742. ->where('scydgy_id', 'in', array_keys($sids))
  8743. ->where('company_name', $companyName);
  8744. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  8745. $details = $detailsQuery->order('id', 'asc')->select();
  8746. } catch (\Throwable $e) {
  8747. $details = [];
  8748. }
  8749. }
  8750. if (!is_array($details) || $details === []) {
  8751. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  8752. }
  8753. $detailLinks = [];
  8754. foreach ($details as $d) {
  8755. if (!is_array($d)) {
  8756. continue;
  8757. }
  8758. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  8759. if ($detailId <= 0) {
  8760. continue;
  8761. }
  8762. $sid = (int)($d['scydgy_id'] ?? 0);
  8763. $gymc = '';
  8764. foreach ($mergeRows as $mr) {
  8765. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  8766. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  8767. break;
  8768. }
  8769. }
  8770. $detailLinks[] = [
  8771. 'detail_id' => $detailId,
  8772. 'cgymc' => $gymc,
  8773. // 询价邮件 → 待报价;下发报价 → 未提交
  8774. 'url' => $this->buildMprocMobileOrderUrl(
  8775. $detailId,
  8776. ($linkListTab === 'rfq' || $sid < 0) ? 'rfq' : 'draft'
  8777. ),
  8778. ];
  8779. }
  8780. if ($detailLinks === []) {
  8781. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  8782. }
  8783. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  8784. $orderTypeCtx = $this->resolveIssueNotifyOrderTypeFromBundle($bundle);
  8785. $ctx['order_type'] = (string)($orderTypeCtx['order_type'] ?? '');
  8786. $ctx['score_weights'] = (string)($orderTypeCtx['score_weights'] ?? '');
  8787. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks, $emailTplScene);
  8788. $notifyBundle['email_log_scene'] = $emailLogScene;
  8789. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  8790. $poIdLog = 0;
  8791. $pos = $bundle['pos'] ?? [];
  8792. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  8793. $poIdLog = (int)($pos[0]['id'] ?? 0);
  8794. }
  8795. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  8796. if ($sendEmail) {
  8797. $mailTplRow = $this->loadNotifyTemplateRow($emailTplScene);
  8798. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  8799. throw new \Exception($this->notifyTemplateMissingMessage($emailTplScene));
  8800. }
  8801. $mailSubject = $this->resolveProcuremenEmailSubject($emailTplScene);
  8802. $mailConfig = $this->loadMailerConfig();
  8803. if (!$this->isProcuremenNotifyDryRun()) {
  8804. if (empty($mailConfig['host'])) {
  8805. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  8806. }
  8807. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  8808. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  8809. }
  8810. }
  8811. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  8812. }
  8813. if ($sendSms) {
  8814. $this->issueSendSupplierSms($notifyBundle);
  8815. }
  8816. }
  8817. /**
  8818. * @param array<int, array<string, mixed>> $quoteGroups
  8819. * @return array<int, array<string, mixed>>
  8820. */
  8821. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  8822. {
  8823. $names = [];
  8824. if (is_string($companiesJson) && $companiesJson !== '') {
  8825. $decoded = json_decode($companiesJson, true);
  8826. if (is_array($decoded)) {
  8827. foreach ($decoded as $nm) {
  8828. $nm = trim((string)$nm);
  8829. if ($nm !== '') {
  8830. $names[] = $nm;
  8831. }
  8832. }
  8833. }
  8834. }
  8835. $names = array_values(array_unique($names));
  8836. if ($names === [] && $selectedCompany !== '') {
  8837. $names = [$selectedCompany];
  8838. }
  8839. if ($names === []) {
  8840. return $quoteGroups;
  8841. }
  8842. $targets = [];
  8843. foreach ($quoteGroups as $g) {
  8844. if (!is_array($g)) {
  8845. continue;
  8846. }
  8847. $cn = trim((string)($g['name'] ?? ''));
  8848. if ($cn !== '' && in_array($cn, $names, true)) {
  8849. $targets[] = $g;
  8850. }
  8851. }
  8852. return $targets;
  8853. }
  8854. /**
  8855. * @return array{pos:array, merge_rows:array, bundle:array}
  8856. */
  8857. protected function loadAuditResendBundle(string $scydgyId): array
  8858. {
  8859. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  8860. $pos = $bundle['pos'];
  8861. $mergeRows = $bundle['merge_rows'];
  8862. if ($pos === [] || $mergeRows === []) {
  8863. $this->error('该订单不在待确认供应商状态');
  8864. }
  8865. $sysRqDb = '';
  8866. if (isset($pos[0]) && is_array($pos[0])) {
  8867. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  8868. }
  8869. foreach ($pos as $i => $poRow) {
  8870. if (is_array($pos[$i]) && $sysRqDb !== '') {
  8871. $pos[$i]['sys_rq'] = $sysRqDb;
  8872. }
  8873. }
  8874. $bundle['pos'] = $pos;
  8875. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  8876. }
  8877. /**
  8878. * @param array<int, array<string, mixed>> $targets
  8879. */
  8880. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  8881. {
  8882. if ($targets === []) {
  8883. $this->error('未找到可通知的供应商');
  8884. }
  8885. $notifyErrors = [];
  8886. try {
  8887. $this->notifyDryRunPreview = [];
  8888. foreach ($targets as $g) {
  8889. if (!is_array($g)) {
  8890. continue;
  8891. }
  8892. $cname = trim((string)($g['name'] ?? ''));
  8893. if ($cname === '') {
  8894. continue;
  8895. }
  8896. $chosen = [
  8897. 'name' => $cname,
  8898. 'company_name' => $cname,
  8899. 'email' => trim((string)($g['email'] ?? '')),
  8900. 'phone' => trim((string)($g['phone'] ?? '')),
  8901. 'username' => trim((string)($g['username'] ?? '')),
  8902. ];
  8903. try {
  8904. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  8905. } catch (\Throwable $e) {
  8906. $notifyErrors[] = $cname . ':' . $e->getMessage();
  8907. }
  8908. }
  8909. } catch (\Throwable $e) {
  8910. $this->error('通知发送失败:' . $e->getMessage());
  8911. }
  8912. if ($notifyErrors !== []) {
  8913. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  8914. }
  8915. if ($this->isProcuremenNotifyDryRun()) {
  8916. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  8917. 'notify_dry_run' => true,
  8918. 'notify_preview' => $this->notifyDryRunPreview,
  8919. ]);
  8920. }
  8921. $nameLabels = [];
  8922. foreach ($targets as $g) {
  8923. if (!is_array($g)) {
  8924. continue;
  8925. }
  8926. $n = trim((string)($g['name'] ?? ''));
  8927. if ($n !== '') {
  8928. $nameLabels[] = $n;
  8929. }
  8930. }
  8931. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  8932. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  8933. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  8934. $seenLogSid = [];
  8935. foreach ($bundle['pos'] ?? [] as $poRow) {
  8936. if (!is_array($poRow)) {
  8937. continue;
  8938. }
  8939. $sid = (int)($poRow['scydgy_id'] ?? 0);
  8940. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  8941. continue;
  8942. }
  8943. $seenLogSid[$sid] = true;
  8944. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  8945. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  8946. }
  8947. if ($seenLogSid === []) {
  8948. foreach ($mergeRows as $mr) {
  8949. if (!is_array($mr)) {
  8950. continue;
  8951. }
  8952. $sid = $this->extractScydgyRowId($mr);
  8953. if ($this->isValidScydgyRowId($sid)) {
  8954. $this->addOrderLog($sid, $logAction, $logMsg, null);
  8955. break;
  8956. }
  8957. }
  8958. }
  8959. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  8960. }
  8961. /**
  8962. * 协助下发 — 发送短信(一家供应商)
  8963. *
  8964. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  8965. */
  8966. protected function issueSendSupplierSms(array $bundle): void
  8967. {
  8968. $companyName = (string)($bundle['company_name'] ?? '');
  8969. $phone = (string)($bundle['phone'] ?? '');
  8970. $smsContent = (string)($bundle['sms_content'] ?? '');
  8971. $this->logIssueNotifyDebug('短信', [
  8972. 'company' => $companyName,
  8973. 'phone' => $phone,
  8974. 'sms_content' => $smsContent,
  8975. ]);
  8976. if ($this->isProcuremenNotifyDryRun()) {
  8977. $this->recordNotifyDryRunPreview([
  8978. 'scene' => 'issue_sms',
  8979. 'company_name' => $companyName,
  8980. 'phone' => $phone,
  8981. 'sms_content' => $smsContent,
  8982. ]);
  8983. return;
  8984. }
  8985. $this->smsbao($phone, $smsContent);
  8986. }
  8987. /**
  8988. * 协助下发 — 发送邮件(一家供应商)
  8989. *
  8990. * @param array<string, mixed> $bundle
  8991. * @param array<string, mixed> $mailConfig
  8992. */
  8993. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  8994. {
  8995. $companyName = (string)($bundle['company_name'] ?? '');
  8996. $toEmail = (string)($bundle['email'] ?? '');
  8997. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  8998. $mailBody = (string)($bundle['mail_body'] ?? '');
  8999. $this->logIssueNotifyDebug('邮件', [
  9000. 'company' => $companyName,
  9001. 'email' => $toEmail,
  9002. 'cc_email' => $this->resolveMprocNotifyCcEmails($toEmail),
  9003. 'mail_subject' => $mailSubject,
  9004. 'mail_body' => $mailPlain,
  9005. ]);
  9006. if ($this->isProcuremenNotifyDryRun()) {
  9007. $this->recordNotifyDryRunPreview([
  9008. 'scene' => 'issue_email',
  9009. 'company_name' => $companyName,
  9010. 'email' => $toEmail,
  9011. 'cc_email' => $this->resolveMprocNotifyCcEmails($toEmail),
  9012. 'mail_subject' => $mailSubject,
  9013. 'mail_body' => $mailPlain,
  9014. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  9015. 'notify_vars' => $bundle['notify_vars'] ?? [],
  9016. 'detail_links' => $bundle['detail_links'] ?? [],
  9017. ]);
  9018. return;
  9019. }
  9020. $mail = new PHPMailer(true);
  9021. $mail->isSMTP();
  9022. $mail->Host = $mailConfig['host'];
  9023. $mail->SMTPAuth = true;
  9024. $mail->Username = $mailConfig['addr'];
  9025. $mail->Password = $mailConfig['pass'];
  9026. $mail->SMTPSecure = $mailConfig['security'];
  9027. $mail->Port = $mailConfig['port'];
  9028. $mail->CharSet = $mailConfig['charset'];
  9029. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  9030. $mail->addAddress($toEmail, $companyName);
  9031. $ccList = $this->resolveMprocNotifyCcEmails($toEmail);
  9032. foreach ($ccList as $cc) {
  9033. $mail->addCC($cc);
  9034. }
  9035. $mail->isHTML(true);
  9036. $mail->Subject = $mailSubject;
  9037. $mail->Body = $mailBody;
  9038. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  9039. $sendOk = true;
  9040. $failReason = '';
  9041. try {
  9042. $mail->send();
  9043. } catch (\Throwable $e) {
  9044. $sendOk = false;
  9045. $failReason = $e->getMessage();
  9046. $this->persistEmailSendLog([
  9047. 'from_email' => $fromEmail,
  9048. 'to_email' => $toEmail,
  9049. 'send_time' => date('Y-m-d H:i:s'),
  9050. 'scene' => (string)($bundle['email_log_scene'] ?? '初选下发'),
  9051. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  9052. 'company_name' => $companyName,
  9053. 'mail_subject' => $mailSubject,
  9054. 'status' => 0,
  9055. 'fail_reason' => $failReason,
  9056. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  9057. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  9058. ]);
  9059. throw $e;
  9060. }
  9061. $this->persistEmailSendLog([
  9062. 'from_email' => $fromEmail,
  9063. 'to_email' => $toEmail,
  9064. 'send_time' => date('Y-m-d H:i:s'),
  9065. 'scene' => (string)($bundle['email_log_scene'] ?? '初选下发'),
  9066. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  9067. 'company_name' => $companyName,
  9068. 'mail_subject' => $mailSubject,
  9069. 'status' => 1,
  9070. 'fail_reason' => '',
  9071. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  9072. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  9073. ]);
  9074. }
  9075. /**
  9076. * 协助通知抄送:读取 mproc.cc_email(逗号分隔),排除与主收件人相同的地址
  9077. *
  9078. * @return array<int, string>
  9079. */
  9080. protected function resolveMprocNotifyCcEmails(string $toEmail = ''): array
  9081. {
  9082. $raw = trim((string)config('mproc.cc_email'));
  9083. if ($raw === '') {
  9084. return [];
  9085. }
  9086. $toNorm = strtolower(trim($toEmail));
  9087. $out = [];
  9088. $seen = [];
  9089. foreach (preg_split('/[,;,;\s]+/', $raw) ?: [] as $piece) {
  9090. $email = strtolower(trim((string)$piece));
  9091. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9092. continue;
  9093. }
  9094. if ($toNorm !== '' && $email === $toNorm) {
  9095. continue;
  9096. }
  9097. if (isset($seen[$email])) {
  9098. continue;
  9099. }
  9100. $seen[$email] = true;
  9101. $out[] = $email;
  9102. }
  9103. return $out;
  9104. }
  9105. /**
  9106. * 下发通知:解析订单类型名称与评分比例文案
  9107. *
  9108. * @param array<string, mixed> $bundle
  9109. * @return array{order_type:string,score_weights:string}
  9110. */
  9111. protected function resolveIssueNotifyOrderTypeFromBundle(array $bundle): array
  9112. {
  9113. $orderType = '';
  9114. $scoreWeights = '';
  9115. $rule = null;
  9116. if (!empty($bundle['score_rule']) && is_array($bundle['score_rule'])) {
  9117. $rule = $bundle['score_rule'];
  9118. }
  9119. $pos = $bundle['pos'] ?? [];
  9120. $po0 = (is_array($pos) && isset($pos[0]) && is_array($pos[0])) ? $pos[0] : null;
  9121. if ($rule === null && is_array($po0)) {
  9122. $ruleId = (int)($po0['score_rule_id'] ?? 0);
  9123. if ($ruleId > 0) {
  9124. try {
  9125. $rule = ProcuremenSupplierScore::getRuleById($ruleId);
  9126. } catch (\Throwable $e) {
  9127. $rule = null;
  9128. }
  9129. }
  9130. if (!is_array($rule) || (int)($rule['id'] ?? 0) <= 0) {
  9131. $qw = (int)($po0['score_quality_weight'] ?? 0);
  9132. $pw = (int)($po0['score_price_weight'] ?? 0);
  9133. $lw = (int)($po0['score_lead_weight'] ?? 0);
  9134. if ($qw > 0 || $pw > 0 || $lw > 0) {
  9135. $rule = [
  9136. 'name' => trim((string)($po0['score_rule_name'] ?? '')),
  9137. 'quality_weight' => $qw,
  9138. 'price_weight' => $pw,
  9139. 'lead_weight' => $lw,
  9140. ];
  9141. }
  9142. }
  9143. }
  9144. if (is_array($rule)) {
  9145. $orderType = trim((string)($rule['name'] ?? ''));
  9146. $scoreWeights = $this->formatScoreRuleWeightsText($rule);
  9147. }
  9148. if ($orderType === '' && is_array($po0)) {
  9149. $orderType = trim((string)($po0['score_rule_name'] ?? ''));
  9150. }
  9151. return [
  9152. 'order_type' => $orderType,
  9153. 'score_weights' => $scoreWeights,
  9154. ];
  9155. }
  9156. /**
  9157. * 评分比例文案:质量30%、价格50%、交货20%
  9158. *
  9159. * @param array{quality_weight?:mixed,price_weight?:mixed,lead_weight?:mixed} $rule
  9160. */
  9161. protected function formatScoreRuleWeightsText(array $rule): string
  9162. {
  9163. $parts = [];
  9164. $qw = max(0, (float)($rule['quality_weight'] ?? 0));
  9165. $pw = max(0, (float)($rule['price_weight'] ?? 0));
  9166. $lw = max(0, (float)($rule['lead_weight'] ?? 0));
  9167. $fmt = static function ($n) {
  9168. $s = rtrim(rtrim(sprintf('%.2F', (float)$n), '0'), '.');
  9169. return $s === '' ? '0' : $s;
  9170. };
  9171. if ($qw > 0) {
  9172. $parts[] = '质量' . $fmt($qw) . '%';
  9173. }
  9174. if ($pw > 0) {
  9175. $parts[] = '价格' . $fmt($pw) . '%';
  9176. }
  9177. if ($lw > 0) {
  9178. $parts[] = '交货' . $fmt($lw) . '%';
  9179. }
  9180. return implode('、', $parts);
  9181. }
  9182. /**
  9183. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  9184. *
  9185. * @param array<int, array<string, mixed>> $mergeRows
  9186. * @return array<string, mixed>
  9187. */
  9188. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  9189. {
  9190. $head = $mergeRows[0] ?? [];
  9191. $isMerge = count($mergeRows) > 1;
  9192. $orderSet = [];
  9193. foreach ($mergeRows as $r) {
  9194. if (!is_array($r)) {
  9195. continue;
  9196. }
  9197. $dh = trim((string)($r['CCYDH'] ?? ''));
  9198. if ($dh !== '') {
  9199. $orderSet[$dh] = true;
  9200. }
  9201. }
  9202. $multiOrder = count($orderSet) > 1;
  9203. // 多订单:明细块自带各订单头,避免模版里 {ccydh}/{cyjmc} 只显示第一单
  9204. $ccydh = $multiOrder ? '' : (isset($head['CCYDH']) ? (string)$head['CCYDH'] : '');
  9205. $cyjmc = $multiOrder ? '' : (isset($head['CYJMC']) ? (string)$head['CYJMC'] : '');
  9206. return [
  9207. 'ccydh' => $ccydh,
  9208. 'cyjmc' => $cyjmc,
  9209. 'cgymc_single' => $multiOrder ? '' : trim((string)($head['CGYMC'] ?? '')),
  9210. 'is_merge' => $isMerge,
  9211. 'multi_order' => $multiOrder,
  9212. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  9213. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  9214. 'deadline' => $sysRqNotify,
  9215. 'order_type' => '',
  9216. 'score_weights' => '',
  9217. ];
  9218. }
  9219. /**
  9220. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  9221. *
  9222. * @param array<string, mixed> $data
  9223. */
  9224. protected function logIssueNotifyDebug(string $type, array $data): void
  9225. {
  9226. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  9227. return;
  9228. }
  9229. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  9230. }
  9231. protected function ensurePurchaseEmailSendLogTableOnce(): void
  9232. {
  9233. try {
  9234. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  9235. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  9236. return;
  9237. } catch (\Throwable $e) {
  9238. }
  9239. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  9240. if (is_file($sqlFile)) {
  9241. $sql = file_get_contents($sqlFile);
  9242. if (is_string($sql) && $sql !== '') {
  9243. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  9244. $stmt = trim($stmt);
  9245. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  9246. continue;
  9247. }
  9248. try {
  9249. Db::execute($stmt);
  9250. } catch (\Throwable $ignore) {
  9251. }
  9252. }
  9253. }
  9254. }
  9255. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  9256. }
  9257. /**
  9258. * @param array<string, mixed> $row
  9259. */
  9260. protected function persistEmailSendLog(array $row): void
  9261. {
  9262. try {
  9263. $this->ensurePurchaseEmailSendLogTableOnce();
  9264. } catch (\Throwable $e) {
  9265. return;
  9266. }
  9267. list($adminId, $adminName) = $this->GetUseName();
  9268. $cut = function ($s, $max) {
  9269. $s = (string)$s;
  9270. if (function_exists('mb_substr')) {
  9271. return mb_substr($s, 0, $max, 'UTF-8');
  9272. }
  9273. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  9274. };
  9275. $data = [
  9276. 'from_email' => $cut($row['from_email'] ?? '', 128),
  9277. 'to_email' => $cut($row['to_email'] ?? '', 128),
  9278. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  9279. 'scene' => $cut($this->normalizeEmailLogSceneForStore((string)($row['scene'] ?? '')), 64),
  9280. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  9281. 'company_name' => $cut($row['company_name'] ?? '', 128),
  9282. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  9283. 'status' => !empty($row['status']) ? 1 : 0,
  9284. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  9285. 'admin_id' => (int)$adminId,
  9286. 'admin_name' => $cut($adminName, 64),
  9287. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  9288. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  9289. 'createtime' => date('Y-m-d H:i:s'),
  9290. ];
  9291. try {
  9292. Db::table('purchase_email_send_log')->insert($data);
  9293. } catch (\Throwable $e) {
  9294. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  9295. }
  9296. }
  9297. /**
  9298. * 邮件日志场景:库内统一存中文;兼容历史英文码
  9299. *
  9300. * @return array<string, string>
  9301. */
  9302. protected function emailLogSceneLabelMap(): array
  9303. {
  9304. return [
  9305. 'pick_issue' => '初选下发',
  9306. 'audit_resend' => '确认页重发',
  9307. 'audit_append' => '确认页追加供应商',
  9308. 'rfq_salesman' => '询价通知业务员',
  9309. 'rfq_supplier' => '供应商询价通知',
  9310. 'delivery_notify'=> '交货情况通知生产部',
  9311. 'confirm_result' => '确认结果通知',
  9312. 'confirm_ok' => '确认已通过通知',
  9313. 'confirm_fail' => '确认未通过通知',
  9314. ];
  9315. }
  9316. /** 写入邮件日志前:英文场景码转中文;已是中文则原样 */
  9317. protected function normalizeEmailLogSceneForStore(string $scene): string
  9318. {
  9319. $scene = trim($scene);
  9320. $map = $this->emailLogSceneLabelMap();
  9321. if ($scene === '') {
  9322. return $map['pick_issue'];
  9323. }
  9324. if (isset($map[$scene])) {
  9325. return $map[$scene];
  9326. }
  9327. // 已是中文标签
  9328. if (in_array($scene, array_values($map), true)) {
  9329. return $scene;
  9330. }
  9331. return $scene;
  9332. }
  9333. protected function formatEmailLogSceneText(string $scene): string
  9334. {
  9335. return $this->normalizeEmailLogSceneForStore($scene);
  9336. }
  9337. /**
  9338. * 邮件发送日志列表
  9339. */
  9340. public function emailLog()
  9341. {
  9342. $this->relationSearch = false;
  9343. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  9344. $this->request->filter(['strip_tags', 'trim']);
  9345. $bakModel = $this->model;
  9346. $this->model = new \app\admin\model\Purchaseemailsendlog;
  9347. if ($this->request->isAjax()) {
  9348. $this->ensurePurchaseEmailSendLogTableOnce();
  9349. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  9350. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  9351. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  9352. $list = $this->model
  9353. ->where($where)
  9354. ->order($sortField, $orderDir)
  9355. ->paginate($limit);
  9356. $rows = [];
  9357. foreach ($list->items() as $item) {
  9358. $row = is_array($item) ? $item : $item->toArray();
  9359. $scene = trim((string)($row['scene'] ?? ''));
  9360. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  9361. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  9362. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  9363. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  9364. $rows[] = $row;
  9365. }
  9366. $this->model = $bakModel;
  9367. return json(['total' => $list->total(), 'rows' => $rows]);
  9368. }
  9369. $this->model = $bakModel;
  9370. return $this->view->fetch('procuremen/emaillog');
  9371. }
  9372. /**
  9373. * 协助下发弹窗(选多家供应商并通知)
  9374. */
  9375. public function pickReview()
  9376. {
  9377. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  9378. $this->error(__('You have no permission'));
  9379. }
  9380. if ($this->request->isPost()) {
  9381. $this->error('请使用弹窗内「确认下发」提交');
  9382. }
  9383. $this->view->assign('pickMode', 1);
  9384. $this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
  9385. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  9386. }
  9387. /**
  9388. * 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
  9389. */
  9390. protected function ensurePurchaseOrderNotifySalesmanColumn(): void
  9391. {
  9392. static $done = false;
  9393. if ($done) {
  9394. return;
  9395. }
  9396. $done = true;
  9397. try {
  9398. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'notify_salesman'");
  9399. if (empty($cols)) {
  9400. Db::execute(
  9401. "ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
  9402. );
  9403. } else {
  9404. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  9405. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
  9406. Db::execute(
  9407. "ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
  9408. );
  9409. }
  9410. }
  9411. } catch (\Throwable $e) {
  9412. // ignore
  9413. }
  9414. }
  9415. /**
  9416. * 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
  9417. */
  9418. protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
  9419. {
  9420. static $done = false;
  9421. if ($done) {
  9422. return;
  9423. }
  9424. $done = true;
  9425. try {
  9426. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
  9427. if (empty($cols)) {
  9428. Db::execute(
  9429. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
  9430. );
  9431. }
  9432. } catch (\Throwable $e) {
  9433. // ignore
  9434. }
  9435. try {
  9436. $cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
  9437. if (empty($cols2)) {
  9438. Db::execute(
  9439. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
  9440. );
  9441. }
  9442. } catch (\Throwable $e) {
  9443. // ignore
  9444. }
  9445. }
  9446. /**
  9447. * 确保「采购确认通过/未通过」邮箱模版存在(正文同短信,末尾加平台链接)
  9448. */
  9449. protected function ensureConfirmResultEmailTemplates(): void
  9450. {
  9451. static $done = false;
  9452. if ($done) {
  9453. return;
  9454. }
  9455. $done = true;
  9456. $now = date('Y-m-d H:i:s');
  9457. $seeds = [
  9458. 'confirm_ok_email' => [
  9459. 'title' => '采购确认结果:已通过',
  9460. 'content' => "【可集达】您好,{company_name}:\n\n您参与的外发加工订单采购确认结果:已通过。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  9461. 'remark' => '审批通过-中标供应商邮箱通知;模版名称作邮件主题',
  9462. ],
  9463. 'confirm_fail_email' => [
  9464. 'title' => '采购确认结果:未通过',
  9465. 'content' => "【可集达】您好,{company_name}:\n\n您参与的外发加工订单采购确认结果:未通过。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  9466. 'remark' => '审批通过-未中标供应商邮箱通知;模版名称作邮件主题',
  9467. ],
  9468. ];
  9469. try {
  9470. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  9471. } catch (\Throwable $e) {
  9472. return;
  9473. }
  9474. $colNames = [];
  9475. foreach ($cols as $c) {
  9476. if (!is_array($c)) {
  9477. continue;
  9478. }
  9479. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  9480. if ($n !== '') {
  9481. $colNames[$n] = true;
  9482. }
  9483. }
  9484. foreach ($seeds as $scene => $seed) {
  9485. try {
  9486. $row = Db::table('purchase_sms_template')->where('scene', $scene)->find();
  9487. } catch (\Throwable $e) {
  9488. continue;
  9489. }
  9490. if (is_array($row) && $row !== []) {
  9491. continue;
  9492. }
  9493. $data = [
  9494. 'scene' => $scene,
  9495. 'title' => $seed['title'],
  9496. 'content' => $seed['content'],
  9497. 'remark' => $seed['remark'],
  9498. 'status' => 1,
  9499. ];
  9500. if (isset($colNames['updatetime'])) {
  9501. $data['updatetime'] = $now;
  9502. }
  9503. if (isset($colNames['createtime'])) {
  9504. $data['createtime'] = $now;
  9505. }
  9506. try {
  9507. Db::table('purchase_sms_template')->insert($data);
  9508. } catch (\Throwable $e) {
  9509. // ignore
  9510. }
  9511. }
  9512. }
  9513. /**
  9514. * 确保「供应商询价通知」邮箱模版存在(查询询价-询价/发邮件;可在短信模版配置中修改)
  9515. */
  9516. protected function ensureRfqSupplierEmailTemplate(): void
  9517. {
  9518. static $done = false;
  9519. if ($done) {
  9520. return;
  9521. }
  9522. $done = true;
  9523. $content = "您好,{company_name}:\n\n"
  9524. . "您有新的协助采购询价需求,请登录平台查看并处理。\n\n"
  9525. . "需求编号:{ccydh}\n"
  9526. . "印件名称:{cyjmc}\n"
  9527. . "{process_lines}\n\n"
  9528. . "请在 {deadline} 前完成回复。\n\n"
  9529. . "平台链接:{platform_url}\n";
  9530. try {
  9531. $row = Db::table('purchase_sms_template')
  9532. ->where('scene', 'rfq_supplier_email')
  9533. ->find();
  9534. } catch (\Throwable $e) {
  9535. return;
  9536. }
  9537. $now = date('Y-m-d H:i:s');
  9538. if (is_array($row) && $row !== []) {
  9539. return;
  9540. }
  9541. try {
  9542. $data = [
  9543. 'scene' => 'rfq_supplier_email',
  9544. 'title' => '供应商询价通知',
  9545. 'content' => $content,
  9546. 'remark' => '查询询价-询价/发邮件通知供应商;模版名称作邮件主题',
  9547. 'status' => 1,
  9548. ];
  9549. try {
  9550. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  9551. } catch (\Throwable $e) {
  9552. $cols = [];
  9553. }
  9554. $colNames = [];
  9555. foreach ($cols as $c) {
  9556. if (!is_array($c)) {
  9557. continue;
  9558. }
  9559. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  9560. if ($n !== '') {
  9561. $colNames[$n] = true;
  9562. }
  9563. }
  9564. if (isset($colNames['updatetime'])) {
  9565. $data['updatetime'] = $now;
  9566. }
  9567. if (isset($colNames['createtime'])) {
  9568. $data['createtime'] = $now;
  9569. }
  9570. Db::table('purchase_sms_template')->insert($data);
  9571. } catch (\Throwable $e) {
  9572. // ignore
  9573. }
  9574. }
  9575. /**
  9576. * 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
  9577. */
  9578. protected function ensureRfqSalesmanEmailTemplate(): void
  9579. {
  9580. static $done = false;
  9581. if ($done) {
  9582. return;
  9583. }
  9584. $done = true;
  9585. $content = "您好,{contact_name}:\n\n"
  9586. . "有新的协助采购询价需求,请知悉。\n"
  9587. . "印件名称:{cyjmc}\n"
  9588. . "工序名称:{cgymc}\n"
  9589. . "本次数量:{this_quantity}\n"
  9590. . "供应商报价:\n{supplier_quotes}\n"
  9591. . "平台链接:{platform_url}\n"
  9592. . "需求发起人:{cywyxm}\n";
  9593. try {
  9594. $row = Db::table('purchase_sms_template')
  9595. ->where('scene', 'rfq_salesman_email')
  9596. ->find();
  9597. } catch (\Throwable $e) {
  9598. return;
  9599. }
  9600. $now = date('Y-m-d H:i:s');
  9601. if (is_array($row) && $row !== []) {
  9602. $old = (string)($row['content'] ?? '');
  9603. // 无报价表格 / 无平台链接 / 链接不在「需求发起人」上方时,同步默认文案
  9604. $urlPos = strpos($old, '{platform_url}');
  9605. $cywyPos = strpos($old, '需求发起人');
  9606. $linkNotAboveStarter = ($urlPos === false)
  9607. || ($cywyPos !== false && $urlPos > $cywyPos);
  9608. $needMigrate = (strpos($old, '{supplier_quotes}') === false)
  9609. || (strpos($old, '供应商:{supplier_name}') !== false)
  9610. || $linkNotAboveStarter;
  9611. if ($needMigrate) {
  9612. $data = ['content' => $content];
  9613. if (trim((string)($row['title'] ?? '')) === '' || trim((string)($row['title'] ?? '')) === '询价通知') {
  9614. $data['title'] = '业务员询价通知';
  9615. }
  9616. try {
  9617. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
  9618. if (!empty($cols)) {
  9619. $data['updatetime'] = $now;
  9620. }
  9621. } catch (\Throwable $e) {
  9622. }
  9623. try {
  9624. Db::table('purchase_sms_template')
  9625. ->where('id', (int)($row['id'] ?? 0))
  9626. ->update($data);
  9627. } catch (\Throwable $e) {
  9628. }
  9629. }
  9630. return;
  9631. }
  9632. try {
  9633. $data = [
  9634. 'scene' => 'rfq_salesman_email',
  9635. 'title' => '业务员询价通知',
  9636. 'content' => $content,
  9637. 'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
  9638. 'status' => 1,
  9639. ];
  9640. try {
  9641. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  9642. } catch (\Throwable $e) {
  9643. $cols = [];
  9644. }
  9645. $colNames = [];
  9646. foreach ($cols as $c) {
  9647. if (!is_array($c)) {
  9648. continue;
  9649. }
  9650. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  9651. if ($n !== '') {
  9652. $colNames[$n] = true;
  9653. }
  9654. }
  9655. if (isset($colNames['updatetime'])) {
  9656. $data['updatetime'] = $now;
  9657. }
  9658. if (isset($colNames['createtime'])) {
  9659. $data['createtime'] = $now;
  9660. }
  9661. Db::table('purchase_sms_template')->insert($data);
  9662. } catch (\Throwable $e) {
  9663. // ignore
  9664. }
  9665. }
  9666. /**
  9667. * 通知业务员邮件:供应商报价明细行(仅名称+单价)
  9668. *
  9669. * @return array<int, array{name:string,amount:string}>
  9670. */
  9671. protected function loadRfqSalesmanSupplierQuoteRows(int $sid, string $supplierRaw = ''): array
  9672. {
  9673. $list = [];
  9674. $seen = [];
  9675. try {
  9676. $rows = Db::table('purchase_order_detail')
  9677. ->where('scydgy_id', $sid)
  9678. ->field('company_name,amount')
  9679. ->order('id', 'asc')
  9680. ->select();
  9681. if (is_array($rows)) {
  9682. foreach ($rows as $r) {
  9683. if (!is_array($r)) {
  9684. continue;
  9685. }
  9686. $cn = trim((string)($r['company_name'] ?? ''));
  9687. if ($cn === '' || isset($seen[$cn])) {
  9688. continue;
  9689. }
  9690. $seen[$cn] = true;
  9691. $amount = trim((string)($r['amount'] ?? ''));
  9692. $list[] = [
  9693. 'name' => $cn,
  9694. 'amount' => $amount !== '' ? $amount : '未报价',
  9695. ];
  9696. }
  9697. }
  9698. } catch (\Throwable $e) {
  9699. }
  9700. if ($list === [] && $supplierRaw !== '') {
  9701. foreach ($this->splitRfqSalesmanNames($supplierRaw) as $cn) {
  9702. if ($cn === '' || isset($seen[$cn])) {
  9703. continue;
  9704. }
  9705. $seen[$cn] = true;
  9706. $list[] = [
  9707. 'name' => $cn,
  9708. 'amount' => '未报价',
  9709. ];
  9710. }
  9711. }
  9712. return $list;
  9713. }
  9714. /**
  9715. * 通知业务员邮件:供应商报价 HTML 表格(名称+单价,不含时间)
  9716. */
  9717. protected function buildRfqSalesmanSupplierQuotesHtml(int $sid, string $supplierRaw = ''): string
  9718. {
  9719. $rows = $this->loadRfqSalesmanSupplierQuoteRows($sid, $supplierRaw);
  9720. if ($rows === []) {
  9721. return '<p style="margin:8px 0;color:#888;">暂无报价</p>';
  9722. }
  9723. $html = '<table cellpadding="0" cellspacing="0" border="1" '
  9724. . 'style="border-collapse:collapse;border-color:#ddd;width:100%;max-width:560px;font-size:14px;margin:8px 0;">'
  9725. . '<thead><tr style="background:#f5f5f5;">'
  9726. . '<th style="padding:8px 10px;text-align:center;width:56px;">序号</th>'
  9727. . '<th style="padding:8px 10px;text-align:left;">供应商名称</th>'
  9728. . '<th style="padding:8px 10px;text-align:center;width:100px;">单价</th>'
  9729. . '</tr></thead><tbody>';
  9730. foreach ($rows as $i => $row) {
  9731. $html .= '<tr>'
  9732. . '<td style="padding:8px 10px;text-align:center;">' . ($i + 1) . '</td>'
  9733. . '<td style="padding:8px 10px;">' . htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8') . '</td>'
  9734. . '<td style="padding:8px 10px;text-align:center;">' . htmlspecialchars($row['amount'], ENT_QUOTES, 'UTF-8') . '</td>'
  9735. . '</tr>';
  9736. }
  9737. $html .= '</tbody></table>';
  9738. return $html;
  9739. }
  9740. /**
  9741. * 询价多选字段:数组或字符串统一为顿号拼接
  9742. *
  9743. * @param mixed $raw
  9744. */
  9745. protected function joinRfqMultiSelectValues($raw): string
  9746. {
  9747. $parts = [];
  9748. if (is_array($raw)) {
  9749. foreach ($raw as $item) {
  9750. if (is_array($item)) {
  9751. continue;
  9752. }
  9753. $v = trim((string)$item);
  9754. if ($v !== '') {
  9755. $parts[] = $v;
  9756. }
  9757. }
  9758. } else {
  9759. $s = trim((string)$raw);
  9760. if ($s !== '') {
  9761. foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
  9762. $v = trim((string)$piece);
  9763. if ($v !== '') {
  9764. $parts[] = $v;
  9765. }
  9766. }
  9767. }
  9768. }
  9769. $parts = array_values(array_unique($parts));
  9770. return implode('、', $parts);
  9771. }
  9772. /**
  9773. * 新增询价:可选供应商名称(仅落库记录,不发通知)
  9774. *
  9775. * @return string[]
  9776. */
  9777. protected function loadRfqSupplierNameOptions(): array
  9778. {
  9779. $out = [];
  9780. try {
  9781. $rows = Db::table('customer')
  9782. ->where(function ($q) {
  9783. $q->where('status', 1)
  9784. ->whereOr('status', '1')
  9785. ->whereOr('status', '')
  9786. ->whereNull('status');
  9787. })
  9788. ->order('id', 'desc')
  9789. ->column('company_name');
  9790. } catch (\Throwable $e) {
  9791. return [];
  9792. }
  9793. if (!is_array($rows)) {
  9794. return [];
  9795. }
  9796. foreach ($rows as $name) {
  9797. $name = trim((string)$name);
  9798. if ($name === '' || isset($out[$name])) {
  9799. continue;
  9800. }
  9801. $out[$name] = $name;
  9802. }
  9803. return array_values($out);
  9804. }
  9805. /**
  9806. * 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
  9807. */
  9808. protected function rfqNotifySalesmanAuthGroupId(): int
  9809. {
  9810. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  9811. if ($id > 0) {
  9812. return $id;
  9813. }
  9814. try {
  9815. $found = Db::name('auth_group')
  9816. ->where('name', '业务员')
  9817. ->where('status', 'normal')
  9818. ->order('id', 'asc')
  9819. ->value('id');
  9820. $id = (int)$found;
  9821. } catch (\Throwable $e) {
  9822. $id = 0;
  9823. }
  9824. return $id > 0 ? $id : 12;
  9825. }
  9826. /**
  9827. * 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
  9828. *
  9829. * @return string[]
  9830. */
  9831. protected function loadRfqSalesmanNameOptions(): array
  9832. {
  9833. $out = [];
  9834. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  9835. $name = trim((string)($row['name'] ?? ''));
  9836. if ($name !== '') {
  9837. $out[] = $name;
  9838. }
  9839. }
  9840. return $out;
  9841. }
  9842. /**
  9843. * 业务员角色组下管理员:姓名、邮箱、手机
  9844. *
  9845. * @return array<int, array{name:string,email:string,mobile:string}>
  9846. */
  9847. protected function loadRfqSalesmanContactOptions(): array
  9848. {
  9849. $out = [];
  9850. $seen = [];
  9851. $groupId = $this->rfqNotifySalesmanAuthGroupId();
  9852. if ($groupId <= 0) {
  9853. return [];
  9854. }
  9855. try {
  9856. $adminIds = Db::name('auth_group_access')
  9857. ->where('group_id', $groupId)
  9858. ->column('uid');
  9859. } catch (\Throwable $e) {
  9860. return [];
  9861. }
  9862. $adminIds = is_array($adminIds)
  9863. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  9864. : [];
  9865. if ($adminIds === []) {
  9866. return [];
  9867. }
  9868. try {
  9869. $rows = Db::name('admin')
  9870. ->where('status', 'normal')
  9871. ->where('id', 'in', $adminIds)
  9872. ->order('id', 'asc')
  9873. ->field('id,nickname,username,email,mobile')
  9874. ->select();
  9875. } catch (\Throwable $e) {
  9876. return [];
  9877. }
  9878. if (!is_array($rows)) {
  9879. return [];
  9880. }
  9881. foreach ($rows as $row) {
  9882. if (!is_array($row)) {
  9883. continue;
  9884. }
  9885. $name = trim((string)($row['nickname'] ?? ''));
  9886. if ($name === '') {
  9887. $name = trim((string)($row['username'] ?? ''));
  9888. }
  9889. if ($name === '' || isset($seen[$name])) {
  9890. continue;
  9891. }
  9892. $seen[$name] = true;
  9893. $out[] = [
  9894. 'name' => $name,
  9895. 'email' => trim((string)($row['email'] ?? '')),
  9896. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  9897. ];
  9898. }
  9899. return $out;
  9900. }
  9901. /**
  9902. * 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
  9903. *
  9904. * @return string[]
  9905. */
  9906. protected function loadRfqDeptNameOptions(): array
  9907. {
  9908. $out = [];
  9909. // ERP 承揽部门(主来源)
  9910. try {
  9911. $vals = Db::table('mcyd')
  9912. ->where('CCLBMMC', '<>', '')
  9913. ->whereNotNull('CCLBMMC')
  9914. ->distinct(true)
  9915. ->limit(300)
  9916. ->column('CCLBMMC');
  9917. } catch (\Throwable $e) {
  9918. $vals = [];
  9919. }
  9920. if (is_array($vals)) {
  9921. foreach ($vals as $v) {
  9922. $v = trim((string)$v);
  9923. if ($v === '' || isset($out[$v])) {
  9924. continue;
  9925. }
  9926. $out[$v] = $v;
  9927. }
  9928. }
  9929. // 手工询价历史部门补全
  9930. try {
  9931. $poVals = Db::table('purchase_order')
  9932. ->where('CCLBMMC', '<>', '')
  9933. ->whereNotNull('CCLBMMC')
  9934. ->distinct(true)
  9935. ->limit(200)
  9936. ->column('CCLBMMC');
  9937. } catch (\Throwable $e) {
  9938. $poVals = [];
  9939. }
  9940. if (is_array($poVals)) {
  9941. foreach ($poVals as $v) {
  9942. $v = trim((string)$v);
  9943. if ($v === '' || isset($out[$v])) {
  9944. continue;
  9945. }
  9946. $out[$v] = $v;
  9947. }
  9948. }
  9949. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  9950. if (!isset($out[$preset])) {
  9951. $out[$preset] = $preset;
  9952. }
  9953. }
  9954. $list = array_values($out);
  9955. // 常用部门靠前
  9956. usort($list, static function ($a, $b) {
  9957. $weight = [
  9958. '营销中心' => 1,
  9959. '业务部' => 2,
  9960. '市场部' => 3,
  9961. '外贸部' => 4,
  9962. '新华技术业务部' => 5,
  9963. ];
  9964. $wa = $weight[$a] ?? 100;
  9965. $wb = $weight[$b] ?? 100;
  9966. if ($wa !== $wb) {
  9967. return $wa <=> $wb;
  9968. }
  9969. return strcmp((string)$a, (string)$b);
  9970. });
  9971. return $list;
  9972. }
  9973. /**
  9974. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  9975. */
  9976. public function add()
  9977. {
  9978. if ($this->request->isPost()) {
  9979. $params = $this->request->post('row/a');
  9980. if (!is_array($params)) {
  9981. $this->error(__('Parameter %s can not be empty', ''));
  9982. }
  9983. [, $adminName] = $this->GetUseName();
  9984. $params['cywyxm'] = $adminName;
  9985. try {
  9986. $sid = $this->saveManualPickOrder($params);
  9987. } catch (\InvalidArgumentException $e) {
  9988. $this->error($e->getMessage());
  9989. } catch (\Throwable $e) {
  9990. $this->error($e->getMessage());
  9991. }
  9992. $this->success('新增成功', '', [
  9993. 'scydgy_id' => $sid,
  9994. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  9995. ]);
  9996. }
  9997. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9998. [, $adminName] = $this->GetUseName();
  9999. $this->view->assign('adminNickname', $adminName);
  10000. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  10001. $this->view->assign('defaultCclbmmc', '营销中心');
  10002. $this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
  10003. $this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
  10004. $this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
  10005. return $this->view->fetch();
  10006. }
  10007. /**
  10008. * 业务员新增进度查询(手工询价;有查询权限看全部,含手机端新增且未通知业务员的)
  10009. */
  10010. public function rfqlist()
  10011. {
  10012. $this->relationSearch = false;
  10013. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ';
  10014. $this->request->filter(['strip_tags', 'trim']);
  10015. $this->ensurePurchaseOrderNotifySalesmanColumn();
  10016. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  10017. $this->ensureRfqSalesmanEmailTemplate();
  10018. $this->ensureRfqSupplierEmailTemplate();
  10019. if ($this->request->isAjax()) {
  10020. try {
  10021. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  10022. $limit = max(10, min(500, (int)$limit));
  10023. $filterYm = trim((string)$this->request->param('filter_ym', ''));
  10024. if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
  10025. $filterYm = date('Y-m');
  10026. }
  10027. $applyFilters = function ($query) use ($where, $filterYm) {
  10028. $query->where('scydgy_id', '<', 0);
  10029. $this->applyPurchaseOrderNotDeletedWhere($query);
  10030. // 查询询价:有菜单权限即可看全部手工单(含手机端新增、尚未通知业务员的)
  10031. $this->applyRfqListMonthFilter($query, $filterYm);
  10032. if (!empty($where)) {
  10033. // 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
  10034. $safeWhere = [];
  10035. $skipFields = [
  10036. 'supplier_name' => true,
  10037. 'progress_text' => true,
  10038. 'createtime_text' => true,
  10039. 'notify_time_text' => true,
  10040. 'can_notify_salesman' => true,
  10041. 'has_issued' => true,
  10042. 'has_quoted' => true,
  10043. ];
  10044. foreach ((array)$where as $cond) {
  10045. if (!is_array($cond) || !isset($cond[0])) {
  10046. continue;
  10047. }
  10048. $field = (string)$cond[0];
  10049. $fieldBase = (string)preg_replace('/\|.*$/', '', $field);
  10050. $fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
  10051. if (isset($skipFields[$fieldBase])) {
  10052. continue;
  10053. }
  10054. if ($fieldBase === 'supplier_name') {
  10055. continue;
  10056. }
  10057. $safeWhere[] = $cond;
  10058. }
  10059. if ($safeWhere !== []) {
  10060. $query->where($safeWhere);
  10061. }
  10062. }
  10063. };
  10064. $countQuery = Db::table('purchase_order');
  10065. $applyFilters($countQuery);
  10066. $total = (int)$countQuery->count();
  10067. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  10068. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  10069. $listQuery = Db::table('purchase_order');
  10070. $applyFilters($listQuery);
  10071. $rows = $listQuery
  10072. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,CDW,CDF,This_quantity,ceilingPrice,cGzzxMc,pick_company_name,cywyxm,notify_salesman,rfq_salesman_notified,rfq_salesman_notify_time,MBZ,createtime,dStamp,status,wflow_status')
  10073. ->order($sortField, $orderDir)
  10074. ->limit($offset, $limit)
  10075. ->select();
  10076. if (!is_array($rows)) {
  10077. $rows = [];
  10078. }
  10079. $sidList = [];
  10080. foreach ($rows as $r) {
  10081. if (!is_array($r)) {
  10082. continue;
  10083. }
  10084. $sid = (int)($r['scydgy_id'] ?? 0);
  10085. if ($sid < 0) {
  10086. $sidList[$sid] = true;
  10087. }
  10088. }
  10089. $issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
  10090. $quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
  10091. $out = [];
  10092. foreach ($rows as $r) {
  10093. if (!is_array($r)) {
  10094. continue;
  10095. }
  10096. $sid = (int)($r['scydgy_id'] ?? 0);
  10097. if ($sid >= 0) {
  10098. continue;
  10099. }
  10100. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  10101. if ($createdText === '') {
  10102. $createdText = trim((string)($r['dStamp'] ?? ''));
  10103. }
  10104. $notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
  10105. $supplier = trim((string)($r['cGzzxMc'] ?? ''));
  10106. if ($supplier === '') {
  10107. $supplier = trim((string)($r['pick_company_name'] ?? ''));
  10108. }
  10109. $hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
  10110. || isset($issuedSidSet[$sid]);
  10111. $hasQuoted = isset($quotedSidSet[$sid]);
  10112. $salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
  10113. $canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
  10114. $out[] = [
  10115. 'id' => (int)($r['id'] ?? 0),
  10116. 'scydgy_id' => $sid,
  10117. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  10118. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  10119. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  10120. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  10121. 'CDW' => trim((string)($r['CDW'] ?? '')),
  10122. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  10123. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  10124. 'CDF' => trim((string)($r['CDF'] ?? '')),
  10125. 'supplier_name' => $supplier,
  10126. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  10127. 'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
  10128. 'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
  10129. 'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
  10130. 'notify_time_text' => $notifyTimeText,
  10131. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  10132. 'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
  10133. 'has_issued' => $hasIssued ? 1 : 0,
  10134. 'has_quoted' => $hasQuoted ? 1 : 0,
  10135. 'can_notify_salesman' => $canNotifySalesman,
  10136. 'createtime' => $r['createtime'] ?? null,
  10137. 'createtime_text' => $createdText,
  10138. ];
  10139. }
  10140. return json(['total' => $total, 'rows' => $out]);
  10141. } catch (\Throwable $e) {
  10142. Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
  10143. return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
  10144. }
  10145. }
  10146. $sidebar = $this->loadRfqSidebarYearMonths();
  10147. $defaultYm = $this->resolveRfqListDefaultYm($sidebar);
  10148. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  10149. [, $adminName] = $this->GetUseName();
  10150. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  10151. $this->view->assign('adminNickname', $adminName);
  10152. $this->view->assign('defaultYm', $defaultYm);
  10153. $this->view->assign('sidebarYearMonths', $sidebar);
  10154. return $this->view->fetch('procuremen/rfqlist');
  10155. }
  10156. /**
  10157. * 列表默认月份:当月有数据用当月,否则取最近有数据的月份
  10158. *
  10159. * @param array<int, array{year:string, months:array}> $sidebar
  10160. */
  10161. protected function resolveRfqListDefaultYm(array $sidebar): string
  10162. {
  10163. $current = date('Y-m');
  10164. $yms = $this->flattenProcuremenSidebarYms($sidebar);
  10165. if (in_array($current, $yms, true)) {
  10166. return $current;
  10167. }
  10168. if ($yms !== []) {
  10169. rsort($yms, SORT_STRING);
  10170. return (string)$yms[0];
  10171. }
  10172. return $current;
  10173. }
  10174. /**
  10175. * 手工询价列表左侧月份(按 createtime / dStamp)
  10176. *
  10177. * @return array<int, array{year:string, months:array}>
  10178. */
  10179. protected function loadRfqSidebarYearMonths(): array
  10180. {
  10181. $ymSet = [];
  10182. try {
  10183. $q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
  10184. $this->applyPurchaseOrderNotDeletedWhere($q);
  10185. $rows = $q->field('createtime,dStamp')->limit(5000)->select();
  10186. } catch (\Throwable $e) {
  10187. $rows = [];
  10188. }
  10189. if (!is_array($rows)) {
  10190. $rows = [];
  10191. }
  10192. foreach ($rows as $r) {
  10193. if (!is_array($r)) {
  10194. continue;
  10195. }
  10196. $t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  10197. if ($t === '') {
  10198. $t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
  10199. }
  10200. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  10201. $ymSet[$m[1] . '-' . $m[2]] = true;
  10202. }
  10203. }
  10204. return $this->buildYearMonthSidebar(array_keys($ymSet));
  10205. }
  10206. /**
  10207. * 手工询价可见范围(用于详情/操作校验):
  10208. * 超管、具备「查询询价」权限、需求发起人、通知业务员 → 可见
  10209. * 列表页本身不再按发起人/通知过滤,避免手机端新增后后台看不到。
  10210. */
  10211. protected function applyManualRfqViewerWhere($query): void
  10212. {
  10213. if ($this->auth->isSuperAdmin() || $this->hasProcuremenPerm(['rfqlist'])) {
  10214. return;
  10215. }
  10216. [, $adminName] = $this->GetUseName();
  10217. $adminName = trim((string)$adminName);
  10218. if ($adminName === '') {
  10219. $query->whereRaw('1 = 0');
  10220. return;
  10221. }
  10222. // 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
  10223. $query->where(function ($q) use ($adminName) {
  10224. $q->where('cywyxm', $adminName)
  10225. ->whereOr('notify_salesman', $adminName)
  10226. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  10227. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  10228. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  10229. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  10230. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  10231. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  10232. });
  10233. }
  10234. /**
  10235. * 当前用户是否可查看/操作该手工询价单
  10236. */
  10237. protected function canViewManualRfqOrder(array $po): bool
  10238. {
  10239. if ($this->auth->isSuperAdmin()) {
  10240. return true;
  10241. }
  10242. // 有查询询价权限则可操作全部手工询价(询价/查看报价/通知业务员等)
  10243. if ($this->hasProcuremenPerm(['rfqlist'])) {
  10244. return true;
  10245. }
  10246. [, $adminName] = $this->GetUseName();
  10247. $adminName = trim((string)$adminName);
  10248. if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
  10249. return true;
  10250. }
  10251. if ($adminName !== '') {
  10252. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  10253. if ($n === $adminName) {
  10254. return true;
  10255. }
  10256. }
  10257. }
  10258. return false;
  10259. }
  10260. /**
  10261. * 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
  10262. */
  10263. protected function applyRfqListMonthFilter($query, string $ym): void
  10264. {
  10265. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  10266. $ym = date('Y-m');
  10267. }
  10268. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  10269. // 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
  10270. $query->whereRaw(
  10271. "("
  10272. . "CASE "
  10273. . "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  10274. . "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
  10275. . "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
  10276. . "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  10277. . "THEN TRIM(CAST(createtime AS CHAR(32))) "
  10278. . "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
  10279. . "END"
  10280. . ") LIKE '{$ymEsc}-%'"
  10281. );
  10282. }
  10283. /**
  10284. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  10285. */
  10286. public function rfqlistDetails()
  10287. {
  10288. return $this->details();
  10289. }
  10290. /**
  10291. * 查询询价 — 弹窗:可选通知业务员名单(勾选后确认通知)
  10292. */
  10293. public function rfqnotifysalesmen()
  10294. {
  10295. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman'])) {
  10296. $this->error(__('You have no permission'));
  10297. }
  10298. $this->ensurePurchaseOrderNotifySalesmanColumn();
  10299. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  10300. $sid = (int)$this->request->param('scydgy_id', 0);
  10301. if ($sid >= 0) {
  10302. $this->error('仅支持手工新增询价单');
  10303. }
  10304. $po = $this->loadManualRfqOrderForNotify($sid);
  10305. $selectedMap = [];
  10306. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  10307. $selectedMap[$n] = true;
  10308. }
  10309. $list = [];
  10310. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  10311. $name = trim((string)($row['name'] ?? ''));
  10312. if ($name === '') {
  10313. continue;
  10314. }
  10315. $email = trim((string)($row['email'] ?? ''));
  10316. $mobile = trim((string)($row['mobile'] ?? ''));
  10317. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  10318. $list[] = [
  10319. 'name' => $name,
  10320. 'email' => $email,
  10321. 'mobile' => $mobile,
  10322. 'can_select' => $hasEmail ? 1 : 0,
  10323. 'checked' => (!empty($selectedMap[$name]) && $hasEmail) ? 1 : 0,
  10324. ];
  10325. }
  10326. $canNotify = $this->canRfqNotifySalesman($po);
  10327. $this->success('', null, [
  10328. 'scydgy_id' => $sid,
  10329. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  10330. 'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
  10331. 'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
  10332. 'can_notify_salesman' => $canNotify ? 1 : 0,
  10333. 'list' => $list,
  10334. ]);
  10335. }
  10336. /**
  10337. * 查询询价 — 补加通知业务员可选名单
  10338. */
  10339. public function rfqsalesmanoptions()
  10340. {
  10341. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen'])) {
  10342. $this->error(__('You have no permission'));
  10343. }
  10344. $out = [];
  10345. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  10346. $email = trim((string)($row['email'] ?? ''));
  10347. $mobile = trim((string)($row['mobile'] ?? ''));
  10348. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  10349. $out[] = [
  10350. 'name' => (string)($row['name'] ?? ''),
  10351. 'email' => $email,
  10352. 'mobile' => $mobile,
  10353. 'can_select' => $hasEmail ? 1 : 0,
  10354. ];
  10355. }
  10356. $this->success('', null, ['list' => $out]);
  10357. }
  10358. /**
  10359. * 查询询价 — 补加通知业务员(合并更新 notify_salesman)
  10360. */
  10361. public function rfqappendsalesmen()
  10362. {
  10363. if (!$this->request->isPost()) {
  10364. $this->error(__('Invalid parameters'));
  10365. }
  10366. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen'])) {
  10367. $this->error(__('You have no permission'));
  10368. }
  10369. $this->ensurePurchaseOrderNotifySalesmanColumn();
  10370. $sid = (int)$this->request->post('scydgy_id', 0);
  10371. if ($sid >= 0) {
  10372. $this->error('仅支持手工新增询价单');
  10373. }
  10374. $po = $this->loadManualRfqOrderForNotify($sid);
  10375. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  10376. $this->error('订单已完结,无法添加业务员');
  10377. }
  10378. $raw = $this->request->post('salesmen/a', []);
  10379. if (!is_array($raw) || $raw === []) {
  10380. $salesmenJson = $this->request->post('salesmen_json', '');
  10381. if (is_string($salesmenJson) && $salesmenJson !== '') {
  10382. $decoded = json_decode($salesmenJson, true);
  10383. $raw = is_array($decoded) ? $decoded : [];
  10384. }
  10385. }
  10386. $addNames = [];
  10387. foreach ((array)$raw as $item) {
  10388. if (is_array($item)) {
  10389. $n = trim((string)($item['name'] ?? ''));
  10390. } else {
  10391. $n = trim((string)$item);
  10392. }
  10393. if ($n !== '') {
  10394. $addNames[] = $n;
  10395. }
  10396. }
  10397. $addNames = array_values(array_unique($addNames));
  10398. if ($addNames === []) {
  10399. $this->error('请选择要添加的业务员');
  10400. }
  10401. $allowedOptions = $this->loadRfqSalesmanContactOptions();
  10402. $allowedMap = [];
  10403. foreach ($allowedOptions as $opt) {
  10404. $n = trim((string)($opt['name'] ?? ''));
  10405. if ($n === '') {
  10406. continue;
  10407. }
  10408. $email = trim((string)($opt['email'] ?? ''));
  10409. $allowedMap[$n] = ($email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL));
  10410. }
  10411. foreach ($addNames as $n) {
  10412. if (!array_key_exists($n, $allowedMap)) {
  10413. $this->error('业务员不在可选名单中:' . $n);
  10414. }
  10415. if (!$allowedMap[$n]) {
  10416. $this->error('业务员未填写有效邮箱,无法添加:' . $n);
  10417. }
  10418. }
  10419. $existingRaw = trim((string)($po['notify_salesman'] ?? ''));
  10420. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  10421. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  10422. try {
  10423. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['notify_salesman' => $mergedStr]);
  10424. } catch (\Throwable $e) {
  10425. $this->error('保存失败:' . $e->getMessage());
  10426. }
  10427. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  10428. $this->addOrderLog($sid, 'rfq_append_salesman', '添加通知业务员:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  10429. $this->success('已添加业务员', null, [
  10430. 'scydgy_id' => $sid,
  10431. 'notify_salesman' => $mergedStr,
  10432. 'added_count' => count($addNames),
  10433. ]);
  10434. }
  10435. /**
  10436. * 查询询价 — 勾选业务员后邮箱通知(salesmen_json)
  10437. */
  10438. public function rfqnotifysalesman()
  10439. {
  10440. if (!$this->request->isPost()) {
  10441. $this->error(__('Invalid parameters'));
  10442. }
  10443. if (!$this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen'])) {
  10444. $this->error(__('You have no permission'));
  10445. }
  10446. $this->ensurePurchaseOrderNotifySalesmanColumn();
  10447. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  10448. $sid = (int)$this->request->post('scydgy_id', 0);
  10449. if ($sid >= 0) {
  10450. $this->error('仅支持手工新增询价单');
  10451. }
  10452. $po = $this->loadManualRfqOrderForNotify($sid);
  10453. $this->assertRfqCanNotifySalesman($po);
  10454. $raw = $this->request->post('salesmen/a', []);
  10455. if (!is_array($raw) || $raw === []) {
  10456. $salesmenJson = $this->request->post('salesmen_json', '');
  10457. if (is_string($salesmenJson) && $salesmenJson !== '') {
  10458. $decoded = json_decode($salesmenJson, true);
  10459. $raw = is_array($decoded) ? $decoded : [];
  10460. }
  10461. }
  10462. // 兼容旧参数:notify_all / 单人 name
  10463. if ((!is_array($raw) || $raw === []) && (int)$this->request->post('notify_all', 0) === 1) {
  10464. $raw = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  10465. }
  10466. if ((!is_array($raw) || $raw === [])) {
  10467. $oneName = trim((string)$this->request->post('name', ''));
  10468. if ($oneName !== '') {
  10469. $raw = [$oneName];
  10470. }
  10471. }
  10472. $selectedNames = [];
  10473. foreach ((array)$raw as $item) {
  10474. if (is_array($item)) {
  10475. $n = trim((string)($item['name'] ?? ''));
  10476. } else {
  10477. $n = trim((string)$item);
  10478. }
  10479. if ($n !== '') {
  10480. $selectedNames[] = $n;
  10481. }
  10482. }
  10483. $selectedNames = array_values(array_unique($selectedNames));
  10484. if ($selectedNames === []) {
  10485. $this->error('请选择要通知的业务员');
  10486. }
  10487. $optionMap = [];
  10488. foreach ($this->loadRfqSalesmanContactOptions() as $opt) {
  10489. $n = trim((string)($opt['name'] ?? ''));
  10490. if ($n === '') {
  10491. continue;
  10492. }
  10493. $optionMap[$n] = $opt;
  10494. }
  10495. $targets = [];
  10496. foreach ($selectedNames as $n) {
  10497. if (!isset($optionMap[$n])) {
  10498. $this->error('业务员不在可选名单中:' . $n);
  10499. }
  10500. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  10501. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  10502. $this->error('业务员未填写有效邮箱,无法通知:' . $n);
  10503. }
  10504. $resolved = $this->resolveRfqSalesmanContactRows([$n]);
  10505. $targets[] = $resolved[0] ?? [
  10506. 'admin_id' => 0,
  10507. 'name' => $n,
  10508. 'email' => $email,
  10509. ];
  10510. }
  10511. $mergedStr = $this->joinRfqMultiSelectValues($selectedNames);
  10512. try {
  10513. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10514. 'notify_salesman' => $mergedStr,
  10515. ]);
  10516. } catch (\Throwable $e) {
  10517. $this->error('保存通知业务员失败:' . $e->getMessage());
  10518. }
  10519. $po['notify_salesman'] = $mergedStr;
  10520. $mailConfig = $this->loadMailerConfig();
  10521. if (empty($mailConfig['host'])) {
  10522. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  10523. }
  10524. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  10525. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  10526. }
  10527. $this->ensureRfqSalesmanEmailTemplate();
  10528. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  10529. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  10530. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  10531. $cdw = trim((string)($po['CDW'] ?? ''));
  10532. $qty = trim((string)$this->resolveProcuremenThisQuantity($po));
  10533. $ceiling = trim((string)$this->resolveProcuremenCeilingPrice($po));
  10534. $mbz = trim((string)($po['MBZ'] ?? ''));
  10535. $cywyxm = trim((string)($po['cywyxm'] ?? ''));
  10536. $supplier = trim((string)($po['cGzzxMc'] ?? ''));
  10537. if ($supplier === '') {
  10538. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  10539. }
  10540. $supplierQuotesHtml = $this->buildRfqSalesmanSupplierQuotesHtml($sid, $supplier);
  10541. try {
  10542. $platformUrl = $this->buildMprocMobileRfqAddUrl($sid, 'pending');
  10543. } catch (\Throwable $e) {
  10544. $platformUrl = '';
  10545. }
  10546. try {
  10547. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
  10548. } catch (\Throwable $e) {
  10549. $this->error($e->getMessage());
  10550. }
  10551. $okNames = [];
  10552. $failMsgs = [];
  10553. foreach ($targets as $contact) {
  10554. $toEmail = trim((string)($contact['email'] ?? ''));
  10555. $toName = trim((string)($contact['name'] ?? ''));
  10556. $notifyVars = [
  10557. 'contact_name' => $toName,
  10558. 'salesman_name' => $toName,
  10559. 'company_name' => $toName,
  10560. 'email' => $toEmail,
  10561. 'ccydh' => $ccydh,
  10562. 'cyjmc' => $cyjmc,
  10563. 'cgymc' => $cgymc,
  10564. 'cdw' => $cdw,
  10565. 'this_quantity' => $qty,
  10566. 'ceilingPrice' => $ceiling,
  10567. 'MBZ' => $mbz,
  10568. 'supplier_name' => $supplier,
  10569. // 占位符,转 HTML 后再替换成表格,避免被 htmlspecialchars 转义
  10570. 'supplier_quotes' => '__RFQ_SUPPLIER_QUOTES_TABLE__',
  10571. 'cywyxm' => $cywyxm,
  10572. 'platform_url' => $platformUrl,
  10573. ];
  10574. try {
  10575. $mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
  10576. $mailSubject = $mailSubjectTpl;
  10577. foreach ($notifyVars as $k => $v) {
  10578. if ($k === 'supplier_quotes') {
  10579. continue;
  10580. }
  10581. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  10582. }
  10583. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  10584. $mailSubject = trim((string)$mailSubject);
  10585. if ($mailSubject === '') {
  10586. $mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  10587. }
  10588. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  10589. $mailBody = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', $supplierQuotesHtml, $mailBody);
  10590. $mailPlainForLog = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', strip_tags(str_replace(['</tr>', '</p>'], "\n", $supplierQuotesHtml)), $mailPlain);
  10591. $bundle = [
  10592. 'company_name' => $toName,
  10593. 'email' => $toEmail,
  10594. 'mail_plain' => $mailPlainForLog,
  10595. 'mail_body' => $mailBody,
  10596. 'ccydh' => $ccydh,
  10597. 'email_log_scene' => 'rfq_salesman',
  10598. 'email_log_scydgy_id' => $sid,
  10599. 'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
  10600. 'notify_vars' => $notifyVars,
  10601. ];
  10602. $this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
  10603. $okNames[] = $toName . '(' . $toEmail . ')';
  10604. } catch (\Throwable $e) {
  10605. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  10606. }
  10607. }
  10608. if ($okNames === []) {
  10609. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  10610. }
  10611. $now = date('Y-m-d H:i:s');
  10612. try {
  10613. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10614. 'rfq_salesman_notified' => 1,
  10615. 'rfq_salesman_notify_time' => $now,
  10616. ]);
  10617. } catch (\Throwable $e) {
  10618. // ignore
  10619. }
  10620. $this->addOrderLog(
  10621. $sid,
  10622. 'rfq_notify_salesman',
  10623. '邮箱通知业务员:' . implode('、', $okNames),
  10624. (int)($po['id'] ?? 0)
  10625. );
  10626. $msg = '已通知 ' . count($okNames) . ' 人';
  10627. if ($failMsgs !== []) {
  10628. $msg .= ';部分失败:' . implode(';', $failMsgs);
  10629. }
  10630. $this->success($msg, null, [
  10631. 'scydgy_id' => $sid,
  10632. 'notify_salesman' => $mergedStr,
  10633. 'rfq_salesman_notified' => 1,
  10634. 'rfq_salesman_notify_time' => $now,
  10635. 'notify_time_text' => $now,
  10636. 'ok_count' => count($okNames),
  10637. 'fail_count' => count($failMsgs),
  10638. ]);
  10639. }
  10640. /**
  10641. * 生产部角色组 id(mproc.mobile_delivery_group_id,缺省按组名「生产部/生产员」查找)
  10642. */
  10643. protected function deliveryNotifyAuthGroupId(): int
  10644. {
  10645. static $mprocCfgLoaded = false;
  10646. if (!$mprocCfgLoaded) {
  10647. $mprocCfgLoaded = true;
  10648. if (is_file(APP_PATH . 'extra/mproc.php')) {
  10649. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  10650. }
  10651. }
  10652. $id = (int)Config::get('mproc.mobile_delivery_group_id');
  10653. if ($id > 0) {
  10654. return $id;
  10655. }
  10656. try {
  10657. foreach (['生产部', '生产员'] as $name) {
  10658. $gid = (int)Db::name('auth_group')->where('name', $name)->value('id');
  10659. if ($gid > 0) {
  10660. return $gid;
  10661. }
  10662. }
  10663. } catch (\Throwable $e) {
  10664. }
  10665. return 0;
  10666. }
  10667. /**
  10668. * 生产部人员:姓名、邮箱、手机
  10669. *
  10670. * @return array<int, array{name:string,email:string,mobile:string,admin_id:int}>
  10671. */
  10672. protected function loadDeliveryStaffContactOptions(): array
  10673. {
  10674. $out = [];
  10675. $seen = [];
  10676. $groupId = $this->deliveryNotifyAuthGroupId();
  10677. if ($groupId <= 0) {
  10678. return [];
  10679. }
  10680. try {
  10681. $adminIds = Db::name('auth_group_access')
  10682. ->where('group_id', $groupId)
  10683. ->column('uid');
  10684. } catch (\Throwable $e) {
  10685. return [];
  10686. }
  10687. $adminIds = is_array($adminIds)
  10688. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  10689. : [];
  10690. if ($adminIds === []) {
  10691. return [];
  10692. }
  10693. try {
  10694. $rows = Db::name('admin')
  10695. ->where('status', 'normal')
  10696. ->where('id', 'in', $adminIds)
  10697. ->order('id', 'asc')
  10698. ->field('id,nickname,username,email,mobile')
  10699. ->select();
  10700. } catch (\Throwable $e) {
  10701. return [];
  10702. }
  10703. if (!is_array($rows)) {
  10704. return [];
  10705. }
  10706. foreach ($rows as $row) {
  10707. if (!is_array($row)) {
  10708. continue;
  10709. }
  10710. $name = trim((string)($row['nickname'] ?? ''));
  10711. if ($name === '') {
  10712. $name = trim((string)($row['username'] ?? ''));
  10713. }
  10714. if ($name === '' || isset($seen[$name])) {
  10715. continue;
  10716. }
  10717. $seen[$name] = true;
  10718. $out[] = [
  10719. 'admin_id' => (int)($row['id'] ?? 0),
  10720. 'name' => $name,
  10721. 'email' => trim((string)($row['email'] ?? '')),
  10722. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  10723. ];
  10724. }
  10725. return $out;
  10726. }
  10727. /**
  10728. * 交货情况页直达链接(邮件用,单参数避免邮箱客户端拆坏)
  10729. */
  10730. protected function buildMprocMobileDeliveryscoreUrl(string $ccydh): string
  10731. {
  10732. static $mprocCfgLoaded = false;
  10733. if (!$mprocCfgLoaded) {
  10734. $mprocCfgLoaded = true;
  10735. if (is_file(APP_PATH . 'extra/mproc.php')) {
  10736. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  10737. }
  10738. }
  10739. $base = $this->resolveMprocMobilePublicBaseUrl();
  10740. if ($base === '') {
  10741. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  10742. }
  10743. $path = '/index.php/index/index/deliveryscore';
  10744. $ccydh = trim($ccydh);
  10745. if ($ccydh === '') {
  10746. return $base . $path;
  10747. }
  10748. return $base . $path . '?ccydh=' . rawurlencode($ccydh);
  10749. }
  10750. /**
  10751. * 按订单号取已审核外发单(合并工序字段)
  10752. *
  10753. * @return array<string, mixed>|null
  10754. */
  10755. protected function loadApprovedOrderForDeliveryNotify(string $ccydh, int $sid = 0): ?array
  10756. {
  10757. $ccydh = trim($ccydh);
  10758. if ($ccydh === '' && $sid > 0) {
  10759. try {
  10760. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
  10761. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  10762. } catch (\Throwable $e) {
  10763. $ccydh = '';
  10764. }
  10765. }
  10766. if ($ccydh === '') {
  10767. return null;
  10768. }
  10769. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  10770. $approvedIn = implode(',', array_map(static function ($v) {
  10771. return "'" . str_replace("'", "''", (string)$v) . "'";
  10772. }, $approvedVals));
  10773. try {
  10774. $rows = Db::table('purchase_order')
  10775. ->where('CCYDH', $ccydh)
  10776. ->where('scydgy_id', '>', 0)
  10777. ->whereRaw('(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')')
  10778. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  10779. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  10780. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,CDW,This_quantity,NGZL,pick_company_name,delivery_deadline,MBZ,cywyxm,wflow_status,status')
  10781. ->order('id', 'asc')
  10782. ->select();
  10783. } catch (\Throwable $e) {
  10784. $rows = [];
  10785. }
  10786. if (!is_array($rows) || $rows === []) {
  10787. return null;
  10788. }
  10789. $gymc = [];
  10790. $qty = [];
  10791. $first = null;
  10792. foreach ($rows as $r) {
  10793. if (!is_array($r)) {
  10794. continue;
  10795. }
  10796. if ($first === null) {
  10797. $first = $r;
  10798. }
  10799. $g = trim((string)($r['CGYMC'] ?? ''));
  10800. if ($g !== '' && !in_array($g, $gymc, true)) {
  10801. $gymc[] = $g;
  10802. }
  10803. $q = trim((string)$this->resolveProcuremenThisQuantity($r));
  10804. if ($q !== '' && !in_array($q, $qty, true)) {
  10805. $qty[] = $q;
  10806. }
  10807. }
  10808. if (!is_array($first)) {
  10809. return null;
  10810. }
  10811. $first['CGYMC'] = $gymc !== [] ? implode('、', $gymc) : '';
  10812. $first['This_quantity'] = $qty !== [] ? implode('、', $qty) : '';
  10813. $first['delivery_deadline'] = $this->mprocFormatYmdForNotify($first['delivery_deadline'] ?? '');
  10814. return $first;
  10815. }
  10816. protected function mprocFormatYmdForNotify($raw): string
  10817. {
  10818. $s = trim((string)$raw);
  10819. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  10820. return '';
  10821. }
  10822. $s = str_replace(['/', '.'], '-', $s);
  10823. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  10824. return $m[1];
  10825. }
  10826. $ts = strtotime(str_replace('T', ' ', $s));
  10827. if ($ts === false || $ts <= 0) {
  10828. return '';
  10829. }
  10830. return date('Y-m-d', $ts);
  10831. }
  10832. /**
  10833. * 确保「交货情况通知生产部-邮箱」模版存在
  10834. */
  10835. protected function ensureDeliveryNotifyEmailTemplate(): void
  10836. {
  10837. static $done = false;
  10838. if ($done) {
  10839. return;
  10840. }
  10841. $done = true;
  10842. $content = "您好,{contact_name}:\n\n"
  10843. . "有订单已中标外发,需要您在手机端确认交货情况(填写库位、交货情况、交货日期等)。\n\n"
  10844. . "订单号:{ccydh}\n"
  10845. . "印件名称:{cyjmc}\n"
  10846. . "工序名称:{cgymc}\n"
  10847. . "订单数量:{this_quantity}\n"
  10848. . "中标供应商:{supplier_name}\n"
  10849. . "交货截止日期:{delivery_deadline}\n\n"
  10850. . "请点击下方链接登录后,找到该订单进行填写:\n"
  10851. . "{platform_url}\n";
  10852. try {
  10853. $row = Db::table('purchase_sms_template')
  10854. ->where('scene', 'delivery_notify_email')
  10855. ->find();
  10856. } catch (\Throwable $e) {
  10857. return;
  10858. }
  10859. $now = date('Y-m-d H:i:s');
  10860. if (is_array($row) && $row !== []) {
  10861. return;
  10862. }
  10863. try {
  10864. $data = [
  10865. 'scene' => 'delivery_notify_email',
  10866. 'title' => '交货情况确认通知 - {ccydh}',
  10867. 'content' => $content,
  10868. 'remark' => '审批通过后通知生产部填写交货情况;模版名称作邮件主题,支持变量',
  10869. 'status' => 1,
  10870. ];
  10871. try {
  10872. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  10873. } catch (\Throwable $e) {
  10874. $cols = [];
  10875. }
  10876. $colNames = [];
  10877. foreach ($cols as $c) {
  10878. if (!is_array($c)) {
  10879. continue;
  10880. }
  10881. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  10882. if ($n !== '') {
  10883. $colNames[$n] = true;
  10884. }
  10885. }
  10886. if (isset($colNames['updatetime'])) {
  10887. $data['updatetime'] = $now;
  10888. }
  10889. if (isset($colNames['createtime'])) {
  10890. $data['createtime'] = $now;
  10891. }
  10892. Db::table('purchase_sms_template')->insert($data);
  10893. } catch (\Throwable $e) {
  10894. // ignore
  10895. }
  10896. }
  10897. /**
  10898. * 通知生产部 — 可选人员名单
  10899. */
  10900. public function deliverynotifymen()
  10901. {
  10902. if (!$this->hasProcuremenPerm(['deliverynotifymen', 'deliverynotify', 'outward_detail', 'outwarddetail', 'purchaseconfirmpick', 'details'])) {
  10903. $this->error(__('You have no permission'));
  10904. }
  10905. $this->ensureDeliveryNotifyEmailTemplate();
  10906. $sid = (int)$this->request->request('scydgy_id', 0);
  10907. $ccydh = trim((string)$this->request->request('ccydh', ''));
  10908. $po = $this->loadApprovedOrderForDeliveryNotify($ccydh, $sid);
  10909. if ($po === null) {
  10910. $this->error('未找到已审核且已中标的订单,无法通知生产部');
  10911. }
  10912. $list = [];
  10913. foreach ($this->loadDeliveryStaffContactOptions() as $opt) {
  10914. $email = trim((string)($opt['email'] ?? ''));
  10915. $list[] = [
  10916. 'name' => (string)($opt['name'] ?? ''),
  10917. 'email' => $email,
  10918. 'mobile' => (string)($opt['mobile'] ?? ''),
  10919. 'can_select' => ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) ? 1 : 0,
  10920. 'checked' => 0,
  10921. ];
  10922. }
  10923. $this->success('', null, [
  10924. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  10925. 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
  10926. 'cgymc' => trim((string)($po['CGYMC'] ?? '')),
  10927. 'this_quantity' => trim((string)($po['This_quantity'] ?? '')),
  10928. 'supplier_name' => trim((string)($po['pick_company_name'] ?? '')),
  10929. 'delivery_deadline' => trim((string)($po['delivery_deadline'] ?? '')),
  10930. 'list' => $list,
  10931. ]);
  10932. }
  10933. /**
  10934. * 通知生产部 — 勾选后发邮件(staff_json / names)
  10935. */
  10936. public function deliverynotify()
  10937. {
  10938. if (!$this->request->isPost()) {
  10939. $this->error(__('Invalid parameters'));
  10940. }
  10941. if (!$this->hasProcuremenPerm(['deliverynotify', 'deliverynotifymen', 'outward_detail', 'outwarddetail', 'purchaseconfirmpick', 'details'])) {
  10942. $this->error(__('You have no permission'));
  10943. }
  10944. $this->ensureDeliveryNotifyEmailTemplate();
  10945. $sid = (int)$this->request->post('scydgy_id', 0);
  10946. $ccydh = trim((string)$this->request->post('ccydh', ''));
  10947. $po = $this->loadApprovedOrderForDeliveryNotify($ccydh, $sid);
  10948. if ($po === null) {
  10949. $this->error('未找到已审核且已中标的订单,无法通知生产部');
  10950. }
  10951. $ccydh = trim((string)($po['CCYDH'] ?? $ccydh));
  10952. $raw = $this->request->post('staff/a', []);
  10953. if (!is_array($raw) || $raw === []) {
  10954. $staffJson = $this->request->post('staff_json', '');
  10955. if (is_string($staffJson) && $staffJson !== '') {
  10956. $decoded = json_decode($staffJson, true);
  10957. $raw = is_array($decoded) ? $decoded : [];
  10958. }
  10959. }
  10960. $selectedNames = [];
  10961. foreach ((array)$raw as $item) {
  10962. if (is_array($item)) {
  10963. $n = trim((string)($item['name'] ?? ''));
  10964. } else {
  10965. $n = trim((string)$item);
  10966. }
  10967. if ($n !== '') {
  10968. $selectedNames[] = $n;
  10969. }
  10970. }
  10971. $selectedNames = array_values(array_unique($selectedNames));
  10972. if ($selectedNames === []) {
  10973. $this->error('请选择要通知的生产部人员');
  10974. }
  10975. $optionMap = [];
  10976. foreach ($this->loadDeliveryStaffContactOptions() as $opt) {
  10977. $n = trim((string)($opt['name'] ?? ''));
  10978. if ($n === '') {
  10979. continue;
  10980. }
  10981. $optionMap[$n] = $opt;
  10982. }
  10983. $targets = [];
  10984. foreach ($selectedNames as $n) {
  10985. if (!isset($optionMap[$n])) {
  10986. $this->error('人员不在生产部可选名单中:' . $n);
  10987. }
  10988. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  10989. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  10990. $this->error('未填写有效邮箱,无法通知:' . $n);
  10991. }
  10992. $targets[] = $optionMap[$n];
  10993. }
  10994. $mailConfig = $this->loadMailerConfig();
  10995. if (empty($mailConfig['host'])) {
  10996. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  10997. }
  10998. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  10999. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  11000. }
  11001. try {
  11002. $platformUrl = $this->buildMprocMobileDeliveryscoreUrl($ccydh);
  11003. } catch (\Throwable $e) {
  11004. $this->error($e->getMessage());
  11005. }
  11006. try {
  11007. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('delivery_notify_email');
  11008. } catch (\Throwable $e) {
  11009. $this->error($e->getMessage());
  11010. }
  11011. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  11012. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  11013. $qty = trim((string)($po['This_quantity'] ?? ''));
  11014. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  11015. $deadline = trim((string)($po['delivery_deadline'] ?? ''));
  11016. $firstSid = (int)($po['scydgy_id'] ?? 0);
  11017. $firstPoId = (int)($po['id'] ?? 0);
  11018. $okNames = [];
  11019. $failMsgs = [];
  11020. foreach ($targets as $contact) {
  11021. $toEmail = trim((string)($contact['email'] ?? ''));
  11022. $toName = trim((string)($contact['name'] ?? ''));
  11023. $notifyVars = [
  11024. 'contact_name' => $toName,
  11025. 'company_name' => $toName,
  11026. 'email' => $toEmail,
  11027. 'ccydh' => $ccydh,
  11028. 'cyjmc' => $cyjmc,
  11029. 'cgymc' => $cgymc,
  11030. 'this_quantity' => $qty,
  11031. 'supplier_name' => $supplier,
  11032. 'delivery_deadline' => $deadline,
  11033. 'platform_url' => $platformUrl,
  11034. ];
  11035. try {
  11036. $mailPlain = $this->renderNotifyTemplate('delivery_notify_email', $notifyVars);
  11037. $mailSubject = $mailSubjectTpl;
  11038. foreach ($notifyVars as $k => $v) {
  11039. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  11040. }
  11041. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  11042. $mailSubject = trim((string)$mailSubject);
  11043. if ($mailSubject === '') {
  11044. $mailSubject = '交货情况确认通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  11045. }
  11046. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  11047. $this->issueSendSupplierEmail([
  11048. 'company_name' => $toName,
  11049. 'email' => $toEmail,
  11050. 'mail_plain' => $mailPlain,
  11051. 'mail_body' => $mailBody,
  11052. 'ccydh' => $ccydh,
  11053. 'email_log_scene' => 'delivery_notify',
  11054. 'email_log_scydgy_id' => $firstSid,
  11055. 'email_log_purchase_order_id' => $firstPoId,
  11056. 'notify_vars' => $notifyVars,
  11057. ], $mailConfig, $mailSubject);
  11058. $okNames[] = $toName . '(' . $toEmail . ')';
  11059. } catch (\Throwable $e) {
  11060. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  11061. }
  11062. }
  11063. if ($okNames === []) {
  11064. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  11065. }
  11066. if ($firstSid > 0) {
  11067. $this->addOrderLog(
  11068. $firstSid,
  11069. 'delivery_notify',
  11070. '邮箱通知生产部:' . implode('、', $okNames),
  11071. $firstPoId > 0 ? $firstPoId : null
  11072. );
  11073. }
  11074. $msg = '已通知 ' . count($okNames) . ' 人';
  11075. if ($failMsgs !== []) {
  11076. $msg .= ';部分失败:' . implode(';', $failMsgs);
  11077. }
  11078. $this->success($msg, null, [
  11079. 'ccydh' => $ccydh,
  11080. 'ok_count' => count($okNames),
  11081. 'fail_count'=> count($failMsgs),
  11082. 'platform_url' => $platformUrl,
  11083. ]);
  11084. }
  11085. /**
  11086. * 查询询价 — 下发前:返回将通知的供应商表格数据
  11087. */
  11088. public function rfqissuesuppliers()
  11089. {
  11090. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers'])) {
  11091. $this->error(__('You have no permission'));
  11092. }
  11093. $sid = (int)$this->request->param('scydgy_id', 0);
  11094. if ($sid >= 0) {
  11095. $this->error('仅支持手工新增询价单');
  11096. }
  11097. $po = $this->loadManualRfqOrderForNotify($sid);
  11098. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  11099. if ($supplierRaw === '') {
  11100. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  11101. }
  11102. $names = $this->splitRfqSalesmanNames($supplierRaw);
  11103. // 已成功发过询价邮件的供应商(含历史 pick_issue 场景)
  11104. $notifiedMap = [];
  11105. try {
  11106. $this->ensurePurchaseEmailSendLogTableOnce();
  11107. $logRows = Db::table('purchase_email_send_log')
  11108. ->where('scydgy_id', $sid)
  11109. ->where('status', 1)
  11110. ->where('scene', 'in', [
  11111. 'rfq_supplier', 'pick_issue',
  11112. '供应商询价通知', '初选下发',
  11113. ])
  11114. ->field('company_name')
  11115. ->select();
  11116. if (is_array($logRows)) {
  11117. foreach ($logRows as $lr) {
  11118. if (!is_array($lr)) {
  11119. continue;
  11120. }
  11121. $cn = trim((string)($lr['company_name'] ?? ''));
  11122. if ($cn !== '') {
  11123. $notifiedMap[$cn] = true;
  11124. }
  11125. }
  11126. }
  11127. } catch (\Throwable $e) {
  11128. }
  11129. // 兼容:明细已生成(曾下发)也视为已通知
  11130. try {
  11131. $detRows = Db::table('purchase_order_detail')
  11132. ->where('scydgy_id', $sid)
  11133. ->field('company_name')
  11134. ->select();
  11135. if (is_array($detRows)) {
  11136. foreach ($detRows as $dr) {
  11137. if (!is_array($dr)) {
  11138. continue;
  11139. }
  11140. $cn = trim((string)($dr['company_name'] ?? ''));
  11141. if ($cn !== '') {
  11142. $notifiedMap[$cn] = true;
  11143. }
  11144. }
  11145. }
  11146. } catch (\Throwable $e) {
  11147. }
  11148. $list = [];
  11149. foreach ($names as $name) {
  11150. // 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
  11151. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  11152. $email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
  11153. $phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
  11154. $username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
  11155. $okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
  11156. $notified = !empty($notifiedMap[$name]) ? 1 : 0;
  11157. $list[] = [
  11158. 'name' => $name,
  11159. 'username' => $username,
  11160. 'email' => $email,
  11161. 'phone' => $phone,
  11162. 'can_notify' => $okEmail ? 1 : 0,
  11163. 'found' => is_array($contact) ? 1 : 0,
  11164. 'notified' => $notified,
  11165. 'notify_status_text' => $notified ? '已通知' : '未通知',
  11166. ];
  11167. }
  11168. $this->success('', null, [
  11169. 'scydgy_id' => $sid,
  11170. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  11171. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  11172. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  11173. 'CDW' => trim((string)($po['CDW'] ?? '')),
  11174. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  11175. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  11176. 'CDF' => trim((string)($po['CDF'] ?? '')),
  11177. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  11178. 'list' => $list,
  11179. ]);
  11180. }
  11181. /**
  11182. * 查询询价 — 补加供应商可选名单
  11183. */
  11184. public function rfqsupplieroptions()
  11185. {
  11186. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
  11187. $this->error(__('You have no permission'));
  11188. }
  11189. $names = array_values($this->loadRfqSupplierNameOptions());
  11190. $out = [];
  11191. foreach ($names as $name) {
  11192. $out[] = ['name' => $name];
  11193. }
  11194. $this->success('', null, ['list' => $out]);
  11195. }
  11196. /**
  11197. * 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
  11198. */
  11199. public function rfqappendsuppliers()
  11200. {
  11201. if (!$this->request->isPost()) {
  11202. $this->error(__('Invalid parameters'));
  11203. }
  11204. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers'])) {
  11205. $this->error(__('You have no permission'));
  11206. }
  11207. $sid = (int)$this->request->post('scydgy_id', 0);
  11208. if ($sid >= 0) {
  11209. $this->error('仅支持手工新增询价单');
  11210. }
  11211. $po = $this->loadManualRfqOrderForNotify($sid);
  11212. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  11213. $this->error('订单已完结,无法补加供应商');
  11214. }
  11215. $raw = $this->request->post('suppliers/a', []);
  11216. if (!is_array($raw) || $raw === []) {
  11217. $suppliersJson = $this->request->post('suppliers_json', '');
  11218. if (is_string($suppliersJson) && $suppliersJson !== '') {
  11219. $decoded = json_decode($suppliersJson, true);
  11220. $raw = is_array($decoded) ? $decoded : [];
  11221. }
  11222. }
  11223. $addNames = [];
  11224. foreach ((array)$raw as $item) {
  11225. if (is_array($item)) {
  11226. $n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
  11227. } else {
  11228. $n = trim((string)$item);
  11229. }
  11230. if ($n !== '') {
  11231. $addNames[] = $n;
  11232. }
  11233. }
  11234. $addNames = array_values(array_unique($addNames));
  11235. if ($addNames === []) {
  11236. $this->error('请选择要补加的供应商');
  11237. }
  11238. $existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
  11239. if ($existingRaw === '') {
  11240. $existingRaw = trim((string)($po['pick_company_name'] ?? ''));
  11241. }
  11242. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  11243. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  11244. try {
  11245. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
  11246. } catch (\Throwable $e) {
  11247. $this->error('保存失败:' . $e->getMessage());
  11248. }
  11249. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11250. $this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  11251. $this->success('已补加供应商', null, [
  11252. 'scydgy_id' => $sid,
  11253. 'cGzzxMc' => $mergedStr,
  11254. 'added_count' => count($addNames),
  11255. ]);
  11256. }
  11257. /**
  11258. * 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
  11259. */
  11260. public function rfqissue()
  11261. {
  11262. if (!$this->request->isPost()) {
  11263. $this->error(__('Invalid parameters'));
  11264. }
  11265. if (!$this->hasProcuremenPerm(['rfqissue'])) {
  11266. $this->error(__('You have no permission'));
  11267. }
  11268. $this->ensureRfqSupplierEmailTemplate();
  11269. $sid = (int)$this->request->post('scydgy_id', 0);
  11270. if ($sid >= 0) {
  11271. $this->error('仅支持手工新增询价单');
  11272. }
  11273. $po = $this->loadManualRfqOrderForNotify($sid);
  11274. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  11275. $this->error('订单已完结,无法下发');
  11276. }
  11277. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  11278. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  11279. $this->error('订单已进入后续流程,无法再下发');
  11280. }
  11281. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  11282. if ($supplierRaw === '') {
  11283. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  11284. }
  11285. $supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
  11286. if ($supplierNames === []) {
  11287. $this->error('请先在新增询价时选择供应商');
  11288. }
  11289. $companies = [];
  11290. $missing = [];
  11291. $noEmail = [];
  11292. foreach ($supplierNames as $name) {
  11293. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  11294. if ($contact === null) {
  11295. $missing[] = $name;
  11296. continue;
  11297. }
  11298. $em = trim((string)($contact['email'] ?? ''));
  11299. if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
  11300. $noEmail[] = $name;
  11301. continue;
  11302. }
  11303. $companies[] = $contact;
  11304. }
  11305. if ($missing !== []) {
  11306. $this->error('未找到供应商档案:' . implode('、', $missing));
  11307. }
  11308. if ($noEmail !== []) {
  11309. $this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
  11310. }
  11311. if ($companies === []) {
  11312. $this->error('没有可通知的供应商');
  11313. }
  11314. $mailConfig = $this->loadMailerConfig();
  11315. if (empty($mailConfig['host'])) {
  11316. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  11317. }
  11318. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  11319. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  11320. }
  11321. $mergeRow = $po;
  11322. $mergeRow['ID'] = $sid;
  11323. $mergeRow['id'] = $sid;
  11324. $mergeRows = [$mergeRow];
  11325. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  11326. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  11327. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  11328. }
  11329. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  11330. $issueTime = date('Y-m-d H:i:s');
  11331. $nameLabels = [];
  11332. foreach ($companies as $c) {
  11333. $nameLabels[] = trim((string)($c['name'] ?? ''));
  11334. }
  11335. $logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
  11336. Db::startTrans();
  11337. try {
  11338. $this->upsertPurchaseOrderFromRow(
  11339. $mergeRow,
  11340. $sysRqDb,
  11341. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  11342. $issueTime,
  11343. $po,
  11344. null,
  11345. $scoreRule
  11346. );
  11347. foreach ($companies as $c) {
  11348. $this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
  11349. }
  11350. Db::commit();
  11351. } catch (\Throwable $e) {
  11352. Db::rollback();
  11353. $this->error($e->getMessage());
  11354. }
  11355. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11356. if ($poId <= 0) {
  11357. try {
  11358. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  11359. } catch (\Throwable $e) {
  11360. $poId = 0;
  11361. }
  11362. }
  11363. $this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
  11364. $posNotify = [];
  11365. try {
  11366. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  11367. if (is_array($fresh)) {
  11368. $fresh['sys_rq'] = $sysRqDb;
  11369. $posNotify = [$fresh];
  11370. }
  11371. } catch (\Throwable $e) {
  11372. $posNotify = [$po];
  11373. $posNotify[0]['sys_rq'] = $sysRqDb;
  11374. }
  11375. $notifyBundle = [
  11376. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  11377. 'pos' => $posNotify,
  11378. 'merge_rows' => $mergeRows,
  11379. ];
  11380. $notifyErrors = [];
  11381. foreach ($companies as $c) {
  11382. $cname = trim((string)($c['name'] ?? ''));
  11383. try {
  11384. // 询价下发:仅邮箱通知供应商
  11385. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  11386. } catch (\Throwable $e) {
  11387. $notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
  11388. }
  11389. }
  11390. if ($notifyErrors !== []) {
  11391. $this->error('下发已保存,但邮件通知失败:' . implode(';', $notifyErrors));
  11392. }
  11393. $this->success('已询价并邮件通知供应商', null, [
  11394. 'scydgy_id' => $sid,
  11395. 'progress_text' => '待报价',
  11396. 'supplier_count' => count($companies),
  11397. ]);
  11398. }
  11399. /**
  11400. * 查询询价 — 弹窗内向单个供应商发送询价邮件
  11401. */
  11402. public function rfqissuesendmail()
  11403. {
  11404. if (!$this->request->isPost()) {
  11405. $this->error(__('Invalid parameters'));
  11406. }
  11407. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail'])) {
  11408. $this->error(__('You have no permission'));
  11409. }
  11410. $this->ensureRfqSupplierEmailTemplate();
  11411. $sid = (int)$this->request->post('scydgy_id', 0);
  11412. $companyName = trim((string)$this->request->post('company_name', ''));
  11413. if ($sid >= 0) {
  11414. $this->error('仅支持手工新增询价单');
  11415. }
  11416. if ($companyName === '') {
  11417. $this->error('请选择供应商');
  11418. }
  11419. $po = $this->loadManualRfqOrderForNotify($sid);
  11420. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  11421. $this->error('订单已完结,无法发送');
  11422. }
  11423. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  11424. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  11425. $this->error('订单已进入后续流程,无法再发送');
  11426. }
  11427. $contact = $this->resolveCustomerContactByCompanyName($companyName, false);
  11428. if ($contact === null) {
  11429. $this->error('未找到供应商档案:' . $companyName);
  11430. }
  11431. $email = trim((string)($contact['email'] ?? ''));
  11432. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  11433. $this->error('该供应商未填写有效邮箱');
  11434. }
  11435. $mailConfig = $this->loadMailerConfig();
  11436. if (empty($mailConfig['host'])) {
  11437. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  11438. }
  11439. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  11440. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  11441. }
  11442. $mergeRow = $po;
  11443. $mergeRow['ID'] = $sid;
  11444. $mergeRow['id'] = $sid;
  11445. $mergeRows = [$mergeRow];
  11446. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  11447. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  11448. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  11449. }
  11450. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  11451. $issueTime = date('Y-m-d H:i:s');
  11452. Db::startTrans();
  11453. try {
  11454. $this->upsertPurchaseOrderFromRow(
  11455. $mergeRow,
  11456. $sysRqDb,
  11457. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  11458. $issueTime,
  11459. $po,
  11460. null,
  11461. $scoreRule
  11462. );
  11463. $this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
  11464. Db::commit();
  11465. } catch (\Throwable $e) {
  11466. Db::rollback();
  11467. $this->error($e->getMessage());
  11468. }
  11469. $posNotify = [];
  11470. try {
  11471. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  11472. if (is_array($fresh)) {
  11473. $fresh['sys_rq'] = $sysRqDb;
  11474. $posNotify = [$fresh];
  11475. }
  11476. } catch (\Throwable $e) {
  11477. $posNotify = [$po];
  11478. $posNotify[0]['sys_rq'] = $sysRqDb;
  11479. }
  11480. $notifyBundle = [
  11481. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  11482. 'pos' => $posNotify,
  11483. 'merge_rows' => $mergeRows,
  11484. ];
  11485. try {
  11486. $this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  11487. } catch (\Throwable $e) {
  11488. $this->error('明细已保存,但邮件发送失败:' . $e->getMessage());
  11489. }
  11490. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11491. if ($poId <= 0) {
  11492. try {
  11493. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  11494. } catch (\Throwable $e) {
  11495. $poId = 0;
  11496. }
  11497. }
  11498. $this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
  11499. $this->success('已向「' . $companyName . '」发送询价邮件', null, [
  11500. 'scydgy_id' => $sid,
  11501. 'company_name' => $companyName,
  11502. ]);
  11503. }
  11504. /**
  11505. * 查询询价 — 查看各供应商报价(单价)
  11506. */
  11507. public function rfqquotes()
  11508. {
  11509. if (!$this->hasProcuremenPerm(['rfqquotes', 'rfqissue'])) {
  11510. $this->error(__('You have no permission'));
  11511. }
  11512. $sid = (int)$this->request->param('scydgy_id', 0);
  11513. if ($sid >= 0) {
  11514. $this->error('仅支持手工新增询价单');
  11515. }
  11516. $po = $this->loadManualRfqOrderForNotify($sid);
  11517. $rows = [];
  11518. try {
  11519. // 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
  11520. $q = Db::table('purchase_order_detail')
  11521. ->where('scydgy_id', $sid)
  11522. ->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
  11523. ->order('id', 'asc');
  11524. $this->applyActivePurchaseOrderDetailWhere($q);
  11525. $rows = $q->select();
  11526. } catch (\Throwable $e) {
  11527. try {
  11528. $q = Db::table('purchase_order_detail')
  11529. ->where('scydgy_id', $sid)
  11530. ->order('id', 'asc');
  11531. $this->applyActivePurchaseOrderDetailWhere($q);
  11532. $rows = $q->select();
  11533. } catch (\Throwable $e2) {
  11534. $rows = [];
  11535. }
  11536. }
  11537. if (!is_array($rows)) {
  11538. $rows = [];
  11539. }
  11540. $list = [];
  11541. foreach ($rows as $row) {
  11542. if (!is_array($row)) {
  11543. continue;
  11544. }
  11545. $amount = trim((string)($row['amount'] ?? ''));
  11546. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  11547. // 未报价不显示时间(createtime 是下发时间,不是报价时间)
  11548. $oper = '';
  11549. if ($isQuoted) {
  11550. $oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
  11551. if ($oper === '') {
  11552. $oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  11553. }
  11554. }
  11555. $list[] = [
  11556. 'id' => (int)($row['id'] ?? 0),
  11557. 'company_name' => trim((string)($row['company_name'] ?? '')),
  11558. 'amount' => $amount,
  11559. 'amount_text' => $isQuoted ? $amount : '',
  11560. 'is_quoted' => $isQuoted,
  11561. 'quote_label' => $isQuoted ? '已报价' : '未报价',
  11562. 'status_name' => trim((string)($row['status_name'] ?? '')),
  11563. 'oper_time' => $oper,
  11564. ];
  11565. }
  11566. $this->success('', null, [
  11567. 'scydgy_id' => $sid,
  11568. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  11569. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  11570. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  11571. 'CDW' => trim((string)($po['CDW'] ?? '')),
  11572. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  11573. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  11574. 'CDF' => trim((string)($po['CDF'] ?? '')),
  11575. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  11576. 'list' => $list,
  11577. ]);
  11578. }
  11579. /**
  11580. * 手工询价是否已下发(有下发明细或已进入待确认及之后)
  11581. */
  11582. protected function isRfqOrderIssued(array $po): bool
  11583. {
  11584. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  11585. return true;
  11586. }
  11587. $sid = (int)($po['scydgy_id'] ?? 0);
  11588. if ($sid >= 0) {
  11589. return false;
  11590. }
  11591. try {
  11592. $q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  11593. $this->applyActivePurchaseOrderDetailWhere($q);
  11594. return (int)$q->count() > 0;
  11595. } catch (\Throwable $e) {
  11596. return false;
  11597. }
  11598. }
  11599. /**
  11600. * 批量:已有下发明细的手工询价 scydgy_id
  11601. *
  11602. * @param int[] $scydgyIds
  11603. * @return array<int, bool>
  11604. */
  11605. protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
  11606. {
  11607. $set = [];
  11608. $ids = [];
  11609. foreach ($scydgyIds as $sid) {
  11610. $sid = (int)$sid;
  11611. if ($sid < 0) {
  11612. $ids[$sid] = true;
  11613. }
  11614. }
  11615. if ($ids === []) {
  11616. return $set;
  11617. }
  11618. try {
  11619. $q = Db::table('purchase_order_detail')
  11620. ->where('scydgy_id', 'in', array_keys($ids))
  11621. ->field('scydgy_id');
  11622. $this->applyActivePurchaseOrderDetailWhere($q);
  11623. $rows = $q->select();
  11624. } catch (\Throwable $e) {
  11625. return $set;
  11626. }
  11627. if (!is_array($rows)) {
  11628. return $set;
  11629. }
  11630. foreach ($rows as $row) {
  11631. if (!is_array($row)) {
  11632. continue;
  11633. }
  11634. $sid = (int)($row['scydgy_id'] ?? 0);
  11635. if ($sid < 0) {
  11636. $set[$sid] = true;
  11637. }
  11638. }
  11639. return $set;
  11640. }
  11641. /**
  11642. * 批量:已填单价(已报价)的手工询价 scydgy_id
  11643. *
  11644. * @param int[] $scydgyIds
  11645. * @return array<int, bool>
  11646. */
  11647. protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
  11648. {
  11649. $set = [];
  11650. $ids = [];
  11651. foreach ($scydgyIds as $sid) {
  11652. $sid = (int)$sid;
  11653. if ($sid < 0) {
  11654. $ids[$sid] = true;
  11655. }
  11656. }
  11657. if ($ids === []) {
  11658. return $set;
  11659. }
  11660. try {
  11661. $q = Db::table('purchase_order_detail')
  11662. ->where('scydgy_id', 'in', array_keys($ids))
  11663. ->field('scydgy_id,amount');
  11664. $this->applyActivePurchaseOrderDetailWhere($q);
  11665. $rows = $q->select();
  11666. } catch (\Throwable $e) {
  11667. return $set;
  11668. }
  11669. if (!is_array($rows)) {
  11670. return $set;
  11671. }
  11672. foreach ($rows as $row) {
  11673. if (!is_array($row)) {
  11674. continue;
  11675. }
  11676. $amount = trim((string)($row['amount'] ?? ''));
  11677. if ($amount === '' || $amount === '0' || $amount === '0.00') {
  11678. continue;
  11679. }
  11680. $sid = (int)($row['scydgy_id'] ?? 0);
  11681. if ($sid < 0) {
  11682. $set[$sid] = true;
  11683. }
  11684. }
  11685. return $set;
  11686. }
  11687. /**
  11688. * 已下发且至少一家供应商已报价,才允许通知业务员
  11689. */
  11690. protected function canRfqNotifySalesman(array $po): bool
  11691. {
  11692. if (!$this->isRfqOrderIssued($po)) {
  11693. return false;
  11694. }
  11695. $sid = (int)($po['scydgy_id'] ?? 0);
  11696. if ($sid >= 0) {
  11697. return false;
  11698. }
  11699. $quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
  11700. return isset($quoted[$sid]);
  11701. }
  11702. protected function assertRfqCanNotifySalesman(array $po): void
  11703. {
  11704. if (!$this->isRfqOrderIssued($po)) {
  11705. $this->error('请先询价并等待供应商报价后再通知业务员');
  11706. }
  11707. if (!$this->canRfqNotifySalesman($po)) {
  11708. $this->error('供应商尚未报价,暂不能通知业务员');
  11709. }
  11710. }
  11711. /**
  11712. * 加载手工询价单(含可见性校验)
  11713. *
  11714. * @return array<string, mixed>
  11715. */
  11716. protected function loadManualRfqOrderForNotify(int $scydgyId): array
  11717. {
  11718. try {
  11719. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  11720. } catch (\Throwable $e) {
  11721. $po = null;
  11722. }
  11723. if (!is_array($po)) {
  11724. $this->error('订单不存在');
  11725. }
  11726. $modRq = trim((string)($po['mod_rq'] ?? ''));
  11727. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  11728. $this->error('订单不存在');
  11729. }
  11730. if ($this->auth->isSuperAdmin()) {
  11731. return $po;
  11732. }
  11733. if ($this->canViewManualRfqOrder($po)) {
  11734. return $po;
  11735. }
  11736. $this->error('无权操作该订单');
  11737. }
  11738. /**
  11739. * @return string[]
  11740. */
  11741. protected function splitRfqSalesmanNames(string $raw): array
  11742. {
  11743. $parts = [];
  11744. $raw = trim($raw);
  11745. if ($raw === '') {
  11746. return [];
  11747. }
  11748. foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
  11749. $v = trim((string)$piece);
  11750. if ($v !== '' && !in_array($v, $parts, true)) {
  11751. $parts[] = $v;
  11752. }
  11753. }
  11754. return $parts;
  11755. }
  11756. /**
  11757. * 按姓名匹配 fa_admin 邮箱
  11758. *
  11759. * @param string[] $names
  11760. * @return array<int, array{admin_id:int,name:string,email:string}>
  11761. */
  11762. protected function resolveRfqSalesmanContactRows(array $names): array
  11763. {
  11764. $out = [];
  11765. foreach ($names as $name) {
  11766. $name = trim((string)$name);
  11767. if ($name === '') {
  11768. continue;
  11769. }
  11770. $adminId = 0;
  11771. $email = '';
  11772. try {
  11773. $row = Db::name('admin')
  11774. ->where(function ($q) use ($name) {
  11775. $q->where('nickname', $name)->whereOr('username', $name);
  11776. })
  11777. ->where('status', 'normal')
  11778. ->order('id', 'asc')
  11779. ->field('id,nickname,username,email')
  11780. ->find();
  11781. } catch (\Throwable $e) {
  11782. $row = null;
  11783. }
  11784. if (is_array($row)) {
  11785. $adminId = (int)($row['id'] ?? 0);
  11786. $email = trim((string)($row['email'] ?? ''));
  11787. $disp = trim((string)($row['nickname'] ?? ''));
  11788. if ($disp === '') {
  11789. $disp = trim((string)($row['username'] ?? ''));
  11790. }
  11791. if ($disp !== '') {
  11792. $name = $disp;
  11793. }
  11794. }
  11795. $out[] = [
  11796. 'admin_id' => $adminId,
  11797. 'name' => $name,
  11798. 'email' => $email,
  11799. ];
  11800. }
  11801. return $out;
  11802. }
  11803. /**
  11804. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  11805. */
  11806. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  11807. {
  11808. if ($scydgyId >= 0) {
  11809. return;
  11810. }
  11811. try {
  11812. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  11813. } catch (\Throwable $e) {
  11814. $po = null;
  11815. }
  11816. if (!is_array($po)) {
  11817. $this->error('订单不存在');
  11818. }
  11819. $modRq = trim((string)($po['mod_rq'] ?? ''));
  11820. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  11821. $this->error('订单不存在');
  11822. }
  11823. if ($this->auth->isSuperAdmin()) {
  11824. return;
  11825. }
  11826. [, $adminName] = $this->GetUseName();
  11827. $cywy = trim((string)($po['cywyxm'] ?? ''));
  11828. if ($cywy !== '' && $cywy === $adminName) {
  11829. return;
  11830. }
  11831. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  11832. try {
  11833. if ($this->auth->check($rule)) {
  11834. return;
  11835. }
  11836. } catch (\Throwable $e) {
  11837. }
  11838. }
  11839. $this->error('无权查看该订单');
  11840. }
  11841. /**
  11842. * 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
  11843. */
  11844. protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
  11845. {
  11846. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  11847. return ProcuremenStatus::PO_COMPLETED;
  11848. }
  11849. $sid = (int)($row['scydgy_id'] ?? 0);
  11850. if ($sid < 0) {
  11851. if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
  11852. return '已通知业务员';
  11853. }
  11854. if ($hasQuoted) {
  11855. return '供应商已报价';
  11856. }
  11857. if ($hasIssued
  11858. || ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
  11859. || ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
  11860. return '待报价';
  11861. }
  11862. try {
  11863. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  11864. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  11865. if ((int)$detCntQuery->count() > 0) {
  11866. return '待报价';
  11867. }
  11868. } catch (\Throwable $e) {
  11869. }
  11870. return '待询价';
  11871. }
  11872. if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
  11873. return '待入库评分';
  11874. }
  11875. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  11876. return '待采购确认';
  11877. }
  11878. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  11879. return '待确认供应商';
  11880. }
  11881. return '待协助下发';
  11882. }
  11883. /**
  11884. * 协助初选列表 — 批量软删除
  11885. */
  11886. public function pickDelete()
  11887. {
  11888. if (!$this->request->isPost() || !$this->request->isAjax()) {
  11889. $this->error(__('Invalid parameters'));
  11890. }
  11891. if (!$this->procuremenCanPickDelete()) {
  11892. $this->error(__('You have no permission'));
  11893. }
  11894. $rowsRaw = $this->request->post('rows_json', '[]');
  11895. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  11896. if (!is_array($rows) || $rows === []) {
  11897. $this->error('请至少勾选一条工序');
  11898. }
  11899. $done = 0;
  11900. Db::startTrans();
  11901. try {
  11902. foreach ($rows as $row) {
  11903. if (!is_array($row)) {
  11904. continue;
  11905. }
  11906. $this->softDeleteProcuremenPickRow($row);
  11907. $done++;
  11908. }
  11909. if ($done < 1) {
  11910. throw new \Exception('没有可删除的工序');
  11911. }
  11912. Db::commit();
  11913. } catch (\InvalidArgumentException $e) {
  11914. Db::rollback();
  11915. $this->error($e->getMessage());
  11916. } catch (\Throwable $e) {
  11917. Db::rollback();
  11918. $this->error($e->getMessage());
  11919. }
  11920. $this->pickHiddenScydgySetCache = null;
  11921. $this->success('已删除 ' . $done . ' 条工序');
  11922. }
  11923. /**
  11924. * 下发 — 手工新增工序(弹窗)
  11925. */
  11926. public function pickAdd()
  11927. {
  11928. if ($this->request->isPost()) {
  11929. $params = $this->request->post('row/a');
  11930. if (!is_array($params)) {
  11931. $this->error(__('Parameter %s can not be empty', ''));
  11932. }
  11933. try {
  11934. $sid = $this->saveManualPickOrder($params);
  11935. } catch (\InvalidArgumentException $e) {
  11936. $this->error($e->getMessage());
  11937. } catch (\Throwable $e) {
  11938. $this->error($e->getMessage());
  11939. }
  11940. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  11941. }
  11942. return $this->view->fetch('procuremen/pick_add');
  11943. }
  11944. /**
  11945. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  11946. */
  11947. public function pickSubmit()
  11948. {
  11949. if (!$this->request->isPost()) {
  11950. $this->error(__('Invalid parameters'));
  11951. }
  11952. // ---------- 接口订单数据 ----------
  11953. $rowJson = $this->request->post('row_json', '');
  11954. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  11955. $companiesJson = $this->request->post('companies_json', '[]');
  11956. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  11957. $companies = json_decode($companiesJson, true);
  11958. if (!is_array($companies)) {
  11959. $this->error('供应商数据无效');
  11960. }
  11961. $issueCompanies = $this->normalizePickCompanies($companies);
  11962. if ($issueCompanies === []) {
  11963. $this->error('请至少选择一家合作供应商');
  11964. }
  11965. $issueNameLabels = [];
  11966. foreach ($issueCompanies as $pc) {
  11967. $issueNameLabels[] = $pc['name'];
  11968. }
  11969. $issueNamesSummary = implode('、', $issueNameLabels);
  11970. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  11971. if ($sysRq === '') {
  11972. $this->error('请选择招标截止日期');
  11973. }
  11974. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  11975. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  11976. (string)$this->request->post('delivery_deadline', ''),
  11977. true
  11978. );
  11979. $scoreRuleId = (int)$this->request->post('score_rule_id', 0);
  11980. if ($scoreRuleId <= 0) {
  11981. $this->error('请选择订单类型');
  11982. }
  11983. $scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
  11984. if ((int)($scoreRule['id'] ?? 0) <= 0) {
  11985. $this->error('订单类型无效,请刷新后重选');
  11986. }
  11987. $scoreRuleId = (int)$scoreRule['id'];
  11988. $this->ensurePurchaseOrderScoreRuleIdColumn();
  11989. $logMsg = '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  11990. $bidDispForLog = $this->formatProcuremenSysRqForDisplay($sysRqDb);
  11991. $delDispForLog = $this->formatProcuremenDeliveryDeadlineForInput($deliveryDeadlineDb);
  11992. if ($delDispForLog === '') {
  11993. $delDispForLog = $this->formatDeliveryYmd($deliveryDeadlineDb);
  11994. }
  11995. $orderTypeForLog = trim((string)($scoreRule['name'] ?? ''));
  11996. $logExtra = [];
  11997. if ($bidDispForLog !== '' && $bidDispForLog !== '—') {
  11998. $logExtra[] = '招标截止日期:' . $bidDispForLog;
  11999. }
  12000. if ($delDispForLog !== '') {
  12001. $logExtra[] = '交货截止日期:' . $delDispForLog;
  12002. }
  12003. if ($orderTypeForLog !== '') {
  12004. $logExtra[] = '订单类型:' . $orderTypeForLog;
  12005. }
  12006. if ($logExtra !== []) {
  12007. $logMsg .= ';' . implode(';', $logExtra);
  12008. }
  12009. $issueTime = date('Y-m-d H:i:s');
  12010. try {
  12011. $issueBatchNo = $this->allocateProcuremenIssueBatchNo();
  12012. } catch (\Throwable $e) {
  12013. $this->error($e->getMessage() !== '' ? $e->getMessage() : '批次号生成失败,请重试');
  12014. }
  12015. $logSidList = [];
  12016. foreach ($mergeRows as $row) {
  12017. if (!is_array($row)) {
  12018. continue;
  12019. }
  12020. $sid = $this->extractScydgyRowId($row);
  12021. if ($this->isValidScydgyRowId($sid)) {
  12022. $logSidList[$sid] = true;
  12023. }
  12024. }
  12025. if ($logSidList === []) {
  12026. $this->error('未找到有效工序,无法下发');
  12027. }
  12028. // 防连点/并发:同一批工序加命名锁,已下发则直接拒绝(避免重复短信邮件)
  12029. $sidKeys = array_keys($logSidList);
  12030. sort($sidKeys, SORT_NUMERIC);
  12031. $pickLockName = 'procuremen_pick_submit_' . md5(implode(',', $sidKeys));
  12032. if (!$this->acquireProcuremenNamedLock($pickLockName, 15)) {
  12033. $this->error('下发处理中,请勿重复点击');
  12034. }
  12035. $existingBySid = [];
  12036. try {
  12037. try {
  12038. $existingRows = Db::table('purchase_order')
  12039. ->where('scydgy_id', 'in', $sidKeys)
  12040. ->select();
  12041. if (is_array($existingRows)) {
  12042. foreach ($existingRows as $poRow) {
  12043. if (!is_array($poRow)) {
  12044. continue;
  12045. }
  12046. $sid = (int)($poRow['scydgy_id'] ?? 0);
  12047. if ($this->isValidScydgyRowId($sid)) {
  12048. $existingBySid[$sid] = $poRow;
  12049. }
  12050. }
  12051. }
  12052. } catch (\Throwable $e) {
  12053. $existingBySid = [];
  12054. }
  12055. foreach ($sidKeys as $sid) {
  12056. $poRow = $existingBySid[$sid] ?? null;
  12057. if (!is_array($poRow)) {
  12058. continue;
  12059. }
  12060. if ($this->isPurchaseOrderSoftDeleted($poRow['mod_rq'] ?? null)) {
  12061. continue;
  12062. }
  12063. $label = $this->formatProcuremenRowLabel(['CCYDH' => $poRow['CCYDH'] ?? '', 'CGYMC' => $poRow['CGYMC'] ?? '']);
  12064. if (ProcuremenStatus::isPoCompleted($poRow['status'] ?? '')) {
  12065. $this->error(($label !== '' ? $label : ('工序#' . $sid)) . '已完结,无法再次下发');
  12066. }
  12067. if (!ProcuremenStatus::isWflowPendingIssue($poRow['wflow_status'] ?? '')) {
  12068. $this->error(($label !== '' ? $label : ('工序#' . $sid)) . '已下发或进入后续流程,请勿重复提交');
  12069. }
  12070. }
  12071. Db::startTrans();
  12072. try {
  12073. $this->enrichProcuremenRowsMbz($mergeRows);
  12074. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  12075. foreach ($mergeRows as $row) {
  12076. if (!is_array($row)) {
  12077. continue;
  12078. }
  12079. $sid = $this->extractScydgyRowId($row);
  12080. $this->upsertPurchaseOrderFromRow(
  12081. $row,
  12082. $sysRqDb,
  12083. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  12084. $issueTime,
  12085. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  12086. $deliveryDeadlineDb,
  12087. $scoreRule,
  12088. $issueBatchNo
  12089. );
  12090. }
  12091. foreach ($issueCompanies as $c) {
  12092. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  12093. }
  12094. Db::commit();
  12095. } catch (\Throwable $e) {
  12096. Db::rollback();
  12097. $this->error($e->getMessage());
  12098. }
  12099. } finally {
  12100. $this->releaseProcuremenNamedLock($pickLockName);
  12101. }
  12102. $poIdBySid = [];
  12103. if ($logSidList !== []) {
  12104. try {
  12105. $poIdBySid = Db::table('purchase_order')
  12106. ->where('scydgy_id', 'in', array_keys($logSidList))
  12107. ->column('id', 'scydgy_id');
  12108. } catch (\Throwable $e) {
  12109. $poIdBySid = [];
  12110. }
  12111. }
  12112. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  12113. if ($logSidList !== []) {
  12114. list($adminId, $adminName) = $this->GetUseName();
  12115. $logRows = [];
  12116. $seenLogSid = [];
  12117. foreach ($mergeRows as $row) {
  12118. if (!is_array($row)) {
  12119. continue;
  12120. }
  12121. $ids = $this->extractScydgyRowId($row);
  12122. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  12123. continue;
  12124. }
  12125. $seenLogSid[$ids] = true;
  12126. $poIdLog = null;
  12127. if (isset($poIdBySid[$ids])) {
  12128. $tid = (int)$poIdBySid[$ids];
  12129. $poIdLog = $tid > 0 ? $tid : null;
  12130. }
  12131. $logRows[] = ProcuremenOperLog::buildInsertRow(
  12132. $ids,
  12133. 'issue_submit',
  12134. $logMsg,
  12135. $poIdLog,
  12136. (int)$adminId,
  12137. (string)$adminName
  12138. );
  12139. }
  12140. if ($logRows !== []) {
  12141. try {
  12142. Db::table('purchase_order_oper_log')->insertAll($logRows);
  12143. } catch (\Throwable $e) {
  12144. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  12145. }
  12146. }
  12147. }
  12148. $notifyErrors = [];
  12149. $posNotify = [];
  12150. if ($logSidList !== []) {
  12151. try {
  12152. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  12153. } catch (\Throwable $e) {
  12154. $posNotify = [];
  12155. }
  12156. }
  12157. if (!is_array($posNotify)) {
  12158. $posNotify = [];
  12159. }
  12160. foreach ($posNotify as $i => $prow) {
  12161. if (is_array($posNotify[$i])) {
  12162. $posNotify[$i]['sys_rq'] = $sysRqDb;
  12163. }
  12164. }
  12165. $ccydhPick = '';
  12166. foreach ($mergeRows as $row) {
  12167. if (!is_array($row)) {
  12168. continue;
  12169. }
  12170. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  12171. if ($ccydhPick !== '') {
  12172. break;
  12173. }
  12174. }
  12175. $notifyBundleBase = [
  12176. 'ccydh' => $ccydhPick,
  12177. 'pos' => $posNotify,
  12178. 'merge_rows' => $mergeRows,
  12179. 'score_rule' => is_array($scoreRule) ? $scoreRule : null,
  12180. ];
  12181. try {
  12182. $this->notifyDryRunPreview = [];
  12183. foreach ($issueCompanies as $c) {
  12184. if (!is_array($c)) {
  12185. continue;
  12186. }
  12187. $cname = trim((string)($c['name'] ?? ''));
  12188. if ($cname === '') {
  12189. continue;
  12190. }
  12191. try {
  12192. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  12193. } catch (\Throwable $e) {
  12194. $notifyErrors[] = $cname . ':' . $e->getMessage();
  12195. }
  12196. }
  12197. } catch (\Throwable $e) {
  12198. $this->error('通知发送失败:' . $e->getMessage());
  12199. }
  12200. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  12201. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  12202. }
  12203. if ($this->isProcuremenNotifyDryRun()) {
  12204. $this->success('【演练模式】已保存并生成通知预览', '', [
  12205. 'notify_dry_run' => true,
  12206. 'notify_preview' => $this->notifyDryRunPreview,
  12207. ]);
  12208. }
  12209. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  12210. }
  12211. /**
  12212. * 确认供应商弹窗
  12213. */
  12214. public function auditIssue()
  12215. {
  12216. $ids = $this->request->param('ids', $this->request->param('id', ''));
  12217. if (is_array($ids)) {
  12218. $ids = isset($ids[0]) ? $ids[0] : '';
  12219. }
  12220. $ids = trim((string)$ids);
  12221. if ($ids === '') {
  12222. $this->error(__('Invalid parameters'));
  12223. }
  12224. if ($this->request->isPost()) {
  12225. $this->error('请使用弹窗内「确认」提交');
  12226. }
  12227. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  12228. $pos = $bundle['pos'];
  12229. if ($pos === []) {
  12230. $this->error('该订单不在待确认供应商状态');
  12231. }
  12232. $po = $pos[0];
  12233. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  12234. if ($quoteGroups === []) {
  12235. $toastMsg = '暂无下发明细,请确认该订单已在「供应商初选」完成下发';
  12236. // 弹层内不要走整页跳转提示,仅 Toastr 后关闭
  12237. $this->view->assign('toastMsg', $toastMsg);
  12238. return $this->view->fetch('procuremen/toast_close');
  12239. }
  12240. $pickedName = '';
  12241. foreach ($pos as $poRow) {
  12242. if (!is_array($poRow)) {
  12243. continue;
  12244. }
  12245. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  12246. if ($pn !== '') {
  12247. $pickedName = $pn;
  12248. break;
  12249. }
  12250. }
  12251. $this->view->assign('po', $po);
  12252. $this->view->assign('scydgyId', $ids);
  12253. $this->view->assign('orderCcydh', $bundle['ccydh']);
  12254. $mergeRows = $bundle['merge_rows'];
  12255. $this->view->assign('processRows', $mergeRows);
  12256. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  12257. $this->view->assign('processCount', count($mergeRows));
  12258. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  12259. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  12260. $this->view->assign('pickedCompanyName', $pickedName);
  12261. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  12262. if ($sysRqForView === '') {
  12263. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  12264. }
  12265. $this->view->assign('sysRq', $sysRqForView);
  12266. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  12267. if ($deliveryDeadlineForView === '') {
  12268. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  12269. }
  12270. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  12271. $this->ensurePurchaseOrderManualPickColumns();
  12272. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
  12273. $manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
  12274. $manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
  12275. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  12276. if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
  12277. $pickedName = $manualPickInfo['company'];
  12278. $this->view->assign('pickedCompanyName', $pickedName);
  12279. }
  12280. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  12281. $this->view->assign('manualPicked', $manualPicked);
  12282. $this->view->assign('manualPickReason', $manualPickInfo['reason']);
  12283. $this->view->assign('quoteVisible', $quoteVisible);
  12284. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
  12285. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  12286. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
  12287. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
  12288. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  12289. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  12290. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  12291. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  12292. return $this->view->fetch('procuremen/audit_issue');
  12293. }
  12294. /**
  12295. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  12296. *
  12297. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  12298. */
  12299. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  12300. {
  12301. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  12302. return false;
  12303. }
  12304. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  12305. return false;
  12306. }
  12307. return true;
  12308. }
  12309. /**
  12310. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  12311. *
  12312. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  12313. */
  12314. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  12315. {
  12316. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  12317. return false;
  12318. }
  12319. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  12320. return false;
  12321. }
  12322. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  12323. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  12324. return true;
  12325. }
  12326. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  12327. }
  12328. /**
  12329. * 确认页 — 补加供应商弹窗
  12330. */
  12331. public function auditAppend()
  12332. {
  12333. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  12334. $this->error(__('You have no permission'));
  12335. }
  12336. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  12337. if (is_array($ids)) {
  12338. $ids = isset($ids[0]) ? $ids[0] : '';
  12339. }
  12340. $ids = trim((string)$ids);
  12341. if ($ids === '') {
  12342. $this->error(__('Invalid parameters'));
  12343. }
  12344. if ($this->request->isPost()) {
  12345. $this->error('请使用弹窗内「确认」提交');
  12346. }
  12347. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  12348. if (($bundle['pos'] ?? []) === []) {
  12349. $this->error('该订单不在待确认供应商状态');
  12350. }
  12351. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  12352. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  12353. $this->error('已开标验证,不能再补加供应商');
  12354. }
  12355. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  12356. $this->error('已指定供应商,不能再补加供应商');
  12357. }
  12358. $this->error('已经超过了招标截止日期,不可操作');
  12359. }
  12360. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  12361. $existingNames = [];
  12362. foreach ($quoteGroups as $g) {
  12363. if (!is_array($g)) {
  12364. continue;
  12365. }
  12366. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  12367. if ($n !== '') {
  12368. $existingNames[$n] = true;
  12369. }
  12370. }
  12371. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  12372. $mergeRows = $bundle['merge_rows'] ?? [];
  12373. $this->view->assign('scydgyId', $ids);
  12374. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  12375. $this->view->assign('po', $po);
  12376. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  12377. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  12378. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  12379. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  12380. if ($sysRqForView === '') {
  12381. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  12382. }
  12383. $this->view->assign('sysRq', $sysRqForView);
  12384. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  12385. if ($deliveryDeadlineForView === '') {
  12386. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  12387. }
  12388. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  12389. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  12390. }
  12391. /**
  12392. * 确认页 — 补加供应商提交
  12393. */
  12394. public function auditAppendSubmit()
  12395. {
  12396. if (!$this->request->isPost()) {
  12397. $this->error(__('Invalid parameters'));
  12398. }
  12399. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  12400. $this->error(__('You have no permission'));
  12401. }
  12402. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  12403. if ($ids === '') {
  12404. $this->error(__('Invalid parameters'));
  12405. }
  12406. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  12407. if (($bundle['pos'] ?? []) === []) {
  12408. $this->error('该订单不在待确认供应商状态');
  12409. }
  12410. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  12411. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  12412. $this->error('已开标验证,不能再补加供应商');
  12413. }
  12414. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  12415. $this->error('已指定供应商,不能再补加供应商');
  12416. }
  12417. $this->error('已经超过了招标截止日期,不可操作');
  12418. }
  12419. $companiesJson = $this->request->post('companies_json', '[]');
  12420. $companies = json_decode((string)$companiesJson, true);
  12421. if (!is_array($companies)) {
  12422. $this->error('供应商数据无效');
  12423. }
  12424. $issueCompanies = $this->normalizePickCompanies($companies);
  12425. if ($issueCompanies === []) {
  12426. $this->error('请至少选择一家合作供应商');
  12427. }
  12428. $mergeRows = $bundle['merge_rows'] ?? [];
  12429. if (!is_array($mergeRows) || $mergeRows === []) {
  12430. $this->error('未找到工序行,无法补加');
  12431. }
  12432. $existingNames = [];
  12433. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  12434. if (!is_array($g)) {
  12435. continue;
  12436. }
  12437. $n = trim((string)($g['company_name'] ?? ''));
  12438. if ($n !== '') {
  12439. $existingNames[$n] = true;
  12440. }
  12441. }
  12442. $toAdd = [];
  12443. foreach ($issueCompanies as $c) {
  12444. if (!is_array($c)) {
  12445. continue;
  12446. }
  12447. $n = trim((string)($c['name'] ?? ''));
  12448. if ($n === '' || isset($existingNames[$n])) {
  12449. continue;
  12450. }
  12451. $toAdd[] = $c;
  12452. }
  12453. if ($toAdd === []) {
  12454. $this->error('所选供应商均已在本单中,请选择新的供应商');
  12455. }
  12456. $addedNames = [];
  12457. Db::startTrans();
  12458. try {
  12459. foreach ($toAdd as $c) {
  12460. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  12461. $addedNames[] = trim((string)($c['name'] ?? ''));
  12462. }
  12463. Db::commit();
  12464. } catch (\Throwable $e) {
  12465. Db::rollback();
  12466. $this->error($e->getMessage());
  12467. }
  12468. $notifyErrors = [];
  12469. $notifyBundleBase = [
  12470. 'ccydh' => $bundle['ccydh'] ?? '',
  12471. 'pos' => $bundle['pos'] ?? [],
  12472. 'merge_rows' => $mergeRows,
  12473. ];
  12474. foreach ($toAdd as $c) {
  12475. if (!is_array($c)) {
  12476. continue;
  12477. }
  12478. $cname = trim((string)($c['name'] ?? ''));
  12479. if ($cname === '') {
  12480. continue;
  12481. }
  12482. try {
  12483. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  12484. } catch (\Throwable $e) {
  12485. $notifyErrors[] = $cname . ':' . $e->getMessage();
  12486. }
  12487. }
  12488. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  12489. $seenLogSid = [];
  12490. foreach ($bundle['pos'] ?? [] as $poRow) {
  12491. if (!is_array($poRow)) {
  12492. continue;
  12493. }
  12494. $sid = (int)($poRow['scydgy_id'] ?? 0);
  12495. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  12496. continue;
  12497. }
  12498. $seenLogSid[$sid] = true;
  12499. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  12500. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  12501. }
  12502. if ($seenLogSid === []) {
  12503. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  12504. if ($this->isValidScydgyRowId($logSid)) {
  12505. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  12506. }
  12507. }
  12508. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  12509. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  12510. }
  12511. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  12512. }
  12513. /**
  12514. * 开标双重验证 — 可选验证人列表
  12515. */
  12516. public function bidOpenUsers()
  12517. {
  12518. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  12519. $this->error('无权限');
  12520. }
  12521. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  12522. if ($scydgyId !== '') {
  12523. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  12524. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  12525. $this->success('已完成开标验证', null, [
  12526. 'verified' => 1,
  12527. 'users' => [],
  12528. ]);
  12529. }
  12530. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  12531. $this->error('本单已指定供应商,无需再开标');
  12532. }
  12533. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  12534. }
  12535. $this->success('', null, [
  12536. 'verified' => 0,
  12537. 'users' => $this->listBidOpenVerifierCandidates(),
  12538. ]);
  12539. }
  12540. /**
  12541. * 开标双重验证 — 向指定管理员发送短信验证码
  12542. */
  12543. public function bidOpenSendCode()
  12544. {
  12545. if (!$this->request->isPost()) {
  12546. $this->error(__('Invalid parameters'));
  12547. }
  12548. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  12549. $this->error('无权限');
  12550. }
  12551. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  12552. $adminId = (int)$this->request->post('admin_id', 0);
  12553. if ($scydgyId === '' || $adminId <= 0) {
  12554. $this->error('参数无效');
  12555. }
  12556. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  12557. if ($bundle['pos'] === []) {
  12558. $this->error('该订单不在待确认供应商状态');
  12559. }
  12560. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  12561. $this->success('已完成开标验证,无需重复发送');
  12562. }
  12563. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  12564. $this->error('本单已指定供应商,无需再开标');
  12565. }
  12566. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  12567. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  12568. if ($ccydh === '') {
  12569. $this->error('订单号无效');
  12570. }
  12571. $admin = $this->loadBidOpenAdminUser($adminId);
  12572. if ($admin === null) {
  12573. $this->error('验证人无效或未绑定手机号');
  12574. }
  12575. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  12576. $cd = max(30, min(120, $cd));
  12577. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  12578. $this->error('发送过于频繁,请稍后再试');
  12579. }
  12580. $code = (string)random_int(100000, 999999);
  12581. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  12582. $ttl = max(60, min(600, $ttl));
  12583. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  12584. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  12585. try {
  12586. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  12587. } catch (\Throwable $e) {
  12588. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  12589. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  12590. $this->error($e->getMessage());
  12591. }
  12592. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  12593. }
  12594. /**
  12595. * 开标双重验证 — 两人验证码校验并记录
  12596. */
  12597. public function bidOpenVerify()
  12598. {
  12599. if (!$this->request->isPost()) {
  12600. $this->error(__('Invalid parameters'));
  12601. }
  12602. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  12603. $this->error('无权限');
  12604. }
  12605. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  12606. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  12607. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  12608. $code1 = trim((string)$this->request->post('code1', ''));
  12609. $code2 = trim((string)$this->request->post('code2', ''));
  12610. if ($scydgyId === '') {
  12611. $this->error('参数无效');
  12612. }
  12613. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  12614. $this->error('请选择两位验证人');
  12615. }
  12616. if ($verifier1Id === $verifier2Id) {
  12617. $this->error('两位验证人不能相同');
  12618. }
  12619. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  12620. $this->error('请输入6位短信验证码');
  12621. }
  12622. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  12623. if ($bundle['pos'] === []) {
  12624. $this->error('该订单不在待确认供应商状态');
  12625. }
  12626. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  12627. if ($ccydh === '') {
  12628. $this->error('订单号无效');
  12629. }
  12630. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  12631. $this->success('已完成开标验证');
  12632. }
  12633. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  12634. $this->error('本单已指定供应商,无需再开标');
  12635. }
  12636. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  12637. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  12638. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  12639. if ($verifier1 === null || $verifier2 === null) {
  12640. $this->error('验证人无效或未绑定手机号');
  12641. }
  12642. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  12643. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  12644. }
  12645. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  12646. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  12647. }
  12648. try {
  12649. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  12650. } catch (\Throwable $e) {
  12651. $this->error($e->getMessage());
  12652. }
  12653. $this->success('开标验证成功,可查看供应商报价与交货日期');
  12654. }
  12655. /**
  12656. * 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
  12657. */
  12658. public function auditManualPick()
  12659. {
  12660. if (!$this->request->isPost()) {
  12661. $this->error(__('Invalid parameters'));
  12662. }
  12663. if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
  12664. $this->error('无权限');
  12665. }
  12666. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  12667. if ($scydgyId === '') {
  12668. $this->error('参数无效');
  12669. }
  12670. $companyName = trim((string)$this->request->post('selected_company', ''));
  12671. $reason = trim((string)$this->request->post('pick_reason', ''));
  12672. if ($companyName === '') {
  12673. $this->error('请选择一家供应商');
  12674. }
  12675. if ($reason === '') {
  12676. $this->error('请填写选择说明');
  12677. }
  12678. if (mb_strlen($reason) > 500) {
  12679. $this->error('选择说明不能超过500字');
  12680. }
  12681. $this->ensurePurchaseOrderManualPickColumns();
  12682. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  12683. $pos = $bundle['pos'];
  12684. if ($pos === []) {
  12685. $this->error('该订单不在待确认供应商状态');
  12686. }
  12687. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  12688. $this->error('本单已开标验证,请直接在列表中选定供应商后确认');
  12689. }
  12690. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  12691. if ($quoteGroups === []) {
  12692. $this->error('暂无供应商,请确认已完成协助初选通知');
  12693. }
  12694. $matched = null;
  12695. foreach ($quoteGroups as $g) {
  12696. if (!is_array($g)) {
  12697. continue;
  12698. }
  12699. if (trim((string)($g['name'] ?? '')) === $companyName) {
  12700. $matched = $g;
  12701. break;
  12702. }
  12703. }
  12704. if ($matched === null) {
  12705. $this->error('所选供应商不在本单报价列表中');
  12706. }
  12707. $logMsg = '指定供应商:' . $companyName . ';说明:' . $reason;
  12708. Db::startTrans();
  12709. try {
  12710. foreach ($pos as $poRow) {
  12711. if (!is_array($poRow)) {
  12712. continue;
  12713. }
  12714. $sid = (int)($poRow['scydgy_id'] ?? 0);
  12715. if (!$this->isValidScydgyRowId($sid)) {
  12716. continue;
  12717. }
  12718. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  12719. 'pick_company_name' => $companyName,
  12720. 'manual_pick' => 1,
  12721. 'manual_pick_reason' => $reason,
  12722. ]);
  12723. }
  12724. Db::commit();
  12725. } catch (\Throwable $e) {
  12726. Db::rollback();
  12727. $this->error($e->getMessage());
  12728. }
  12729. foreach ($pos as $poRow) {
  12730. if (!is_array($poRow)) {
  12731. continue;
  12732. }
  12733. $sid = (int)($poRow['scydgy_id'] ?? 0);
  12734. if (!$this->isValidScydgyRowId($sid)) {
  12735. continue;
  12736. }
  12737. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  12738. $this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  12739. }
  12740. // 自选后可见报价:按本批各订单分别计算评分(与开标后一致)
  12741. try {
  12742. $bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  12743. $this->saveProcuremenSupplierScoresForBundle($bundleFresh, date('Y-m'));
  12744. } catch (\Throwable $e) {
  12745. Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
  12746. }
  12747. $this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
  12748. }
  12749. /**
  12750. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  12751. */
  12752. public function auditSubmit()
  12753. {
  12754. if (!$this->request->isPost()) {
  12755. $this->error(__('Invalid parameters'));
  12756. }
  12757. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  12758. if ($scydgyId === '') {
  12759. $this->error('参数无效');
  12760. }
  12761. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  12762. $pos = $bundle['pos'];
  12763. $mergeRows = $bundle['merge_rows'];
  12764. if ($pos === [] || $mergeRows === []) {
  12765. $this->error('该订单不在待确认供应商状态');
  12766. }
  12767. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  12768. if ($quoteGroups === []) {
  12769. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  12770. }
  12771. $companyName = trim((string)$this->request->post('selected_company', ''));
  12772. if ($companyName === '') {
  12773. $this->error('请选择一家供应商');
  12774. }
  12775. $matched = null;
  12776. foreach ($quoteGroups as $g) {
  12777. if (!is_array($g)) {
  12778. continue;
  12779. }
  12780. if (trim((string)($g['name'] ?? '')) === $companyName) {
  12781. $matched = $g;
  12782. break;
  12783. }
  12784. }
  12785. if ($matched === null) {
  12786. $this->error('所选供应商不在本单报价列表中');
  12787. }
  12788. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  12789. if ($sysRqDb === '') {
  12790. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  12791. } else {
  12792. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  12793. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  12794. }
  12795. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  12796. $this->error('未到招标截止日期,暂不可确认');
  12797. }
  12798. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
  12799. && !$this->isProcuremenManualPickedForBundle($bundle)
  12800. ) {
  12801. $this->error('请先完成开标双重验证或指定供应商后再确认');
  12802. }
  12803. $logMsg = '确认供应商:' . $companyName;
  12804. Db::startTrans();
  12805. try {
  12806. foreach ($pos as $poRow) {
  12807. if (!is_array($poRow)) {
  12808. continue;
  12809. }
  12810. $sid = (int)($poRow['scydgy_id'] ?? 0);
  12811. if (!$this->isValidScydgyRowId($sid)) {
  12812. continue;
  12813. }
  12814. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  12815. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  12816. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  12817. 'pick_company_name' => $companyName,
  12818. 'sys_rq' => $sysRqDb,
  12819. ]);
  12820. }
  12821. Db::commit();
  12822. } catch (\Throwable $e) {
  12823. Db::rollback();
  12824. $this->error($e->getMessage());
  12825. }
  12826. foreach ($pos as $poRow) {
  12827. if (!is_array($poRow)) {
  12828. continue;
  12829. }
  12830. $sid = (int)($poRow['scydgy_id'] ?? 0);
  12831. if (!$this->isValidScydgyRowId($sid)) {
  12832. continue;
  12833. }
  12834. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  12835. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  12836. }
  12837. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  12838. }
  12839. /**
  12840. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  12841. */
  12842. public function auditResendSms()
  12843. {
  12844. if (!$this->request->isPost()) {
  12845. $this->error(__('Invalid parameters'));
  12846. }
  12847. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  12848. if ($scydgyId === '') {
  12849. $this->error('参数无效');
  12850. }
  12851. $loaded = $this->loadAuditResendBundle($scydgyId);
  12852. $mergeRows = $loaded['merge_rows'];
  12853. $bundle = $loaded['bundle'];
  12854. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  12855. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  12856. if ($quoteGroups === []) {
  12857. $this->error('暂无可通知的供应商');
  12858. }
  12859. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  12860. $companiesJson = (string)$this->request->post('companies_json', '');
  12861. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  12862. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  12863. }
  12864. /**
  12865. * 确认供应商 — 二次发送邮件(可选单家/批量)
  12866. */
  12867. public function auditResendEmail()
  12868. {
  12869. if (!$this->request->isPost()) {
  12870. $this->error(__('Invalid parameters'));
  12871. }
  12872. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  12873. if ($scydgyId === '') {
  12874. $this->error('参数无效');
  12875. }
  12876. $loaded = $this->loadAuditResendBundle($scydgyId);
  12877. $mergeRows = $loaded['merge_rows'];
  12878. $bundle = $loaded['bundle'];
  12879. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  12880. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  12881. if ($quoteGroups === []) {
  12882. $this->error('暂无可通知的供应商');
  12883. }
  12884. $companiesJson = (string)$this->request->post('companies_json', '');
  12885. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  12886. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  12887. if ($companiesJson === '' && $selectedCompany === '') {
  12888. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  12889. }
  12890. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  12891. }
  12892. /**
  12893. * 废弃单个订单 bundle(退回供应商初选,明细归档留痕)
  12894. *
  12895. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  12896. * @return array<int, true> 已处理的 scydgy_id 集合
  12897. */
  12898. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回供应商初选'): array
  12899. {
  12900. $pos = $bundle['pos'] ?? [];
  12901. if (!is_array($pos) || $pos === []) {
  12902. return [];
  12903. }
  12904. $sids = [];
  12905. $poIdBySid = [];
  12906. foreach ($pos as $poRow) {
  12907. if (!is_array($poRow)) {
  12908. continue;
  12909. }
  12910. $sid = (int)($poRow['scydgy_id'] ?? 0);
  12911. if ($this->isValidScydgyRowId($sid)) {
  12912. $sids[$sid] = true;
  12913. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  12914. if ($poId > 0) {
  12915. $poIdBySid[$sid] = $poId;
  12916. }
  12917. }
  12918. }
  12919. if ($sids === []) {
  12920. return [];
  12921. }
  12922. $logMsg = '重新下发';
  12923. $suffix = trim((string)$logSuffix, ',, ');
  12924. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  12925. $logMsg .= ':从历史存证退回供应商初选';
  12926. } else {
  12927. $logMsg .= ':退回供应商初选';
  12928. }
  12929. Db::table('purchase_order')
  12930. ->where('scydgy_id', 'in', array_keys($sids))
  12931. ->update([
  12932. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  12933. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  12934. 'pick_company_name' => '',
  12935. 'pick_time' => null,
  12936. 'sys_rq' => null,
  12937. 'mod_rq' => null,
  12938. ]);
  12939. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  12940. foreach (array_keys($sids) as $sid) {
  12941. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  12942. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  12943. }
  12944. return $sids;
  12945. }
  12946. /**
  12947. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  12948. *
  12949. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  12950. */
  12951. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  12952. {
  12953. $scydgyId = trim($scydgyId);
  12954. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  12955. if ($scydgyId === '') {
  12956. return $empty;
  12957. }
  12958. try {
  12959. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  12960. } catch (\Throwable $e) {
  12961. $anchor = null;
  12962. }
  12963. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  12964. return $empty;
  12965. }
  12966. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  12967. if ($ccydh === '') {
  12968. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  12969. }
  12970. try {
  12971. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  12972. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  12973. $pos = $query->order('scydgy_id', 'asc')->select();
  12974. } catch (\Throwable $e) {
  12975. $pos = [$anchor];
  12976. }
  12977. if (!is_array($pos) || $pos === []) {
  12978. $pos = [$anchor];
  12979. }
  12980. return [
  12981. 'ccydh' => $ccydh,
  12982. 'pos' => $pos,
  12983. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  12984. ];
  12985. }
  12986. protected function purchaseOrderRowIsCompleted(array $po): bool
  12987. {
  12988. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  12989. }
  12990. /**
  12991. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  12992. *
  12993. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  12994. */
  12995. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  12996. {
  12997. $scydgyId = trim($scydgyId);
  12998. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  12999. if ($scydgyId === '') {
  13000. return $empty;
  13001. }
  13002. try {
  13003. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  13004. } catch (\Throwable $e) {
  13005. $anchor = null;
  13006. }
  13007. if (!is_array($anchor)) {
  13008. return $empty;
  13009. }
  13010. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  13011. if ($ccydh === '') {
  13012. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  13013. }
  13014. try {
  13015. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  13016. } catch (\Throwable $e) {
  13017. $pos = [$anchor];
  13018. }
  13019. if (!is_array($pos) || $pos === []) {
  13020. $pos = [$anchor];
  13021. }
  13022. $pos = $this->filterPurchaseOrdersSameIssueBatch($pos, $anchor);
  13023. return [
  13024. 'ccydh' => $ccydh,
  13025. 'pos' => $pos,
  13026. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  13027. ];
  13028. }
  13029. /**
  13030. * 废弃订单 — 退回供应商初选重新询价(支持单条或批量)
  13031. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  13032. */
  13033. public function auditAbandon()
  13034. {
  13035. if (!$this->request->isPost()) {
  13036. $this->error(__('Invalid parameters'));
  13037. }
  13038. $anchorIds = [];
  13039. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  13040. if ($batchRaw !== '') {
  13041. $decoded = json_decode($batchRaw, true);
  13042. if (is_array($decoded)) {
  13043. foreach ($decoded as $id) {
  13044. $s = trim((string)$id);
  13045. if ($s !== '') {
  13046. $anchorIds[] = $s;
  13047. }
  13048. }
  13049. }
  13050. }
  13051. if ($anchorIds === []) {
  13052. $single = trim((string)$this->request->post('scydgy_id', ''));
  13053. if ($single !== '') {
  13054. $anchorIds[] = $single;
  13055. }
  13056. }
  13057. if ($anchorIds === []) {
  13058. $this->error('请至少选择一条订单');
  13059. }
  13060. $processedCcydh = [];
  13061. $doneOrders = 0;
  13062. $allSids = [];
  13063. Db::startTrans();
  13064. try {
  13065. foreach ($anchorIds as $anchorId) {
  13066. $fromArchive = false;
  13067. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  13068. if (($bundle['pos'] ?? []) === []) {
  13069. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  13070. $fromArchive = ($bundle['pos'] ?? []) !== [];
  13071. }
  13072. if (($bundle['pos'] ?? []) === []) {
  13073. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  13074. $fromArchive = ($bundle['pos'] ?? []) !== [];
  13075. }
  13076. if (($bundle['pos'] ?? []) === []) {
  13077. continue;
  13078. }
  13079. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  13080. $batchTime = '';
  13081. if (!empty($bundle['pos'][0]) && is_array($bundle['pos'][0])) {
  13082. $batchTime = $this->procuremenIssueBatchTime($bundle['pos'][0]);
  13083. }
  13084. $dedupeKey = $ccydh !== '' ? ($ccydh . '|' . $batchTime) : ('sid:' . $anchorId);
  13085. if (isset($processedCcydh[$dedupeKey])) {
  13086. continue;
  13087. }
  13088. $processedCcydh[$dedupeKey] = true;
  13089. $sids = $fromArchive
  13090. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回供应商初选')
  13091. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  13092. if ($sids === []) {
  13093. continue;
  13094. }
  13095. $doneOrders++;
  13096. foreach (array_keys($sids) as $sid) {
  13097. $allSids[(int)$sid] = true;
  13098. }
  13099. }
  13100. if ($doneOrders < 1) {
  13101. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  13102. }
  13103. Db::commit();
  13104. } catch (\Throwable $e) {
  13105. Db::rollback();
  13106. $this->error($e->getMessage());
  13107. }
  13108. $this->pickHiddenScydgySetCache = null;
  13109. $msg = $doneOrders > 1
  13110. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回供应商初选,历史下发与操作记录已保留')
  13111. : '已退回供应商初选,请重新选择供应商下发(历史记录已保留)';
  13112. $this->success($msg);
  13113. }
  13114. /**
  13115. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  13116. */
  13117. public function archiveAbandon()
  13118. {
  13119. return $this->auditAbandon();
  13120. }
  13121. /**
  13122. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  13123. */
  13124. public function purchaseApprovalReject()
  13125. {
  13126. if (!$this->request->isPost() || !$this->request->isAjax()) {
  13127. $this->error(__('Invalid parameters'));
  13128. }
  13129. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  13130. $this->error(__('You have no permission'));
  13131. }
  13132. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  13133. $decoded = json_decode($batchRaw, true);
  13134. if (!is_array($decoded) || $decoded === []) {
  13135. $this->error('提交数据无效');
  13136. }
  13137. $done = 0;
  13138. Db::startTrans();
  13139. try {
  13140. foreach ($decoded as $item) {
  13141. if (!is_array($item)) {
  13142. continue;
  13143. }
  13144. $sid = (int)($item['scydgy_id'] ?? 0);
  13145. if (!$this->isValidScydgyRowId($sid)) {
  13146. continue;
  13147. }
  13148. $this->runPurchaseApprovalRejectForSid($sid);
  13149. $done++;
  13150. }
  13151. if ($done < 1) {
  13152. throw new \Exception('所选订单均不在待审批状态');
  13153. }
  13154. Db::commit();
  13155. } catch (\Throwable $e) {
  13156. Db::rollback();
  13157. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  13158. }
  13159. $this->pickHiddenScydgySetCache = null;
  13160. $this->success('已驳回并退回「协助审批下发」');
  13161. }
  13162. /**
  13163. * @throws \Exception
  13164. */
  13165. protected function runPurchaseApprovalRejectForSid(int $sid): void
  13166. {
  13167. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  13168. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  13169. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  13170. $allIds = $this->purchaseOrderDetail($sid);
  13171. if ($allIds === []) {
  13172. throw new \Exception('未找到下发明细');
  13173. }
  13174. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  13175. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  13176. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  13177. 'pick_company_name' => '',
  13178. ]);
  13179. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  13180. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  13181. $poId = 0;
  13182. try {
  13183. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  13184. if (is_array($po)) {
  13185. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  13186. }
  13187. } catch (\Throwable $e) {
  13188. }
  13189. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  13190. }
  13191. /**
  13192. * 审核弹窗(旧入口,POST 已关闭)
  13193. */
  13194. public function review()
  13195. {
  13196. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  13197. $this->error(__('You have no permission'));
  13198. }
  13199. if ($this->request->isPost()) {
  13200. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  13201. }
  13202. $this->view->assign('pickMode', 0);
  13203. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  13204. }
  13205. /**
  13206. * 审核弹窗获取公司列表
  13207. */
  13208. public function reviewCompanies()
  13209. {
  13210. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  13211. $this->error(__('You have no permission'));
  13212. }
  13213. if (!$this->request->isAjax()) {
  13214. $this->error(__('Invalid parameters'));
  13215. }
  13216. $list = [];
  13217. try {
  13218. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  13219. $rows = Db::table('customer')
  13220. ->where(function ($q) {
  13221. $q->where('status', 1)
  13222. ->whereOr('status', '1')
  13223. ->whereOr('status', '')
  13224. ->whereNull('status');
  13225. })
  13226. ->order('id', 'desc')
  13227. ->select();
  13228. } catch (\Throwable $e) {
  13229. $this->success('', '', []);
  13230. return;
  13231. }
  13232. if (!is_array($rows)) {
  13233. $this->success('', '', []);
  13234. return;
  13235. }
  13236. $detailColCandidates = [
  13237. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  13238. 'company_detail', 'company_desc', 'address',
  13239. ];
  13240. foreach ($rows as $row) {
  13241. if (!is_array($row)) {
  13242. continue;
  13243. }
  13244. $norm = [];
  13245. foreach ($row as $k => $v) {
  13246. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  13247. }
  13248. $row = $norm;
  13249. $st = $row['status'] ?? '';
  13250. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  13251. continue;
  13252. }
  13253. $payload = $this->buildCustomerContactPayloadFromRow($row, false);
  13254. if ($payload === null) {
  13255. continue;
  13256. }
  13257. $detail = '';
  13258. foreach ($detailColCandidates as $dk) {
  13259. if (!isset($row[$dk])) {
  13260. continue;
  13261. }
  13262. $dv = trim((string)$row[$dk]);
  13263. if ($dv !== '') {
  13264. $detail = $dv;
  13265. break;
  13266. }
  13267. }
  13268. $payload['detail'] = $detail;
  13269. $list[] = $this->maskSupplierContactFields($payload);
  13270. }
  13271. $this->success('', '', $list);
  13272. }
  13273. /**
  13274. * 采购确认-下发明细弹窗:
  13275. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  13276. */
  13277. public function outward_detail()
  13278. {
  13279. $ids = $this->request->param('ids', $this->request->param('id', ''));
  13280. if (is_array($ids)) {
  13281. $ids = isset($ids[0]) ? $ids[0] : '';
  13282. }
  13283. $ids = trim((string)$ids);
  13284. if ($ids === '') {
  13285. $this->error(__('Invalid parameters'));
  13286. }
  13287. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  13288. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  13289. $wffTab = 'all';
  13290. }
  13291. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  13292. $purchaseOrderId = 0;
  13293. $po = null;
  13294. try {
  13295. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  13296. if (is_array($po)) {
  13297. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  13298. }
  13299. } catch (\Throwable $e) {
  13300. $purchaseOrderId = 0;
  13301. $po = null;
  13302. }
  13303. if (!$isPurchaseConfirm && is_array($po)) {
  13304. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  13305. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  13306. $isPurchaseConfirm = true;
  13307. }
  13308. }
  13309. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  13310. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  13311. $confirmProcessCount = 1;
  13312. $confirmPickGroups = [];
  13313. $processDisplayRows = [];
  13314. $allDetailsBySid = [];
  13315. $requiredSidList = [];
  13316. $sidList = [$ids];
  13317. if ($isPurchaseConfirm) {
  13318. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  13319. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  13320. if ($mergeRows !== []) {
  13321. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  13322. }
  13323. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  13324. if ($confirmBundle['pos'] !== []) {
  13325. $sidList = [];
  13326. foreach ($confirmBundle['pos'] as $poRow) {
  13327. if (!is_array($poRow)) {
  13328. continue;
  13329. }
  13330. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13331. if (!$this->isValidScydgyRowId($sid)) {
  13332. continue;
  13333. }
  13334. $sidList[] = (string)$sid;
  13335. $requiredSidList[] = $sid;
  13336. }
  13337. }
  13338. if ($sidList === []) {
  13339. $sidList = [$ids];
  13340. $requiredSidList = [(int)$ids];
  13341. }
  13342. $confirmProcessCount = max(1, count($requiredSidList));
  13343. if (is_array($po) && $purchaseOrderId <= 0) {
  13344. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  13345. }
  13346. }
  13347. $rows = [];
  13348. try {
  13349. if (count($sidList) === 1) {
  13350. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  13351. } else {
  13352. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  13353. }
  13354. } catch (\Throwable $e) {
  13355. $rows = [];
  13356. }
  13357. if ($isPurchaseConfirm) {
  13358. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  13359. }
  13360. foreach ($rows as &$r) {
  13361. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  13362. $r['id'] = $r['ID'];
  13363. }
  13364. if (isset($r['createtime'])) {
  13365. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  13366. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  13367. } else {
  13368. $r['createtime_text'] = (string)$r['createtime'];
  13369. }
  13370. } else {
  13371. $r['createtime_text'] = '';
  13372. }
  13373. if (is_array($r)) {
  13374. $r = $this->maskSupplierContactFields($r);
  13375. }
  13376. }
  13377. unset($r);
  13378. $pickedCompanyName = '';
  13379. $manualPicked = 0;
  13380. $manualPickReason = '';
  13381. $quoteVisible = 0;
  13382. $bidOpenVerified = 0;
  13383. if ($isPurchaseConfirm) {
  13384. // 确认包为空时,用当前主单兜底,避免指定说明读不到
  13385. if (($confirmBundle['ccydh'] ?? '') === '' && is_array($po)) {
  13386. $confirmBundle['ccydh'] = trim((string)($po['CCYDH'] ?? ''));
  13387. }
  13388. if (($confirmBundle['pos'] ?? []) === [] && is_array($po)) {
  13389. $confirmBundle['pos'] = [$po];
  13390. }
  13391. $manualPickInfo = $this->resolveProcuremenManualPickInfo($confirmBundle);
  13392. $manualPicked = $this->isProcuremenManualPickedForBundle($confirmBundle) ? 1 : 0;
  13393. $manualPickReason = (string)($manualPickInfo['reason'] ?? '');
  13394. if ($manualPickInfo['company'] !== '') {
  13395. $pickedCompanyName = $manualPickInfo['company'];
  13396. }
  13397. if ($pickedCompanyName === '') {
  13398. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  13399. if (!is_array($poRow)) {
  13400. continue;
  13401. }
  13402. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  13403. if ($pn !== '') {
  13404. $pickedCompanyName = $pn;
  13405. break;
  13406. }
  13407. }
  13408. }
  13409. // 再兜底:直接读当前主单字段
  13410. if (is_array($po) && (int)($po['manual_pick'] ?? 0) === 1) {
  13411. $manualPicked = 1;
  13412. if ($manualPickReason === '') {
  13413. $manualPickReason = trim((string)($po['manual_pick_reason'] ?? ''));
  13414. }
  13415. if ($pickedCompanyName === '') {
  13416. $pickedCompanyName = trim((string)($po['pick_company_name'] ?? ''));
  13417. }
  13418. }
  13419. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle) ? 1 : 0;
  13420. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  13421. }
  13422. $this->view->assign('rows', $rows ?: []);
  13423. $this->view->assign('rowCount', count($rows ?: []));
  13424. $this->view->assign('scydgyId', $ids);
  13425. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  13426. $this->view->assign('headTitle', $headTitle);
  13427. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  13428. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  13429. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  13430. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  13431. $this->view->assign('processDisplayRows', $processDisplayRows);
  13432. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  13433. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  13434. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  13435. $this->view->assign('manualPicked', $manualPicked);
  13436. $this->view->assign('manualPickReason', $manualPickReason);
  13437. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  13438. $this->view->assign('quoteVisible', $quoteVisible);
  13439. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
  13440. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  13441. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
  13442. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
  13443. $sysRqDisplay = '—';
  13444. if ($isPurchaseConfirm) {
  13445. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  13446. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  13447. );
  13448. }
  13449. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  13450. $this->view->assign('sysRq', $isPurchaseConfirm
  13451. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  13452. : '');
  13453. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  13454. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  13455. : '');
  13456. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  13457. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  13458. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  13459. if ($isPurchaseConfirm) {
  13460. return $this->view->fetch();
  13461. }
  13462. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  13463. $this->view->engine->layout(false);
  13464. try {
  13465. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  13466. $this->view->assign('dialogBody', $bodyHtml);
  13467. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  13468. } finally {
  13469. if ($restoreLayout) {
  13470. $this->view->engine->layout($restoreLayout);
  13471. }
  13472. }
  13473. }
  13474. /**
  13475. * 月度导出记录表(不存在时自动创建)
  13476. */
  13477. protected function ensurePurchaseMonthExportLogTable(): void
  13478. {
  13479. try {
  13480. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  13481. } catch (\Throwable $e) {
  13482. Db::execute(
  13483. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  13484. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  13485. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  13486. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  13487. `admin_name` varchar(64) NOT NULL DEFAULT '',
  13488. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  13489. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  13490. `createtime` int(10) unsigned DEFAULT NULL,
  13491. PRIMARY KEY (`id`),
  13492. KEY `idx_ym` (`ym`),
  13493. KEY `idx_ct` (`createtime`)
  13494. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  13495. );
  13496. }
  13497. }
  13498. /**
  13499. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  13500. *
  13501. * @param array<int, mixed> $dbRows
  13502. * @return array<int, array<string, mixed>>
  13503. */
  13504. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  13505. {
  13506. $keyword = trim((string)$this->request->get('search', ''));
  13507. if ($keyword === '') {
  13508. $keyword = trim((string)$this->request->request('search', ''));
  13509. }
  13510. $filter = $this->request->get('filter', '');
  13511. $op = $this->request->get('op', '');
  13512. if (is_string($filter) && $filter !== '') {
  13513. $filterArr = (array)json_decode($filter, true);
  13514. } else {
  13515. $filterArr = is_array($filter) ? $filter : [];
  13516. }
  13517. if (is_string($op) && $op !== '') {
  13518. $opArr = (array)json_decode($op, true);
  13519. } else {
  13520. $opArr = is_array($op) ? $op : [];
  13521. }
  13522. if ($keyword === '' && $filterArr === []) {
  13523. return array_values(array_filter($dbRows, 'is_array'));
  13524. }
  13525. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  13526. $out = [];
  13527. foreach ($dbRows as $row) {
  13528. if (!is_array($row)) {
  13529. continue;
  13530. }
  13531. if ($keyword !== '') {
  13532. $hit = false;
  13533. foreach ($searchFields as $f) {
  13534. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  13535. $hit = true;
  13536. break;
  13537. }
  13538. }
  13539. if (!$hit) {
  13540. continue;
  13541. }
  13542. }
  13543. $passFilter = true;
  13544. foreach ($filterArr as $field => $val) {
  13545. $field = (string)$field;
  13546. $val = trim((string)$val);
  13547. if ($field === '' || $val === '') {
  13548. continue;
  13549. }
  13550. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  13551. continue;
  13552. }
  13553. $cell = (string)($row[$field] ?? '');
  13554. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  13555. if ($mode === '=' || $mode === 'EQUAL') {
  13556. if (strcasecmp($cell, $val) !== 0) {
  13557. $passFilter = false;
  13558. break;
  13559. }
  13560. } elseif (mb_stripos($cell, $val) === false) {
  13561. $passFilter = false;
  13562. break;
  13563. }
  13564. }
  13565. if (!$passFilter) {
  13566. continue;
  13567. }
  13568. $out[] = $row;
  13569. }
  13570. return $out;
  13571. }
  13572. /**
  13573. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  13574. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  13575. */
  13576. public function export_month_outward()
  13577. {
  13578. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  13579. $this->error(__('You have no permission'));
  13580. }
  13581. $bundle = $this->prepareMonthOutwardExportBundle();
  13582. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  13583. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  13584. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  13585. $spreadsheet = new Spreadsheet();
  13586. $sheet = $spreadsheet->getActiveSheet();
  13587. $sheet->setTitle('外协加工明细');
  13588. $mon = (int)substr($ym, 5, 2);
  13589. $sheet->mergeCells('A1:H1');
  13590. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  13591. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  13592. $sheet->getStyle('A1')->getAlignment()
  13593. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  13594. ->setVertical(Alignment::VERTICAL_CENTER);
  13595. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  13596. $col = 'A';
  13597. foreach ($headers as $h) {
  13598. $sheet->setCellValue($col . '2', $h);
  13599. $col++;
  13600. }
  13601. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  13602. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  13603. $rowNum = 3;
  13604. $sumSubtotalCounts = 0;
  13605. $grandAmount = 0.0;
  13606. $globalSeq = 0;
  13607. if ($groups === []) {
  13608. $sheet->mergeCells('A3:H3');
  13609. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  13610. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  13611. $rowNum = 4;
  13612. } else {
  13613. foreach ($groups as $items) {
  13614. if ($items === []) {
  13615. continue;
  13616. }
  13617. $groupLineCount = count($items);
  13618. $subAmount = 0.0;
  13619. foreach ($items as $line) {
  13620. $globalSeq++;
  13621. $dr = $line['detail'];
  13622. $amt = $this->procuremenExportAmount($dr);
  13623. $subAmount += $amt;
  13624. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  13625. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  13626. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  13627. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  13628. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  13629. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  13630. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  13631. $sheet->setCellValue('H' . $rowNum, $amt);
  13632. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  13633. $rowNum++;
  13634. }
  13635. $sumSubtotalCounts += $groupLineCount;
  13636. $grandAmount += $subAmount;
  13637. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  13638. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  13639. $sheet->getStyle('G' . $rowNum)->getAlignment()
  13640. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  13641. ->setVertical(Alignment::VERTICAL_CENTER);
  13642. $rowNum++;
  13643. }
  13644. }
  13645. $sheet->setCellValue('A' . $rowNum, '总计');
  13646. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  13647. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  13648. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  13649. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  13650. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  13651. $lastRow = $rowNum;
  13652. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  13653. 'borders' => [
  13654. 'allBorders' => [
  13655. 'borderStyle' => Border::BORDER_THIN,
  13656. 'color' => ['rgb' => '000000'],
  13657. ],
  13658. ],
  13659. ]);
  13660. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  13661. if ($lastRow >= 3) {
  13662. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  13663. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  13664. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  13665. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  13666. }
  13667. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  13668. $sheet->getColumnDimension('A')->setWidth(7);
  13669. $sheet->getColumnDimension('B')->setWidth(16);
  13670. $sheet->getColumnDimension('C')->setWidth(52);
  13671. $sheet->getColumnDimension('D')->setWidth(32);
  13672. $sheet->getColumnDimension('E')->setWidth(12);
  13673. $sheet->getColumnDimension('F')->setWidth(44);
  13674. $sheet->getColumnDimension('G')->setWidth(26);
  13675. $sheet->getColumnDimension('H')->setWidth(13);
  13676. $sheet->getRowDimension(1)->setRowHeight(28);
  13677. $ymCompact = str_replace('-', '', $ym);
  13678. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  13679. $filename = $fileBase . '.xlsx';
  13680. try {
  13681. $this->ensurePurchaseMonthExportLogTable();
  13682. list($adminId, $adminName) = $this->GetUseName();
  13683. Db::table('purchase_month_export_log')->insert([
  13684. 'ym' => $ym,
  13685. 'admin_id' => (int)$adminId,
  13686. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  13687. 'row_count' => count($exportLines),
  13688. 'total_amount' => round($grandAmount, 2),
  13689. 'createtime' => time(),
  13690. ]);
  13691. } catch (\Throwable $e) {
  13692. Log::write('month export log: ' . $e->getMessage(), 'error');
  13693. }
  13694. if (ob_get_length()) {
  13695. ob_end_clean();
  13696. }
  13697. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  13698. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  13699. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  13700. header('Cache-Control: max-age=0');
  13701. $writer = new Xlsx($spreadsheet);
  13702. $writer->save('php://output');
  13703. $spreadsheet->disconnectWorksheets();
  13704. unset($spreadsheet);
  13705. exit;
  13706. }
  13707. /**
  13708. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  13709. */
  13710. public function export_month_quote()
  13711. {
  13712. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  13713. $this->error(__('You have no permission'));
  13714. }
  13715. $bundle = $this->prepareMonthOutwardExportBundle();
  13716. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  13717. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  13718. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  13719. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  13720. $spreadsheet = new Spreadsheet();
  13721. $sheet = $spreadsheet->getActiveSheet();
  13722. $sheet->setTitle('供应商报价明细');
  13723. $mon = (int)substr($ym, 5, 2);
  13724. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  13725. $sheet->getColumnDimension('A')->setWidth(7);
  13726. $sheet->getColumnDimension('B')->setWidth(16);
  13727. $sheet->getColumnDimension('C')->setWidth(52);
  13728. $sheet->getColumnDimension('D')->setWidth(26);
  13729. $sheet->getColumnDimension('E')->setWidth(32);
  13730. $sheet->getColumnDimension('F')->setWidth(12);
  13731. $sheet->getColumnDimension('G')->setWidth(14);
  13732. $sheet->getColumnDimension('H')->setWidth(12);
  13733. if ($quoteLastRow < 1) {
  13734. $quoteLastRow = 3;
  13735. }
  13736. $ymCompact = str_replace('-', '', $ym);
  13737. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  13738. if (ob_get_length()) {
  13739. ob_end_clean();
  13740. }
  13741. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  13742. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  13743. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  13744. header('Cache-Control: max-age=0');
  13745. $writer = new Xlsx($spreadsheet);
  13746. $writer->save('php://output');
  13747. $spreadsheet->disconnectWorksheets();
  13748. unset($spreadsheet);
  13749. exit;
  13750. }
  13751. /**
  13752. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  13753. *
  13754. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  13755. */
  13756. protected function prepareMonthOutwardExportBundle(): array
  13757. {
  13758. $this->request->filter(['strip_tags', 'trim']);
  13759. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  13760. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  13761. $ym = date('Y-m');
  13762. }
  13763. $dbRows = [];
  13764. try {
  13765. $query = Db::table('purchase_order');
  13766. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  13767. $dbRows = $query->select();
  13768. } catch (\Throwable $e) {
  13769. $dbRows = [];
  13770. }
  13771. if (!is_array($dbRows)) {
  13772. $dbRows = [];
  13773. }
  13774. $completeTsMap = [];
  13775. $sidList = [];
  13776. foreach ($dbRows as $dbRow) {
  13777. if (!is_array($dbRow)) {
  13778. continue;
  13779. }
  13780. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  13781. if ($sid > 0) {
  13782. $sidList[$sid] = true;
  13783. }
  13784. }
  13785. if ($sidList !== []) {
  13786. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  13787. }
  13788. // 导出始终按「查看月份」取当月完结单;搜索只在当月内再缩小(勿跨月,否则会与列表不一致)
  13789. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  13790. if (!is_array($dbRow)) {
  13791. return false;
  13792. }
  13793. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  13794. if ($done['ts'] <= 0) {
  13795. return false;
  13796. }
  13797. return date('Y-m', $done['ts']) === $ym;
  13798. }));
  13799. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  13800. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  13801. $mainBySid = [];
  13802. foreach ($pool as $rw) {
  13803. if (!is_array($rw)) {
  13804. continue;
  13805. }
  13806. $rid = (int)($rw['ID'] ?? 0);
  13807. if ($rid > 0) {
  13808. $mainBySid[$rid] = $rw;
  13809. }
  13810. }
  13811. if ($mainBySid === []) {
  13812. $detailRows = [];
  13813. } else {
  13814. try {
  13815. $detailRows = Db::table('purchase_order_detail')
  13816. ->where('scydgy_id', 'in', array_keys($mainBySid))
  13817. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  13818. ->order('status', 'desc')
  13819. ->order('CCYDH', 'asc')
  13820. ->order('company_name', 'asc')
  13821. ->order('id', 'asc')
  13822. ->select();
  13823. } catch (\Throwable $e) {
  13824. try {
  13825. $detailRows = Db::table('purchase_order_detail')
  13826. ->where('scydgy_id', 'in', array_keys($mainBySid))
  13827. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  13828. ->order('status', 'desc')
  13829. ->order('CCYDH', 'asc')
  13830. ->order('company_name', 'asc')
  13831. ->order('ID', 'asc')
  13832. ->select();
  13833. } catch (\Throwable $e2) {
  13834. $detailRows = [];
  13835. }
  13836. }
  13837. }
  13838. if (!is_array($detailRows)) {
  13839. $detailRows = [];
  13840. }
  13841. $exportLines = [];
  13842. $detailSidSeen = [];
  13843. foreach ($detailRows as $dr) {
  13844. if (!is_array($dr)) {
  13845. continue;
  13846. }
  13847. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  13848. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  13849. continue;
  13850. }
  13851. if (isset($detailSidSeen[$sid])) {
  13852. continue;
  13853. }
  13854. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  13855. continue;
  13856. }
  13857. $detailSidSeen[$sid] = true;
  13858. $m = $mainBySid[$sid];
  13859. $exportLines[] = [
  13860. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  13861. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  13862. 'company_name' => (string)($dr['company_name'] ?? ''),
  13863. 'CDF' => (string)($m['CDF'] ?? ''),
  13864. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  13865. 'gx' => $this->procuremenExportGxText($m),
  13866. 'detail' => $dr,
  13867. ];
  13868. }
  13869. foreach ($detailRows as $dr) {
  13870. if (!is_array($dr)) {
  13871. continue;
  13872. }
  13873. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  13874. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  13875. continue;
  13876. }
  13877. $detailSidSeen[$sid] = true;
  13878. $m = $mainBySid[$sid];
  13879. $exportLines[] = [
  13880. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  13881. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  13882. 'company_name' => (string)($dr['company_name'] ?? ''),
  13883. 'CDF' => (string)($m['CDF'] ?? ''),
  13884. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  13885. 'gx' => $this->procuremenExportGxText($m),
  13886. 'detail' => $dr,
  13887. ];
  13888. }
  13889. foreach ($mainBySid as $sid => $m) {
  13890. if (isset($detailSidSeen[$sid])) {
  13891. continue;
  13892. }
  13893. $company = trim((string)($m['pick_company_name'] ?? ''));
  13894. $exportLines[] = [
  13895. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  13896. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  13897. 'company_name' => $company,
  13898. 'CDF' => (string)($m['CDF'] ?? ''),
  13899. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  13900. 'gx' => $this->procuremenExportGxText($m),
  13901. 'detail' => [],
  13902. ];
  13903. }
  13904. $groups = [];
  13905. foreach ($exportLines as $line) {
  13906. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  13907. if (!isset($groups[$k])) {
  13908. $groups[$k] = [];
  13909. }
  13910. $groups[$k][] = $line;
  13911. }
  13912. ksort($groups, SORT_STRING);
  13913. return [
  13914. 'ym' => $ym,
  13915. 'mainBySid' => $mainBySid,
  13916. 'detailRows' => $detailRows,
  13917. 'exportLines' => $exportLines,
  13918. 'groups' => $groups,
  13919. ];
  13920. }
  13921. /**
  13922. * 导出用:工序列文案
  13923. */
  13924. protected function procuremenExportGxText(array $r)
  13925. {
  13926. $a = trim((string)($r['CDXMC'] ?? ''));
  13927. $b = trim((string)($r['CGYMC'] ?? ''));
  13928. if ($a !== '' && $b !== '') {
  13929. return $a . ':' . $b;
  13930. }
  13931. return $a !== '' ? $a : $b;
  13932. }
  13933. /**
  13934. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  13935. */
  13936. protected function procuremenExportAmount(array $r)
  13937. {
  13938. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  13939. if (!array_key_exists($k, $r)) {
  13940. continue;
  13941. }
  13942. $v = $r[$k];
  13943. if ($v === null || $v === '') {
  13944. continue;
  13945. }
  13946. if (is_numeric($v)) {
  13947. return (float)$v;
  13948. }
  13949. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  13950. if ($v !== '' && is_numeric($v)) {
  13951. return (float)$v;
  13952. }
  13953. }
  13954. return 0.0;
  13955. }
  13956. /**
  13957. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  13958. *
  13959. * @param array<int, array<string, mixed>> $detailRows
  13960. * @param array<int, array<string, mixed>> $mainBySid
  13961. * @return array<int, array<string, mixed>>
  13962. */
  13963. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  13964. {
  13965. $lines = [];
  13966. foreach ($detailRows as $dr) {
  13967. if (!is_array($dr)) {
  13968. continue;
  13969. }
  13970. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  13971. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  13972. continue;
  13973. }
  13974. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  13975. continue;
  13976. }
  13977. $cn = trim((string)($dr['company_name'] ?? ''));
  13978. if ($cn === '') {
  13979. continue;
  13980. }
  13981. $m = $mainBySid[$sid];
  13982. $am = trim((string)($dr['amount'] ?? ''));
  13983. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  13984. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  13985. $amountText = $amountFilled
  13986. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  13987. : '未填写';
  13988. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  13989. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  13990. if ($deliveryShow === '' && $deliveryRaw !== '') {
  13991. $deliveryShow = $deliveryRaw;
  13992. }
  13993. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  13994. ? $deliveryShow
  13995. : '未填写';
  13996. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  13997. $lines[] = [
  13998. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  13999. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  14000. 'gx' => $this->procuremenExportGxText($m),
  14001. 'company_name' => $cn,
  14002. 'amount_text' => $amountText,
  14003. 'amount_num' => $amountFilled ? $amountNum : null,
  14004. 'delivery_text' => $deliveryText,
  14005. 'picked_text' => $picked ? '中标' : '未中标',
  14006. 'picked' => $picked,
  14007. ];
  14008. }
  14009. $winnerSupplierByOrder = [];
  14010. foreach ($lines as $line) {
  14011. $dh = trim((string)($line['CCYDH'] ?? ''));
  14012. $cn = trim((string)($line['company_name'] ?? ''));
  14013. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  14014. $winnerSupplierByOrder[$dh][$cn] = true;
  14015. }
  14016. }
  14017. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  14018. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  14019. if ($c !== 0) {
  14020. return $c;
  14021. }
  14022. $dh = trim((string)($a['CCYDH'] ?? ''));
  14023. $aCn = trim((string)($a['company_name'] ?? ''));
  14024. $bCn = trim((string)($b['company_name'] ?? ''));
  14025. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  14026. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  14027. if ($aSupplierWin !== $bSupplierWin) {
  14028. return $aSupplierWin ? -1 : 1;
  14029. }
  14030. $c = strcmp($aCn, $bCn);
  14031. if ($c !== 0) {
  14032. return $c;
  14033. }
  14034. if (!empty($a['picked']) !== !empty($b['picked'])) {
  14035. return !empty($a['picked']) ? -1 : 1;
  14036. }
  14037. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  14038. if ($c !== 0) {
  14039. return $c;
  14040. }
  14041. return 0;
  14042. });
  14043. return $lines;
  14044. }
  14045. /**
  14046. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  14047. *
  14048. * @param array<int, array<string, mixed>> $quoteLines
  14049. */
  14050. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  14051. {
  14052. $mon = (int)substr($ym, 5, 2);
  14053. $titleRow = $startRow;
  14054. $headerRow = $startRow + 1;
  14055. $dataStartRow = $startRow + 2;
  14056. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  14057. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  14058. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  14059. $sheet->getStyle('A' . $titleRow)->getAlignment()
  14060. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  14061. ->setVertical(Alignment::VERTICAL_CENTER);
  14062. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  14063. $col = 'A';
  14064. foreach ($headers as $h) {
  14065. $sheet->setCellValue($col . $headerRow, $h);
  14066. $col++;
  14067. }
  14068. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  14069. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  14070. $rowNum = $dataStartRow;
  14071. if ($quoteLines === []) {
  14072. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  14073. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  14074. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  14075. $rowNum = $dataStartRow + 1;
  14076. } else {
  14077. $i = 0;
  14078. foreach ($quoteLines as $line) {
  14079. $i++;
  14080. $sheet->setCellValue('A' . $rowNum, $i);
  14081. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  14082. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  14083. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  14084. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  14085. if ($line['amount_num'] !== null) {
  14086. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  14087. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  14088. } else {
  14089. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  14090. }
  14091. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  14092. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  14093. if (!empty($line['picked'])) {
  14094. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  14095. }
  14096. $rowNum++;
  14097. }
  14098. }
  14099. $lastRow = $rowNum - 1;
  14100. if ($lastRow >= $headerRow) {
  14101. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  14102. 'borders' => [
  14103. 'allBorders' => [
  14104. 'borderStyle' => Border::BORDER_THIN,
  14105. 'color' => ['rgb' => '000000'],
  14106. ],
  14107. ],
  14108. ]);
  14109. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  14110. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14111. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14112. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14113. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  14114. if ($lastRow >= $dataStartRow) {
  14115. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  14116. }
  14117. }
  14118. return $lastRow;
  14119. }
  14120. /**
  14121. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  14122. */
  14123. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  14124. {
  14125. if ($lastRow < $dataStartRow || $headerRow < 1) {
  14126. return;
  14127. }
  14128. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  14129. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  14130. ->setVertical(Alignment::VERTICAL_CENTER);
  14131. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  14132. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  14133. ->setVertical(Alignment::VERTICAL_CENTER);
  14134. if ($lastCol > 'B') {
  14135. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  14136. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  14137. ->setVertical(Alignment::VERTICAL_CENTER);
  14138. }
  14139. }
  14140. /**
  14141. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  14142. */
  14143. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  14144. {
  14145. $s = trim($ccydh);
  14146. if ($s === '') {
  14147. return 'ORDER';
  14148. }
  14149. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  14150. $s = trim($s, '._-');
  14151. if ($s === '') {
  14152. return 'ORDER';
  14153. }
  14154. if (function_exists('mb_substr')) {
  14155. return mb_substr($s, 0, 80, 'UTF-8');
  14156. }
  14157. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  14158. }
  14159. /**
  14160. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  14161. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  14162. *
  14163. * @return array{objectKey: string, webPath: string}
  14164. */
  14165. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  14166. {
  14167. $sid = (int)$scydgyId;
  14168. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  14169. $y = date('Y');
  14170. $m = date('m');
  14171. $d = date('d');
  14172. $basename = $safeOrder . '_' . $sid . '.pdf';
  14173. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  14174. return [
  14175. 'objectKey' => $objectKey,
  14176. 'webPath' => '/' . $objectKey,
  14177. ];
  14178. }
  14179. /**
  14180. * 采购确认成功后 / 已完结刷新:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  14181. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  14182. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  14183. * 说明:审批通过时会先存一版;质量+交货评分使订单「已完结」后,详情页打开或评分保存完成时会再重存,以含最终步骤与操作记录。
  14184. *
  14185. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  14186. */
  14187. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  14188. {
  14189. if (!$this->isValidScydgyRowId($scydgyId)) {
  14190. return '';
  14191. }
  14192. $ids = trim((string)$scydgyId);
  14193. $prep = $this->prepareProcuremenDetailsView($ids);
  14194. if (!$prep['ok']) {
  14195. return '';
  14196. }
  14197. $ccydh = $prep['ccydh'];
  14198. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  14199. $objectKey = $paths['objectKey'];
  14200. $webPath = $paths['webPath'];
  14201. $cyjmc = '';
  14202. try {
  14203. $poMeta = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->field('CYJMC')->find();
  14204. if (is_array($poMeta)) {
  14205. $cyjmc = trim((string)($poMeta['CYJMC'] ?? ''));
  14206. }
  14207. } catch (\Throwable $e) {
  14208. $cyjmc = '';
  14209. }
  14210. $genTime = date('Y-m-d H:i:s');
  14211. $metaIds = '工序行ID ' . $ids . ' | 主表订单ID ' . (int)$purchaseOrderId;
  14212. $metaLeft = $metaIds . ($cyjmc !== '' ? ' | ' . $cyjmc : '');
  14213. // PDF 进度:去掉「未发」;节点用纯色圆点(不用图片,避免 mPDF 破图)
  14214. $pdfSteps = [];
  14215. $viewSteps = $prep['steps'] ?? [];
  14216. if (is_array($viewSteps)) {
  14217. foreach ($viewSteps as $st) {
  14218. if (!is_array($st)) {
  14219. continue;
  14220. }
  14221. if (trim((string)($st['title'] ?? '')) === '未发') {
  14222. continue;
  14223. }
  14224. $pdfSteps[] = $st;
  14225. }
  14226. }
  14227. $pdfStepW = count($pdfSteps) > 0 ? (round(100 / count($pdfSteps), 2) . '%') : '16.66%';
  14228. $nPdf = count($pdfSteps);
  14229. foreach ($pdfSteps as $idx => &$pst) {
  14230. if ($idx === 0) {
  14231. $pst['pdf_left_bg'] = '';
  14232. } else {
  14233. $pst['pdf_left_bg'] = !empty($pdfSteps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  14234. }
  14235. if ($idx >= $nPdf - 1) {
  14236. $pst['pdf_right_bg'] = '';
  14237. } else {
  14238. $pst['pdf_right_bg'] = !empty($pst['done']) ? '#1890ff' : '#e0e0e0';
  14239. }
  14240. }
  14241. unset($pst);
  14242. $this->view->assign([
  14243. 'pdf_export' => 1,
  14244. 'pdfMetaLine' => $metaLeft,
  14245. 'pdfMetaLeft' => $metaLeft,
  14246. 'pdfMetaIds' => $metaIds,
  14247. 'pdfMetaTitle' => $cyjmc,
  14248. 'pdfMetaTime' => 'PDF生成时间 ' . $genTime,
  14249. 'pdfSteps' => $pdfSteps,
  14250. 'pdfStepWidth' => $pdfStepW,
  14251. ]);
  14252. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  14253. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  14254. $this->view->engine->layout(false);
  14255. try {
  14256. $html = $this->view->fetch('procuremen/details_pdf_shell');
  14257. } catch (\Throwable $e) {
  14258. if ($restoreLayout) {
  14259. $this->view->engine->layout($restoreLayout);
  14260. }
  14261. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  14262. $this->view->assign([
  14263. 'pdf_export' => '', 'pdfMetaLine' => '', 'pdfMetaLeft' => '',
  14264. 'pdfMetaIds' => '', 'pdfMetaTitle' => '', 'pdfMetaTime' => '',
  14265. 'pdfSteps' => [], 'pdfStepWidth' => '',
  14266. ]);
  14267. return '';
  14268. }
  14269. if ($restoreLayout) {
  14270. $this->view->engine->layout($restoreLayout);
  14271. }
  14272. $this->view->assign([
  14273. 'pdf_export' => '', 'pdfMetaLine' => '', 'pdfMetaLeft' => '',
  14274. 'pdfMetaIds' => '', 'pdfMetaTitle' => '', 'pdfMetaTime' => '',
  14275. 'pdfSteps' => [], 'pdfStepWidth' => '',
  14276. ]);
  14277. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  14278. if (!is_dir($tempDir)) {
  14279. @mkdir($tempDir, 0755, true);
  14280. }
  14281. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  14282. try {
  14283. $mpdf = new \Mpdf\Mpdf([
  14284. 'mode' => 'utf-8',
  14285. 'format' => 'A4',
  14286. 'margin_left' => 12,
  14287. 'margin_right' => 12,
  14288. 'margin_top' => 14,
  14289. 'margin_bottom' => 14,
  14290. 'tempDir' => $tempDir,
  14291. 'autoScriptToLang' => true,
  14292. 'autoLangToFont' => true,
  14293. ]);
  14294. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  14295. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  14296. $mpdf->SetBasePath('http://127.0.0.1/');
  14297. $mpdf->WriteHTML($html);
  14298. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  14299. } catch (\Throwable $e) {
  14300. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  14301. if (is_file($tempPdf)) {
  14302. @unlink($tempPdf);
  14303. }
  14304. return '';
  14305. }
  14306. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  14307. if ($ossUrl !== '') {
  14308. @unlink($tempPdf);
  14309. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  14310. return $ossUrl;
  14311. }
  14312. $pi = pathinfo($objectKey);
  14313. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  14314. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  14315. if ($baseFile === '') {
  14316. @unlink($tempPdf);
  14317. return '';
  14318. }
  14319. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  14320. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  14321. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  14322. @unlink($tempPdf);
  14323. return '';
  14324. }
  14325. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  14326. if (!@copy($tempPdf, $fullPath)) {
  14327. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  14328. @unlink($tempPdf);
  14329. return '';
  14330. }
  14331. @unlink($tempPdf);
  14332. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  14333. return $webPath;
  14334. }
  14335. /**
  14336. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  14337. */
  14338. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  14339. {
  14340. if ($scydgyId <= 0 || $webPath === '') {
  14341. return;
  14342. }
  14343. try {
  14344. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  14345. } catch (\Throwable $e) {
  14346. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  14347. }
  14348. }
  14349. /**
  14350. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  14351. *
  14352. * @param array<string, string> $vars
  14353. * @return array<string, string>
  14354. */
  14355. protected function normalizeSmsTemplateVars(array $vars): array
  14356. {
  14357. $out = [];
  14358. foreach ($vars as $k => $v) {
  14359. $out[(string)$k] = trim((string)$v);
  14360. }
  14361. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  14362. $out['contact_name'] = $out['company_name'];
  14363. }
  14364. return $out;
  14365. }
  14366. /**
  14367. * 按手机号或公司名称查 customer 表联系人姓名
  14368. */
  14369. protected function resolveCustomerContactName(string $phone, string $companyName): string
  14370. {
  14371. $phone = trim($phone);
  14372. $companyName = trim($companyName);
  14373. try {
  14374. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  14375. $row = Db::table('customer')
  14376. ->where(function ($q) use ($phone) {
  14377. $q->where('phone', $phone)->whereOr('account', $phone);
  14378. })
  14379. ->order('id', 'asc')
  14380. ->find();
  14381. if (is_array($row)) {
  14382. $nm = trim((string)($row['username'] ?? ''));
  14383. if ($nm !== '') {
  14384. return $nm;
  14385. }
  14386. }
  14387. }
  14388. if ($companyName !== '') {
  14389. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  14390. if (is_array($row)) {
  14391. return trim((string)($row['username'] ?? ''));
  14392. }
  14393. }
  14394. } catch (\Throwable $e) {
  14395. }
  14396. return '';
  14397. }
  14398. /**
  14399. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;;http(s) 链接做成可点的 &lt;a&gt;(微信 QQ 邮箱提醒纯文本 URL 常不可点)
  14400. */
  14401. protected function plainTextToHtmlEmailBody(string $text): string
  14402. {
  14403. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  14404. $parts = explode("\n", $text);
  14405. $out = [];
  14406. foreach ($parts as $line) {
  14407. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  14408. $out[] = $line;
  14409. } else {
  14410. $esc = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  14411. // 保留工序行空格,便于「单位/工作量」列对齐
  14412. $esc = str_replace(' ', '&nbsp;', $esc);
  14413. $esc = preg_replace(
  14414. '#(https?://[^\s<>"\']+)#iu',
  14415. '<a href="$1" style="color:#1565c0;text-decoration:underline;word-break:break-all;">$1</a>',
  14416. $esc
  14417. );
  14418. $out[] = $esc;
  14419. }
  14420. }
  14421. return implode("<br>\n", $out);
  14422. }
  14423. /**
  14424. * 短信场景:去掉链接类变量,避免误填 URL
  14425. *
  14426. * @param array<string, string> $vars
  14427. * @return array<string, string>
  14428. */
  14429. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  14430. {
  14431. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  14432. return $vars;
  14433. }
  14434. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  14435. $vars[$k] = '';
  14436. }
  14437. return $vars;
  14438. }
  14439. /**
  14440. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  14441. *
  14442. * @param array<string, string> $vars
  14443. */
  14444. protected function renderNotifyTemplate(string $scene, array $vars): string
  14445. {
  14446. $vars = $this->normalizeSmsTemplateVars($vars);
  14447. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  14448. $row = $this->loadNotifyTemplateRow($scene);
  14449. if ($row === null) {
  14450. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  14451. }
  14452. $tpl = trim((string)($row['content'] ?? ''));
  14453. if ($tpl === '') {
  14454. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  14455. }
  14456. foreach ($vars as $k => $v) {
  14457. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  14458. }
  14459. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  14460. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  14461. return $tpl;
  14462. }
  14463. protected function resolveProcuremenEmailSubject(string $scene): string
  14464. {
  14465. // 询价 / 采购确认结果邮箱:模版名称即邮件主题
  14466. if (in_array($scene, ['rfq_salesman_email', 'rfq_supplier_email', 'confirm_ok_email', 'confirm_fail_email', 'delivery_notify_email'], true)) {
  14467. $row = $this->loadNotifyTemplateRow($scene);
  14468. $title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
  14469. if ($title !== '') {
  14470. return $title;
  14471. }
  14472. $fallback = [
  14473. 'rfq_supplier_email' => '供应商询价通知',
  14474. 'rfq_salesman_email' => '协助采购询价通知',
  14475. 'confirm_ok_email' => '采购确认结果:已通过',
  14476. 'confirm_fail_email' => '采购确认结果:未通过',
  14477. 'delivery_notify_email' => '交货情况确认通知',
  14478. ];
  14479. return $fallback[$scene] ?? '协助采购通知';
  14480. }
  14481. $map = [
  14482. 'review_email' => '您有新的协助加工订单',
  14483. ];
  14484. $subject = trim((string)($map[$scene] ?? ''));
  14485. if ($subject === '') {
  14486. $this->error('未配置邮件主题:' . $scene);
  14487. }
  14488. return $subject;
  14489. }
  14490. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  14491. {
  14492. $map = [
  14493. 'review_email' => '协助下发-邮箱',
  14494. 'review_sms' => '协助下发-短信',
  14495. 'confirm_ok' => '采购确认-通过',
  14496. 'confirm_fail' => '采购确认-未通过',
  14497. 'confirm_ok_email' => '采购确认通过-邮箱',
  14498. 'confirm_fail_email' => '采购确认未通过-邮箱',
  14499. 'bid_open' => '开标双重验证',
  14500. 'rfq_salesman_email' => '询价通知业务员-邮箱',
  14501. 'rfq_supplier_email' => '供应商询价通知',
  14502. 'delivery_notify_email'=> '交货情况通知生产部-邮箱',
  14503. ];
  14504. $label = $map[$scene] ?? $scene;
  14505. if ($titleRequired) {
  14506. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  14507. }
  14508. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  14509. }
  14510. /**
  14511. * 是否开启协助通知演练(不发真实短信/邮件)
  14512. */
  14513. protected function isProcuremenNotifyDryRun(): bool
  14514. {
  14515. return (bool)Config::get('procuremen_notify_dry_run');
  14516. }
  14517. /**
  14518. * @param array<string, mixed> $payload
  14519. */
  14520. protected function recordNotifyDryRunPreview(array $payload): void
  14521. {
  14522. $this->notifyDryRunPreview[] = $payload;
  14523. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  14524. }
  14525. /**
  14526. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  14527. * @throws \Exception
  14528. */
  14529. protected function smsbao($phone, $content)
  14530. {
  14531. if ($this->isProcuremenNotifyDryRun()) {
  14532. $this->recordNotifyDryRunPreview([
  14533. 'scene' => 'sms_only',
  14534. 'phone' => $phone,
  14535. 'sms_content' => $content,
  14536. ]);
  14537. return;
  14538. }
  14539. $statusStr = [
  14540. '0' => '短信发送成功',
  14541. '-1' => '参数不全',
  14542. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  14543. '30' => '密码错误',
  14544. '40' => '账号不存在',
  14545. '41' => '余额不足',
  14546. '42' => '帐户已过期',
  14547. '43' => 'IP地址限制',
  14548. '50' => '内容含有敏感词',
  14549. ];
  14550. $smsapi = 'http://api.smsbao.com/';
  14551. $user = 'zhuwei123';
  14552. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  14553. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  14554. $result = @file_get_contents($sendurl);
  14555. if ($result === false) {
  14556. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  14557. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  14558. }
  14559. $result = trim((string)$result);
  14560. if ($result !== '0') {
  14561. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  14562. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  14563. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  14564. }
  14565. }
  14566. }