Procuremen.php 630 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenFormat;
  6. use app\common\library\ProcuremenGuard;
  7. use app\common\library\ProcuremenOperLog;
  8. use app\common\library\ProcuremenSchema;
  9. use app\common\library\ProcuremenStatus;
  10. use app\common\library\ProcuremenSupplierScore;
  11. use app\common\library\ProcuremenTime;
  12. use PHPMailer\PHPMailer\PHPMailer;
  13. use think\Config;
  14. use think\Cache;
  15. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  16. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  17. use PhpOffice\PhpSpreadsheet\Style\Border;
  18. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  19. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  20. use think\Db;
  21. use think\Log;
  22. class Procuremen extends Backend
  23. {
  24. /**
  25. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  26. */
  27. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,b.czlyq,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  28. /**
  29. * Procuremen模型对象
  30. * @var \app\admin\model\Procuremen
  31. */
  32. protected $model = null;
  33. /**
  34. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  35. */
  36. protected $notifyDryRunPreview = [];
  37. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  38. protected $procuremenRedisCache = null;
  39. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  40. protected $pickHiddenScydgySetCache = null;
  41. /** 邮件发送日志表结构已就绪缓存键 */
  42. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v2';
  43. /**
  44. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  45. * @var array
  46. */
  47. protected $noNeedRight = [
  48. 'pickreview', 'review', 'reviewcompanies',
  49. // 方法内用 hasProcuremenPerm 校验(兼容 auditsubmit / auditissue)
  50. 'auditmanualpick',
  51. // 与 rfqlist 同权,方法内校验
  52. 'rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqissuesuppliers', 'rfqissue', 'rfqissuesendmail', 'rfqquotes',
  53. 'rfqappendsuppliers', 'rfqsupplieroptions', 'rfqsalesmanoptions', 'rfqappendsalesmen',
  54. 'deliverynotifymen', 'deliverynotify',
  55. ];
  56. public function _initialize()
  57. {
  58. parent::_initialize();
  59. $this->model = new \app\admin\model\Procuremen;
  60. $this->maybeMigrateLegacyWflowStatusText();
  61. $this->assignProcuremenAuthConfig();
  62. try {
  63. ProcuremenSchema::ensureAll();
  64. } catch (\Throwable $e) {
  65. }
  66. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  67. $this->ensurePurchaseEmailSendLogTableOnce();
  68. }
  69. }
  70. /**
  71. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  72. */
  73. protected function maybeMigrateLegacyWflowStatusText(): void
  74. {
  75. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  76. if (is_file($flagFile)) {
  77. return;
  78. }
  79. $map = [
  80. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  81. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  82. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  83. '3' => ProcuremenStatus::WFLOW_APPROVED,
  84. '4' => ProcuremenStatus::WFLOW_REJECTED,
  85. ];
  86. try {
  87. foreach ($map as $num => $text) {
  88. Db::table('purchase_order')
  89. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  90. ->update(['wflow_status' => $text]);
  91. }
  92. @file_put_contents($flagFile, date('c'));
  93. } catch (\Throwable $e) {
  94. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  95. }
  96. }
  97. /**
  98. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  99. *
  100. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  101. */
  102. protected function hasProcuremenPerm(array $actions): bool
  103. {
  104. foreach ($actions as $action) {
  105. $action = strtolower(trim((string)$action));
  106. if ($action === '') {
  107. continue;
  108. }
  109. if (strpos($action, 'procuremen/') !== 0) {
  110. $action = 'procuremen/' . $action;
  111. }
  112. if ($this->auth->check($action)) {
  113. return true;
  114. }
  115. }
  116. $suffixes = [];
  117. foreach ($actions as $action) {
  118. $action = strtolower(trim((string)$action));
  119. $action = preg_replace('#^procuremen/#', '', $action);
  120. if ($action !== '') {
  121. $suffixes[$action] = true;
  122. }
  123. }
  124. if ($suffixes === []) {
  125. return false;
  126. }
  127. try {
  128. foreach ($this->auth->getRuleList() as $rule) {
  129. $rule = strtolower((string)$rule);
  130. if (strpos($rule, 'procuremen/') !== 0) {
  131. continue;
  132. }
  133. foreach (array_keys($suffixes) as $suffix) {
  134. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  135. return true;
  136. }
  137. }
  138. }
  139. } catch (\Throwable $e) {
  140. }
  141. return false;
  142. }
  143. /**
  144. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  145. *
  146. * @param string[] $actions
  147. */
  148. protected function hasProcuremenPermStrict(array $actions): bool
  149. {
  150. foreach ($actions as $action) {
  151. $action = strtolower(trim((string)$action));
  152. if ($action === '') {
  153. continue;
  154. }
  155. if (strpos($action, 'procuremen/') !== 0) {
  156. $action = 'procuremen/' . $action;
  157. }
  158. if ($this->auth->check($action)) {
  159. return true;
  160. }
  161. }
  162. return false;
  163. }
  164. /**
  165. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  166. *
  167. * @param string[] $titles
  168. */
  169. protected function authHasAssignedRuleTitle(array $titles): bool
  170. {
  171. $titles = array_values(array_filter(array_map('trim', $titles)));
  172. if ($titles === []) {
  173. return false;
  174. }
  175. try {
  176. $ids = $this->auth->getRuleIds();
  177. if (in_array('*', $ids, true)) {
  178. return true;
  179. }
  180. if ($ids === []) {
  181. return false;
  182. }
  183. $rows = Db::name('auth_rule')
  184. ->where('status', 'normal')
  185. ->whereIn('id', $ids)
  186. ->column('title');
  187. foreach ($rows as $title) {
  188. $t = trim((string)$title);
  189. if ($t !== '' && in_array($t, $titles, true)) {
  190. return true;
  191. }
  192. }
  193. } catch (\Throwable $e) {
  194. }
  195. return false;
  196. }
  197. protected function procuremenCanPickDelete(): bool
  198. {
  199. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  200. return true;
  201. }
  202. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  203. }
  204. protected function procuremenCanComplete(): bool
  205. {
  206. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  207. return true;
  208. }
  209. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  210. }
  211. protected function procuremenCanDispatch(): bool
  212. {
  213. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  214. }
  215. /**
  216. * 前端按钮显隐(Config.procuremenAuth)
  217. */
  218. protected function assignProcuremenAuthConfig(): void
  219. {
  220. $authMap = [
  221. 'pickreview' => $this->procuremenCanDispatch(),
  222. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  223. 'pickdelete' => $this->procuremenCanPickDelete(),
  224. 'completedirectly' => $this->procuremenCanComplete(),
  225. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  226. 'auditissue' => $this->hasProcuremenPerm(['auditissue', 'audit']),
  227. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  228. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  229. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  230. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  231. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail', 'confirm']),
  232. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  233. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  234. 'details' => $this->hasProcuremenPerm(['details', 'confirm', 'audit', 'index', 'pick']),
  235. 'confirm' => $this->hasProcuremenPerm(['confirm']),
  236. 'audit' => $this->hasProcuremenPerm(['audit']),
  237. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  238. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  239. 'export_month_quote' => $this->hasProcuremenPerm(['export_month_quote', 'exportMonthQuote', 'export_month_outward', 'exportMonthOutward']),
  240. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  241. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  242. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  243. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  244. 'auditmanualpick' => $this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue']),
  245. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  246. 'add' => $this->hasProcuremenPerm(['add']),
  247. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  248. // 查询询价三个操作按钮:各自独立,不再因有 rfqlist 就全部放开
  249. 'rfqissue' => $this->hasProcuremenPerm(['rfqissue']),
  250. 'rfqquotes' => $this->hasProcuremenPerm(['rfqquotes']),
  251. 'rfqnotifysalesman' => $this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen']),
  252. 'rfqnotifysalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman']),
  253. // 询价附属接口:有「询价」按钮权限即可(无需再单独勾选)
  254. 'rfqissuesuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers']),
  255. 'rfqissuesendmail' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail']),
  256. 'rfqappendsuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers']),
  257. 'rfqsupplieroptions' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions']),
  258. 'rfqsalesmanoptions' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen']),
  259. 'rfqappendsalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen']),
  260. 'deliverynotify' => $this->hasProcuremenPerm(['deliverynotify', 'deliverynotifymen', 'outward_detail', 'outwarddetail', 'purchaseconfirmpick', 'details']),
  261. 'deliverynotifymen' => $this->hasProcuremenPerm(['deliverynotifymen', 'deliverynotify', 'outward_detail', 'outwarddetail', 'purchaseconfirmpick', 'details']),
  262. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  263. ];
  264. $this->assignconfig('procuremenAuth', $authMap);
  265. }
  266. /**
  267. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  268. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  269. * 列表 Tab 写入 hash(mproc_tab),避免邮件客户端拆坏多 query 参数;浏览器端再补全 tab=
  270. *
  271. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  272. * @param string $listTab rfq|draft|submitted|done|rfq_submitted,空则仅靠服务端按状态推断
  273. */
  274. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId, $listTab = '')
  275. {
  276. static $mprocCfgLoaded = false;
  277. if (!$mprocCfgLoaded) {
  278. $mprocCfgLoaded = true;
  279. if (is_file(APP_PATH . 'extra/mproc.php')) {
  280. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  281. }
  282. }
  283. $eid = (int)$purchaseOrderDetailId;
  284. $base = $this->resolveMprocMobilePublicBaseUrl();
  285. if ($base === '') {
  286. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  287. }
  288. $path = trim((string)Config::get('mproc.mobile_index_path'));
  289. if ($path === '') {
  290. $path = '/index.php/index/index/index';
  291. } else {
  292. $path = '/' . ltrim($path, '/');
  293. }
  294. $tab = trim((string)$listTab);
  295. if (!in_array($tab, ['rfq', 'rfq_submitted', 'draft', 'submitted', 'done'], true)) {
  296. $tab = '';
  297. }
  298. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份 Tab
  299. if ($eid > 0) {
  300. $hash = 'mproc_fe=' . $eid;
  301. if ($tab !== '') {
  302. $hash .= '&mproc_tab=' . $tab;
  303. }
  304. return $base . $path . '?focus_eid=' . $eid . '#' . $hash;
  305. }
  306. return $base . $path . '?main_tab=orders' . ($tab !== '' ? ('&tab=' . $tab) : '');
  307. }
  308. /**
  309. * 业务员手机端「订单询价」直达链接(默认待询价)
  310. *
  311. * @param int $scydgyId 手工询价 scydgy_id(负数)
  312. * @param string $status pending|quoted
  313. */
  314. protected function buildMprocMobileRfqAddUrl($scydgyId = 0, $status = 'pending')
  315. {
  316. static $mprocCfgLoaded = false;
  317. if (!$mprocCfgLoaded) {
  318. $mprocCfgLoaded = true;
  319. if (is_file(APP_PATH . 'extra/mproc.php')) {
  320. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  321. }
  322. }
  323. $base = $this->resolveMprocMobilePublicBaseUrl();
  324. if ($base === '') {
  325. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  326. }
  327. $indexPath = trim((string)Config::get('mproc.mobile_index_path'));
  328. if ($indexPath === '') {
  329. $indexPath = '/index.php/index/index/index';
  330. } else {
  331. $indexPath = '/' . ltrim($indexPath, '/');
  332. }
  333. $path = preg_replace('#/index$#', '/rfqadd', rtrim($indexPath, '/'));
  334. if ($path === null || $path === '' || substr($path, -6) === '/index') {
  335. $path = '/index.php/index/index/rfqadd';
  336. }
  337. $status = trim((string)$status) === 'quoted' ? 'quoted' : 'pending';
  338. $sid = (int)$scydgyId;
  339. $q = 'status=' . $status;
  340. $hash = '';
  341. if ($sid < 0) {
  342. $q .= '&focus_sid=' . $sid;
  343. $hash = '#mproc_fs=' . $sid;
  344. }
  345. return $base . $path . '?' . $q . $hash;
  346. }
  347. /**
  348. * 邮件/短信外链:须为带点的公网域名
  349. */
  350. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  351. {
  352. $u = trim((string)$baseUrl);
  353. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  354. return false;
  355. }
  356. $host = parse_url($u, PHP_URL_HOST);
  357. if (!is_string($host) || $host === '') {
  358. return false;
  359. }
  360. if (strcasecmp($host, 'localhost') === 0) {
  361. return false;
  362. }
  363. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  364. return false;
  365. }
  366. if (strpos($host, '.') === false) {
  367. return false;
  368. }
  369. return true;
  370. }
  371. /**
  372. * 解析用于协助邮件/短信的手机端站点根
  373. */
  374. protected function resolveMprocMobilePublicBaseUrl()
  375. {
  376. $candidates = [];
  377. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  378. $candidates[] = trim((string)Config::get('site.indexurl'));
  379. $cdn = trim((string)Config::get('site.cdnurl'));
  380. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  381. $candidates[] = rtrim($cdn, '/');
  382. }
  383. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  384. $candidates[] = $reqBase;
  385. foreach ($candidates as $c) {
  386. if ($c === '') {
  387. continue;
  388. }
  389. $c = rtrim($c, '/');
  390. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  391. return $c;
  392. }
  393. }
  394. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  395. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  396. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  397. return $reqBase;
  398. }
  399. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  400. return '';
  401. }
  402. /**
  403. * 获取 Redis 中 procuremen_redis
  404. */
  405. protected function ProcuremenRedis(): array
  406. {
  407. if ($this->procuremenRedisCache !== null) {
  408. return $this->procuremenRedisCache;
  409. }
  410. try {
  411. $redis = redis();
  412. $raw = $redis->get('procuremen_redis');
  413. if ($raw === false || $raw === '') {
  414. $this->procuremenRedisCache = [];
  415. return $this->procuremenRedisCache;
  416. }
  417. $decoded = json_decode($raw, true);
  418. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  419. $this->procuremenRedisCache = [];
  420. return $this->procuremenRedisCache;
  421. }
  422. $this->procuremenRedisCache = $decoded['data'];
  423. // 整包已解码时顺带补齐侧栏小键,避免下次首屏再扫库
  424. if ($this->loadProcuremenSidebarYmList() === []) {
  425. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($this->procuremenRedisCache));
  426. }
  427. return $this->procuremenRedisCache;
  428. } catch (\Throwable $e) {
  429. $this->procuremenRedisCache = [];
  430. return $this->procuremenRedisCache;
  431. }
  432. }
  433. /**
  434. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  435. *
  436. * @return array<int, array<string, mixed>>
  437. */
  438. protected function procuremenFetchErpPoolFromDb(): array
  439. {
  440. try {
  441. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  442. $endTime = date('Y-m-d 23:59:59');
  443. $list = Db::table('scydgy')
  444. ->alias('a')
  445. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  446. ->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')
  447. ->where([
  448. 'a.bwjg' => 1,
  449. 'a.iEndBz' => 0,
  450. 'a.iType' => 0,
  451. 'a.iStatus' => 10,
  452. ])
  453. ->where('a.dStamp', '>=', $startTime)
  454. ->where('a.dStamp', '<=', $endTime)
  455. ->order('a.dStamp', 'desc')
  456. ->select();
  457. if (!is_array($list)) {
  458. return [];
  459. }
  460. try {
  461. $redis = redis();
  462. $payload = [
  463. 'code' => 200,
  464. 'msg' => 'success',
  465. 'data' => $list,
  466. ];
  467. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  468. $this->procuremenRedisCache = $list;
  469. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($list));
  470. $this->clearPickMonthPoolCaches();
  471. $this->warmPickMonthPoolCachesFromPool($list);
  472. } catch (\Throwable $e) {
  473. }
  474. return $list;
  475. } catch (\Throwable $e) {
  476. Log::write('拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  477. return [];
  478. }
  479. }
  480. /**
  481. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  482. *
  483. * @return array<int, array<string, mixed>>
  484. */
  485. protected function procuremenEnsureRedisPool(): array
  486. {
  487. $pool = $this->ProcuremenRedis();
  488. if (is_array($pool) && $pool !== []) {
  489. return $pool;
  490. }
  491. static $warmed = false;
  492. if ($warmed) {
  493. return is_array($pool) ? $pool : [];
  494. }
  495. $warmed = true;
  496. return $this->procuremenFetchErpPoolFromDb();
  497. }
  498. /**
  499. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  500. *
  501. * @param array<string, mixed> $row
  502. */
  503. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  504. {
  505. $t = $this->procuremenRowListSortTime($row, $primary);
  506. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  507. return null;
  508. }
  509. $mo = (int)$m[2];
  510. if ($mo < 1 || $mo > 12) {
  511. return null;
  512. }
  513. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  514. }
  515. /**
  516. * @param array<int, array{year:string, months:array}> $sidebar
  517. * @return array<int, array{year:string, months:array}>
  518. */
  519. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  520. {
  521. $ym = trim($ym);
  522. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  523. return $sidebar;
  524. }
  525. foreach ($sidebar as $block) {
  526. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  527. continue;
  528. }
  529. foreach ($block['months'] as $item) {
  530. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  531. return $sidebar;
  532. }
  533. }
  534. }
  535. $y = substr($ym, 0, 4);
  536. $mo = (int)substr($ym, 5, 2);
  537. $sidebar[] = [
  538. 'year' => $y,
  539. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  540. ];
  541. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  542. }
  543. /**
  544. * @param array<int, array{year:string, months:array}> $sidebar
  545. * @return string[]
  546. */
  547. protected function flattenProcuremenSidebarYms(array $sidebar): array
  548. {
  549. $yms = [];
  550. foreach ($sidebar as $block) {
  551. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  552. continue;
  553. }
  554. foreach ($block['months'] as $item) {
  555. if (!is_array($item)) {
  556. continue;
  557. }
  558. $ym = trim((string)($item['ym'] ?? ''));
  559. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  560. $yms[$ym] = true;
  561. }
  562. }
  563. }
  564. return array_keys($yms);
  565. }
  566. /**
  567. * 左侧菜单(协助初选)
  568. * 优先 Redis 月份小键;为空时用轻量 DISTINCT 查库补齐(避免只显示空当月、漏掉有数据的月份)。
  569. */
  570. protected function GetIndexYearMonths()
  571. {
  572. $ymList = $this->ensureProcuremenPickSidebarYmList();
  573. if ($ymList === []) {
  574. $def = date('Y-m');
  575. $ymList = [preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m')];
  576. }
  577. return $this->buildYearMonthSidebar($ymList);
  578. }
  579. /**
  580. * 初选侧栏月份:以轻量 DISTINCT 查库为准(有数据才显示),并写回 Redis 小键。
  581. *
  582. * @return string[]
  583. */
  584. protected function ensureProcuremenPickSidebarYmList(bool $forceRefresh = false): array
  585. {
  586. static $memo = null;
  587. if (!$forceRefresh && is_array($memo)) {
  588. return $memo;
  589. }
  590. $fromDb = $this->queryProcuremenPickSidebarYmListLight();
  591. if ($fromDb !== []) {
  592. $this->saveProcuremenSidebarYmList($fromDb);
  593. $memo = $fromDb;
  594. return $memo;
  595. }
  596. // 库侧暂无初选数据时,再回退 Redis / 当月,避免侧栏空白
  597. $cached = $this->loadProcuremenSidebarYmList();
  598. if ($cached !== []) {
  599. $memo = $cached;
  600. return $memo;
  601. }
  602. $memo = [date('Y-m')];
  603. return $memo;
  604. }
  605. /**
  606. * @return string[] 形如 2026-07
  607. */
  608. protected function loadProcuremenSidebarYmList(): array
  609. {
  610. try {
  611. $raw = redis()->get('procuremen_redis_yms');
  612. if ($raw === false || $raw === null || $raw === '') {
  613. return [];
  614. }
  615. $decoded = json_decode((string)$raw, true);
  616. if (!is_array($decoded)) {
  617. return [];
  618. }
  619. $out = [];
  620. foreach ($decoded as $ym) {
  621. $ym = trim((string)$ym);
  622. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  623. $out[$ym] = true;
  624. }
  625. }
  626. return array_keys($out);
  627. } catch (\Throwable $e) {
  628. return [];
  629. }
  630. }
  631. /**
  632. * @param string[] $ymList
  633. */
  634. protected function saveProcuremenSidebarYmList(array $ymList): void
  635. {
  636. $out = [];
  637. foreach ($ymList as $ym) {
  638. $ym = trim((string)$ym);
  639. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  640. $out[$ym] = true;
  641. }
  642. }
  643. if ($out === []) {
  644. return;
  645. }
  646. try {
  647. redis()->set('procuremen_redis_yms', json_encode(array_keys($out), JSON_UNESCAPED_UNICODE));
  648. } catch (\Throwable $e) {
  649. }
  650. }
  651. /**
  652. * @param array<int, array<string, mixed>> $pool
  653. * @return string[]
  654. */
  655. protected function extractYearMonthsFromPoolRows(array $pool): array
  656. {
  657. $ymSet = [];
  658. foreach ($pool as $r) {
  659. if (!is_array($r)) {
  660. continue;
  661. }
  662. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  663. continue;
  664. }
  665. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  666. if ($ym !== null) {
  667. $ymSet[$ym] = true;
  668. }
  669. }
  670. return array_keys($ymSet);
  671. }
  672. /**
  673. * 轻量查询初选侧栏月份(只取 DISTINCT 年月,不拉整包工序)
  674. *
  675. * @return string[]
  676. */
  677. protected function queryProcuremenPickSidebarYmListLight(): array
  678. {
  679. try {
  680. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  681. $endTime = date('Y-m-d 23:59:59');
  682. $sql = 'SELECT DISTINCT DATE_FORMAT('
  683. . 'IF(b.dputrecord IS NOT NULL AND TRIM(CAST(b.dputrecord AS CHAR(32))) <> \'\''
  684. . ' AND TRIM(CAST(b.dputrecord AS CHAR(32))) NOT LIKE \'0000-00-00%\','
  685. . ' b.dputrecord, a.dStamp), \'%Y-%m\') AS ym'
  686. . ' FROM scydgy a'
  687. . ' INNER JOIN mcyd b ON b.ICYDID = a.ICYDID AND b.iStatus >= 10'
  688. . ' WHERE a.bwjg = 1 AND a.iEndBz = 0 AND a.iType = 0 AND a.iStatus = 10'
  689. . ' AND a.dStamp >= ? AND a.dStamp <= ?';
  690. $rows = Db::query($sql, [$startTime, $endTime]);
  691. if (!is_array($rows)) {
  692. return [];
  693. }
  694. $out = [];
  695. foreach ($rows as $r) {
  696. $ym = trim((string)($r['ym'] ?? ''));
  697. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  698. $out[$ym] = true;
  699. }
  700. }
  701. return array_keys($out);
  702. } catch (\Throwable $e) {
  703. Log::write('初选侧栏月份查询失败:' . $e->getMessage(), 'warning');
  704. return [];
  705. }
  706. }
  707. /**
  708. * @return string[] 含当月在内的近 N 个自然月
  709. */
  710. protected function buildRecentCalendarYmList(int $months = 12): array
  711. {
  712. $months = max(1, min(24, $months));
  713. $out = [];
  714. $base = strtotime(date('Y-m-01'));
  715. for ($i = 0; $i < $months; $i++) {
  716. $out[] = date('Y-m', strtotime('-' . $i . ' month', $base));
  717. }
  718. return $out;
  719. }
  720. /**
  721. * 初选按月工序池:优先月缓存;未命中则直接按月查 ERP。
  722. * 禁止为列表去解近一年整包 Redis(解包/连接异常会造成长时间转圈)。
  723. *
  724. * @return array<int, array<string, mixed>>
  725. */
  726. protected function loadPickPoolForYm(string $ym): array
  727. {
  728. $ym = trim($ym);
  729. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  730. return [];
  731. }
  732. $hit = $this->readPickMonthPoolCache($ym);
  733. if ($hit !== null) {
  734. return $hit;
  735. }
  736. return $this->queryPickPoolForYmFromDb($ym);
  737. }
  738. /**
  739. * @return array<int, array<string, mixed>>|null null=无有效缓存(含旧版空数组误缓存)
  740. */
  741. protected function readPickMonthPoolCache(string $ym): ?array
  742. {
  743. try {
  744. $raw = redis()->get('procuremen_pick_pool:' . $ym);
  745. if ($raw === false || $raw === null || $raw === '') {
  746. return null;
  747. }
  748. $decoded = json_decode((string)$raw, true);
  749. if (!is_array($decoded)) {
  750. return null;
  751. }
  752. // 新格式:{ok:1, rows:[...]},空月也算有效(已从整包确认)
  753. if (isset($decoded['ok']) && (int)$decoded['ok'] === 1 && isset($decoded['rows']) && is_array($decoded['rows'])) {
  754. return $decoded['rows'];
  755. }
  756. // 旧格式:仅非空行列表可命中;[] 多半是错误 SQL 写入,视为未命中
  757. if ($decoded === []) {
  758. try {
  759. redis()->del('procuremen_pick_pool:' . $ym);
  760. } catch (\Throwable $e) {
  761. }
  762. return null;
  763. }
  764. if (isset($decoded[0]) && is_array($decoded[0])) {
  765. return $decoded;
  766. }
  767. return null;
  768. } catch (\Throwable $e) {
  769. return null;
  770. }
  771. }
  772. /**
  773. * @param array<int, array<string, mixed>> $rows
  774. */
  775. protected function writePickMonthPoolCache(string $ym, array $rows): void
  776. {
  777. try {
  778. redis()->setex(
  779. 'procuremen_pick_pool:' . $ym,
  780. 600,
  781. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  782. );
  783. } catch (\Throwable $e) {
  784. }
  785. }
  786. /**
  787. * @param array<int, array<string, mixed>> $pool
  788. * @return array<int, array<string, mixed>>
  789. */
  790. protected function filterPoolRowsByYm(array $pool, string $ym): array
  791. {
  792. $out = [];
  793. foreach ($pool as $r) {
  794. if (!is_array($r)) {
  795. continue;
  796. }
  797. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  798. continue;
  799. }
  800. if ($this->procuremenRowYearMonth($r, 'dputrecord') === $ym) {
  801. $out[] = $r;
  802. }
  803. }
  804. return $out;
  805. }
  806. /**
  807. * 按 dStamp 取当月附近数据,再用列表规则(dputrecord 优先)精确到 ym
  808. *
  809. * @return array<int, array<string, mixed>>
  810. */
  811. protected function queryPickPoolForYmFromDb(string $ym): array
  812. {
  813. $monthStart = $ym . '-01 00:00:00';
  814. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  815. // 略放大窗口,避免 dStamp 与 dputrecord 跨月导致漏数;最终仍按 ym 精确过滤
  816. $queryStart = date('Y-m-d 00:00:00', strtotime($monthStart . ' -7 days'));
  817. $queryEnd = date('Y-m-d 23:59:59', strtotime($monthEnd . ' +7 days'));
  818. try {
  819. $list = Db::table('scydgy')
  820. ->alias('a')
  821. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  822. ->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')
  823. ->where([
  824. 'a.bwjg' => 1,
  825. 'a.iEndBz' => 0,
  826. 'a.iType' => 0,
  827. 'a.iStatus' => 10,
  828. ])
  829. ->where('a.dStamp', '>=', $queryStart)
  830. ->where('a.dStamp', '<=', $queryEnd)
  831. ->order('a.dStamp', 'desc')
  832. ->select();
  833. } catch (\Throwable $e) {
  834. Log::write('初选按月取数失败 ym=' . $ym . ':' . $e->getMessage(), 'error');
  835. return [];
  836. }
  837. if (!is_array($list)) {
  838. $list = [];
  839. }
  840. $out = $this->filterPoolRowsByYm($list, $ym);
  841. // 新格式缓存(含空月),避免重复打库;读侧只认 ok=1
  842. $this->writePickMonthPoolCache($ym, $out);
  843. try {
  844. $yms = $this->loadProcuremenSidebarYmList();
  845. if ($out !== [] && ($yms === [] || !in_array($ym, $yms, true))) {
  846. $yms[] = $ym;
  847. $this->saveProcuremenSidebarYmList($yms);
  848. }
  849. } catch (\Throwable $e) {
  850. }
  851. return $out;
  852. }
  853. /**
  854. * 整包写入后拆成按月小缓存,供初选列表秒开
  855. *
  856. * @param array<int, array<string, mixed>> $pool
  857. */
  858. protected function warmPickMonthPoolCachesFromPool(array $pool): void
  859. {
  860. if ($pool === []) {
  861. return;
  862. }
  863. $byYm = [];
  864. foreach ($pool as $r) {
  865. if (!is_array($r)) {
  866. continue;
  867. }
  868. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  869. continue;
  870. }
  871. $rowYm = $this->procuremenRowYearMonth($r, 'dputrecord');
  872. if ($rowYm === null) {
  873. continue;
  874. }
  875. $byYm[$rowYm][] = $r;
  876. }
  877. if ($byYm === []) {
  878. return;
  879. }
  880. try {
  881. $redis = redis();
  882. foreach ($byYm as $rowYm => $rows) {
  883. $redis->setex(
  884. 'procuremen_pick_pool:' . $rowYm,
  885. 600,
  886. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  887. );
  888. }
  889. try {
  890. $redis->del('procuremen_pick_hidden_scydgy_v1');
  891. } catch (\Throwable $e) {
  892. }
  893. } catch (\Throwable $e) {
  894. }
  895. }
  896. /**
  897. * 刷新整包后清理近月缓存,避免脏读
  898. */
  899. protected function clearPickMonthPoolCaches(int $months = 24): void
  900. {
  901. try {
  902. $redis = redis();
  903. foreach ($this->buildRecentCalendarYmList($months) as $ym) {
  904. try {
  905. $redis->del('procuremen_pick_pool:' . $ym);
  906. } catch (\Throwable $e) {
  907. }
  908. }
  909. } catch (\Throwable $e) {
  910. }
  911. $this->invalidatePickHiddenScydgyCache();
  912. }
  913. /**
  914. * 下发/完结后清隐藏集缓存,避免初选列表最多 90 秒仍显示已下发行
  915. */
  916. protected function invalidatePickHiddenScydgyCache(): void
  917. {
  918. $this->pickHiddenScydgySetCache = null;
  919. try {
  920. redis()->del('procuremen_pick_hidden_scydgy_v1');
  921. } catch (\Throwable $e) {
  922. }
  923. }
  924. /** 列表/首屏读完鉴权后尽早释放 session,避免多 iframe 串行卡死 */
  925. protected function procuremenReleaseSessionLock(): void
  926. {
  927. if (session_status() === PHP_SESSION_ACTIVE) {
  928. @session_write_close();
  929. }
  930. }
  931. /**
  932. * @param string[] $ymList 形如 2026-06
  933. * @return array<int, array{year:string, months:array}>
  934. */
  935. protected function buildYearMonthSidebar(array $ymList): array
  936. {
  937. rsort($ymList, SORT_STRING);
  938. $byYear = [];
  939. foreach ($ymList as $ym) {
  940. $y = substr($ym, 0, 4);
  941. $mo = (int)substr($ym, 5, 2);
  942. if (!isset($byYear[$y])) {
  943. $byYear[$y] = [];
  944. }
  945. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  946. }
  947. krsort($byYear, SORT_NUMERIC);
  948. foreach ($byYear as $y => $items) {
  949. usort($byYear[$y], function ($a, $b) {
  950. return strcmp($b['ym'], $a['ym']);
  951. });
  952. }
  953. $sidebar = [];
  954. foreach ($byYear as $y => $months) {
  955. $sidebar[] = ['year' => $y, 'months' => $months];
  956. }
  957. return $sidebar;
  958. }
  959. /**
  960. * 已下发/审批/确认列表左侧月份:SQL DISTINCT,禁止把该阶段全部行拉进 PHP
  961. * 注意:MySQL8 严格模式下勿对 datetime 用 <> '',否则报 Incorrect DATETIME value 被吞掉后侧栏只剩默认月
  962. */
  963. protected function GetIssuedOrderYearMonths(string $stage): array
  964. {
  965. if ($stage !== 'audit' && $stage !== 'confirm') {
  966. return $this->GetIndexYearMonths();
  967. }
  968. $ymSet = [];
  969. $addYm = function ($raw) use (&$ymSet): void {
  970. $ym = trim((string)$raw);
  971. if (preg_match('/^([12]\d{3})-(\d{2})/', $ym, $m)) {
  972. $ymSet[$m[1] . '-' . $m[2]] = true;
  973. }
  974. };
  975. try {
  976. $query = Db::table('purchase_order')->field('pick_time,createtime,dStamp');
  977. $this->applyPurchaseOrderNotDeletedWhere($query);
  978. $this->applyPurchaseOrderConfirmAuditListWhere($query);
  979. $rows = $query->select();
  980. if (is_array($rows)) {
  981. foreach ($rows as $r) {
  982. if (!is_array($r)) {
  983. continue;
  984. }
  985. $pick = trim((string)($r['pick_time'] ?? ''));
  986. if ($pick !== '' && stripos($pick, '0000-00-00') !== 0) {
  987. $addYm($pick);
  988. continue;
  989. }
  990. $ct = $r['createtime'] ?? null;
  991. if (is_numeric($ct) && (int)$ct > 946684800) {
  992. $addYm(date('Y-m-d', (int)$ct));
  993. continue;
  994. }
  995. $ctStr = trim((string)$ct);
  996. if ($ctStr !== '' && stripos($ctStr, '0000-00-00') !== 0) {
  997. $addYm($ctStr);
  998. continue;
  999. }
  1000. $ds = trim((string)($r['dStamp'] ?? ''));
  1001. if ($ds !== '' && stripos($ds, '0000-00-00') !== 0) {
  1002. $addYm($ds);
  1003. }
  1004. }
  1005. }
  1006. } catch (\Throwable $e) {
  1007. Log::write('GetIssuedOrderYearMonths: ' . $e->getMessage(), 'error');
  1008. $ymSet = [];
  1009. }
  1010. $ymList = array_keys($ymSet);
  1011. if ($ymList === []) {
  1012. $def = $this->resolveProcuremenDefaultYm($stage);
  1013. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  1014. }
  1015. return $this->buildYearMonthSidebar($ymList);
  1016. }
  1017. /**
  1018. * 列表默认月份:已下发类取最近有数据的月份;初选也取最近有数据月份(避免跨月后落到空当月)
  1019. */
  1020. protected function resolveProcuremenDefaultYm(string $stage): string
  1021. {
  1022. if ($stage === 'pick') {
  1023. $yms = $this->ensureProcuremenPickSidebarYmList();
  1024. if ($yms !== []) {
  1025. rsort($yms, SORT_STRING);
  1026. return $yms[0];
  1027. }
  1028. return date('Y-m');
  1029. }
  1030. try {
  1031. $query = Db::table('purchase_order');
  1032. $this->applyPurchaseOrderNotDeletedWhere($query);
  1033. if ($stage === 'audit') {
  1034. $query->whereIn('wflow_status', ProcuremenStatus::wflowConfirmAndAuditListValues());
  1035. } elseif ($stage === 'confirm') {
  1036. $this->applyPurchaseOrderConfirmStageWhere($query);
  1037. } else {
  1038. return date('Y-m');
  1039. }
  1040. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  1041. if ($latest === null || $latest === '') {
  1042. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  1043. }
  1044. $t = $this->formatProcuremenDetailTime($latest);
  1045. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  1046. return $m[1] . '-' . $m[2];
  1047. }
  1048. } catch (\Throwable $e) {
  1049. }
  1050. return date('Y-m');
  1051. }
  1052. protected function applyPurchaseOrderNotDeletedWhere($query): void
  1053. {
  1054. $query->whereRaw("(mod_rq IS NULL OR mod_rq = '' OR mod_rq LIKE '0000-00-00%')");
  1055. }
  1056. /**
  1057. * 确认/审批列表共用:待确认 + 待审核(待审批) + 已审核
  1058. */
  1059. protected function applyPurchaseOrderConfirmAuditListWhere($query): void
  1060. {
  1061. $vals = ProcuremenStatus::wflowConfirmAndAuditListValues();
  1062. $quoted = [];
  1063. foreach ($vals as $v) {
  1064. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  1065. }
  1066. if ($quoted === []) {
  1067. $query->whereRaw('1 = 0');
  1068. return;
  1069. }
  1070. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  1071. }
  1072. /**
  1073. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  1074. * 完结判断必须走 CAST 文案比较:status 为 0/'0' 时,NOT IN ('已完结','1') 会被 MySQL 把「已完结」转成 0 而整表滤空
  1075. */
  1076. protected function applyPurchaseOrderConfirmStageWhere($query): void
  1077. {
  1078. // 与确认页共用数据范围(待确认/待审核/已审核)
  1079. $this->applyPurchaseOrderConfirmAuditListWhere($query);
  1080. }
  1081. /**
  1082. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  1083. *
  1084. * @param array<string, mixed> $row
  1085. * @return array<string, mixed>
  1086. */
  1087. protected function normalizePurchaseOrderListTimeRow(array $row): array
  1088. {
  1089. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  1090. $pick = trim((string)($row['pick_time'] ?? ''));
  1091. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  1092. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  1093. $t = trim((string)($row[$key] ?? ''));
  1094. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1095. $row['pick_time'] = $t;
  1096. break;
  1097. }
  1098. }
  1099. }
  1100. return $row;
  1101. }
  1102. /**
  1103. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  1104. */
  1105. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  1106. {
  1107. if (!in_array($stage, ['audit', 'confirm'], true)) {
  1108. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1109. }
  1110. if ($pool === []) {
  1111. $def = $this->resolveProcuremenDefaultYm($stage);
  1112. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  1113. }
  1114. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  1115. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1116. return false;
  1117. }
  1118. $monthStart = $ym . '-01 00:00:00';
  1119. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1120. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  1121. return $probe !== [];
  1122. };
  1123. if ($tryYm($requestedYm)) {
  1124. return $requestedYm;
  1125. }
  1126. $fallback = $this->resolveProcuremenDefaultYm($stage);
  1127. if ($tryYm($fallback)) {
  1128. return $fallback;
  1129. }
  1130. $bestYm = '';
  1131. $bestTime = '';
  1132. foreach ($pool as $row) {
  1133. if (!is_array($row)) {
  1134. continue;
  1135. }
  1136. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  1137. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  1138. continue;
  1139. }
  1140. $ymRow = $m[1];
  1141. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  1142. $bestTime = $t;
  1143. $bestYm = $ymRow;
  1144. }
  1145. }
  1146. if ($bestYm !== '') {
  1147. return $bestYm;
  1148. }
  1149. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1150. }
  1151. protected function isPurchaseOrderDetailVoid(array $row): bool
  1152. {
  1153. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  1154. return true;
  1155. }
  1156. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  1157. }
  1158. /**
  1159. * 仅当前有效下发明细(排除废弃归档)
  1160. */
  1161. protected function applyActivePurchaseOrderDetailWhere($query): void
  1162. {
  1163. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1164. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  1165. }
  1166. /**
  1167. * @param array<string, mixed> $detailRow
  1168. */
  1169. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  1170. {
  1171. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  1172. return false;
  1173. }
  1174. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  1175. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  1176. }
  1177. /**
  1178. * 废弃退回初选:下发明细标记归档,不物理删除
  1179. *
  1180. * @param array<int, int|string> $scydgyIds
  1181. */
  1182. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  1183. {
  1184. $ids = [];
  1185. foreach ($scydgyIds as $sid) {
  1186. $n = (int)$sid;
  1187. if ($this->isValidScydgyRowId($n) || $n < 0) {
  1188. $ids[$n] = true;
  1189. }
  1190. }
  1191. if ($ids === []) {
  1192. return;
  1193. }
  1194. $void = ProcuremenStatus::POD_VOID;
  1195. Db::table('purchase_order_detail')
  1196. ->where('scydgy_id', 'in', array_keys($ids))
  1197. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1198. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  1199. ->update([
  1200. 'status' => $void,
  1201. 'status_name' => $void,
  1202. ]);
  1203. }
  1204. /**
  1205. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  1206. */
  1207. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  1208. {
  1209. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  1210. $norm = function (string $col) use ($p): string {
  1211. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  1212. };
  1213. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  1214. $parts = [];
  1215. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  1216. if ($key === 'createtime') {
  1217. $parts[] = $createtime;
  1218. } else {
  1219. $parts[] = $norm($key);
  1220. }
  1221. }
  1222. return 'COALESCE(' . implode(', ', $parts) . ')';
  1223. }
  1224. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  1225. {
  1226. if (!preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $monthStart)
  1227. || !preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $monthEnd)) {
  1228. return;
  1229. }
  1230. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  1231. // 禁止 whereRaw 用 ? :与 whereIn 命名绑定混用时 PDO 会失败,列表被 catch 成空
  1232. $query->whereRaw("({$expr}) >= '{$monthStart}' AND ({$expr}) <= '{$monthEnd}'");
  1233. }
  1234. /**
  1235. * @return array<int, array<string, mixed>>
  1236. */
  1237. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  1238. {
  1239. $this->ensurePurchaseOrderCzlyqColumn();
  1240. $this->ensurePurchaseOrderManualPickColumns();
  1241. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1242. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name,manual_pick,order_batch_no';
  1243. try {
  1244. $this->ensurePurchaseOrderOrderBatchNoColumn();
  1245. $query = Db::table('purchase_order')->field($fields);
  1246. $this->applyPurchaseOrderNotDeletedWhere($query);
  1247. if ($stage === 'audit') {
  1248. $query->whereIn('wflow_status', ProcuremenStatus::wflowConfirmAndAuditListValues());
  1249. } elseif ($stage === 'confirm') {
  1250. $this->applyPurchaseOrderConfirmStageWhere($query);
  1251. } else {
  1252. return [];
  1253. }
  1254. $query->order('pick_time', 'desc')->order('id', 'desc');
  1255. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1256. $monthStart = $ym . '-01 00:00:00';
  1257. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1258. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  1259. }
  1260. $rows = $query->select();
  1261. } catch (\Throwable $e) {
  1262. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  1263. $rows = [];
  1264. }
  1265. return is_array($rows) ? $rows : [];
  1266. }
  1267. /**
  1268. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  1269. */
  1270. protected function resolveProcuremenListStage(): string
  1271. {
  1272. $tab = trim((string)$this->request->request('wff_tab', ''));
  1273. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  1274. return $tab;
  1275. }
  1276. $action = strtolower((string)$this->request->action());
  1277. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  1278. return $action;
  1279. }
  1280. return 'pick';
  1281. }
  1282. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  1283. {
  1284. $this->procuremenReleaseSessionLock();
  1285. $rootTrue = rtrim((string)$this->request->root(true), '/');
  1286. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  1287. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  1288. $indexPhpRoot = $rootTrue . '/index.php';
  1289. }
  1290. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  1291. if ($stage === 'pick') {
  1292. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  1293. $sidebar = $this->GetIndexYearMonths();
  1294. } else {
  1295. $sidebar = $this->GetIssuedOrderYearMonths($stage);
  1296. $defaultYm = $this->latestYmFromSidebar($sidebar);
  1297. }
  1298. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  1299. $this->view->assign('defaultYm', $defaultYm);
  1300. $this->view->assign('sidebarYearMonths', $sidebar);
  1301. $this->view->assign('procuremenStage', $stage);
  1302. $this->view->assign('procuremenPageTitle', $pageTitle);
  1303. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  1304. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  1305. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  1306. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  1307. // 筛选项由列表 AJAX 带回,避免进页再扫 4 次 DISTINCT 白屏
  1308. $this->assignconfig('procuremenFilterOptions', [
  1309. 'czlyq' => [],
  1310. 'CCLBMMC' => [],
  1311. 'cywyxm' => [],
  1312. 'CGYMC' => [],
  1313. ]);
  1314. }
  1315. /**
  1316. * @param array<int, array{year?:string, months?:array}> $sidebar
  1317. */
  1318. protected function latestYmFromSidebar(array $sidebar): string
  1319. {
  1320. $best = '';
  1321. foreach ($sidebar as $block) {
  1322. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  1323. continue;
  1324. }
  1325. foreach ($block['months'] as $item) {
  1326. $ym = is_array($item) ? trim((string)($item['ym'] ?? '')) : '';
  1327. if (preg_match('/^\d{4}-\d{2}$/', $ym) && ($best === '' || strcmp($ym, $best) > 0)) {
  1328. $best = $ym;
  1329. }
  1330. }
  1331. }
  1332. return $best !== '' ? $best : date('Y-m');
  1333. }
  1334. /**
  1335. * 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
  1336. *
  1337. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1338. */
  1339. protected function buildProcuremenFilterOptions(string $stage): array
  1340. {
  1341. $buckets = [
  1342. 'czlyq' => [],
  1343. 'CCLBMMC' => [],
  1344. 'cywyxm' => [],
  1345. 'CGYMC' => [],
  1346. ];
  1347. $maxPerField = 300;
  1348. try {
  1349. if ($stage === 'pick') {
  1350. // 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
  1351. return $buckets;
  1352. }
  1353. if (in_array($stage, ['audit', 'confirm'], true)) {
  1354. $this->ensurePurchaseOrderCzlyqColumn();
  1355. foreach (array_keys($buckets) as $field) {
  1356. try {
  1357. $query = Db::table('purchase_order')->field($field);
  1358. $this->applyPurchaseOrderNotDeletedWhere($query);
  1359. if ($stage === 'audit') {
  1360. $query->whereIn('wflow_status', ProcuremenStatus::wflowConfirmAndAuditListValues());
  1361. } else {
  1362. $this->applyPurchaseOrderConfirmStageWhere($query);
  1363. }
  1364. $query->where($field, '<>', '')->whereNotNull($field);
  1365. $vals = $query->distinct(true)->limit($maxPerField)->column($field);
  1366. if (!is_array($vals)) {
  1367. continue;
  1368. }
  1369. foreach ($vals as $v) {
  1370. $v = trim((string)$v);
  1371. if ($v !== '') {
  1372. $buckets[$field][$v] = $v;
  1373. }
  1374. }
  1375. } catch (\Throwable $e) {
  1376. // 单字段失败不影响其它
  1377. }
  1378. }
  1379. }
  1380. } catch (\Throwable $e) {
  1381. Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
  1382. }
  1383. foreach ($buckets as &$set) {
  1384. if ($set !== []) {
  1385. ksort($set, SORT_STRING);
  1386. }
  1387. }
  1388. unset($set);
  1389. return $buckets;
  1390. }
  1391. /**
  1392. * filter JSON 是否含有效条件
  1393. *
  1394. * @param array<string, mixed> $filterArr
  1395. */
  1396. protected function procuremenFilterArrHasValue(array $filterArr): bool
  1397. {
  1398. foreach ($filterArr as $v) {
  1399. if (is_array($v)) {
  1400. if (array_filter($v, function ($x) {
  1401. return $x !== '' && $x !== null;
  1402. })) {
  1403. return true;
  1404. }
  1405. } elseif ($v !== '' && $v !== null) {
  1406. return true;
  1407. }
  1408. }
  1409. return false;
  1410. }
  1411. /**
  1412. * 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
  1413. *
  1414. * @param array<string, mixed> $filterArr
  1415. * @param array<string, mixed> $opArr
  1416. */
  1417. protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
  1418. {
  1419. if ($search !== '') {
  1420. return false;
  1421. }
  1422. foreach ($filterArr as $fk => $fv) {
  1423. if (is_array($fv)) {
  1424. continue;
  1425. }
  1426. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  1427. continue;
  1428. }
  1429. if ($fv === null) {
  1430. continue;
  1431. }
  1432. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  1433. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  1434. if ($sym === '' || $sym === '=') {
  1435. continue;
  1436. }
  1437. return false;
  1438. }
  1439. return true;
  1440. }
  1441. /**
  1442. * 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
  1443. *
  1444. * @param array<int, mixed> $rows
  1445. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1446. */
  1447. protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
  1448. {
  1449. $buckets = [
  1450. 'czlyq' => [],
  1451. 'CCLBMMC' => [],
  1452. 'cywyxm' => [],
  1453. 'CGYMC' => [],
  1454. ];
  1455. foreach ($rows as $r) {
  1456. if (!is_array($r)) {
  1457. continue;
  1458. }
  1459. foreach ($buckets as $field => &$set) {
  1460. if (count($set) >= $maxPerField) {
  1461. continue;
  1462. }
  1463. $v = trim((string)($r[$field] ?? ''));
  1464. if ($v !== '') {
  1465. $set[$v] = $v;
  1466. }
  1467. }
  1468. unset($set);
  1469. $full = true;
  1470. foreach ($buckets as $set) {
  1471. if (count($set) < $maxPerField) {
  1472. $full = false;
  1473. break;
  1474. }
  1475. }
  1476. if ($full) {
  1477. break;
  1478. }
  1479. }
  1480. foreach ($buckets as &$set) {
  1481. if ($set !== []) {
  1482. // 保证 json 编码为对象(避免 list 下标 0,1,2… 被前端当选项)
  1483. $normalized = [];
  1484. foreach ($set as $k => $v) {
  1485. $s = trim((string)(is_scalar($v) ? $v : $k));
  1486. if ($s === '') {
  1487. continue;
  1488. }
  1489. $normalized[$s] = $s;
  1490. }
  1491. ksort($normalized, SORT_STRING);
  1492. $set = $normalized;
  1493. }
  1494. }
  1495. unset($set);
  1496. return $buckets;
  1497. }
  1498. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  1499. public function pick()
  1500. {
  1501. $this->request->filter(['strip_tags', 'trim']);
  1502. if (!$this->request->isAjax()) {
  1503. $this->assignProcuremenListPage('pick', '协助下发');
  1504. return $this->view->fetch('procuremen/index');
  1505. }
  1506. return $this->index();
  1507. }
  1508. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  1509. public function audit()
  1510. {
  1511. $this->request->filter(['strip_tags', 'trim']);
  1512. if (!$this->request->isAjax()) {
  1513. $this->assignProcuremenListPage('audit', '确认供应商');
  1514. return $this->view->fetch('procuremen/index');
  1515. }
  1516. return $this->index();
  1517. }
  1518. /** 采购确认(定标) */
  1519. public function confirm()
  1520. {
  1521. $this->request->filter(['strip_tags', 'trim']);
  1522. if (!$this->request->isAjax()) {
  1523. $this->assignProcuremenListPage('confirm', '采购确认');
  1524. return $this->view->fetch('procuremen/index');
  1525. }
  1526. return $this->index();
  1527. }
  1528. /**
  1529. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  1530. */
  1531. public function index()
  1532. {
  1533. $this->request->filter(['strip_tags', 'trim']);
  1534. if (!$this->request->isAjax()) {
  1535. $this->assignProcuremenListPage('pick', '协助下发');
  1536. return $this->view->fetch('procuremen/index');
  1537. }
  1538. if ($this->request->request('keyField')) {
  1539. return $this->selectpage();
  1540. }
  1541. $this->procuremenReleaseSessionLock();
  1542. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  1543. $limit = max(10, min(500, (int)$limit));
  1544. $ym = $this->request->request('ym', '');
  1545. $ym = is_string($ym) ? trim($ym) : '';
  1546. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  1547. $wffTab = $this->resolveProcuremenListStage();
  1548. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1549. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  1550. ? $this->resolveProcuremenDefaultYm($wffTab)
  1551. : date('Y-m');
  1552. }
  1553. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1554. $ym = date('Y-m');
  1555. }
  1556. $monthStart = $ym . '-01 00:00:00';
  1557. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1558. $search = trim((string)$this->request->get('search', ''));
  1559. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  1560. $opArr = (array)json_decode($this->request->get('op', ''), true);
  1561. if (!is_array($filterArr)) {
  1562. $filterArr = [];
  1563. }
  1564. if (!is_array($opArr)) {
  1565. $opArr = [];
  1566. }
  1567. // 开标状态 / 订单状态为计算字段,不能进池内等值筛选;单独抽出后在合并后再滤
  1568. $bidOpenStatusFilter = '';
  1569. foreach (['bid_open_status_text', 'a.bid_open_status_text'] as $bidFk) {
  1570. if (!array_key_exists($bidFk, $filterArr)) {
  1571. continue;
  1572. }
  1573. $bidOpenStatusFilter = trim((string)$filterArr[$bidFk]);
  1574. unset($filterArr[$bidFk], $opArr[$bidFk]);
  1575. }
  1576. $orderStatusFilter = '';
  1577. foreach (['order_status_text', 'a.order_status_text'] as $osFk) {
  1578. if (!array_key_exists($osFk, $filterArr)) {
  1579. continue;
  1580. }
  1581. $orderStatusFilter = trim((string)$filterArr[$osFk]);
  1582. unset($filterArr[$osFk], $opArr[$osFk]);
  1583. }
  1584. // 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
  1585. $applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
  1586. $hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
  1587. try {
  1588. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  1589. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1590. $dbRows = $this->loadPurchaseOrderRowsForListStage($wffTab, $ym, $applyMonthRange);
  1591. if ($applyMonthRange && $dbRows === []) {
  1592. $fallbackYm = $this->resolveProcuremenDefaultYm($wffTab);
  1593. if ($fallbackYm !== $ym && preg_match('/^\d{4}-\d{2}$/', $fallbackYm)) {
  1594. $ym = $fallbackYm;
  1595. $monthStart = $ym . '-01 00:00:00';
  1596. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1597. $dbRows = $this->loadPurchaseOrderRowsForListStage($wffTab, $ym, true);
  1598. }
  1599. }
  1600. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(is_array($dbRows) ? $dbRows : []);
  1601. if ($wffTab === 'confirm' && $pool === []) {
  1602. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1603. }
  1604. } else {
  1605. // 初选:按月直查 ERP(不解整包 Redis,避免长时间转圈)
  1606. if ($applyMonthRange) {
  1607. $pool = $this->loadPickPoolForYm($ym);
  1608. } else {
  1609. $pool = $this->procuremenEnsureRedisPool();
  1610. }
  1611. if (!is_array($pool)) {
  1612. $pool = [];
  1613. }
  1614. // 只针对本页候选 ID 查隐藏集,避免全表扫 purchase_order_detail
  1615. $hideSet = $this->loadPickHiddenScydgySetForIds($this->extractScydgyIdsFromPool($pool));
  1616. if ($pool !== [] && $hideSet !== []) {
  1617. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1618. if (!is_array($r)) {
  1619. return false;
  1620. }
  1621. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1622. return $id <= 0 || !isset($hideSet[$id]);
  1623. }));
  1624. }
  1625. // 手工新增(YW / scydgy_id<0)只走「新增询价/查询询价」,不进初选表格
  1626. if ($pool === []) {
  1627. return json([
  1628. 'total' => 0,
  1629. 'rows' => [],
  1630. 'activeYm' => $ym,
  1631. 'filterOptions' => (
  1632. (int)$offset === 0
  1633. && !$hasActiveSearch
  1634. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1635. )
  1636. ? $this->extractProcuremenFilterOptionsFromRows([])
  1637. : new \stdClass(),
  1638. ]);
  1639. }
  1640. }
  1641. $filtered = $this->filterProcuremenIndexPool(
  1642. $pool,
  1643. $monthStart,
  1644. $monthEnd,
  1645. $applyMonthRange,
  1646. $search,
  1647. $filterArr,
  1648. $opArr,
  1649. $listTimePrimary
  1650. );
  1651. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1652. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1653. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1654. }
  1655. if (in_array($wffTab, ['audit', 'confirm'], true) && $bidOpenStatusFilter !== '') {
  1656. $filtered = $this->filterProcuremenPoolByBidOpenStatus($filtered, $bidOpenStatusFilter);
  1657. }
  1658. if (in_array($wffTab, ['audit', 'confirm'], true) && $orderStatusFilter !== '') {
  1659. $filtered = $this->filterProcuremenPoolByOrderStatus($filtered, $orderStatusFilter);
  1660. }
  1661. $sortField = 'ID';
  1662. if (is_string($sort) && $sort !== '') {
  1663. $parts = explode(',', $sort);
  1664. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1665. if ($sortField === '') {
  1666. $sortField = 'ID';
  1667. }
  1668. }
  1669. // 列表「下发时间」列字段为 issue_time,与 pick_time 同义
  1670. if ($sortField === 'issue_time') {
  1671. $sortField = 'pick_time';
  1672. }
  1673. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1674. $nFiltered = count($filtered);
  1675. if (in_array($wffTab, ['audit', 'confirm'], true) && $nFiltered > 1) {
  1676. // 确认/审批:状态分组优先;同状态内固定按下发时间倒序(最新在上,不跟前端 ASC/DESC 翻转)
  1677. // 先补齐下发时间,避免 pick_time 空时回退到提交日导致顺序错乱
  1678. $this->hydrateProcuremenListIssueSortTimes($filtered);
  1679. usort($filtered, function ($a, $b) use ($wffTab) {
  1680. if (!is_array($a)) {
  1681. return 1;
  1682. }
  1683. if (!is_array($b)) {
  1684. return -1;
  1685. }
  1686. $statusKeyA = $a['order_status_text'] ?? $a['wflow_status'] ?? '';
  1687. if (trim((string)$statusKeyA) === '') {
  1688. $statusKeyA = $a['wflow_status'] ?? '';
  1689. }
  1690. $statusKeyB = $b['order_status_text'] ?? $b['wflow_status'] ?? '';
  1691. if (trim((string)$statusKeyB) === '') {
  1692. $statusKeyB = $b['wflow_status'] ?? '';
  1693. }
  1694. $wa = ProcuremenStatus::orderStatusSortWeight($wffTab, $statusKeyA);
  1695. $wb = ProcuremenStatus::orderStatusSortWeight($wffTab, $statusKeyB);
  1696. if ($wa !== $wb) {
  1697. return $wa <=> $wb;
  1698. }
  1699. $ta = trim((string)($a['_issue_sort_time'] ?? ''));
  1700. if ($ta === '') {
  1701. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  1702. }
  1703. $tb = trim((string)($b['_issue_sort_time'] ?? ''));
  1704. if ($tb === '') {
  1705. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  1706. }
  1707. if ($ta !== $tb) {
  1708. if ($ta === '') {
  1709. return 1;
  1710. }
  1711. if ($tb === '') {
  1712. return -1;
  1713. }
  1714. // 倒序:新的在前
  1715. return strcmp($tb, $ta);
  1716. }
  1717. return ((int)($b['ID'] ?? 0) <=> (int)($a['ID'] ?? 0));
  1718. });
  1719. } elseif ($nFiltered > 1) {
  1720. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1721. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1722. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1723. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1724. if ($ta === $tb) {
  1725. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1726. }
  1727. if ($ta === '') {
  1728. return 1;
  1729. }
  1730. if ($tb === '') {
  1731. return -1;
  1732. }
  1733. return strcmp($ta, $tb) * $ord;
  1734. });
  1735. } elseif ($sortField === 'ID') {
  1736. $sortKeys = [];
  1737. foreach ($filtered as $i => $row) {
  1738. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1739. }
  1740. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1741. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1742. } elseif ($sortField === 'CCYDH') {
  1743. usort($filtered, function ($a, $b) use ($ord) {
  1744. $sa = trim((string)($a['CCYDH'] ?? ''));
  1745. $sb = trim((string)($b['CCYDH'] ?? ''));
  1746. if ($sa === $sb) {
  1747. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1748. }
  1749. if ($sa === '') {
  1750. return 1;
  1751. }
  1752. if ($sb === '') {
  1753. return -1;
  1754. }
  1755. return strcmp($sa, $sb) * $ord;
  1756. });
  1757. } else {
  1758. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1759. $va = $a[$sortField] ?? null;
  1760. $vb = $b[$sortField] ?? null;
  1761. $sa = (string)$va;
  1762. $sb = (string)$vb;
  1763. if ($sa === $sb) {
  1764. return 0;
  1765. }
  1766. return strcmp($sa, $sb) * $ord;
  1767. });
  1768. }
  1769. }
  1770. $offset = max(0, (int)$offset);
  1771. $limit = max(1, (int)$limit);
  1772. $rows = array_slice($filtered, $offset, $limit);
  1773. foreach ($rows as &$rw) {
  1774. if (!is_array($rw)) {
  1775. continue;
  1776. }
  1777. $rid = (int)($rw['ID'] ?? 0);
  1778. $rw['_iss_out'] = ($wffTab !== 'pick');
  1779. }
  1780. unset($rw);
  1781. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1782. $idList = [];
  1783. foreach ($rows as $rw) {
  1784. if (!is_array($rw)) {
  1785. continue;
  1786. }
  1787. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1788. foreach ($rw['_order_merge_rows'] as $mr) {
  1789. $mid = (int)($mr['ID'] ?? 0);
  1790. if ($this->isValidScydgyRowId($mid)) {
  1791. $idList[$mid] = true;
  1792. }
  1793. }
  1794. }
  1795. $id = (int)($rw['ID'] ?? 0);
  1796. if ($this->isValidScydgyRowId($id)) {
  1797. $idList[$id] = true;
  1798. }
  1799. }
  1800. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1801. foreach ($rows as &$rw) {
  1802. if (!is_array($rw)) {
  1803. continue;
  1804. }
  1805. $mergeIds = [];
  1806. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1807. foreach ($rw['_order_merge_rows'] as $mr) {
  1808. $mid = (int)($mr['ID'] ?? 0);
  1809. if ($this->isValidScydgyRowId($mid)) {
  1810. $mergeIds[$mid] = true;
  1811. }
  1812. }
  1813. }
  1814. $rid = (int)($rw['ID'] ?? 0);
  1815. if ($this->isValidScydgyRowId($rid)) {
  1816. $mergeIds[$rid] = true;
  1817. }
  1818. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1819. $rw['po_detail_count'] = $s['cnt'];
  1820. $rw['po_amount_fill_cnt'] = $s['amt'];
  1821. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1822. }
  1823. unset($rw);
  1824. }
  1825. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1826. $idList = [];
  1827. foreach ($rows as $rw) {
  1828. if (!is_array($rw)) {
  1829. continue;
  1830. }
  1831. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1832. foreach ($rw['_order_merge_rows'] as $mr) {
  1833. $mid = (int)($mr['ID'] ?? 0);
  1834. if ($this->isValidScydgyRowId($mid)) {
  1835. $idList[$mid] = true;
  1836. }
  1837. }
  1838. }
  1839. $id = (int)($rw['ID'] ?? 0);
  1840. if ($this->isValidScydgyRowId($id)) {
  1841. $idList[$id] = true;
  1842. }
  1843. }
  1844. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1845. $bidOpenSet = [];
  1846. $manualPickSet = [];
  1847. $bidOpenBatchSet = [];
  1848. $ccydhList = [];
  1849. $batchList = [];
  1850. foreach ($rows as $rw0) {
  1851. if (!is_array($rw0)) {
  1852. continue;
  1853. }
  1854. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1855. if ($c0 !== '') {
  1856. $ccydhList[] = $c0;
  1857. }
  1858. $b0 = $this->resolveProcuremenOrderBatchNo($rw0);
  1859. if ($b0 !== '') {
  1860. $batchList[] = $b0;
  1861. }
  1862. if (!empty($rw0['_order_merge_rows']) && is_array($rw0['_order_merge_rows'])) {
  1863. foreach ($rw0['_order_merge_rows'] as $mr0) {
  1864. if (!is_array($mr0)) {
  1865. continue;
  1866. }
  1867. $cm = trim((string)($mr0['CCYDH'] ?? ''));
  1868. if ($cm !== '') {
  1869. $ccydhList[] = $cm;
  1870. }
  1871. $bm = $this->resolveProcuremenOrderBatchNo($mr0);
  1872. if ($bm !== '') {
  1873. $batchList[] = $bm;
  1874. }
  1875. }
  1876. }
  1877. }
  1878. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1879. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  1880. $bidOpenBatchSet = $this->loadProcuremenBidOpenVerifiedBatchSet($batchList);
  1881. foreach ($rows as &$rw) {
  1882. if (!is_array($rw)) {
  1883. continue;
  1884. }
  1885. $mergeIds = [];
  1886. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1887. foreach ($rw['_order_merge_rows'] as $mr) {
  1888. $mid = (int)($mr['ID'] ?? 0);
  1889. if ($this->isValidScydgyRowId($mid)) {
  1890. $mergeIds[$mid] = true;
  1891. }
  1892. }
  1893. }
  1894. $rid = (int)($rw['ID'] ?? 0);
  1895. if ($this->isValidScydgyRowId($rid)) {
  1896. $mergeIds[$rid] = true;
  1897. }
  1898. $buckets = [];
  1899. foreach (array_keys($mergeIds) as $mid) {
  1900. if (isset($quoteBucket[$mid])) {
  1901. $buckets[] = $quoteBucket[$mid];
  1902. }
  1903. }
  1904. $supplierText = $buckets !== []
  1905. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1906. : '';
  1907. $picked = trim((string)($rw['pick_company_name'] ?? $rw['picked_supplier_name'] ?? ''));
  1908. if ($picked === '') {
  1909. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1910. foreach ($rw['_order_merge_rows'] as $mr) {
  1911. if (!is_array($mr)) {
  1912. continue;
  1913. }
  1914. $pn = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  1915. if ($pn !== '') {
  1916. $picked = $pn;
  1917. break;
  1918. }
  1919. }
  1920. }
  1921. }
  1922. $rw['picked_supplier_name'] = $picked;
  1923. $rw['notify_supplier_text'] = $supplierText;
  1924. $wflowRaw = trim((string)($rw['wflow_status'] ?? ''));
  1925. if ($wflowRaw === '' && !empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1926. foreach ($rw['_order_merge_rows'] as $mr) {
  1927. if (!is_array($mr)) {
  1928. continue;
  1929. }
  1930. $wf = trim((string)($mr['wflow_status'] ?? ''));
  1931. if ($wf !== '') {
  1932. $wflowRaw = $wf;
  1933. break;
  1934. }
  1935. }
  1936. }
  1937. $rw['wflow_status'] = $wflowRaw;
  1938. $rw['order_status_text'] = ProcuremenStatus::orderStatusLabelForList($wflowRaw);
  1939. $bidState = $this->resolveProcuremenListBidOpenState($rw, $bidOpenSet, $manualPickSet, $bidOpenBatchSet);
  1940. $rw['bid_open_verified'] = !empty($bidState['verified']) ? 1 : 0;
  1941. $rw['manual_picked'] = !empty($bidState['manual']) ? 1 : 0;
  1942. $rw['bid_open_status_text'] = (string)($bidState['text'] ?? '待开标');
  1943. }
  1944. unset($rw);
  1945. }
  1946. if (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
  1947. $this->enrichProcuremenListMilestoneTimes($rows);
  1948. $this->syncCollapsedOrderQtyPriceForList($rows);
  1949. }
  1950. if ($wffTab === 'all' && count($rows) > 0) {
  1951. $this->mergePurchaseOrder($rows);
  1952. }
  1953. if ($wffTab === 'pick' && count($rows) > 0) {
  1954. $this->mergePurchaseOrder($rows);
  1955. }
  1956. foreach ($rows as &$rwClean) {
  1957. if (is_array($rwClean)) {
  1958. unset($rwClean['_order_merge_rows']);
  1959. if (array_key_exists('NGZL', $rwClean)) {
  1960. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1961. }
  1962. }
  1963. }
  1964. unset($rwClean);
  1965. return json([
  1966. 'total' => count($filtered),
  1967. 'rows' => $rows,
  1968. 'activeYm' => $ym,
  1969. // 初选:把有数据的月份带回,替换「空月份日历」侧栏
  1970. 'sidebarYms' => (in_array($wffTab, ['pick', 'audit', 'confirm'], true) && (int)$offset === 0)
  1971. ? (
  1972. $wffTab === 'pick'
  1973. ? $this->ensureProcuremenPickSidebarYmList()
  1974. : $this->flattenProcuremenSidebarYms($this->GetIssuedOrderYearMonths($wffTab))
  1975. )
  1976. : [],
  1977. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1978. 'filterOptions' => (
  1979. (int)$offset === 0
  1980. && !$hasActiveSearch
  1981. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1982. )
  1983. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1984. : new \stdClass(),
  1985. ]);
  1986. } catch (\Throwable $e) {
  1987. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1988. return json([
  1989. 'total' => 0,
  1990. 'rows' => [],
  1991. ]);
  1992. }
  1993. }
  1994. /**
  1995. * @param array<int, array<string, mixed>> $pool
  1996. * @return int[]
  1997. */
  1998. protected function extractScydgyIdsFromPool(array $pool): array
  1999. {
  2000. $ids = [];
  2001. foreach ($pool as $r) {
  2002. if (!is_array($r)) {
  2003. continue;
  2004. }
  2005. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  2006. if ($id > 0) {
  2007. $ids[$id] = $id;
  2008. }
  2009. }
  2010. return array_values($ids);
  2011. }
  2012. /**
  2013. * 仅查询指定工序 ID 是否已下发/进入后续流程(初选列表加速)
  2014. *
  2015. * @param int[] $scydgyIds
  2016. * @return array<int, true>
  2017. */
  2018. protected function loadPickHiddenScydgySetForIds(array $scydgyIds): array
  2019. {
  2020. $hideSet = [];
  2021. $scydgyIds = array_values(array_filter(array_map('intval', $scydgyIds), function ($id) {
  2022. return $id > 0;
  2023. }));
  2024. if ($scydgyIds === []) {
  2025. return $hideSet;
  2026. }
  2027. // 分批,避免 whereIn 过长
  2028. foreach (array_chunk($scydgyIds, 500) as $chunk) {
  2029. try {
  2030. $poIds = Db::table('purchase_order')
  2031. ->where('scydgy_id', 'in', $chunk)
  2032. ->where(function ($q) {
  2033. $q->whereIn('wflow_status', array_merge(
  2034. ProcuremenStatus::wflowPendingConfirmValues(),
  2035. ProcuremenStatus::wflowPendingApprovalValues()
  2036. ))
  2037. ->whereOr(function ($q1) {
  2038. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  2039. })
  2040. ->whereOr(function ($q2) {
  2041. $q2->whereNotNull('pick_time')
  2042. ->where('pick_time', '<>', '')
  2043. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  2044. })
  2045. ->whereOr(function ($q3) {
  2046. $q3->whereNotNull('mod_rq')
  2047. ->where('mod_rq', '<>', '')
  2048. ->where('mod_rq', 'not like', '0000-00-00%');
  2049. });
  2050. })
  2051. ->column('scydgy_id');
  2052. if (is_array($poIds)) {
  2053. foreach ($poIds as $pid) {
  2054. $k = (int)$pid;
  2055. if ($k !== 0) {
  2056. $hideSet[$k] = true;
  2057. }
  2058. }
  2059. }
  2060. } catch (\Throwable $e) {
  2061. }
  2062. try {
  2063. $detIdsQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $chunk);
  2064. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  2065. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  2066. if (is_array($detIds)) {
  2067. foreach ($detIds as $pid) {
  2068. $k = (int)$pid;
  2069. if ($this->isValidScydgyRowId($k)) {
  2070. $hideSet[$k] = true;
  2071. }
  2072. }
  2073. }
  2074. } catch (\Throwable $e) {
  2075. }
  2076. }
  2077. return $hideSet;
  2078. }
  2079. /**
  2080. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  2081. *
  2082. * @return array<int, true>
  2083. */
  2084. protected function loadPickHiddenScydgySet(): array
  2085. {
  2086. if ($this->pickHiddenScydgySetCache !== null) {
  2087. return $this->pickHiddenScydgySetCache;
  2088. }
  2089. $cacheKey = 'procuremen_pick_hidden_scydgy_v1';
  2090. try {
  2091. $raw = redis()->get($cacheKey);
  2092. if ($raw !== false && $raw !== null && $raw !== '') {
  2093. $ids = json_decode((string)$raw, true);
  2094. if (is_array($ids)) {
  2095. $hideSet = [];
  2096. foreach ($ids as $pid) {
  2097. $k = (int)$pid;
  2098. if ($k !== 0) {
  2099. $hideSet[$k] = true;
  2100. }
  2101. }
  2102. $this->pickHiddenScydgySetCache = $hideSet;
  2103. return $hideSet;
  2104. }
  2105. }
  2106. } catch (\Throwable $e) {
  2107. }
  2108. $hideSet = [];
  2109. try {
  2110. $poIds = Db::table('purchase_order')
  2111. ->where(function ($q) {
  2112. $q->whereIn('wflow_status', array_merge(
  2113. ProcuremenStatus::wflowPendingConfirmValues(),
  2114. ProcuremenStatus::wflowPendingApprovalValues()
  2115. ))
  2116. ->whereOr(function ($q1) {
  2117. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  2118. })
  2119. ->whereOr(function ($q2) {
  2120. $q2->whereNotNull('pick_time')
  2121. ->where('pick_time', '<>', '')
  2122. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  2123. })
  2124. ->whereOr(function ($q3) {
  2125. $q3->whereNotNull('mod_rq')
  2126. ->where('mod_rq', '<>', '')
  2127. ->where('mod_rq', 'not like', '0000-00-00%');
  2128. });
  2129. })
  2130. ->column('scydgy_id');
  2131. if (is_array($poIds)) {
  2132. foreach ($poIds as $pid) {
  2133. $k = (int)$pid;
  2134. if ($k !== 0) {
  2135. $hideSet[$k] = true;
  2136. }
  2137. }
  2138. }
  2139. } catch (\Throwable $e) {
  2140. }
  2141. try {
  2142. $detIdsQuery = Db::table('purchase_order_detail');
  2143. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  2144. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  2145. if (is_array($detIds)) {
  2146. foreach ($detIds as $pid) {
  2147. $k = (int)$pid;
  2148. if ($this->isValidScydgyRowId($k)) {
  2149. $hideSet[$k] = true;
  2150. }
  2151. }
  2152. }
  2153. } catch (\Throwable $e) {
  2154. }
  2155. $this->pickHiddenScydgySetCache = $hideSet;
  2156. try {
  2157. redis()->setex($cacheKey, 90, json_encode(array_map('intval', array_keys($hideSet))));
  2158. } catch (\Throwable $e) {
  2159. }
  2160. return $hideSet;
  2161. }
  2162. /**
  2163. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  2164. *
  2165. * @return array<int, array<string, mixed>>
  2166. */
  2167. protected function loadPickManualOrderRows(): array
  2168. {
  2169. try {
  2170. $dbRows = Db::table('purchase_order')
  2171. ->where('scydgy_id', '<', 0)
  2172. ->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%\')')
  2173. ->order('scydgy_id', 'asc')
  2174. ->select();
  2175. } catch (\Throwable $e) {
  2176. try {
  2177. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  2178. } catch (\Throwable $e2) {
  2179. return [];
  2180. }
  2181. }
  2182. if (!is_array($dbRows) || $dbRows === []) {
  2183. return [];
  2184. }
  2185. $detailSidSet = [];
  2186. try {
  2187. $negIds = [];
  2188. foreach ($dbRows as $dbRow) {
  2189. if (!is_array($dbRow)) {
  2190. continue;
  2191. }
  2192. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2193. if ($sid < 0) {
  2194. $negIds[$sid] = true;
  2195. }
  2196. }
  2197. if ($negIds !== []) {
  2198. $detQuery = Db::table('purchase_order_detail')
  2199. ->where('scydgy_id', 'in', array_keys($negIds));
  2200. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  2201. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  2202. if (is_array($detRows)) {
  2203. foreach ($detRows as $did) {
  2204. $detailSidSet[(int)$did] = true;
  2205. }
  2206. }
  2207. }
  2208. } catch (\Throwable $e) {
  2209. }
  2210. $pool = [];
  2211. foreach ($dbRows as $dbRow) {
  2212. if (!is_array($dbRow)) {
  2213. continue;
  2214. }
  2215. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2216. if ($sid >= 0) {
  2217. continue;
  2218. }
  2219. // 已进入确认/审批的不进初选;仅废弃明细残留的仍算可下发
  2220. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  2221. continue;
  2222. }
  2223. // 仅排除已完结;空 status / 「进行中」/ 0 均保留(新建手工单)
  2224. if (ProcuremenStatus::isPoCompleted($dbRow['status'] ?? '')) {
  2225. continue;
  2226. }
  2227. if (isset($detailSidSet[$sid])) {
  2228. continue;
  2229. }
  2230. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  2231. $r['_is_manual'] = 1;
  2232. $pool[] = $r;
  2233. }
  2234. return $pool;
  2235. }
  2236. /**
  2237. * 确认/审批列表排序:补齐下发时间(pick_time + 下发操作日志)
  2238. *
  2239. * @param array<int, array<string, mixed>> $rows
  2240. */
  2241. protected function hydrateProcuremenListIssueSortTimes(array &$rows): void
  2242. {
  2243. if ($rows === []) {
  2244. return;
  2245. }
  2246. $sidList = [];
  2247. foreach ($rows as $rw) {
  2248. if (!is_array($rw)) {
  2249. continue;
  2250. }
  2251. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  2252. foreach ($rw['_order_merge_rows'] as $mr) {
  2253. if (!is_array($mr)) {
  2254. continue;
  2255. }
  2256. $mid = (int)($mr['ID'] ?? 0);
  2257. if ($this->isValidScydgyRowId($mid)) {
  2258. $sidList[$mid] = true;
  2259. }
  2260. }
  2261. }
  2262. $id = (int)($rw['ID'] ?? 0);
  2263. if ($this->isValidScydgyRowId($id)) {
  2264. $sidList[$id] = true;
  2265. }
  2266. }
  2267. $issueBySid = [];
  2268. $sids = array_keys($sidList);
  2269. if ($sids !== []) {
  2270. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  2271. if ($issueActs !== []) {
  2272. try {
  2273. $logs = Db::table('purchase_order_oper_log')
  2274. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  2275. ->where(ProcuremenOperLog::COL_ACTION, 'in', $issueActs)
  2276. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_TIME)
  2277. ->order('id', 'asc')
  2278. ->select();
  2279. } catch (\Throwable $e) {
  2280. $logs = [];
  2281. }
  2282. if (is_array($logs)) {
  2283. foreach ($logs as $lg) {
  2284. if (!is_array($lg)) {
  2285. continue;
  2286. }
  2287. $lg = ProcuremenOperLog::normalizeRow($lg);
  2288. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  2289. if ($sid === 0) {
  2290. continue;
  2291. }
  2292. $tm = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  2293. if ($tm === '') {
  2294. continue;
  2295. }
  2296. if (!isset($issueBySid[$sid]) || strcmp($tm, $issueBySid[$sid]) > 0) {
  2297. $issueBySid[$sid] = $tm;
  2298. }
  2299. }
  2300. }
  2301. }
  2302. }
  2303. foreach ($rows as &$rw) {
  2304. if (!is_array($rw)) {
  2305. continue;
  2306. }
  2307. $mergeSids = [];
  2308. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  2309. foreach ($rw['_order_merge_rows'] as $mr) {
  2310. if (!is_array($mr)) {
  2311. continue;
  2312. }
  2313. $mid = (int)($mr['ID'] ?? 0);
  2314. if ($this->isValidScydgyRowId($mid)) {
  2315. $mergeSids[] = $mid;
  2316. }
  2317. }
  2318. }
  2319. $rid = (int)($rw['ID'] ?? 0);
  2320. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  2321. $mergeSids[] = $rid;
  2322. }
  2323. $best = $this->procuremenRowListSortTime($rw, 'pick_time');
  2324. foreach ($mergeSids as $sid) {
  2325. if (isset($issueBySid[$sid]) && ($best === '' || strcmp($issueBySid[$sid], $best) > 0)) {
  2326. $best = $issueBySid[$sid];
  2327. }
  2328. }
  2329. $rw['_issue_sort_time'] = $best;
  2330. if ($best !== '') {
  2331. $pickOut = trim((string)($rw['pick_time'] ?? ''));
  2332. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  2333. $rw['pick_time'] = $best;
  2334. }
  2335. $rw['issue_time'] = $best;
  2336. }
  2337. }
  2338. unset($rw);
  2339. }
  2340. /**
  2341. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  2342. */
  2343. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  2344. {
  2345. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  2346. foreach ($keys as $k) {
  2347. $t = trim((string)($row[$k] ?? ''));
  2348. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2349. return $t;
  2350. }
  2351. }
  2352. return '';
  2353. }
  2354. /**
  2355. * 分配手工新增工序行 ID(负数递减)
  2356. * 调用方须在命名锁内执行,避免并发重复
  2357. */
  2358. protected function allocateManualScydgyId(): int
  2359. {
  2360. try {
  2361. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  2362. $min = (int)$min;
  2363. return $min < 0 ? $min - 1 : -1;
  2364. } catch (\Throwable $e) {
  2365. return -1;
  2366. }
  2367. }
  2368. /**
  2369. * 手工新增订单号:YW + 年月日 + 当日序号(如 YW20260618001)
  2370. * 调用方须在命名锁内执行,避免并发重复
  2371. */
  2372. protected function allocateManualOrderCcydh(): string
  2373. {
  2374. $prefix = 'YW' . date('Ymd');
  2375. $maxSeq = 0;
  2376. try {
  2377. $rows = Db::table('purchase_order')
  2378. ->where('CCYDH', 'like', $prefix . '%')
  2379. ->column('CCYDH');
  2380. if (is_array($rows)) {
  2381. foreach ($rows as $ccydh) {
  2382. $ccydh = trim((string)$ccydh);
  2383. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3,})$/', $ccydh, $m)) {
  2384. $maxSeq = max($maxSeq, (int)$m[1]);
  2385. }
  2386. }
  2387. }
  2388. } catch (\Throwable $e) {
  2389. }
  2390. $next = $maxSeq + 1;
  2391. $width = $next > 999 ? strlen((string)$next) : 3;
  2392. return $prefix . str_pad((string)$next, $width, '0', STR_PAD_LEFT);
  2393. }
  2394. /**
  2395. * MySQL 命名锁(跨连接防并发撞号)
  2396. */
  2397. protected function acquireProcuremenNamedLock(string $name, int $timeoutSec = 10): bool
  2398. {
  2399. $name = trim($name);
  2400. if ($name === '') {
  2401. return false;
  2402. }
  2403. try {
  2404. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2405. $rows = Db::query('SELECT GET_LOCK(\'' . $nameSql . '\', ' . max(1, $timeoutSec) . ') AS locked');
  2406. if (!is_array($rows) || $rows === []) {
  2407. return false;
  2408. }
  2409. $v = $rows[0]['locked'] ?? $rows[0]['LOCKED'] ?? null;
  2410. return (int)$v === 1;
  2411. } catch (\Throwable $e) {
  2412. return false;
  2413. }
  2414. }
  2415. protected function releaseProcuremenNamedLock(string $name): void
  2416. {
  2417. $name = trim($name);
  2418. if ($name === '') {
  2419. return;
  2420. }
  2421. try {
  2422. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2423. Db::query('SELECT RELEASE_LOCK(\'' . $nameSql . '\')');
  2424. } catch (\Throwable $e) {
  2425. }
  2426. }
  2427. /**
  2428. * purchase_order.mod_rq 是否有有效软删除时间
  2429. */
  2430. protected function isPurchaseOrderSoftDeleted($modRq): bool
  2431. {
  2432. $t = trim((string)$modRq);
  2433. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  2434. }
  2435. /**
  2436. * 列表行 → purchase_order 写入字段
  2437. *
  2438. * @return array<string, mixed>
  2439. */
  2440. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  2441. {
  2442. return $this->normalizePurchaseOrderWritePayload([
  2443. 'scydgy_id' => $scydgyId,
  2444. 'CCYDH' => $row['CCYDH'] ?? null,
  2445. 'CYJMC' => $row['CYJMC'] ?? null,
  2446. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2447. 'CDXMC' => $row['CDXMC'] ?? null,
  2448. 'CGYBH' => $row['CGYBH'] ?? null,
  2449. 'CGYMC' => $row['CGYMC'] ?? null,
  2450. 'CDW' => $row['CDW'] ?? null,
  2451. 'czlyq' => $row['czlyq'] ?? null,
  2452. 'NGZL' => $row['NGZL'] ?? null,
  2453. 'CDF' => $row['CDF'] ?? null,
  2454. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2455. 'MBZ' => $row['MBZ'] ?? null,
  2456. 'bwjg' => $row['bwjg'] ?? null,
  2457. 'iStatus' => $row['iStatus'] ?? null,
  2458. 'dStamp' => $row['dStamp'] ?? null,
  2459. 'dputrecord' => $row['dputrecord'] ?? null,
  2460. 'cywyxm' => $row['cywyxm'] ?? null,
  2461. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2462. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2463. ], $row);
  2464. }
  2465. /**
  2466. * purchase_order 写入前规范化:NOT NULL 列勿显式传 null(会绕过 DEFAULT 触发 1048)
  2467. *
  2468. * @param array<string, mixed> $data
  2469. * @param array<string, mixed> $row 原始列表行(可用于补齐 czlyq)
  2470. * @return array<string, mixed>
  2471. */
  2472. protected function normalizePurchaseOrderWritePayload(array $data, array $row = []): array
  2473. {
  2474. $this->ensurePurchaseOrderCzlyqColumn();
  2475. $cz = '';
  2476. foreach (['czlyq', 'CZLYQ'] as $k) {
  2477. if (isset($data[$k]) && trim((string)$data[$k]) !== '') {
  2478. $cz = trim((string)$data[$k]);
  2479. break;
  2480. }
  2481. if (isset($row[$k]) && trim((string)$row[$k]) !== '') {
  2482. $cz = trim((string)$row[$k]);
  2483. break;
  2484. }
  2485. }
  2486. if ($cz === '') {
  2487. $ccydh = trim((string)($data['CCYDH'] ?? $row['CCYDH'] ?? ''));
  2488. if ($ccydh !== '') {
  2489. try {
  2490. $fromMcyd = Db::table('mcyd')->where('CCYDH', $ccydh)->value('czlyq');
  2491. $cz = trim((string)$fromMcyd);
  2492. } catch (\Throwable $e) {
  2493. $cz = '';
  2494. }
  2495. }
  2496. }
  2497. $data['czlyq'] = $cz;
  2498. // 显式 NULL 的字符串 NOT NULL 列改为空串
  2499. foreach (['czlyq', 'notify_salesman', 'manual_pick_reason', 'score_rule_name'] as $col) {
  2500. if (!array_key_exists($col, $data)) {
  2501. continue;
  2502. }
  2503. if ($data[$col] === null || !is_scalar($data[$col])) {
  2504. $data[$col] = '';
  2505. } else {
  2506. $data[$col] = (string)$data[$col];
  2507. }
  2508. }
  2509. foreach (['rfq_salesman_notified', 'manual_pick', 'score_rule_id', 'score_quality_weight', 'score_price_weight', 'score_lead_weight'] as $col) {
  2510. if (array_key_exists($col, $data) && $data[$col] === null) {
  2511. $data[$col] = 0;
  2512. }
  2513. }
  2514. return $data;
  2515. }
  2516. /**
  2517. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  2518. *
  2519. * @return array{po:?array<string,mixed>, hidden:bool}
  2520. */
  2521. protected function resolvePickRowPoContext(int $sid): array
  2522. {
  2523. $po = null;
  2524. try {
  2525. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2526. if (is_array($found)) {
  2527. $po = $found;
  2528. }
  2529. } catch (\Throwable $e) {
  2530. }
  2531. $hideSet = $this->loadPickHiddenScydgySet();
  2532. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  2533. }
  2534. /**
  2535. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  2536. */
  2537. protected function assertPickRowCanDelete(int $sid, array $row): void
  2538. {
  2539. $ctx = $this->resolvePickRowPoContext($sid);
  2540. $po = $ctx['po'];
  2541. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2542. return;
  2543. }
  2544. if (is_array($po)) {
  2545. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2546. throw new \InvalidArgumentException('该工序已完结,无法删除');
  2547. }
  2548. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2549. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  2550. }
  2551. }
  2552. if ($ctx['hidden']) {
  2553. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2554. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  2555. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  2556. }
  2557. }
  2558. /**
  2559. * 初选直接完结前校验
  2560. */
  2561. protected function assertPickRowCanComplete(int $sid, array $row): void
  2562. {
  2563. $ctx = $this->resolvePickRowPoContext($sid);
  2564. $po = $ctx['po'];
  2565. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2566. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  2567. }
  2568. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2569. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  2570. }
  2571. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  2572. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  2573. }
  2574. }
  2575. /**
  2576. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  2577. */
  2578. protected function softDeleteProcuremenPickRow(array $row): void
  2579. {
  2580. $sid = $this->extractScydgyRowId($row);
  2581. if (!$this->isValidScydgyRowId($sid)) {
  2582. throw new \InvalidArgumentException('无效的行主键');
  2583. }
  2584. $this->assertPickRowCanDelete($sid, $row);
  2585. $po = $this->resolvePickRowPoContext($sid)['po'];
  2586. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2587. return;
  2588. }
  2589. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2590. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  2591. }
  2592. $now = date('Y-m-d H:i:s');
  2593. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2594. if (is_array($exists)) {
  2595. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  2596. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  2597. } else {
  2598. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  2599. $data['mod_rq'] = $now;
  2600. $data['createtime'] = $now;
  2601. Db::table('purchase_order')->insert($data);
  2602. $poIdLog = (int)Db::getLastInsID();
  2603. }
  2604. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  2605. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  2606. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  2607. if ($gymcLog !== '') {
  2608. $logTail .= ' / ' . $gymcLog;
  2609. }
  2610. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  2611. }
  2612. /**
  2613. * 手工新增协助工序(写入 purchase_order)
  2614. *
  2615. * @param array<string, mixed> $params
  2616. * @return int scydgy_id
  2617. */
  2618. protected function saveManualPickOrder(array $params): int
  2619. {
  2620. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  2621. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  2622. $ccydhIn = trim((string)($params['CCYDH'] ?? ''));
  2623. $lockName = 'procuremen_manual_order_alloc';
  2624. if (!$this->acquireProcuremenNamedLock($lockName, 10)) {
  2625. throw new \RuntimeException('系统繁忙,请稍后重试');
  2626. }
  2627. try {
  2628. $ccydh = $ccydhIn !== '' ? $ccydhIn : $this->allocateManualOrderCcydh();
  2629. $now = date('Y-m-d H:i:s');
  2630. $sid = $this->allocateManualScydgyId();
  2631. $this->ensurePurchaseOrderNotifySalesmanColumn();
  2632. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  2633. // 选择供应商 / 通知业务员:支持多选,落库用顿号拼接
  2634. $supplierName = $this->joinRfqMultiSelectValues($params['cGzzxMc'] ?? ($params['pick_company_name'] ?? ''));
  2635. $notifySalesman = $this->joinRfqMultiSelectValues($params['notify_salesman'] ?? '');
  2636. $data = [
  2637. 'scydgy_id' => $sid,
  2638. 'CCYDH' => $ccydh,
  2639. 'CYJMC' => $cyjmc,
  2640. 'CGYMC' => $cgymc,
  2641. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  2642. 'CDW' => trim((string)($params['CDW'] ?? '')),
  2643. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  2644. 'CDF' => trim((string)($params['CDF'] ?? '')),
  2645. 'cGzzxMc' => $supplierName,
  2646. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  2647. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  2648. 'notify_salesman' => $notifySalesman,
  2649. 'rfq_salesman_notified' => 0,
  2650. 'rfq_salesman_notify_time' => null,
  2651. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  2652. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  2653. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  2654. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  2655. 'createtime' => $now,
  2656. 'dStamp' => $now,
  2657. 'dputrecord' => $now,
  2658. ];
  2659. Db::table('purchase_order')->insert($data);
  2660. $poId = (int)Db::getLastInsID();
  2661. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  2662. return $sid;
  2663. } finally {
  2664. $this->releaseProcuremenNamedLock($lockName);
  2665. }
  2666. }
  2667. protected function formatProcuremenRowLabel(array $row): string
  2668. {
  2669. return ProcuremenFormat::rowLabel($row);
  2670. }
  2671. /**
  2672. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  2673. */
  2674. protected function extractScydgyRowId(array $row): int
  2675. {
  2676. return ProcuremenFormat::extractScydgyRowId($row);
  2677. }
  2678. protected function isValidScydgyRowId(int $id): bool
  2679. {
  2680. return ProcuremenGuard::isValidScydgyId($id);
  2681. }
  2682. protected function isManualScydgyRowId(int $id): bool
  2683. {
  2684. return $id < 0;
  2685. }
  2686. /**
  2687. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  2688. *
  2689. * @param int[] $scydgyIds
  2690. * @return array<int, string[]>
  2691. */
  2692. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  2693. {
  2694. $out = [];
  2695. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2696. if ($scydgyIds === []) {
  2697. return $out;
  2698. }
  2699. try {
  2700. $rows = Db::table('purchase_order_detail')
  2701. ->where('scydgy_id', 'in', $scydgyIds)
  2702. ->field('scydgy_id,company_name')
  2703. ->order('company_name', 'asc')
  2704. ->select();
  2705. } catch (\Throwable $e) {
  2706. $rows = [];
  2707. }
  2708. if (!is_array($rows)) {
  2709. return $out;
  2710. }
  2711. foreach ($rows as $r) {
  2712. if (!is_array($r)) {
  2713. continue;
  2714. }
  2715. $sid = (int)($r['scydgy_id'] ?? 0);
  2716. $cn = trim((string)($r['company_name'] ?? ''));
  2717. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2718. continue;
  2719. }
  2720. if (!isset($out[$sid])) {
  2721. $out[$sid] = [];
  2722. }
  2723. if (!in_array($cn, $out[$sid], true)) {
  2724. $out[$sid][] = $cn;
  2725. }
  2726. }
  2727. return $out;
  2728. }
  2729. /**
  2730. * 列表展示通知供应商(完整列表,前端单行省略展开)
  2731. *
  2732. * @param string[] $names
  2733. */
  2734. protected function formatNotifySupplierDisplay(array $names): string
  2735. {
  2736. return ProcuremenFormat::notifySupplierDisplay($names);
  2737. }
  2738. /**
  2739. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  2740. *
  2741. * @param int[] $scydgyIds
  2742. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  2743. */
  2744. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  2745. {
  2746. $out = [];
  2747. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2748. if ($scydgyIds === []) {
  2749. return $out;
  2750. }
  2751. try {
  2752. $rows = Db::table('purchase_order_detail')
  2753. ->where('scydgy_id', 'in', $scydgyIds)
  2754. ->field('scydgy_id,company_name,amount')
  2755. ->select();
  2756. } catch (\Throwable $e) {
  2757. $rows = [];
  2758. }
  2759. if (!is_array($rows)) {
  2760. return $out;
  2761. }
  2762. foreach ($rows as $r) {
  2763. if (!is_array($r)) {
  2764. continue;
  2765. }
  2766. $sid = (int)($r['scydgy_id'] ?? 0);
  2767. $cn = trim((string)($r['company_name'] ?? ''));
  2768. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2769. continue;
  2770. }
  2771. if (!isset($out[$sid])) {
  2772. $out[$sid] = ['all' => [], 'quoted' => []];
  2773. }
  2774. $out[$sid]['all'][$cn] = true;
  2775. $am = trim((string)($r['amount'] ?? ''));
  2776. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2777. $out[$sid]['quoted'][$cn] = true;
  2778. }
  2779. }
  2780. return $out;
  2781. }
  2782. /**
  2783. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  2784. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  2785. */
  2786. protected function mergeQuotedSupplierBuckets(array $buckets): array
  2787. {
  2788. $merged = ['all' => [], 'quoted' => []];
  2789. foreach ($buckets as $b) {
  2790. if (!is_array($b)) {
  2791. continue;
  2792. }
  2793. foreach ($b['all'] ?? [] as $cn => $_) {
  2794. $merged['all'][$cn] = true;
  2795. }
  2796. foreach ($b['quoted'] ?? [] as $cn => $_) {
  2797. $merged['quoted'][$cn] = true;
  2798. }
  2799. }
  2800. return $merged;
  2801. }
  2802. /**
  2803. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  2804. */
  2805. protected function formatQuotedSupplierLines(array $bucket): string
  2806. {
  2807. return ProcuremenFormat::quotedSupplierLines($bucket);
  2808. }
  2809. /**
  2810. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  2811. */
  2812. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  2813. {
  2814. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2815. $this->view->engine->layout(false);
  2816. try {
  2817. $bodyHtml = $this->view->fetch($view);
  2818. $this->view->assign('dialogBody', $bodyHtml);
  2819. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  2820. return $this->view->fetch('procuremen/dialog_lite_shell');
  2821. } finally {
  2822. if ($restoreLayout) {
  2823. $this->view->engine->layout($restoreLayout);
  2824. }
  2825. }
  2826. }
  2827. /**
  2828. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  2829. */
  2830. protected function resolveBundleSysRq(array $bundle): string
  2831. {
  2832. foreach ($bundle['pos'] ?? [] as $po) {
  2833. if (!is_array($po)) {
  2834. continue;
  2835. }
  2836. $sr = trim((string)($po['sys_rq'] ?? ''));
  2837. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  2838. return $sr;
  2839. }
  2840. }
  2841. return '';
  2842. }
  2843. /**
  2844. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  2845. */
  2846. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  2847. {
  2848. $raw = trim((string)$sysRq);
  2849. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  2850. return true;
  2851. }
  2852. $ts = strtotime(str_replace('T', ' ', $raw));
  2853. if ($ts === false || $ts <= 0) {
  2854. return true;
  2855. }
  2856. return time() >= $ts;
  2857. }
  2858. /**
  2859. * 开标前校验:必须已过报价截止时间
  2860. *
  2861. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2862. */
  2863. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  2864. {
  2865. $sysRq = $this->resolveBundleSysRq($bundle);
  2866. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  2867. $this->error('未到招标截止日期');
  2868. }
  2869. }
  2870. /**
  2871. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  2872. *
  2873. * @param array<string, mixed> $d
  2874. * @param string $deliveryYmd
  2875. */
  2876. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  2877. {
  2878. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  2879. return max(0, (int)$d['lead_days']);
  2880. }
  2881. if ($deliveryYmd === '') {
  2882. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  2883. }
  2884. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  2885. return null;
  2886. }
  2887. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2888. $t2 = strtotime($m[1] . ' 00:00:00');
  2889. if ($t1 === false || $t2 === false) {
  2890. return null;
  2891. }
  2892. return max(0, (int)round(($t2 - $t1) / 86400));
  2893. }
  2894. /**
  2895. * @param int|null $days
  2896. */
  2897. protected function formatProcuremenLeadDaysText($days): string
  2898. {
  2899. return ProcuremenFormat::leadDaysText($days);
  2900. }
  2901. /**
  2902. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2903. *
  2904. * @param array<string, mixed> $line
  2905. */
  2906. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2907. {
  2908. $amountFilled = !empty($line['amount_filled']);
  2909. $deliveryFilled = !empty($line['delivery_filled']);
  2910. $leadFilled = !empty($line['lead_days_filled']);
  2911. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2912. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2913. $line['amount_show'] = '';
  2914. if (array_key_exists('amount_text', $line)) {
  2915. $line['amount_text'] = $line['unit_price_text'];
  2916. }
  2917. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2918. $line['delivery_show'] = $deliveryText;
  2919. if (array_key_exists('delivery_text', $line)) {
  2920. $line['delivery_text'] = $deliveryText;
  2921. }
  2922. $line['delivery_ymd'] = '';
  2923. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2924. $line['lead_days_show'] = $leadText;
  2925. $line['lead_days_text'] = $leadText;
  2926. $line['lead_days'] = '';
  2927. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2928. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2929. $line['subtotal_num'] = null;
  2930. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2931. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2932. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2933. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2934. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2935. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2936. $line['amount_filled'] = false;
  2937. $line['delivery_filled'] = false;
  2938. $line['lead_days_filled'] = false;
  2939. $line['is_quoted'] = false;
  2940. if (array_key_exists('quote_label', $line)) {
  2941. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2942. }
  2943. }
  2944. protected function ensurePurchaseOrderBidOpenTable(): void
  2945. {
  2946. static $ready = false;
  2947. if ($ready) {
  2948. return;
  2949. }
  2950. $cacheKey = 'procuremen_bid_open_table_ok_v2';
  2951. try {
  2952. if (Cache::get($cacheKey)) {
  2953. $ready = true;
  2954. return;
  2955. }
  2956. } catch (\Throwable $e) {
  2957. }
  2958. try {
  2959. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2960. $ready = true;
  2961. try {
  2962. Cache::set($cacheKey, 1, 86400);
  2963. } catch (\Throwable $e) {
  2964. }
  2965. } catch (\Throwable $e) {
  2966. Db::execute(
  2967. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2968. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2969. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2970. `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号(多订单同批开标)',
  2971. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2972. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2973. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2974. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2975. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2976. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2977. `createtime` datetime DEFAULT NULL,
  2978. PRIMARY KEY (`id`),
  2979. UNIQUE KEY `uk_ccydh` (`ccydh`),
  2980. KEY `idx_order_batch_no` (`order_batch_no`)
  2981. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2982. );
  2983. $ready = true;
  2984. try {
  2985. Cache::set($cacheKey, 1, 86400);
  2986. } catch (\Throwable $e2) {
  2987. }
  2988. }
  2989. // 旧表兼容:补批次号列(不影响已有按订单号的开标记录)
  2990. try {
  2991. $cols = Db::query("SHOW COLUMNS FROM `purchase_order_bid_open` LIKE 'order_batch_no'");
  2992. if (!is_array($cols) || $cols === []) {
  2993. Db::execute(
  2994. "ALTER TABLE `purchase_order_bid_open` ADD COLUMN `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号(多订单同批开标)' AFTER `ccydh`"
  2995. );
  2996. }
  2997. } catch (\Throwable $e) {
  2998. // ignore
  2999. }
  3000. try {
  3001. $idx = Db::query("SHOW INDEX FROM `purchase_order_bid_open` WHERE Key_name = 'idx_order_batch_no'");
  3002. if (!is_array($idx) || $idx === []) {
  3003. Db::execute('ALTER TABLE `purchase_order_bid_open` ADD INDEX `idx_order_batch_no` (`order_batch_no`)');
  3004. }
  3005. } catch (\Throwable $e) {
  3006. // ignore
  3007. }
  3008. }
  3009. /**
  3010. * 列表/合并行订单号可能为「A、B」拼接,拆成单个订单号
  3011. *
  3012. * @param mixed $raw
  3013. * @return array<int, string>
  3014. */
  3015. protected function expandProcuremenCcydhTokens($raw): array
  3016. {
  3017. $s = trim((string)$raw);
  3018. if ($s === '') {
  3019. return [];
  3020. }
  3021. $parts = preg_split('/[、;;,\n\r]+/u', $s);
  3022. if (!is_array($parts)) {
  3023. return [$s];
  3024. }
  3025. $out = [];
  3026. foreach ($parts as $p) {
  3027. $p = trim((string)$p);
  3028. if ($p !== '' && !in_array($p, $out, true)) {
  3029. $out[] = $p;
  3030. }
  3031. }
  3032. return $out;
  3033. }
  3034. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  3035. {
  3036. $ccydh = trim($ccydh);
  3037. if ($ccydh === '') {
  3038. return false;
  3039. }
  3040. $this->ensurePurchaseOrderBidOpenTable();
  3041. try {
  3042. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3043. return is_array($row);
  3044. } catch (\Throwable $e) {
  3045. return false;
  3046. }
  3047. }
  3048. protected function isProcuremenBidOpenVerifiedByBatchNo(string $batchNo): bool
  3049. {
  3050. $batchNo = trim($batchNo);
  3051. if ($batchNo === '') {
  3052. return false;
  3053. }
  3054. $this->ensurePurchaseOrderBidOpenTable();
  3055. try {
  3056. $row = Db::table('purchase_order_bid_open')
  3057. ->where('order_batch_no', $batchNo)
  3058. ->find();
  3059. return is_array($row);
  3060. } catch (\Throwable $e) {
  3061. return false;
  3062. }
  3063. }
  3064. /**
  3065. * 批量查询订单是否已开标验证(入参支持「A、B」拼接)
  3066. *
  3067. * @param array<int, string> $ccydhs
  3068. * @return array<string, bool> ccydh => true
  3069. */
  3070. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  3071. {
  3072. $set = [];
  3073. $list = [];
  3074. foreach ($ccydhs as $c) {
  3075. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  3076. $list[$one] = true;
  3077. }
  3078. }
  3079. if ($list === []) {
  3080. return $set;
  3081. }
  3082. $this->ensurePurchaseOrderBidOpenTable();
  3083. try {
  3084. $rows = Db::table('purchase_order_bid_open')
  3085. ->where('ccydh', 'in', array_keys($list))
  3086. ->field('ccydh')
  3087. ->select();
  3088. foreach ($rows as $row) {
  3089. if (!is_array($row)) {
  3090. continue;
  3091. }
  3092. $c = trim((string)($row['ccydh'] ?? ''));
  3093. if ($c !== '') {
  3094. $set[$c] = true;
  3095. }
  3096. }
  3097. } catch (\Throwable $e) {
  3098. return [];
  3099. }
  3100. return $set;
  3101. }
  3102. /**
  3103. * 批量查询批次是否已开标
  3104. *
  3105. * @param array<int, string> $batchNos
  3106. * @return array<string, bool>
  3107. */
  3108. protected function loadProcuremenBidOpenVerifiedBatchSet(array $batchNos): array
  3109. {
  3110. $set = [];
  3111. $list = [];
  3112. foreach ($batchNos as $b) {
  3113. $b = trim((string)$b);
  3114. if ($b !== '') {
  3115. $list[$b] = true;
  3116. }
  3117. }
  3118. if ($list === []) {
  3119. return $set;
  3120. }
  3121. $this->ensurePurchaseOrderBidOpenTable();
  3122. try {
  3123. $rows = Db::table('purchase_order_bid_open')
  3124. ->where('order_batch_no', 'in', array_keys($list))
  3125. ->field('order_batch_no')
  3126. ->select();
  3127. foreach ($rows as $row) {
  3128. if (!is_array($row)) {
  3129. continue;
  3130. }
  3131. $b = trim((string)($row['order_batch_no'] ?? ''));
  3132. if ($b !== '') {
  3133. $set[$b] = true;
  3134. }
  3135. }
  3136. } catch (\Throwable $e) {
  3137. return [];
  3138. }
  3139. return $set;
  3140. }
  3141. /**
  3142. * 批量查询订单是否已指定供应商(免开标;入参支持「A、B」拼接)
  3143. * 仅统计未软删除行(mod_rq 空)
  3144. *
  3145. * @param array<int, string> $ccydhs
  3146. * @return array<string, bool> ccydh => true
  3147. */
  3148. protected function loadProcuremenManualPickedCcydhSet(array $ccydhs): array
  3149. {
  3150. $set = [];
  3151. $list = [];
  3152. foreach ($ccydhs as $c) {
  3153. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  3154. $list[$one] = true;
  3155. }
  3156. }
  3157. if ($list === []) {
  3158. return $set;
  3159. }
  3160. $this->ensurePurchaseOrderManualPickColumns();
  3161. try {
  3162. $q = Db::table('purchase_order')
  3163. ->where('CCYDH', 'in', array_keys($list))
  3164. ->where('manual_pick', 1)
  3165. ->whereRaw("(mod_rq IS NULL OR mod_rq = '' OR mod_rq LIKE '0000-00-00%')")
  3166. ->field('CCYDH');
  3167. $rows = $q->select();
  3168. foreach ($rows as $row) {
  3169. if (!is_array($row)) {
  3170. continue;
  3171. }
  3172. $c = trim((string)($row['CCYDH'] ?? ''));
  3173. if ($c !== '') {
  3174. $set[$c] = true;
  3175. }
  3176. }
  3177. } catch (\Throwable $e) {
  3178. return [];
  3179. }
  3180. return $set;
  3181. }
  3182. /**
  3183. * 清除开标验证记录(按订单号 + 批次号)
  3184. *
  3185. * @param array<int, string> $ccydhs
  3186. * @param array<int, string> $batchNos
  3187. */
  3188. protected function clearProcuremenBidOpenRecords(array $ccydhs = [], array $batchNos = []): void
  3189. {
  3190. $ccydhList = [];
  3191. foreach ($ccydhs as $c) {
  3192. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  3193. $ccydhList[$one] = true;
  3194. }
  3195. }
  3196. $batchList = [];
  3197. foreach ($batchNos as $b) {
  3198. $b = trim((string)$b);
  3199. if ($b !== '') {
  3200. $batchList[$b] = true;
  3201. }
  3202. }
  3203. if ($ccydhList === [] && $batchList === []) {
  3204. return;
  3205. }
  3206. try {
  3207. $this->ensurePurchaseOrderBidOpenTable();
  3208. if ($ccydhList !== []) {
  3209. Db::table('purchase_order_bid_open')->where('ccydh', 'in', array_keys($ccydhList))->delete();
  3210. }
  3211. if ($batchList !== []) {
  3212. Db::table('purchase_order_bid_open')->where('order_batch_no', 'in', array_keys($batchList))->delete();
  3213. }
  3214. } catch (\Throwable $e) {
  3215. // ignore
  3216. }
  3217. }
  3218. /**
  3219. * 新下发/重新下发:同订单号+同工序下「其它有明确批次号」的未完结主单记 mod_rq 软删除。
  3220. * 不处理:本批保留行、无批次号旧数据、已完结单(避免误伤生产并行工序)。
  3221. *
  3222. * @param array<int, string> $ccydhs
  3223. * @param array<int, int|string> $keepScydgyIds 保留的工序 ID(本批)
  3224. * @param string $keepBatchNo 本批批次号(同批其它工序行也保留)
  3225. * @param array<int, string> $cgySet 本批工序名称集合(防止同订单不同工序被误删)
  3226. * @return array<int, true> 实际被软删的 scydgy_id 集合
  3227. */
  3228. protected function softDeleteOtherBatchPurchaseOrders(array $ccydhs, array $keepScydgyIds = [], string $keepBatchNo = '', array $cgySet = []): array
  3229. {
  3230. $ccydhList = [];
  3231. foreach ($ccydhs as $c) {
  3232. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  3233. $ccydhList[$one] = true;
  3234. }
  3235. }
  3236. $keepBatchNo = trim($keepBatchNo);
  3237. // 无本批批次号时不做软删,避免把同订单其它有效工序一并清掉
  3238. if ($ccydhList === [] || $keepBatchNo === '') {
  3239. return [];
  3240. }
  3241. $keepSid = [];
  3242. foreach ($keepScydgyIds as $sid) {
  3243. $sid = (int)$sid;
  3244. if ($this->isValidScydgyRowId($sid)) {
  3245. $keepSid[$sid] = true;
  3246. }
  3247. }
  3248. $now = date('Y-m-d H:i:s');
  3249. $bnEsc = str_replace(["\\", "'"], ["\\\\", "''"], $keepBatchNo);
  3250. try {
  3251. $q = Db::table('purchase_order')
  3252. ->where('CCYDH', 'in', array_keys($ccydhList))
  3253. ->whereRaw("(mod_rq IS NULL OR mod_rq = '' OR mod_rq LIKE '0000-00-00%')")
  3254. // 仅软删「其它非空批次」;空批次号旧数据留给展示层按批次隔离
  3255. ->whereRaw("TRIM(CAST(order_batch_no AS CHAR(64))) <> ''")
  3256. ->whereRaw("order_batch_no <> '{$bnEsc}'")
  3257. // 已完结不软删
  3258. ->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  3259. // 按工序名称隔离,防止同订单不同工序被误删
  3260. if ($cgySet !== []) {
  3261. $cgyEscList = [];
  3262. foreach ($cgySet as $cgy) {
  3263. $cgyEsc = str_replace(["\\", "'"], ["\\\\", "''"], trim((string)$cgy));
  3264. if ($cgyEsc !== '') {
  3265. $cgyEscList[] = "'" . $cgyEsc . "'";
  3266. }
  3267. }
  3268. if ($cgyEscList !== []) {
  3269. $q->whereRaw("CGYMC IN (" . implode(',', $cgyEscList) . ")");
  3270. }
  3271. }
  3272. if ($keepSid !== []) {
  3273. $q->where('scydgy_id', 'not in', array_keys($keepSid));
  3274. }
  3275. $q->update([
  3276. 'mod_rq' => $now,
  3277. 'manual_pick' => 0,
  3278. 'manual_pick_reason' => '',
  3279. ]);
  3280. // 返回本次实际被软删的 scydgy_id,供调用方废弃明细用
  3281. return Db::table('purchase_order')
  3282. ->where('CCYDH', 'in', array_keys($ccydhList))
  3283. ->whereRaw("(mod_rq IS NULL OR mod_rq = '' OR mod_rq LIKE '0000-00-00%')")
  3284. ->whereRaw("TRIM(CAST(order_batch_no AS CHAR(64))) <> ''")
  3285. ->whereRaw("order_batch_no <> '{$bnEsc}'")
  3286. ->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')')
  3287. ->where('mod_rq', $now)
  3288. ->column('scydgy_id');
  3289. } catch (\Throwable $e) {
  3290. Log::write('softDeleteOtherBatchPurchaseOrders: ' . $e->getMessage(), 'error');
  3291. return [];
  3292. }
  3293. }
  3294. /**
  3295. * 重新下发/新下发:清掉按订单号落库的供应商评分,避免旧批 0 分/旧排名串到新批
  3296. *
  3297. * @param array<int, string> $ccydhs
  3298. */
  3299. protected function clearProcuremenSupplierScoresForCcydhs(array $ccydhs): void
  3300. {
  3301. $list = [];
  3302. foreach ($ccydhs as $c) {
  3303. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  3304. $list[$one] = true;
  3305. }
  3306. }
  3307. if ($list === []) {
  3308. return;
  3309. }
  3310. try {
  3311. Db::table('supplier_service_score')->where('ccydh', 'in', array_keys($list))->delete();
  3312. } catch (\Throwable $e) {
  3313. Log::write('clearProcuremenSupplierScoresForCcydhs: ' . $e->getMessage(), 'error');
  3314. }
  3315. }
  3316. /**
  3317. * 列表行开标状态:有批次号时只认本批次开标/本行指定,避免同订单号旧批串读
  3318. *
  3319. * @param array<string, mixed> $rw
  3320. * @param array<string, bool> $bidOpenSet
  3321. * @param array<string, bool> $manualPickSet
  3322. * @param array<string, bool> $bidOpenBatchSet
  3323. * @return array{verified:bool,manual:bool,text:string}
  3324. */
  3325. protected function resolveProcuremenListBidOpenState(
  3326. array $rw,
  3327. array $bidOpenSet,
  3328. array $manualPickSet,
  3329. array $bidOpenBatchSet = []
  3330. ): array {
  3331. $batchNo = $this->resolveProcuremenOrderBatchNo($rw);
  3332. if ($batchNo === '' && !empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3333. foreach ($rw['_order_merge_rows'] as $mr) {
  3334. if (!is_array($mr)) {
  3335. continue;
  3336. }
  3337. $batchNo = $this->resolveProcuremenOrderBatchNo($mr);
  3338. if ($batchNo !== '') {
  3339. break;
  3340. }
  3341. }
  3342. }
  3343. $manual = ((int)($rw['manual_pick'] ?? 0) === 1);
  3344. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3345. foreach ($rw['_order_merge_rows'] as $mr) {
  3346. if (!is_array($mr)) {
  3347. continue;
  3348. }
  3349. // 合并行仅认同一批次(无批次号时退回同订单兼容)
  3350. if ($batchNo !== '') {
  3351. $mrBatch = $this->resolveProcuremenOrderBatchNo($mr);
  3352. if ($mrBatch !== '' && $mrBatch !== $batchNo) {
  3353. continue;
  3354. }
  3355. }
  3356. if ((int)($mr['manual_pick'] ?? 0) === 1) {
  3357. $manual = true;
  3358. }
  3359. }
  3360. }
  3361. // 收集本行/合并行订单号,供开标记录与自选集合兜底(自选=免开标,等同已开标可继续确认)
  3362. $ccydhTokens = $this->expandProcuremenCcydhTokens($rw['CCYDH'] ?? '');
  3363. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3364. foreach ($rw['_order_merge_rows'] as $mr) {
  3365. if (!is_array($mr)) {
  3366. continue;
  3367. }
  3368. if ($batchNo !== '') {
  3369. $mrBatch = $this->resolveProcuremenOrderBatchNo($mr);
  3370. if ($mrBatch !== '' && $mrBatch !== $batchNo) {
  3371. continue;
  3372. }
  3373. }
  3374. foreach ($this->expandProcuremenCcydhTokens($mr['CCYDH'] ?? '') as $one) {
  3375. if (!in_array($one, $ccydhTokens, true)) {
  3376. $ccydhTokens[] = $one;
  3377. }
  3378. }
  3379. }
  3380. }
  3381. if ($batchNo !== '') {
  3382. // 有正式批次号:开标只看本批
  3383. $verified = isset($bidOpenBatchSet[$batchNo]);
  3384. // 自选兜底:本行字段漏带时,仍可用有效主单上的自选标记(旧批已软删,不会串读)
  3385. if (!$manual) {
  3386. foreach ($ccydhTokens as $c) {
  3387. if (isset($manualPickSet[$c])) {
  3388. $manual = true;
  3389. break;
  3390. }
  3391. }
  3392. }
  3393. } else {
  3394. // 旧数据无批次号:兼容按订单号开标/指定
  3395. $verified = false;
  3396. foreach ($ccydhTokens as $c) {
  3397. if (isset($bidOpenSet[$c])) {
  3398. $verified = true;
  3399. }
  3400. if (isset($manualPickSet[$c])) {
  3401. $manual = true;
  3402. }
  3403. }
  3404. }
  3405. if ($verified) {
  3406. $text = '已开标';
  3407. } elseif ($manual) {
  3408. $text = '已指定供应商';
  3409. } else {
  3410. $text = '待开标';
  3411. }
  3412. return ['verified' => $verified, 'manual' => $manual, 'text' => $text];
  3413. }
  3414. /**
  3415. * 确认供应商列表:按开标状态筛选(已开标 / 已指定供应商 / 待开标)
  3416. *
  3417. * @param array<int, array<string, mixed>> $pool
  3418. * @return array<int, array<string, mixed>>
  3419. */
  3420. protected function filterProcuremenPoolByBidOpenStatus(array $pool, string $status): array
  3421. {
  3422. $status = trim($status);
  3423. if ($status === '' || !in_array($status, ['待开标', '已开标', '已指定供应商'], true)) {
  3424. return $pool;
  3425. }
  3426. $ccydhList = [];
  3427. $batchList = [];
  3428. foreach ($pool as $rw) {
  3429. if (!is_array($rw)) {
  3430. continue;
  3431. }
  3432. $c = trim((string)($rw['CCYDH'] ?? ''));
  3433. if ($c !== '') {
  3434. $ccydhList[] = $c;
  3435. }
  3436. $b = $this->resolveProcuremenOrderBatchNo($rw);
  3437. if ($b !== '') {
  3438. $batchList[] = $b;
  3439. }
  3440. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3441. foreach ($rw['_order_merge_rows'] as $mr) {
  3442. if (!is_array($mr)) {
  3443. continue;
  3444. }
  3445. $cm = trim((string)($mr['CCYDH'] ?? ''));
  3446. if ($cm !== '') {
  3447. $ccydhList[] = $cm;
  3448. }
  3449. $bm = $this->resolveProcuremenOrderBatchNo($mr);
  3450. if ($bm !== '') {
  3451. $batchList[] = $bm;
  3452. }
  3453. }
  3454. }
  3455. }
  3456. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  3457. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  3458. $bidOpenBatchSet = $this->loadProcuremenBidOpenVerifiedBatchSet($batchList);
  3459. $out = [];
  3460. foreach ($pool as $rw) {
  3461. if (!is_array($rw)) {
  3462. continue;
  3463. }
  3464. $state = $this->resolveProcuremenListBidOpenState($rw, $bidOpenSet, $manualPickSet, $bidOpenBatchSet);
  3465. if (($state['text'] ?? '') === $status) {
  3466. $out[] = $rw;
  3467. }
  3468. }
  3469. return $out;
  3470. }
  3471. /**
  3472. * 按订单状态筛选(待确认 / 已驳回 / 待审核 / 已审核)
  3473. *
  3474. * @param array<int, array<string, mixed>> $pool
  3475. * @return array<int, array<string, mixed>>
  3476. */
  3477. protected function filterProcuremenPoolByOrderStatus(array $pool, string $status): array
  3478. {
  3479. $status = trim($status);
  3480. if ($status === '' || !in_array($status, ['待确认', '已驳回', '待审核', '已审核'], true)) {
  3481. return $pool;
  3482. }
  3483. $out = [];
  3484. foreach ($pool as $rw) {
  3485. if (!is_array($rw)) {
  3486. continue;
  3487. }
  3488. $label = trim((string)($rw['order_status_text'] ?? ''));
  3489. if ($label === '') {
  3490. $label = ProcuremenStatus::orderStatusLabelForList($rw['wflow_status'] ?? '');
  3491. }
  3492. if ($label === $status) {
  3493. $out[] = $rw;
  3494. }
  3495. }
  3496. return $out;
  3497. }
  3498. /**
  3499. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  3500. *
  3501. * @param array<string, mixed> $group
  3502. */
  3503. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  3504. {
  3505. if ($quoteVisible) {
  3506. $group['remark_quote_pending'] = 0;
  3507. return;
  3508. }
  3509. $group['remark'] = '';
  3510. $group['remark_quote_pending'] = 0;
  3511. }
  3512. /**
  3513. * 下发订单备注 MBZ(印件规格),不是供应商填写
  3514. *
  3515. * @param array{pos?:array, merge_rows?:array} $bundle
  3516. */
  3517. protected function resolveBundleOrderMbz(array $bundle): string
  3518. {
  3519. foreach (['pos', 'merge_rows'] as $key) {
  3520. foreach ($bundle[$key] ?? [] as $row) {
  3521. if (!is_array($row)) {
  3522. continue;
  3523. }
  3524. $mbz = trim((string)($row['MBZ'] ?? $row['mbz'] ?? ''));
  3525. if ($mbz !== '') {
  3526. return $mbz;
  3527. }
  3528. }
  3529. }
  3530. return '';
  3531. }
  3532. /**
  3533. * 供应商自己填的备注;与订单 MBZ 相同视为未填(历史误把规格写入明细)
  3534. */
  3535. protected function resolveSupplierOwnRemark($detailRemark, $orderMbz = ''): string
  3536. {
  3537. $own = trim((string)$detailRemark);
  3538. $mbz = trim((string)$orderMbz);
  3539. if ($own === '' || ($mbz !== '' && $own === $mbz)) {
  3540. return '';
  3541. }
  3542. return $own;
  3543. }
  3544. /**
  3545. * 供应商备注展示:仅自己填写的;有工序行时始终占一行「投标备注」(空也显示标签)
  3546. *
  3547. * @param array<string, mixed> $group
  3548. */
  3549. protected function finalizeSupplierRemarkDisplay(array &$group, string $orderMbz, bool $quoteVisible): void
  3550. {
  3551. $group['remark'] = $this->resolveSupplierOwnRemark($group['remark'] ?? '', $orderMbz);
  3552. $this->maskSupplierRemarkBeforeBidOpen($group, $quoteVisible);
  3553. $lineCount = (int)($group['line_count'] ?? 0);
  3554. if ($lineCount <= 0) {
  3555. $lines = $group['lines'] ?? $group['pick_lines'] ?? [];
  3556. $lineCount = is_array($lines) ? count($lines) : 0;
  3557. }
  3558. // 与手机端一致:有供应商工序行就显示投标备注行,内容可为空
  3559. $group['has_remark'] = $lineCount > 0;
  3560. $extra = (!empty($group['has_remark']) ? 1 : 0) + (!empty($group['has_total']) ? 1 : 0);
  3561. $group['display_rowspan'] = $lineCount > 0 ? ($lineCount + $extra) : 0;
  3562. }
  3563. /**
  3564. * @param array{ccydh?:string,pos?:array,order_batch_no?:string} $bundle
  3565. */
  3566. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  3567. {
  3568. $batchNo = $this->resolveBundleOrderBatchNo($bundle);
  3569. // 有批次号:只认本批开标,避免同订单号历史开标串到新批
  3570. if ($batchNo !== '') {
  3571. return $this->isProcuremenBidOpenVerifiedByBatchNo($batchNo);
  3572. }
  3573. $list = [];
  3574. foreach ($bundle['pos'] ?? [] as $po) {
  3575. if (!is_array($po)) {
  3576. continue;
  3577. }
  3578. foreach ($this->expandProcuremenCcydhTokens($po['CCYDH'] ?? '') as $dh) {
  3579. $list[$dh] = true;
  3580. }
  3581. }
  3582. $primary = trim((string)($bundle['ccydh'] ?? ''));
  3583. foreach ($this->expandProcuremenCcydhTokens($primary) as $dh) {
  3584. $list[$dh] = true;
  3585. }
  3586. if ($list === []) {
  3587. return false;
  3588. }
  3589. // 旧数据无批次号:全部订单号都有开标记录才算已开标
  3590. foreach (array_keys($list) as $ccydh) {
  3591. if (!$this->isProcuremenBidOpenVerified($ccydh)) {
  3592. return false;
  3593. }
  3594. }
  3595. return true;
  3596. }
  3597. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  3598. {
  3599. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  3600. return true;
  3601. }
  3602. return $this->isProcuremenManualPickedForBundle($bundle);
  3603. }
  3604. /**
  3605. * 确保 purchase_order 自选供应商字段
  3606. */
  3607. protected function ensurePurchaseOrderManualPickColumns(): void
  3608. {
  3609. static $done = false;
  3610. if ($done) {
  3611. return;
  3612. }
  3613. $done = true;
  3614. $adds = [
  3615. 'manual_pick' => "ADD COLUMN `manual_pick` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=自选供应商(免开标)' AFTER `pick_company_name`",
  3616. 'manual_pick_reason' => "ADD COLUMN `manual_pick_reason` varchar(500) NOT NULL DEFAULT '' COMMENT '自选供应商选择说明' AFTER `manual_pick`",
  3617. ];
  3618. foreach ($adds as $col => $ddl) {
  3619. try {
  3620. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  3621. if (!is_array($cols) || $cols === []) {
  3622. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  3623. }
  3624. } catch (\Throwable $e) {
  3625. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  3626. }
  3627. }
  3628. }
  3629. /**
  3630. * 是否已自选供应商(免开标查看报价)——仅看本 bundle 行,不按订单号串旧批
  3631. *
  3632. * @param array{pos?:array} $bundle
  3633. */
  3634. protected function isProcuremenManualPickedForBundle(array $bundle): bool
  3635. {
  3636. $this->ensurePurchaseOrderManualPickColumns();
  3637. foreach ($bundle['pos'] ?? [] as $poRow) {
  3638. if (!is_array($poRow)) {
  3639. continue;
  3640. }
  3641. if ((int)($poRow['manual_pick'] ?? 0) === 1) {
  3642. return true;
  3643. }
  3644. }
  3645. return false;
  3646. }
  3647. /**
  3648. * @param array{pos?:array} $bundle
  3649. * @return array{company:string,reason:string}
  3650. */
  3651. protected function resolveProcuremenManualPickInfo(array $bundle): array
  3652. {
  3653. $this->ensurePurchaseOrderManualPickColumns();
  3654. foreach ($bundle['pos'] ?? [] as $poRow) {
  3655. if (!is_array($poRow)) {
  3656. continue;
  3657. }
  3658. if ((int)($poRow['manual_pick'] ?? 0) !== 1) {
  3659. continue;
  3660. }
  3661. $cn = trim((string)($poRow['pick_company_name'] ?? ''));
  3662. $reason = trim((string)($poRow['manual_pick_reason'] ?? ''));
  3663. return ['company' => $cn, 'reason' => $reason];
  3664. }
  3665. return ['company' => '', 'reason' => ''];
  3666. }
  3667. protected function loadBidOpenAdminUser(int $adminId): ?array
  3668. {
  3669. if ($adminId <= 0) {
  3670. return null;
  3671. }
  3672. try {
  3673. $row = Db::name('admin')->where('id', $adminId)->find();
  3674. } catch (\Throwable $e) {
  3675. return null;
  3676. }
  3677. if (!is_array($row)) {
  3678. return null;
  3679. }
  3680. $status = strtolower(trim((string)($row['status'] ?? '')));
  3681. if ($status !== '' && $status !== 'normal') {
  3682. return null;
  3683. }
  3684. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  3685. return null;
  3686. }
  3687. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  3688. if (!preg_match('/^1\d{10}$/', $phone)) {
  3689. return null;
  3690. }
  3691. $name = trim((string)($row['nickname'] ?? ''));
  3692. if ($name === '') {
  3693. $name = trim((string)($row['username'] ?? ''));
  3694. }
  3695. return [
  3696. 'id' => (int)$row['id'],
  3697. 'username' => trim((string)($row['username'] ?? '')),
  3698. 'nickname' => $name,
  3699. 'mobile' => $phone,
  3700. ];
  3701. }
  3702. /**
  3703. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  3704. */
  3705. protected function bidOpenVerifierAuthGroupRootId(): int
  3706. {
  3707. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  3708. return $id > 0 ? $id : 10;
  3709. }
  3710. /**
  3711. * @return int[]
  3712. */
  3713. protected function loadBidOpenVerifierAuthGroupIds(): array
  3714. {
  3715. static $memo = [];
  3716. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  3717. if (isset($memo[$rootId])) {
  3718. return $memo[$rootId];
  3719. }
  3720. try {
  3721. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  3722. } catch (\Throwable $e) {
  3723. $memo[$rootId] = [$rootId];
  3724. return $memo[$rootId];
  3725. }
  3726. if (!is_array($groups) || $groups === []) {
  3727. $memo[$rootId] = [$rootId];
  3728. return $memo[$rootId];
  3729. }
  3730. $groupList = [];
  3731. foreach ($groups as $g) {
  3732. if (is_array($g)) {
  3733. $groupList[] = $g;
  3734. }
  3735. }
  3736. if ($groupList === []) {
  3737. $memo[$rootId] = [$rootId];
  3738. return $memo[$rootId];
  3739. }
  3740. $tree = \fast\Tree::instance();
  3741. $tree->init($groupList);
  3742. $ids = $tree->getChildrenIds($rootId, true);
  3743. if (!is_array($ids) || $ids === []) {
  3744. $memo[$rootId] = [$rootId];
  3745. return $memo[$rootId];
  3746. }
  3747. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  3748. return $memo[$rootId];
  3749. }
  3750. protected function isBidOpenVerifierAdmin(int $adminId): bool
  3751. {
  3752. if ($adminId <= 0) {
  3753. return false;
  3754. }
  3755. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3756. if ($groupIds === []) {
  3757. return false;
  3758. }
  3759. try {
  3760. return (bool)Db::name('auth_group_access')
  3761. ->where('uid', $adminId)
  3762. ->where('group_id', 'in', $groupIds)
  3763. ->count();
  3764. } catch (\Throwable $e) {
  3765. return false;
  3766. }
  3767. }
  3768. /**
  3769. * @return array<int, array<string, mixed>>
  3770. */
  3771. protected function listBidOpenVerifierCandidates(): array
  3772. {
  3773. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3774. if ($groupIds === []) {
  3775. return [];
  3776. }
  3777. try {
  3778. $adminIds = Db::name('auth_group_access')
  3779. ->where('group_id', 'in', $groupIds)
  3780. ->column('uid');
  3781. } catch (\Throwable $e) {
  3782. $adminIds = [];
  3783. }
  3784. $adminIds = is_array($adminIds)
  3785. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  3786. : [];
  3787. if ($adminIds === []) {
  3788. return [];
  3789. }
  3790. try {
  3791. $rows = Db::name('admin')
  3792. ->where('status', 'normal')
  3793. ->where('id', 'in', $adminIds)
  3794. ->where('mobile', '<>', '')
  3795. ->order('id', 'asc')
  3796. ->select();
  3797. } catch (\Throwable $e) {
  3798. return [];
  3799. }
  3800. if (!is_array($rows)) {
  3801. return [];
  3802. }
  3803. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  3804. $out = [];
  3805. foreach ($rows as $row) {
  3806. if (!is_array($row)) {
  3807. continue;
  3808. }
  3809. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  3810. if ($one === null) {
  3811. continue;
  3812. }
  3813. $out[] = [
  3814. 'id' => $one['id'],
  3815. 'username' => $one['username'],
  3816. 'nickname' => $one['nickname'],
  3817. 'group_name' => $groupNameMap[$one['id']] ?? '',
  3818. 'mobile' => mask_phone($one['mobile']),
  3819. 'mobile_plain' => (string)$one['mobile'],
  3820. ];
  3821. }
  3822. return $out;
  3823. }
  3824. /**
  3825. * @param int[] $adminIds
  3826. * @return array<int, string>
  3827. */
  3828. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  3829. {
  3830. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  3831. if ($adminIds === []) {
  3832. return [];
  3833. }
  3834. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3835. try {
  3836. $rows = Db::name('auth_group_access')
  3837. ->alias('aga')
  3838. ->join('auth_group ag', 'aga.group_id = ag.id')
  3839. ->where('aga.uid', 'in', $adminIds)
  3840. ->where('aga.group_id', 'in', $groupIds)
  3841. ->field('aga.uid,ag.name')
  3842. ->order('aga.uid', 'asc')
  3843. ->order('aga.group_id', 'asc')
  3844. ->select();
  3845. } catch (\Throwable $e) {
  3846. return [];
  3847. }
  3848. if (!is_array($rows)) {
  3849. return [];
  3850. }
  3851. $out = [];
  3852. foreach ($rows as $row) {
  3853. if (!is_array($row)) {
  3854. continue;
  3855. }
  3856. $uid = (int)($row['uid'] ?? 0);
  3857. $name = trim((string)($row['name'] ?? ''));
  3858. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  3859. continue;
  3860. }
  3861. $out[$uid] = $name;
  3862. }
  3863. return $out;
  3864. }
  3865. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  3866. {
  3867. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  3868. }
  3869. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  3870. {
  3871. return 'procuremen_bidopen_wait_' . $adminId;
  3872. }
  3873. protected function renderBidOpenVerifySms(string $code): string
  3874. {
  3875. $tpl = '';
  3876. try {
  3877. $row = $this->loadNotifyTemplateRow('bid_open');
  3878. if (is_array($row)) {
  3879. $tpl = trim((string)($row['content'] ?? ''));
  3880. }
  3881. } catch (\Throwable $e) {
  3882. $tpl = '';
  3883. }
  3884. if ($tpl === '') {
  3885. $tpl = '【可集达】您的短信验证码是{code}';
  3886. }
  3887. return str_replace('{code}', $code, $tpl);
  3888. }
  3889. protected function sendBidOpenVerifySms(string $phone, string $code): void
  3890. {
  3891. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  3892. }
  3893. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  3894. {
  3895. $code = trim($code);
  3896. if (!preg_match('/^\d{6}$/', $code)) {
  3897. return false;
  3898. }
  3899. $mock = Config::get('mproc.mock_sms_code');
  3900. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3901. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3902. return true;
  3903. }
  3904. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3905. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3906. return false;
  3907. }
  3908. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3909. return true;
  3910. }
  3911. /**
  3912. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3913. */
  3914. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  3915. {
  3916. $ccydhList = [];
  3917. $batchNo = $this->resolveBundleOrderBatchNo($bundle);
  3918. foreach ($bundle['pos'] ?? [] as $poRow) {
  3919. if (!is_array($poRow)) {
  3920. continue;
  3921. }
  3922. foreach ($this->expandProcuremenCcydhTokens($poRow['CCYDH'] ?? '') as $dh) {
  3923. $ccydhList[$dh] = true;
  3924. }
  3925. if ($batchNo === '') {
  3926. $batchNo = $this->resolveProcuremenOrderBatchNo($poRow);
  3927. }
  3928. }
  3929. $primaryCcydh = trim((string)($bundle['ccydh'] ?? ''));
  3930. foreach ($this->expandProcuremenCcydhTokens($primaryCcydh) as $dh) {
  3931. $ccydhList[$dh] = true;
  3932. }
  3933. if ($ccydhList === []) {
  3934. throw new \InvalidArgumentException('订单号无效');
  3935. }
  3936. $this->ensurePurchaseOrderBidOpenTable();
  3937. list($operatorId, $operatorName) = $this->GetUseName();
  3938. $now = date('Y-m-d H:i:s');
  3939. $payloadBase = [
  3940. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  3941. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  3942. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  3943. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  3944. 'operator_id' => (int)$operatorId,
  3945. 'operator_name' => trim((string)$operatorName),
  3946. 'createtime' => $now,
  3947. 'order_batch_no' => $batchNo,
  3948. ];
  3949. foreach (array_keys($ccydhList) as $ccydh) {
  3950. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3951. $payload = $payloadBase;
  3952. $payload['ccydh'] = $ccydh;
  3953. if (is_array($exists)) {
  3954. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  3955. } else {
  3956. Db::table('purchase_order_bid_open')->insert($payload);
  3957. }
  3958. }
  3959. $name1 = $payloadBase['verifier1_name'] !== '' ? $payloadBase['verifier1_name'] : ('ID' . $payloadBase['verifier1_id']);
  3960. $name2 = $payloadBase['verifier2_name'] !== '' ? $payloadBase['verifier2_name'] : ('ID' . $payloadBase['verifier2_id']);
  3961. $labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
  3962. (int)$payloadBase['verifier1_id'],
  3963. (int)$payloadBase['verifier2_id'],
  3964. ]);
  3965. if (isset($labelMap[(int)$payloadBase['verifier1_id']]) && (int)$payloadBase['verifier1_id'] > 0) {
  3966. $name1 = $labelMap[(int)$payloadBase['verifier1_id']];
  3967. }
  3968. if (isset($labelMap[(int)$payloadBase['verifier2_id']]) && (int)$payloadBase['verifier2_id'] > 0) {
  3969. $name2 = $labelMap[(int)$payloadBase['verifier2_id']];
  3970. }
  3971. $logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
  3972. $seenSid = [];
  3973. foreach ($bundle['pos'] ?? [] as $poRow) {
  3974. if (!is_array($poRow)) {
  3975. continue;
  3976. }
  3977. $sid = (int)($poRow['scydgy_id'] ?? 0);
  3978. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  3979. continue;
  3980. }
  3981. $seenSid[$sid] = true;
  3982. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  3983. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  3984. }
  3985. if ($seenSid === []) {
  3986. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  3987. if ($this->isValidScydgyRowId($anchor)) {
  3988. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  3989. }
  3990. }
  3991. // 开标通过后:按订单号分别计算并写入供应商服务评分(避免多订单串分)
  3992. try {
  3993. $ym = date('Y-m', strtotime($now) ?: time());
  3994. $this->saveProcuremenSupplierScoresForBundle($bundle, $ym);
  3995. } catch (\Throwable $e) {
  3996. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  3997. }
  3998. }
  3999. /**
  4000. * 按 bundle 内各订单分别计分落库(单订单价格分);一批多单展示时再按数量×限价比例跨单加权
  4001. *
  4002. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  4003. */
  4004. protected function saveProcuremenSupplierScoresForBundle(array $bundle, ?string $ym = null): void
  4005. {
  4006. $batchNo = $this->resolveBundleOrderBatchNo($bundle);
  4007. $posByCcydh = [];
  4008. foreach ($bundle['pos'] ?? [] as $po) {
  4009. if (!is_array($po)) {
  4010. continue;
  4011. }
  4012. $dh = trim((string)($po['CCYDH'] ?? ''));
  4013. if ($dh === '') {
  4014. continue;
  4015. }
  4016. if (!isset($posByCcydh[$dh])) {
  4017. $posByCcydh[$dh] = [];
  4018. }
  4019. $posByCcydh[$dh][] = $po;
  4020. }
  4021. if ($posByCcydh === []) {
  4022. $fallback = trim((string)($bundle['ccydh'] ?? ''));
  4023. if ($fallback === '') {
  4024. return;
  4025. }
  4026. $groups = $this->loadAuditSupplierQuoteGroups($bundle);
  4027. ProcuremenSupplierScore::saveForOrder($fallback, $groups, $ym, $batchNo);
  4028. return;
  4029. }
  4030. $mergeAll = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  4031. foreach ($posByCcydh as $ccydh => $posList) {
  4032. $sidSet = [];
  4033. foreach ($posList as $po) {
  4034. $sid = (int)($po['scydgy_id'] ?? 0);
  4035. if ($this->isValidScydgyRowId($sid)) {
  4036. $sidSet[$sid] = true;
  4037. }
  4038. }
  4039. $mergeRows = [];
  4040. foreach ($mergeAll as $mr) {
  4041. if (!is_array($mr)) {
  4042. continue;
  4043. }
  4044. $gid = $this->extractScydgyRowId($mr);
  4045. if ($this->isValidScydgyRowId($gid) && isset($sidSet[$gid])) {
  4046. $mergeRows[] = $mr;
  4047. }
  4048. }
  4049. $subBundle = [
  4050. 'ccydh' => $ccydh,
  4051. 'order_batch_no' => $batchNo,
  4052. 'pos' => $posList,
  4053. 'merge_rows' => $mergeRows !== [] ? $mergeRows : $this->scydgyRowsForPurchaseOrders($posList),
  4054. ];
  4055. $groups = $this->loadAuditSupplierQuoteGroups($subBundle);
  4056. ProcuremenSupplierScore::saveForOrder($ccydh, $groups, $ym, $batchNo);
  4057. }
  4058. }
  4059. /**
  4060. * 报价行展示字段默认值(模板安全访问)
  4061. *
  4062. * @param array<string, mixed> $line
  4063. * @return array<string, mixed>
  4064. */
  4065. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  4066. {
  4067. if (!array_key_exists('amount_quote_pending', $line)) {
  4068. $line['amount_quote_pending'] = 0;
  4069. }
  4070. if (!array_key_exists('delivery_quote_pending', $line)) {
  4071. $line['delivery_quote_pending'] = 0;
  4072. }
  4073. if (!array_key_exists('quote_before_deadline', $line)) {
  4074. $line['quote_before_deadline'] = 0;
  4075. }
  4076. if (!array_key_exists('amount_filled', $line)) {
  4077. $line['amount_filled'] = 0;
  4078. }
  4079. if (!array_key_exists('delivery_filled', $line)) {
  4080. $line['delivery_filled'] = 0;
  4081. }
  4082. if (!array_key_exists('lead_days_filled', $line)) {
  4083. $line['lead_days_filled'] = 0;
  4084. }
  4085. if (!array_key_exists('lead_days_quote_pending', $line)) {
  4086. $line['lead_days_quote_pending'] = 0;
  4087. }
  4088. if (!array_key_exists('lead_days_show', $line)) {
  4089. $line['lead_days_show'] = '未填写';
  4090. }
  4091. if (!array_key_exists('lead_days_text', $line)) {
  4092. $line['lead_days_text'] = $line['lead_days_show'];
  4093. }
  4094. if (!array_key_exists('ccydh', $line)) {
  4095. $line['ccydh'] = '';
  4096. }
  4097. if (!array_key_exists('cgymc', $line)) {
  4098. $line['cgymc'] = '';
  4099. }
  4100. // 工序列展示文案:上行订单号、下行工序(无括号;兼容旧模板)
  4101. if (!array_key_exists('cgymc_display', $line) || trim((string)$line['cgymc_display']) === '') {
  4102. $dh = trim((string)$line['ccydh']);
  4103. $gy = trim((string)$line['cgymc']);
  4104. $line['cgymc_display'] = $dh !== '' ? ($dh . "\n" . $gy) : $gy;
  4105. }
  4106. return $line;
  4107. }
  4108. /**
  4109. * 供应商报价表「工序名称」列:订单号 + 工序名(不加 [])
  4110. *
  4111. * @return array{ccydh:string,cgymc:string,cgymc_display:string}
  4112. */
  4113. protected function buildSupplierProcessNameFields(string $ccydh, string $cgymc): array
  4114. {
  4115. $ccydh = trim($ccydh);
  4116. $cgymc = trim($cgymc);
  4117. if ($cgymc === '') {
  4118. $cgymc = '工序';
  4119. }
  4120. return [
  4121. 'ccydh' => $ccydh,
  4122. 'cgymc' => $cgymc,
  4123. 'cgymc_display' => $ccydh !== '' ? ($ccydh . "\n" . $cgymc) : $cgymc,
  4124. ];
  4125. }
  4126. /**
  4127. * 审核弹窗:按供应商汇总报价明细
  4128. *
  4129. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  4130. * @return array<int, array<string, mixed>>
  4131. */
  4132. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  4133. {
  4134. $sids = [];
  4135. foreach ($bundle['pos'] ?? [] as $po) {
  4136. if (!is_array($po)) {
  4137. continue;
  4138. }
  4139. $sid = (int)($po['scydgy_id'] ?? 0);
  4140. if ($this->isValidScydgyRowId($sid)) {
  4141. $sids[$sid] = true;
  4142. }
  4143. }
  4144. if ($sids === []) {
  4145. return [];
  4146. }
  4147. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  4148. $orderMbz = $this->resolveBundleOrderMbz($bundle);
  4149. $orderDeadlineMap = $this->buildBundleOrderDeliveryDeadlineMap($bundle);
  4150. $gymcMap = [];
  4151. $ccydhBySid = [];
  4152. $qtyBySid = [];
  4153. $ceilingBySid = [];
  4154. $extraSids = [];
  4155. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  4156. if (!is_array($mr)) {
  4157. continue;
  4158. }
  4159. $gid = $this->extractScydgyRowId($mr);
  4160. if ($this->isValidScydgyRowId($gid)) {
  4161. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  4162. $dh = trim((string)($mr['CCYDH'] ?? ''));
  4163. if ($dh !== '') {
  4164. $ccydhBySid[$gid] = $dh;
  4165. }
  4166. $qtyBySid[$gid] = $this->resolveProcuremenThisQuantity($mr);
  4167. $ceilingBySid[$gid] = $this->resolveProcuremenCeilingPrice($mr);
  4168. }
  4169. }
  4170. foreach ($bundle['pos'] ?? [] as $po) {
  4171. if (!is_array($po)) {
  4172. continue;
  4173. }
  4174. $gid = (int)($po['scydgy_id'] ?? 0);
  4175. if ($this->isValidScydgyRowId($gid)) {
  4176. $nm = trim((string)($po['CGYMC'] ?? ''));
  4177. if ($nm !== '') {
  4178. $gymcMap[$gid] = $nm;
  4179. }
  4180. $dh = trim((string)($po['CCYDH'] ?? ''));
  4181. if ($dh !== '' && empty($ccydhBySid[$gid])) {
  4182. $ccydhBySid[$gid] = $dh;
  4183. }
  4184. if (!isset($qtyBySid[$gid]) || trim((string)$qtyBySid[$gid]) === '') {
  4185. $qtyBySid[$gid] = $this->resolveProcuremenThisQuantity($po);
  4186. }
  4187. if (!isset($ceilingBySid[$gid]) || trim((string)$ceilingBySid[$gid]) === '') {
  4188. $ceilingBySid[$gid] = $this->resolveProcuremenCeilingPrice($po);
  4189. }
  4190. $extraSids[] = $gid;
  4191. }
  4192. }
  4193. // 与上方工序表一致:按订单号升序排供应商明细行
  4194. $orderedSids = $this->orderedScydgyIdsLikeProcessDisplay(
  4195. is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [],
  4196. $extraSids
  4197. );
  4198. try {
  4199. $detailsQuery = Db::table('purchase_order_detail')
  4200. ->where('scydgy_id', 'in', array_keys($sids));
  4201. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  4202. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  4203. } catch (\Throwable $e) {
  4204. try {
  4205. $detailsQuery = Db::table('purchase_order_detail')
  4206. ->where('scydgy_id', 'in', array_keys($sids));
  4207. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  4208. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  4209. } catch (\Throwable $e2) {
  4210. $details = [];
  4211. }
  4212. }
  4213. if (!is_array($details)) {
  4214. $details = [];
  4215. }
  4216. $byCompany = [];
  4217. foreach ($details as $d) {
  4218. if (!is_array($d)) {
  4219. continue;
  4220. }
  4221. $cn = trim((string)($d['company_name'] ?? ''));
  4222. if ($cn === '') {
  4223. continue;
  4224. }
  4225. if (!isset($byCompany[$cn])) {
  4226. $ph = trim((string)($d['phone'] ?? ''));
  4227. $username = trim((string)($d['username'] ?? ''));
  4228. if ($username === '') {
  4229. $username = $this->resolveCustomerContactName($ph, $cn);
  4230. }
  4231. $byCompany[$cn] = [
  4232. 'name' => $cn,
  4233. 'email' => trim((string)($d['email'] ?? '')),
  4234. 'phone' => $ph,
  4235. 'username' => $username,
  4236. 'remark' => '',
  4237. 'has_quote' => false,
  4238. 'lines_map' => [],
  4239. ];
  4240. }
  4241. if ($byCompany[$cn]['remark'] === '') {
  4242. $rm = '';
  4243. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  4244. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  4245. $rm = trim((string)$d[$rk]);
  4246. break;
  4247. }
  4248. }
  4249. if ($rm !== '') {
  4250. $byCompany[$cn]['remark'] = $rm;
  4251. }
  4252. }
  4253. $sid = (int)($d['scydgy_id'] ?? 0);
  4254. $am = trim((string)($d['amount'] ?? ''));
  4255. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  4256. $ccydhLine = trim((string)($ccydhBySid[$sid] ?? ''));
  4257. $processName = $this->buildSupplierProcessNameFields($ccydhLine, $gymc);
  4258. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  4259. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  4260. if ($deliveryShow === '' && $deliveryRaw !== '') {
  4261. $deliveryShow = $deliveryRaw;
  4262. }
  4263. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  4264. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  4265. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  4266. $subtotal = null;
  4267. if ($amountNum !== null) {
  4268. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  4269. }
  4270. $unitPriceText = $amountFilled
  4271. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  4272. : '未填写';
  4273. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  4274. $leadFilled = ($leadDays !== null);
  4275. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  4276. $lineRow = array_merge($processName, [
  4277. 'scydgy_id' => $sid,
  4278. 'This_quantity' => (string)($qtyBySid[$sid] ?? ''),
  4279. 'ceilingPrice' => (string)($ceilingBySid[$sid] ?? ''),
  4280. 'amount' => $am,
  4281. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  4282. 'amount_filled' => $amountFilled,
  4283. 'unit_price_text' => $unitPriceText,
  4284. 'delivery' => $deliveryRaw,
  4285. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  4286. 'delivery_filled' => $deliveryFilled,
  4287. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  4288. 'order_delivery_deadline' => $orderDeadlineMap[$ccydhLine] ?? '',
  4289. 'lead_days' => $leadFilled ? $leadDays : '',
  4290. 'lead_days_filled' => $leadFilled,
  4291. 'lead_days_show' => $leadText,
  4292. 'lead_days_text' => $leadText,
  4293. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  4294. 'subtotal_num' => $subtotal,
  4295. 'status_name' => trim((string)($d['status_name'] ?? '')),
  4296. 'is_quoted' => $amountFilled,
  4297. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  4298. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  4299. ]);
  4300. if (!$quoteVisible) {
  4301. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  4302. }
  4303. // 按工序 id 暂存,下面再按上方工序表顺序输出
  4304. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  4305. }
  4306. foreach ($byCompany as $cn => $g) {
  4307. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  4308. $lines = [];
  4309. $usedSids = [];
  4310. foreach ($orderedSids as $sid) {
  4311. if (!isset($linesMap[$sid])) {
  4312. continue;
  4313. }
  4314. $lines[] = $linesMap[$sid];
  4315. $usedSids[$sid] = true;
  4316. }
  4317. foreach ($linesMap as $sid => $ln) {
  4318. if (isset($usedSids[$sid])) {
  4319. continue;
  4320. }
  4321. $lines[] = $ln;
  4322. }
  4323. $total = count($lines);
  4324. $quoted = 0;
  4325. $groupTotal = 0.0;
  4326. $groupHasTotal = false;
  4327. if ($quoteVisible) {
  4328. foreach ($lines as $ln) {
  4329. $am = trim((string)($ln['amount'] ?? ''));
  4330. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  4331. $quoted++;
  4332. }
  4333. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  4334. $groupTotal += (float)$ln['subtotal_num'];
  4335. $groupHasTotal = true;
  4336. }
  4337. }
  4338. }
  4339. unset($byCompany[$cn]['lines_map']);
  4340. $byCompany[$cn]['lines'] = $lines;
  4341. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  4342. $byCompany[$cn]['line_count'] = $total;
  4343. $byCompany[$cn]['has_total'] = $total > 0;
  4344. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  4345. $this->finalizeSupplierRemarkDisplay($byCompany[$cn], $orderMbz, $quoteVisible);
  4346. }
  4347. $groups = array_values($byCompany);
  4348. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  4349. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  4350. }
  4351. /**
  4352. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  4353. *
  4354. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  4355. * @return array<int, array<string, mixed>>
  4356. */
  4357. protected function loadConfirmSupplierPickGroups(array $bundle): array
  4358. {
  4359. $sids = [];
  4360. $poIdMap = [];
  4361. foreach ($bundle['pos'] ?? [] as $po) {
  4362. if (!is_array($po)) {
  4363. continue;
  4364. }
  4365. $sid = (int)($po['scydgy_id'] ?? 0);
  4366. if ($this->isValidScydgyRowId($sid)) {
  4367. $sids[$sid] = true;
  4368. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  4369. }
  4370. }
  4371. if ($sids === []) {
  4372. return [];
  4373. }
  4374. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  4375. $orderMbz = $this->resolveBundleOrderMbz($bundle);
  4376. $orderDeadlineMap = $this->buildBundleOrderDeliveryDeadlineMap($bundle);
  4377. $gymcMap = [];
  4378. $ccydhBySid = [];
  4379. $qtyBySid = [];
  4380. $ceilingBySid = [];
  4381. $extraSids = [];
  4382. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  4383. if (!is_array($mr)) {
  4384. continue;
  4385. }
  4386. $gid = $this->extractScydgyRowId($mr);
  4387. if ($this->isValidScydgyRowId($gid)) {
  4388. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  4389. $dh = trim((string)($mr['CCYDH'] ?? ''));
  4390. if ($dh !== '') {
  4391. $ccydhBySid[$gid] = $dh;
  4392. }
  4393. $qtyBySid[$gid] = $this->resolveProcuremenThisQuantity($mr);
  4394. $ceilingBySid[$gid] = $this->resolveProcuremenCeilingPrice($mr);
  4395. }
  4396. }
  4397. foreach ($bundle['pos'] ?? [] as $po) {
  4398. if (!is_array($po)) {
  4399. continue;
  4400. }
  4401. $gid = (int)($po['scydgy_id'] ?? 0);
  4402. if ($this->isValidScydgyRowId($gid)) {
  4403. $nm = trim((string)($po['CGYMC'] ?? ''));
  4404. if ($nm !== '') {
  4405. $gymcMap[$gid] = $nm;
  4406. }
  4407. $dh = trim((string)($po['CCYDH'] ?? ''));
  4408. if ($dh !== '' && empty($ccydhBySid[$gid])) {
  4409. $ccydhBySid[$gid] = $dh;
  4410. }
  4411. if (!isset($qtyBySid[$gid]) || trim((string)$qtyBySid[$gid]) === '') {
  4412. $qtyBySid[$gid] = $this->resolveProcuremenThisQuantity($po);
  4413. }
  4414. if (!isset($ceilingBySid[$gid]) || trim((string)$ceilingBySid[$gid]) === '') {
  4415. $ceilingBySid[$gid] = $this->resolveProcuremenCeilingPrice($po);
  4416. }
  4417. $extraSids[] = $gid;
  4418. }
  4419. }
  4420. // 与上方工序表一致:按订单号升序排供应商明细行
  4421. $orderedSids = $this->orderedScydgyIdsLikeProcessDisplay(
  4422. is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [],
  4423. $extraSids
  4424. );
  4425. try {
  4426. $details = Db::table('purchase_order_detail')
  4427. ->where('scydgy_id', 'in', array_keys($sids))
  4428. ->order('company_name', 'asc')
  4429. ->order('id', 'asc')
  4430. ->select();
  4431. } catch (\Throwable $e) {
  4432. try {
  4433. $details = Db::table('purchase_order_detail')
  4434. ->where('scydgy_id', 'in', array_keys($sids))
  4435. ->order('company_name', 'asc')
  4436. ->order('ID', 'asc')
  4437. ->select();
  4438. } catch (\Throwable $e2) {
  4439. $details = [];
  4440. }
  4441. }
  4442. if (!is_array($details)) {
  4443. $details = [];
  4444. }
  4445. $byCompany = [];
  4446. foreach ($details as $d) {
  4447. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  4448. continue;
  4449. }
  4450. $cn = trim((string)($d['company_name'] ?? ''));
  4451. if ($cn === '') {
  4452. continue;
  4453. }
  4454. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  4455. $sid = (int)($d['scydgy_id'] ?? 0);
  4456. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  4457. continue;
  4458. }
  4459. if (!isset($byCompany[$cn])) {
  4460. $ph = trim((string)($d['phone'] ?? ''));
  4461. $username = trim((string)($d['username'] ?? ''));
  4462. if ($username === '') {
  4463. $username = $this->resolveCustomerContactName($ph, $cn);
  4464. }
  4465. $byCompany[$cn] = [
  4466. 'name' => $cn,
  4467. 'email' => trim((string)($d['email'] ?? '')),
  4468. 'phone' => $ph,
  4469. 'username' => $username,
  4470. 'remark' => '',
  4471. 'pick_lines' => [],
  4472. 'detail_picks' => [],
  4473. ];
  4474. }
  4475. if ($byCompany[$cn]['remark'] === '') {
  4476. $rm = '';
  4477. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  4478. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  4479. $rm = trim((string)$d[$rk]);
  4480. break;
  4481. }
  4482. }
  4483. if ($rm !== '') {
  4484. $byCompany[$cn]['remark'] = $rm;
  4485. }
  4486. }
  4487. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  4488. $ccydhLine = trim((string)($ccydhBySid[$sid] ?? ''));
  4489. $processName = $this->buildSupplierProcessNameFields($ccydhLine, $gymc);
  4490. $am = trim((string)($d['amount'] ?? ''));
  4491. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  4492. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  4493. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  4494. if ($deliveryShow === '' && $deliveryRaw !== '') {
  4495. $deliveryShow = $deliveryRaw;
  4496. }
  4497. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  4498. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  4499. $subtotal = null;
  4500. if ($amountNum !== null) {
  4501. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  4502. }
  4503. $unitPriceText = $amountFilled
  4504. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  4505. : '未填写';
  4506. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  4507. $leadFilled = ($leadDays !== null);
  4508. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  4509. $pickLine = array_merge($processName, [
  4510. 'scydgy_id' => $sid,
  4511. 'This_quantity' => (string)($qtyBySid[$sid] ?? ''),
  4512. 'ceilingPrice' => (string)($ceilingBySid[$sid] ?? ''),
  4513. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  4514. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  4515. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  4516. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  4517. 'order_delivery_deadline' => $orderDeadlineMap[$ccydhLine] ?? '',
  4518. 'amount_filled' => $amountFilled,
  4519. 'delivery_filled' => $deliveryFilled,
  4520. 'unit_price_text' => $unitPriceText,
  4521. 'lead_days' => $leadFilled ? $leadDays : '',
  4522. 'lead_days_filled' => $leadFilled,
  4523. 'lead_days_show' => $leadText,
  4524. 'lead_days_text' => $leadText,
  4525. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  4526. 'subtotal_num' => $subtotal,
  4527. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  4528. 'is_quoted' => $amountFilled,
  4529. ]);
  4530. if (!$quoteVisible) {
  4531. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  4532. }
  4533. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  4534. $byCompany[$cn]['detail_picks'][$sid] = [
  4535. 'scydgy_id' => $sid,
  4536. 'detail_id' => $detailId,
  4537. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  4538. 'cgymc' => $processName['cgymc'],
  4539. 'ccydh' => $processName['ccydh'],
  4540. ];
  4541. }
  4542. $out = [];
  4543. foreach ($byCompany as $g) {
  4544. $pickLinesMap = $g['pick_lines'] ?? [];
  4545. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  4546. continue;
  4547. }
  4548. $pickLines = [];
  4549. $usedLineSids = [];
  4550. foreach ($orderedSids as $sid) {
  4551. if (!isset($pickLinesMap[$sid])) {
  4552. continue;
  4553. }
  4554. $pickLines[] = $pickLinesMap[$sid];
  4555. $usedLineSids[$sid] = true;
  4556. }
  4557. foreach ($pickLinesMap as $sid => $ln) {
  4558. if (isset($usedLineSids[$sid])) {
  4559. continue;
  4560. }
  4561. $pickLines[] = $ln;
  4562. }
  4563. $groupTotal = 0.0;
  4564. $groupHasTotal = false;
  4565. if ($quoteVisible) {
  4566. foreach ($pickLines as $ln) {
  4567. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  4568. $groupTotal += (float)$ln['subtotal_num'];
  4569. $groupHasTotal = true;
  4570. }
  4571. }
  4572. }
  4573. $lineCount = count($pickLines);
  4574. $g['pick_lines'] = $pickLines;
  4575. $g['line_count'] = $lineCount;
  4576. $g['has_total'] = $lineCount > 0;
  4577. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  4578. $this->finalizeSupplierRemarkDisplay($g, $orderMbz, $quoteVisible);
  4579. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  4580. $detailPicks = [];
  4581. $usedPickSids = [];
  4582. foreach ($orderedSids as $sid) {
  4583. if (!isset($detailPicksMap[$sid])) {
  4584. continue;
  4585. }
  4586. $detailPicks[] = $detailPicksMap[$sid];
  4587. $usedPickSids[$sid] = true;
  4588. }
  4589. foreach ($detailPicksMap as $sid => $dp) {
  4590. if (isset($usedPickSids[$sid])) {
  4591. continue;
  4592. }
  4593. $detailPicks[] = $dp;
  4594. }
  4595. $g['detail_picks'] = $detailPicks;
  4596. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  4597. unset($g['detail_picks']);
  4598. $out[] = $g;
  4599. }
  4600. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  4601. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  4602. }
  4603. /**
  4604. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  4605. * @return array<int, int[]> scydgy_id => detail_id[]
  4606. */
  4607. protected function mapDetailIdsByScydgyId(array $details): array
  4608. {
  4609. $out = [];
  4610. foreach ($details as $d) {
  4611. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  4612. continue;
  4613. }
  4614. $sid = (int)($d['scydgy_id'] ?? 0);
  4615. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  4616. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  4617. continue;
  4618. }
  4619. if (!isset($out[$sid])) {
  4620. $out[$sid] = [];
  4621. }
  4622. $out[$sid][] = $pk;
  4623. }
  4624. foreach ($out as $sid => $ids) {
  4625. $out[$sid] = array_values(array_unique($ids));
  4626. }
  4627. return $out;
  4628. }
  4629. /**
  4630. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  4631. *
  4632. * @param array<string, mixed> $dbRow
  4633. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  4634. */
  4635. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  4636. {
  4637. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  4638. $r = [
  4639. 'ID' => $sid,
  4640. 'scydgy_id' => $sid,
  4641. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  4642. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  4643. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  4644. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  4645. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  4646. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  4647. 'CDW' => $dbRow['CDW'] ?? '',
  4648. 'czlyq' => $dbRow['czlyq'] ?? '',
  4649. 'NGZL' => $dbRow['NGZL'] ?? '',
  4650. 'CDF' => $dbRow['CDF'] ?? '',
  4651. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  4652. 'MBZ' => $dbRow['MBZ'] ?? '',
  4653. 'bwjg' => $dbRow['bwjg'] ?? '',
  4654. 'iStatus' => $dbRow['iStatus'] ?? '',
  4655. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  4656. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  4657. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  4658. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  4659. 'dStamp' => $dbRow['dStamp'] ?? '',
  4660. 'pick_time' => $dbRow['pick_time'] ?? '',
  4661. 'order_batch_no' => $this->resolveProcuremenOrderBatchNo($dbRow),
  4662. ];
  4663. $r['This_quantity'] = $this->resolveProcuremenThisQuantity($r);
  4664. $r['ceilingPrice'] = $this->resolveProcuremenCeilingPrice($r);
  4665. if ($sid > 0 && isset($dStampMap[$sid])) {
  4666. $t = trim((string)$dStampMap[$sid]);
  4667. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  4668. $r['dStamp'] = $dStampMap[$sid];
  4669. }
  4670. }
  4671. $dsOut = trim((string)($r['dStamp'] ?? ''));
  4672. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  4673. $ct = $dbRow['createtime'];
  4674. if (is_numeric($ct) && (int)$ct > 946684800) {
  4675. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  4676. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  4677. $r['dStamp'] = trim($ct);
  4678. }
  4679. }
  4680. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  4681. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  4682. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  4683. $fallback = trim((string)($r['dStamp'] ?? ''));
  4684. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  4685. $r['dputrecord'] = $fallback;
  4686. }
  4687. }
  4688. if (array_key_exists('id', $dbRow)) {
  4689. $r['purchase_order_id'] = (int)$dbRow['id'];
  4690. }
  4691. if ($sid < 0) {
  4692. $r['_is_manual'] = 1;
  4693. }
  4694. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  4695. $pickOut = trim((string)($r['pick_time'] ?? ''));
  4696. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  4697. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  4698. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  4699. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  4700. $r['pick_time'] = $pickFallback;
  4701. break;
  4702. }
  4703. }
  4704. }
  4705. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  4706. if ($pickNm !== '') {
  4707. $r['pick_company_name'] = $pickNm;
  4708. $r['picked_supplier_name'] = $pickNm;
  4709. }
  4710. // 列表开标状态依赖此字段:有批次号时只认本行/合并行,必须从库带出
  4711. $r['manual_pick'] = ((int)($dbRow['manual_pick'] ?? 0) === 1) ? 1 : 0;
  4712. $r['wflow_status'] = trim((string)($dbRow['wflow_status'] ?? ''));
  4713. $r['order_status_text'] = ProcuremenStatus::orderStatusLabelForList($r['wflow_status']);
  4714. if (array_key_exists('status', $dbRow)) {
  4715. $r['status'] = $dbRow['status'];
  4716. }
  4717. return $r;
  4718. }
  4719. /**
  4720. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  4721. *
  4722. * @return array<int, array<string, mixed>>
  4723. */
  4724. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  4725. {
  4726. $pool = [];
  4727. if (!is_array($dbRows) || $dbRows === []) {
  4728. return $pool;
  4729. }
  4730. $dStampMap = [];
  4731. $sidList = [];
  4732. foreach ($dbRows as $tmpRow) {
  4733. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  4734. $sid = (int)$tmpRow['scydgy_id'];
  4735. if ($sid > 0) {
  4736. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  4737. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  4738. $sidList[$sid] = true;
  4739. }
  4740. }
  4741. }
  4742. }
  4743. if ($sidList !== []) {
  4744. try {
  4745. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  4746. } catch (\Throwable $e) {
  4747. $dStampMap = [];
  4748. }
  4749. }
  4750. foreach ($dbRows as $dbRow) {
  4751. if (!is_array($dbRow)) {
  4752. continue;
  4753. }
  4754. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  4755. }
  4756. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  4757. $needCcydh = [];
  4758. foreach ($pool as $row) {
  4759. if (!is_array($row)) {
  4760. continue;
  4761. }
  4762. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  4763. continue;
  4764. }
  4765. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  4766. if ($ccydh !== '') {
  4767. $needCcydh[$ccydh] = true;
  4768. }
  4769. }
  4770. if ($needCcydh !== []) {
  4771. $czMap = [];
  4772. try {
  4773. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  4774. } catch (\Throwable $e) {
  4775. $czMap = [];
  4776. }
  4777. if (is_array($czMap) && $czMap !== []) {
  4778. foreach ($pool as &$row) {
  4779. if (!is_array($row)) {
  4780. continue;
  4781. }
  4782. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  4783. continue;
  4784. }
  4785. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  4786. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  4787. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  4788. }
  4789. }
  4790. unset($row);
  4791. }
  4792. }
  4793. return $pool;
  4794. }
  4795. /**
  4796. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  4797. *
  4798. * @param int[] $scydgyIds
  4799. * @return array<int, array<string, mixed>>
  4800. */
  4801. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  4802. {
  4803. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4804. if ($scydgyIds === []) {
  4805. return [];
  4806. }
  4807. try {
  4808. $list = Db::table('purchase_order_detail')
  4809. ->where('scydgy_id', 'in', $scydgyIds)
  4810. ->field('scydgy_id,company_name,amount,delivery')
  4811. ->select();
  4812. } catch (\Throwable $e) {
  4813. $list = [];
  4814. }
  4815. return is_array($list) ? $list : [];
  4816. }
  4817. /**
  4818. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  4819. *
  4820. * @param int[] $scydgyIds
  4821. * @param array<int, array<string, mixed>> $allRows
  4822. * @return array{cnt:int, amt:int, deliv:int}
  4823. */
  4824. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  4825. {
  4826. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4827. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4828. if ($scydgyIds === [] || $allRows === []) {
  4829. return $out;
  4830. }
  4831. $idSet = array_flip($scydgyIds);
  4832. $all = [];
  4833. $withAmt = [];
  4834. $withDeliv = [];
  4835. foreach ($allRows as $r) {
  4836. if (!is_array($r)) {
  4837. continue;
  4838. }
  4839. $sid = (int)($r['scydgy_id'] ?? 0);
  4840. if (!isset($idSet[$sid])) {
  4841. continue;
  4842. }
  4843. $cn = trim((string)($r['company_name'] ?? ''));
  4844. if ($cn === '') {
  4845. continue;
  4846. }
  4847. $all[$cn] = true;
  4848. $am = $r['amount'] ?? null;
  4849. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  4850. $withAmt[$cn] = true;
  4851. }
  4852. $dv = $r['delivery'] ?? null;
  4853. if ($dv !== null && trim((string)$dv) !== '') {
  4854. $withDeliv[$cn] = true;
  4855. }
  4856. }
  4857. return [
  4858. 'cnt' => count($all),
  4859. 'amt' => count($withAmt),
  4860. 'deliv' => count($withDeliv),
  4861. ];
  4862. }
  4863. /**
  4864. * 本次数量:优先 This_quantity,空则回退工作量 NGZL(与下发/确认/审批弹窗一致)
  4865. *
  4866. * @param array<string, mixed> $row
  4867. */
  4868. protected function resolveProcuremenThisQuantity(array $row): string
  4869. {
  4870. $q = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  4871. if ($q !== '') {
  4872. return $q;
  4873. }
  4874. $ngzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  4875. if (!is_scalar($ngzl)) {
  4876. return '';
  4877. }
  4878. $s = trim((string)$ngzl);
  4879. if ($s === '') {
  4880. return '';
  4881. }
  4882. if (is_numeric($s) && (float)$s === 0.0) {
  4883. return '';
  4884. }
  4885. return $s;
  4886. }
  4887. /**
  4888. * @param array<string, mixed> $row
  4889. */
  4890. protected function resolveProcuremenCeilingPrice(array $row): string
  4891. {
  4892. return trim((string)($row['ceilingPrice'] ?? $row['ceiling_price'] ?? ''));
  4893. }
  4894. /**
  4895. * 多工序数量/限价拼接:跳过空值,避免出现「、10」「304、」
  4896. *
  4897. * @param array<int, mixed> $parts
  4898. */
  4899. protected function joinProcuremenNonEmpty(array $parts, string $sep = '、'): string
  4900. {
  4901. $out = [];
  4902. foreach ($parts as $p) {
  4903. $s = trim((string)$p);
  4904. if ($s !== '') {
  4905. $out[] = $s;
  4906. }
  4907. }
  4908. return $out === [] ? '' : implode($sep, $out);
  4909. }
  4910. /**
  4911. * 确认/审批列表:合并行按各工序同步本次数量、最高限价(顿号间隔)
  4912. *
  4913. * @param array<int, array<string, mixed>> $rows
  4914. */
  4915. protected function syncCollapsedOrderQtyPriceForList(array &$rows): void
  4916. {
  4917. if ($rows === []) {
  4918. return;
  4919. }
  4920. $idList = [];
  4921. foreach ($rows as $rw) {
  4922. if (!is_array($rw)) {
  4923. continue;
  4924. }
  4925. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4926. foreach ($rw['_order_merge_rows'] as $mr) {
  4927. if (!is_array($mr)) {
  4928. continue;
  4929. }
  4930. $mid = (int)($mr['ID'] ?? 0);
  4931. if ($this->isValidScydgyRowId($mid)) {
  4932. $idList[$mid] = true;
  4933. }
  4934. }
  4935. }
  4936. $id = (int)($rw['ID'] ?? 0);
  4937. if ($this->isValidScydgyRowId($id)) {
  4938. $idList[$id] = true;
  4939. }
  4940. }
  4941. if ($idList === []) {
  4942. return;
  4943. }
  4944. try {
  4945. $list = Db::table('purchase_order')
  4946. ->where('scydgy_id', 'in', array_keys($idList))
  4947. ->field('scydgy_id,This_quantity,ceilingPrice,NGZL,pick_company_name')
  4948. ->select();
  4949. } catch (\Throwable $e) {
  4950. return;
  4951. }
  4952. if (!is_array($list)) {
  4953. return;
  4954. }
  4955. $byId = [];
  4956. foreach ($list as $dbRow) {
  4957. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4958. continue;
  4959. }
  4960. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4961. }
  4962. foreach ($rows as &$rw) {
  4963. if (!is_array($rw)) {
  4964. continue;
  4965. }
  4966. $mergeRows = [];
  4967. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4968. $mergeRows = $rw['_order_merge_rows'];
  4969. } else {
  4970. $mergeRows = [$rw];
  4971. }
  4972. $qtyList = [];
  4973. $priceList = [];
  4974. $picked = '';
  4975. foreach ($mergeRows as $mr) {
  4976. if (!is_array($mr)) {
  4977. continue;
  4978. }
  4979. $sid = (int)($mr['ID'] ?? 0);
  4980. $db = ($sid !== 0 && isset($byId[$sid])) ? $byId[$sid] : null;
  4981. $src = $mr;
  4982. if (is_array($db)) {
  4983. $qDb = trim((string)($db['This_quantity'] ?? $db['this_quantity'] ?? ''));
  4984. $pDb = trim((string)($db['ceilingPrice'] ?? $db['ceiling_price'] ?? ''));
  4985. $ngzlDb = $db['NGZL'] ?? $db['ngzl'] ?? null;
  4986. if ($qDb !== '') {
  4987. $src['This_quantity'] = $qDb;
  4988. }
  4989. if ($pDb !== '') {
  4990. $src['ceilingPrice'] = $pDb;
  4991. }
  4992. if ($ngzlDb !== null && trim((string)$ngzlDb) !== '') {
  4993. $src['NGZL'] = $ngzlDb;
  4994. }
  4995. if ($picked === '') {
  4996. $picked = trim((string)($db['pick_company_name'] ?? ''));
  4997. }
  4998. }
  4999. if ($picked === '') {
  5000. $picked = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  5001. }
  5002. $qtyList[] = $this->resolveProcuremenThisQuantity($src);
  5003. $priceList[] = $this->resolveProcuremenCeilingPrice($src);
  5004. }
  5005. $rw['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  5006. $rw['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  5007. if ($picked !== '') {
  5008. $rw['pick_company_name'] = $picked;
  5009. $rw['picked_supplier_name'] = $picked;
  5010. }
  5011. }
  5012. unset($rw);
  5013. }
  5014. /**
  5015. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  5016. *
  5017. * @param int[] $scydgyIds
  5018. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  5019. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  5020. */
  5021. protected function OrderDetailSummary(array $scydgyIds)
  5022. {
  5023. $out = [];
  5024. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  5025. if ($scydgyIds === []) {
  5026. return $out;
  5027. }
  5028. $list = [];
  5029. try {
  5030. $list = Db::table('purchase_order_detail')
  5031. ->where('scydgy_id', 'in', $scydgyIds)
  5032. ->field('id,scydgy_id,amount,delivery')
  5033. ->select();
  5034. } catch (\Throwable $e) {
  5035. $list = [];
  5036. }
  5037. if (!is_array($list)) {
  5038. return $out;
  5039. }
  5040. foreach ($list as $r) {
  5041. if (!is_array($r)) {
  5042. continue;
  5043. }
  5044. $ids = (int)($r['scydgy_id'] ?? 0);
  5045. if (!$this->isValidScydgyRowId($ids)) {
  5046. continue;
  5047. }
  5048. if (!isset($out[$ids])) {
  5049. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  5050. }
  5051. $out[$ids]['cnt']++;
  5052. $am = $r['amount'] ?? null;
  5053. if ($am !== null && $am !== '') {
  5054. if (!(is_string($am) && trim($am) === '')) {
  5055. $out[$ids]['amt']++;
  5056. }
  5057. }
  5058. $dv = $r['delivery'] ?? null;
  5059. if ($dv !== null && trim((string)$dv) !== '') {
  5060. $out[$ids]['deliv']++;
  5061. }
  5062. }
  5063. return $out;
  5064. }
  5065. /**
  5066. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  5067. *
  5068. * @return array
  5069. */
  5070. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  5071. {
  5072. $strContains = function ($haystack, $needle) {
  5073. if ($needle === '') {
  5074. return false;
  5075. }
  5076. $haystack = (string)$haystack;
  5077. if (function_exists('mb_stripos')) {
  5078. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  5079. }
  5080. return stripos($haystack, $needle) !== false;
  5081. };
  5082. $stripAlias = function ($f) {
  5083. return preg_replace('/^[ab]\./i', '', (string)$f);
  5084. };
  5085. $searchColNames = [];
  5086. foreach (explode(',', $this->searchFields) as $colRaw) {
  5087. $c = $stripAlias(trim($colRaw));
  5088. if ($c !== '') {
  5089. $searchColNames[] = $c;
  5090. }
  5091. }
  5092. // 等值条件先行(表头下拉),减少后续日期解析量
  5093. $eqFilters = [];
  5094. $otherFilters = [];
  5095. foreach ($filterArr as $fk => $fv) {
  5096. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  5097. continue;
  5098. }
  5099. if (is_array($fv)) {
  5100. continue;
  5101. }
  5102. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  5103. continue;
  5104. }
  5105. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  5106. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  5107. $field = $stripAlias($fk);
  5108. if ($sym === '=' || $sym === '') {
  5109. $eqFilters[$field] = trim((string)$fv);
  5110. } else {
  5111. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  5112. }
  5113. }
  5114. $ymTarget = '';
  5115. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  5116. $ymTarget = $ymM[1];
  5117. }
  5118. $filtered = [];
  5119. foreach ($pool as $r) {
  5120. if (!is_array($r)) {
  5121. continue;
  5122. }
  5123. foreach ($eqFilters as $field => $fv) {
  5124. if (trim((string)($r[$field] ?? '')) !== $fv) {
  5125. continue 2;
  5126. }
  5127. }
  5128. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  5129. // 初选池不应含手工单;若混入则直接剔除
  5130. if ($isManual) {
  5131. continue;
  5132. }
  5133. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  5134. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  5135. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  5136. continue;
  5137. }
  5138. if ($applyMonthRange) {
  5139. $mo = (int)$m[2];
  5140. if ($mo < 1 || $mo > 12) {
  5141. continue;
  5142. }
  5143. if ($ymTarget !== '') {
  5144. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  5145. if ($ymRow !== $ymTarget) {
  5146. continue;
  5147. }
  5148. } else {
  5149. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  5150. $rowMonthStart = $ymRow . '-01 00:00:00';
  5151. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  5152. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  5153. continue;
  5154. }
  5155. }
  5156. }
  5157. if ($search !== '') {
  5158. $hitSearch = false;
  5159. foreach ($searchColNames as $c) {
  5160. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  5161. if ($cell !== '' && $strContains($cell, $search)) {
  5162. $hitSearch = true;
  5163. break;
  5164. }
  5165. }
  5166. if (!$hitSearch) {
  5167. continue;
  5168. }
  5169. }
  5170. foreach ($otherFilters as $item) {
  5171. $fv = $item['fv'];
  5172. $sym = $item['sym'];
  5173. $field = $item['field'];
  5174. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  5175. $cellStr = trim((string)$cell);
  5176. switch ($sym) {
  5177. case '<>':
  5178. if ((string)$cell === (string)$fv) {
  5179. continue 3;
  5180. }
  5181. break;
  5182. case 'LIKE':
  5183. case 'NOT LIKE':
  5184. $needle = trim((string)$fv);
  5185. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  5186. if ($sym === 'LIKE' && !$hit) {
  5187. continue 3;
  5188. }
  5189. if ($sym === 'NOT LIKE' && $hit) {
  5190. continue 3;
  5191. }
  5192. break;
  5193. case 'BETWEEN':
  5194. case 'RANGE':
  5195. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  5196. if (count($parts) < 2) {
  5197. $parts = is_string($fv) ? explode(',', $fv) : [];
  5198. }
  5199. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  5200. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  5201. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  5202. continue 3;
  5203. }
  5204. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  5205. continue 3;
  5206. }
  5207. break;
  5208. case '>':
  5209. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  5210. continue 3;
  5211. }
  5212. break;
  5213. case '>=':
  5214. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  5215. continue 3;
  5216. }
  5217. break;
  5218. case '<':
  5219. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  5220. continue 3;
  5221. }
  5222. break;
  5223. case '<=':
  5224. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  5225. continue 3;
  5226. }
  5227. break;
  5228. default:
  5229. if ((string)$cell !== (string)$fv) {
  5230. continue 3;
  5231. }
  5232. break;
  5233. }
  5234. }
  5235. $filtered[] = $r;
  5236. }
  5237. return $filtered;
  5238. }
  5239. /**
  5240. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  5241. */
  5242. public function snapshotToProcure()
  5243. {
  5244. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5245. $this->error(__('Invalid parameters'));
  5246. }
  5247. $row = json_decode($this->request->post('row_json', ''), true);
  5248. if (!is_array($row)) {
  5249. $this->error(__('Invalid parameters'));
  5250. }
  5251. try {
  5252. $ids = $this->extractScydgyRowId($row);
  5253. if (!$this->isValidScydgyRowId($ids)) {
  5254. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  5255. }
  5256. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5257. $data = $this->normalizePurchaseOrderWritePayload([
  5258. 'scydgy_id' => $ids,
  5259. 'CCYDH' => $row['CCYDH'] ?? null,
  5260. 'CYJMC' => $row['CYJMC'] ?? null,
  5261. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  5262. 'CDXMC' => $row['CDXMC'] ?? null,
  5263. 'CGYBH' => $row['CGYBH'] ?? null,
  5264. 'CGYMC' => $row['CGYMC'] ?? null,
  5265. 'CDW' => $row['CDW'] ?? null,
  5266. 'czlyq' => $row['czlyq'] ?? null,
  5267. 'NGZL' => $row['NGZL'] ?? null,
  5268. 'CDF' => $row['CDF'] ?? null,
  5269. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  5270. 'MBZ' => $row['MBZ'] ?? null,
  5271. 'bwjg' => $row['bwjg'] ?? null,
  5272. 'iStatus' => $row['iStatus'] ?? null,
  5273. 'dStamp' => $row['dStamp'] ?? null,
  5274. 'dputrecord' => $row['dputrecord'] ?? null,
  5275. 'cywyxm' => $row['cywyxm'] ?? null,
  5276. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  5277. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  5278. ], $row);
  5279. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  5280. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  5281. $mbzSnap = trim((string)($data['MBZ'] ?? ''));
  5282. if (!$exists && $qtySnap === '' && $priceSnap === '' && $mbzSnap === '') {
  5283. $this->success('操作成功');
  5284. return;
  5285. }
  5286. if ($exists) {
  5287. $upd = $data;
  5288. unset($upd['scydgy_id'], $upd['status']);
  5289. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  5290. } else {
  5291. // 新增:不写 status(空/走库默认);仅写创建时间
  5292. $data['createtime'] = date('Y-m-d H:i:s');
  5293. Db::table('purchase_order')->insert($data);
  5294. }
  5295. } catch (\Throwable $e) {
  5296. $this->error($e->getMessage());
  5297. }
  5298. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  5299. $this->success('操作成功');
  5300. }
  5301. /**
  5302. * 未发列表
  5303. * 「完结」或「仅保存本次数量/最高限价/备注」:有则改、无则插
  5304. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  5305. */
  5306. public function completeDirectly()
  5307. {
  5308. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5309. $this->error(__('参数错误'));
  5310. }
  5311. if (!$this->procuremenCanComplete()) {
  5312. $this->error(__('You have no permission'));
  5313. }
  5314. $row = json_decode($this->request->post('row_json', ''), true);
  5315. if (!is_array($row)) {
  5316. $this->error(__('Invalid parameters'));
  5317. }
  5318. $finishRaw = $this->request->post('finish', '1');
  5319. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  5320. $poIdLog = null;
  5321. try {
  5322. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  5323. $ids = $this->extractScydgyRowId($row);
  5324. if (!$this->isValidScydgyRowId($ids)) {
  5325. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  5326. }
  5327. if ($asComplete) {
  5328. $this->assertPickRowCanComplete($ids, $row);
  5329. }
  5330. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5331. $data = $this->normalizePurchaseOrderWritePayload([
  5332. 'scydgy_id' => $ids,
  5333. 'CCYDH' => $row['CCYDH'] ?? null,
  5334. 'CYJMC' => $row['CYJMC'] ?? null,
  5335. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  5336. 'CDXMC' => $row['CDXMC'] ?? null,
  5337. 'CGYBH' => $row['CGYBH'] ?? null,
  5338. 'CGYMC' => $row['CGYMC'] ?? null,
  5339. 'CDW' => $row['CDW'] ?? null,
  5340. 'czlyq' => $row['czlyq'] ?? null,
  5341. 'NGZL' => $row['NGZL'] ?? null,
  5342. 'CDF' => $row['CDF'] ?? null,
  5343. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  5344. 'MBZ' => $row['MBZ'] ?? null,
  5345. 'bwjg' => $row['bwjg'] ?? null,
  5346. 'iStatus' => $row['iStatus'] ?? null,
  5347. 'dStamp' => $row['dStamp'] ?? null,
  5348. 'dputrecord' => $row['dputrecord'] ?? null,
  5349. 'cywyxm' => $row['cywyxm'] ?? null,
  5350. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  5351. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  5352. ], $row);
  5353. if ($asComplete) {
  5354. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  5355. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  5356. }
  5357. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  5358. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  5359. $mbzCd = trim((string)($data['MBZ'] ?? ''));
  5360. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '' && $mbzCd === '') {
  5361. $this->success('操作成功');
  5362. return;
  5363. }
  5364. if ($exists) {
  5365. $upd = $data;
  5366. unset($upd['scydgy_id']);
  5367. if (!$asComplete) {
  5368. unset($upd['status']);
  5369. }
  5370. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  5371. } else {
  5372. // 新增:不写 status;完结时 $data 已含 status=1
  5373. $data['createtime'] = date('Y-m-d H:i:s');
  5374. Db::table('purchase_order')->insert($data);
  5375. }
  5376. } catch (\Throwable $e) {
  5377. $this->error($e->getMessage());
  5378. }
  5379. try {
  5380. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5381. if (is_array($rpo)) {
  5382. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  5383. $poIdLog = $tid > 0 ? $tid : null;
  5384. }
  5385. } catch (\Throwable $e) {
  5386. $poIdLog = null;
  5387. }
  5388. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  5389. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  5390. if ($asComplete) {
  5391. $this->addOrderLog(
  5392. $ids,
  5393. 'mark_complete',
  5394. '点击「完结」,已标记为已完结',
  5395. $poIdLog
  5396. );
  5397. try {
  5398. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  5399. if ($pdfPublicPath === '') {
  5400. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  5401. }
  5402. } catch (\Throwable $e) {
  5403. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  5404. }
  5405. } else {
  5406. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  5407. $mbz = isset($data['MBZ']) ? trim((string)$data['MBZ']) : '';
  5408. $parts = [];
  5409. if ($q !== '') {
  5410. $parts[] = ($gymc !== '' ? ($gymc . '本次数量') : '本次数量') . '「' . $q . '」';
  5411. } elseif ($gymc !== '') {
  5412. // 仅改限价/备注时仍带工序名便于辨认
  5413. $parts[] = $gymc;
  5414. }
  5415. if ($p !== '') {
  5416. $parts[] = '最高限价「' . $p . '」';
  5417. }
  5418. if ($mbz !== '') {
  5419. $parts[] = '招标备注「' . $mbz . '」';
  5420. }
  5421. $detail = $parts !== [] ? implode(',', $parts) : '(未改数量/限价/招标备注)';
  5422. $this->addOrderLog(
  5423. $ids,
  5424. 'save_qty_price',
  5425. '保存本次数量、最高限价、招标备注:' . $detail,
  5426. $poIdLog
  5427. );
  5428. }
  5429. $this->pickHiddenScydgySetCache = null;
  5430. $this->success("操作成功");
  5431. }
  5432. /**
  5433. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价、备注(若表中有对应列)
  5434. *
  5435. * @param array<int, array> $rows 引用传递当前页行
  5436. */
  5437. protected function mergePurchaseOrder(array &$rows)
  5438. {
  5439. if ($rows === []) {
  5440. return;
  5441. }
  5442. $ids = [];
  5443. foreach ($rows as $rw) {
  5444. if (!is_array($rw)) {
  5445. continue;
  5446. }
  5447. $id = (int)($rw['ID'] ?? 0);
  5448. // 含手工新增负数 scydgy_id,避免限价/数量不同步
  5449. if ($this->isValidScydgyRowId($id)) {
  5450. $ids[$id] = true;
  5451. }
  5452. }
  5453. $idList = array_keys($ids);
  5454. if ($idList === []) {
  5455. return;
  5456. }
  5457. try {
  5458. $list = Db::table('purchase_order')
  5459. ->where('scydgy_id', 'in', $idList)
  5460. ->field('scydgy_id,This_quantity,ceilingPrice,MBZ')
  5461. ->select();
  5462. } catch (\Throwable $e) {
  5463. return;
  5464. }
  5465. if (!is_array($list)) {
  5466. return;
  5467. }
  5468. $byId = [];
  5469. foreach ($list as $dbRow) {
  5470. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  5471. continue;
  5472. }
  5473. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  5474. }
  5475. foreach ($rows as &$rw) {
  5476. if (!is_array($rw)) {
  5477. continue;
  5478. }
  5479. $sid = (int)($rw['ID'] ?? 0);
  5480. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  5481. continue;
  5482. }
  5483. $db = $byId[$sid];
  5484. // 有 purchase_order 记录时同步数量/限价/备注(含清空后的空串,避免刷新后又冒出来)
  5485. if (array_key_exists('This_quantity', $db)) {
  5486. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  5487. }
  5488. if (array_key_exists('ceilingPrice', $db)) {
  5489. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  5490. } elseif (array_key_exists('ceiling_price', $db)) {
  5491. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  5492. }
  5493. if (array_key_exists('MBZ', $db)) {
  5494. $poMbz = $db['MBZ'] === null ? '' : trim((string)$db['MBZ']);
  5495. if ($poMbz !== '') {
  5496. $rw['MBZ'] = $poMbz;
  5497. }
  5498. }
  5499. }
  5500. unset($rw);
  5501. }
  5502. /**
  5503. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  5504. */
  5505. public function purchaseConfirmPick()
  5506. {
  5507. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5508. $this->error(__('Invalid parameters'));
  5509. }
  5510. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  5511. $this->error(__('You have no permission'));
  5512. }
  5513. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  5514. if ($batchRaw !== '') {
  5515. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  5516. return;
  5517. }
  5518. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5519. $sid = (int)$scydgyId;
  5520. if (!$this->isValidScydgyRowId($sid)) {
  5521. $this->error('参数无效');
  5522. }
  5523. $parseIdList = function ($raw) {
  5524. if (is_array($raw)) {
  5525. $arr = $raw;
  5526. } else {
  5527. $decoded = json_decode((string)$raw, true);
  5528. $arr = is_array($decoded) ? $decoded : [];
  5529. }
  5530. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  5531. };
  5532. $selectedRaw = $this->request->post('selected_ids', null);
  5533. if ($selectedRaw === null || $selectedRaw === '') {
  5534. $legacy = (int)$this->request->post('selected_id', 0);
  5535. $selectedIds = $legacy > 0 ? [$legacy] : [];
  5536. } else {
  5537. $selectedIds = $parseIdList($selectedRaw);
  5538. }
  5539. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  5540. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  5541. try {
  5542. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  5543. } catch (\InvalidArgumentException $e) {
  5544. $this->error($e->getMessage());
  5545. } catch (\Throwable $e) {
  5546. $this->error($e->getMessage());
  5547. }
  5548. $this->pickHiddenScydgySetCache = null;
  5549. $this->success('操作成功', '', $result);
  5550. }
  5551. /**
  5552. * 整单采购确认(多道工序一次提交)
  5553. */
  5554. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  5555. {
  5556. $decoded = json_decode($batchRaw, true);
  5557. if (!is_array($decoded) || $decoded === []) {
  5558. $this->error('提交数据无效');
  5559. }
  5560. $picks = [];
  5561. foreach ($decoded as $item) {
  5562. if (!is_array($item)) {
  5563. continue;
  5564. }
  5565. $sid = (int)($item['scydgy_id'] ?? 0);
  5566. if (!$this->isValidScydgyRowId($sid)) {
  5567. continue;
  5568. }
  5569. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  5570. if (!is_array($sel)) {
  5571. $sel = [(int)$sel];
  5572. }
  5573. $unsel = $item['unselected_ids'] ?? [];
  5574. if (!is_array($unsel)) {
  5575. $unsel = json_decode((string)$unsel, true);
  5576. $unsel = is_array($unsel) ? $unsel : [];
  5577. }
  5578. $picks[] = [
  5579. 'scydgy_id' => $sid,
  5580. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  5581. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  5582. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  5583. ];
  5584. }
  5585. if ($picks === []) {
  5586. $this->error('提交数据无效');
  5587. }
  5588. Db::startTrans();
  5589. $results = [];
  5590. try {
  5591. foreach ($picks as $pick) {
  5592. $results[] = $this->runPurchaseConfirmPick(
  5593. (int)$pick['scydgy_id'],
  5594. $pick['selected_ids'],
  5595. $pick['unselected_ids'],
  5596. (int)$pick['purchase_order_id'],
  5597. false,
  5598. false
  5599. );
  5600. }
  5601. Db::commit();
  5602. } catch (\Throwable $e) {
  5603. Db::rollback();
  5604. $msg = $e->getMessage();
  5605. $this->error($msg !== '' ? $msg : '提交失败');
  5606. }
  5607. try {
  5608. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  5609. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  5610. } catch (\Throwable $e) {
  5611. Log::write('采购确认通知批量发送异常: ' . $e->getMessage(), 'error');
  5612. }
  5613. $this->pickHiddenScydgySetCache = null;
  5614. $this->success('操作成功', '', ['batch' => $results]);
  5615. }
  5616. /**
  5617. * @return array<string, mixed>
  5618. */
  5619. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  5620. {
  5621. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  5622. ProcuremenGuard::assertWflowPendingApproval($poRow);
  5623. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  5624. $scydgyId = (string)$sid;
  5625. if ($selectedIds === []) {
  5626. throw new \InvalidArgumentException('请至少勾选一条明细');
  5627. }
  5628. $inter = array_intersect($selectedIds, $unselectedIds);
  5629. if ($inter !== []) {
  5630. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  5631. }
  5632. $allIds = $this->purchaseOrderDetail($sid);
  5633. if ($allIds === []) {
  5634. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  5635. }
  5636. foreach ($selectedIds as $id) {
  5637. if (!in_array($id, $allIds, true)) {
  5638. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  5639. }
  5640. }
  5641. foreach ($unselectedIds as $id) {
  5642. if (!in_array($id, $allIds, true)) {
  5643. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  5644. }
  5645. }
  5646. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  5647. sort($union, SORT_NUMERIC);
  5648. $expect = $allIds;
  5649. sort($expect, SORT_NUMERIC);
  5650. if ($union !== $expect) {
  5651. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  5652. }
  5653. if ($manageTransaction) {
  5654. Db::startTrans();
  5655. }
  5656. try {
  5657. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  5658. $aff = 0;
  5659. try {
  5660. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  5661. } catch (\Throwable $e) {
  5662. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  5663. }
  5664. if ($aff < 1) {
  5665. throw new \Exception('更新选中状态失败');
  5666. }
  5667. $poPayload = [
  5668. // 审核通过后进入「待入库评分」;合格/不合格后才置已完结
  5669. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5670. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  5671. ];
  5672. if ($purchaseOrderId > 0) {
  5673. $poAff = (int)Db::table('purchase_order')
  5674. ->where('id', $purchaseOrderId)
  5675. ->where('scydgy_id', $sid)
  5676. ->update($poPayload);
  5677. if ($poAff < 1) {
  5678. throw new \Exception('主表订单不存在或与工序行不匹配');
  5679. }
  5680. } else {
  5681. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  5682. if ($poAff < 1) {
  5683. throw new \Exception('未找到');
  5684. }
  5685. }
  5686. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  5687. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  5688. if ($manageTransaction) {
  5689. Db::commit();
  5690. }
  5691. } catch (\Throwable $e) {
  5692. if ($manageTransaction) {
  5693. Db::rollback();
  5694. }
  5695. throw $e;
  5696. }
  5697. $poIdFinal = $purchaseOrderId;
  5698. if ($poIdFinal <= 0) {
  5699. try {
  5700. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  5701. if (is_array($rpo)) {
  5702. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  5703. }
  5704. } catch (\Throwable $e) {
  5705. $poIdFinal = 0;
  5706. }
  5707. }
  5708. $pickNames = [];
  5709. foreach ($selectedIds as $pid) {
  5710. $dr = $this->purchaseOrderDetai($sid, $pid);
  5711. $nm = trim((string)($dr['company_name'] ?? ''));
  5712. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  5713. }
  5714. $this->addOrderLog(
  5715. $sid,
  5716. 'purchase_confirm',
  5717. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  5718. $poIdFinal > 0 ? $poIdFinal : null
  5719. );
  5720. if ($sendNotifications) {
  5721. try {
  5722. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  5723. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  5724. 'scydgy_id' => $sid,
  5725. 'selected_ids' => $selectedIds,
  5726. 'unselected_ids' => $unselectedIds,
  5727. 'purchase_order_id' => $purchaseOrderId,
  5728. ]]);
  5729. } catch (\Throwable $e) {
  5730. Log::write('采购确认通知发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  5731. }
  5732. }
  5733. Log::write(sprintf(
  5734. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  5735. $scydgyId,
  5736. $purchaseOrderId,
  5737. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  5738. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  5739. ), 'notice');
  5740. $pdfPublicPath = '';
  5741. try {
  5742. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  5743. } catch (\Throwable $e) {
  5744. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  5745. }
  5746. return [
  5747. 'scydgy_id' => $scydgyId,
  5748. 'purchase_order_id' => $purchaseOrderId,
  5749. 'selected_ids' => $selectedIds,
  5750. 'unselected_ids' => $unselectedIds,
  5751. 'purchase_confirm_pdf' => $pdfPublicPath,
  5752. ];
  5753. }
  5754. /**
  5755. * 审批通过短信:按本次涉及的工序汇总 process_lines
  5756. *
  5757. * @param int[]|string[] $scydgyIds
  5758. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  5759. */
  5760. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  5761. {
  5762. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  5763. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  5764. if ($scydgyIds === []) {
  5765. return $empty;
  5766. }
  5767. $pos = [];
  5768. try {
  5769. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  5770. } catch (\Throwable $e) {
  5771. $rows = [];
  5772. }
  5773. if (is_array($rows)) {
  5774. foreach ($rows as $po) {
  5775. if (is_array($po)) {
  5776. $pos[] = $po;
  5777. }
  5778. }
  5779. }
  5780. if ($pos === []) {
  5781. return $empty;
  5782. }
  5783. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  5784. return [
  5785. 'ccydh' => $ccydh,
  5786. 'pos' => $pos,
  5787. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  5788. ];
  5789. }
  5790. /**
  5791. * 审批通过/未通过:短信 + 邮件(同一供应商只发一条;邮件含平台链接)
  5792. *
  5793. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  5794. * @param array<int, array<string, mixed>> $picks
  5795. */
  5796. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  5797. {
  5798. if ($picks === []) {
  5799. return;
  5800. }
  5801. $this->ensureConfirmResultEmailTemplates();
  5802. $fallbackDetailId = 0;
  5803. $winners = [];
  5804. $losers = [];
  5805. foreach ($picks as $pick) {
  5806. if (!is_array($pick)) {
  5807. continue;
  5808. }
  5809. $sid = (int)($pick['scydgy_id'] ?? 0);
  5810. if (!$this->isValidScydgyRowId($sid)) {
  5811. continue;
  5812. }
  5813. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  5814. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  5815. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  5816. $fallbackDetailId = (int)$selectedIds[0];
  5817. }
  5818. foreach ($selectedIds as $pid) {
  5819. $dr = $this->purchaseOrderDetai($sid, $pid);
  5820. if (!is_array($dr)) {
  5821. continue;
  5822. }
  5823. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  5824. }
  5825. foreach ($unselectedIds as $pid) {
  5826. $dr = $this->purchaseOrderDetai($sid, $pid);
  5827. if (!is_array($dr)) {
  5828. continue;
  5829. }
  5830. $key = $this->notifySupplierDedupeKey($dr);
  5831. if (!isset($winners[$key])) {
  5832. $losers[$key] = $dr;
  5833. }
  5834. }
  5835. }
  5836. if ($winners === [] && $losers === []) {
  5837. return;
  5838. }
  5839. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  5840. $poIdLog = 0;
  5841. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5842. if (isset($pos[0]) && is_array($pos[0])) {
  5843. $poIdLog = (int)($pos[0]['id'] ?? 0);
  5844. }
  5845. $mergeRowsLog = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  5846. $emailLogCcydh = $this->collectCcydhListForEmailLog($mergeRowsLog, $pos);
  5847. $emailLogBatchNo = $this->resolveBundleOrderBatchNo($bundle);
  5848. $sendSmsSafe = function ($phone, $content) {
  5849. $phone = trim((string)$phone);
  5850. if ($phone === '') {
  5851. return;
  5852. }
  5853. try {
  5854. $this->smsbao($phone, $content);
  5855. } catch (\Throwable $e) {
  5856. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  5857. }
  5858. };
  5859. $sendConfirmEmailSafe = function (array $dr, string $emailScene) use ($confirmNotifyVars, $poIdLog, $emailLogCcydh, $emailLogBatchNo) {
  5860. $cname = trim((string)($dr['company_name'] ?? ''));
  5861. $ph = trim((string)($dr['phone'] ?? ''));
  5862. $toEmail = trim((string)($dr['email'] ?? ''));
  5863. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5864. Log::write('采购确认邮件跳过:无有效邮箱 company=' . $cname, 'error');
  5865. return;
  5866. }
  5867. $detailId = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5868. if ($detailId <= 0) {
  5869. $detailId = (int)($confirmNotifyVars['_fallback_detail_id'] ?? 0);
  5870. }
  5871. try {
  5872. $platformUrl = $this->buildMprocMobileOrderUrl($detailId);
  5873. } catch (\Throwable $e) {
  5874. Log::write('采购确认邮件链接失败: ' . $e->getMessage(), 'error');
  5875. $platformUrl = '';
  5876. }
  5877. $vars = array_merge($confirmNotifyVars, [
  5878. 'company_name' => $cname,
  5879. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5880. 'phone' => $ph,
  5881. 'email' => $toEmail,
  5882. 'platform_url' => $platformUrl,
  5883. ]);
  5884. unset($vars['_fallback_detail_id']);
  5885. try {
  5886. $mailPlain = $this->renderNotifyTemplate($emailScene, $vars);
  5887. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  5888. $mailSubject = $this->resolveProcuremenEmailSubject($emailScene);
  5889. $mailConfig = $this->loadMailerConfig();
  5890. $this->issueSendSupplierEmail([
  5891. 'company_name' => $cname,
  5892. 'email' => $toEmail,
  5893. 'mail_plain' => $mailPlain,
  5894. 'mail_body' => $mailBody,
  5895. 'notify_vars' => $vars,
  5896. 'sms_content' => '',
  5897. 'detail_links' => $platformUrl !== '' ? [['url' => $platformUrl, 'cgymc' => '']] : [],
  5898. 'email_log_scene' => (strpos((string)$emailScene, 'confirm_ok') !== false) ? 'confirm_ok' : 'confirm_fail',
  5899. 'email_log_scydgy_id' => (int)($dr['scydgy_id'] ?? 0),
  5900. 'email_log_purchase_order_id' => $poIdLog,
  5901. 'email_log_ccydh' => $emailLogCcydh !== '' ? $emailLogCcydh : trim((string)($vars['ccydh'] ?? '')),
  5902. 'email_log_order_batch_no' => $emailLogBatchNo,
  5903. ], $mailConfig, $mailSubject);
  5904. } catch (\Throwable $e) {
  5905. Log::write('采购确认邮件失败 company=' . $cname . ' email=' . $toEmail . ' ' . $e->getMessage(), 'error');
  5906. }
  5907. };
  5908. $confirmNotifyVars['_fallback_detail_id'] = $fallbackDetailId;
  5909. foreach ($winners as $dr) {
  5910. $cname = trim((string)($dr['company_name'] ?? ''));
  5911. $ph = trim((string)($dr['phone'] ?? ''));
  5912. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  5913. 'company_name' => $cname,
  5914. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5915. 'phone' => $ph,
  5916. ]));
  5917. $sendSmsSafe($ph, $sms);
  5918. $sendConfirmEmailSafe($dr, 'confirm_ok_email');
  5919. }
  5920. foreach ($losers as $dr) {
  5921. $cname = trim((string)($dr['company_name'] ?? ''));
  5922. $ph = trim((string)($dr['phone'] ?? ''));
  5923. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  5924. 'company_name' => $cname,
  5925. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5926. 'phone' => $ph,
  5927. ]));
  5928. $sendSmsSafe($ph, $sms);
  5929. $sendConfirmEmailSafe($dr, 'confirm_fail_email');
  5930. }
  5931. }
  5932. /**
  5933. * 短信去重键:优先手机号,否则公司名
  5934. */
  5935. protected function notifySupplierDedupeKey(array $detailRow): string
  5936. {
  5937. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  5938. if ($ph !== '') {
  5939. return 'p:' . $ph;
  5940. }
  5941. $cn = trim((string)($detailRow['company_name'] ?? ''));
  5942. return 'c:' . $cn;
  5943. }
  5944. /**
  5945. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  5946. *
  5947. * @param int[] $detailIds
  5948. */
  5949. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  5950. {
  5951. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  5952. if ($detailIds === []) {
  5953. return;
  5954. }
  5955. $payload = ['status_name' => $statusName];
  5956. try {
  5957. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  5958. } catch (\Throwable $e) {
  5959. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  5960. }
  5961. }
  5962. /**
  5963. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  5964. */
  5965. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  5966. {
  5967. try {
  5968. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  5969. } catch (\Throwable $e) {
  5970. return;
  5971. }
  5972. if (!is_array($rows)) {
  5973. return;
  5974. }
  5975. foreach ($rows as $dr) {
  5976. if (!is_array($dr)) {
  5977. continue;
  5978. }
  5979. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5980. if ($id <= 0) {
  5981. continue;
  5982. }
  5983. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  5984. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  5985. try {
  5986. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  5987. } catch (\Throwable $e) {
  5988. }
  5989. }
  5990. }
  5991. /**
  5992. * @param array<string, mixed> $detailRow
  5993. */
  5994. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  5995. {
  5996. $am = $detailRow['amount'] ?? null;
  5997. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  5998. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  5999. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  6000. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  6001. }
  6002. /**
  6003. * @return int[]
  6004. */
  6005. protected function purchaseOrderDetail(int $scydgyId): array
  6006. {
  6007. if (!$this->isValidScydgyRowId($scydgyId)) {
  6008. return [];
  6009. }
  6010. try {
  6011. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  6012. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  6013. $list = $listQuery->select();
  6014. } catch (\Throwable $e) {
  6015. return [];
  6016. }
  6017. if (!is_array($list)) {
  6018. return [];
  6019. }
  6020. $ids = [];
  6021. foreach ($list as $r) {
  6022. if (!is_array($r)) {
  6023. continue;
  6024. }
  6025. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  6026. if ($pk > 0) {
  6027. $ids[] = $pk;
  6028. }
  6029. }
  6030. return array_values(array_unique($ids));
  6031. }
  6032. /**
  6033. * 获取当前登录用户信息 [id, 展示名]
  6034. * admin_name 一律记「名称」(昵称),无昵称再回退账号
  6035. */
  6036. protected function GetUseName(): array
  6037. {
  6038. $id = 0;
  6039. $name = '';
  6040. try {
  6041. if ($this->auth && $this->auth->isLogin()) {
  6042. $u = $this->auth->getUserInfo();
  6043. if (is_array($u)) {
  6044. $id = (int)($u['id'] ?? 0);
  6045. $name = trim((string)($u['nickname'] ?? ''));
  6046. // 会话昵称缺失或等于登录账号时,再查库取正式昵称
  6047. $sessionUser = trim((string)($u['username'] ?? ''));
  6048. if ($id > 0 && ($name === '' || ($sessionUser !== '' && strcasecmp($name, $sessionUser) === 0))) {
  6049. try {
  6050. $row = Db::name('admin')->where('id', $id)->field('nickname,username')->find();
  6051. if (is_array($row)) {
  6052. $nick = trim((string)($row['nickname'] ?? ''));
  6053. if ($nick !== '') {
  6054. $name = $nick;
  6055. } elseif ($name === '') {
  6056. $name = trim((string)($row['username'] ?? ''));
  6057. }
  6058. }
  6059. } catch (\Throwable $e) {
  6060. }
  6061. }
  6062. if ($name === '') {
  6063. $name = $sessionUser;
  6064. }
  6065. }
  6066. }
  6067. } catch (\Throwable $e) {
  6068. }
  6069. if ($name === '') {
  6070. $name = '未知用户';
  6071. }
  6072. return [$id, $name];
  6073. }
  6074. /**
  6075. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  6076. */
  6077. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  6078. {
  6079. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  6080. }
  6081. /**
  6082. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  6083. *
  6084. * @param array<int, array<string, mixed>> $rows
  6085. */
  6086. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  6087. {
  6088. $sidList = [];
  6089. foreach ($rows as $rw) {
  6090. if (!is_array($rw)) {
  6091. continue;
  6092. }
  6093. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  6094. foreach ($rw['_order_merge_rows'] as $mr) {
  6095. $mid = (int)($mr['ID'] ?? 0);
  6096. if ($this->isValidScydgyRowId($mid)) {
  6097. $sidList[$mid] = true;
  6098. }
  6099. }
  6100. }
  6101. $id = (int)($rw['ID'] ?? 0);
  6102. if ($this->isValidScydgyRowId($id)) {
  6103. $sidList[$id] = true;
  6104. }
  6105. }
  6106. $sids = array_keys($sidList);
  6107. $issueBySid = [];
  6108. $confirmBySid = [];
  6109. $approveBySid = [];
  6110. if ($sids !== []) {
  6111. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  6112. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  6113. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  6114. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  6115. try {
  6116. $logs = Db::table('purchase_order_oper_log')
  6117. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  6118. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  6119. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  6120. ->order('id', 'asc')
  6121. ->select();
  6122. } catch (\Throwable $e) {
  6123. $logs = [];
  6124. }
  6125. if (is_array($logs)) {
  6126. $issueSet = array_fill_keys($issueActs, true);
  6127. $confirmSet = array_fill_keys($confirmActs, true);
  6128. $approveSet = array_fill_keys($approveActs, true);
  6129. foreach ($logs as $lg) {
  6130. if (!is_array($lg)) {
  6131. continue;
  6132. }
  6133. $lg = ProcuremenOperLog::normalizeRow($lg);
  6134. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  6135. if ($sid === 0) {
  6136. continue;
  6137. }
  6138. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  6139. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  6140. if ($t === '') {
  6141. continue;
  6142. }
  6143. if (isset($issueSet[$action])) {
  6144. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  6145. $issueBySid[$sid] = $t;
  6146. }
  6147. }
  6148. if (isset($confirmSet[$action])) {
  6149. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  6150. $confirmBySid[$sid] = $t;
  6151. }
  6152. }
  6153. if (isset($approveSet[$action])) {
  6154. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  6155. $approveBySid[$sid] = $t;
  6156. }
  6157. }
  6158. }
  6159. }
  6160. }
  6161. foreach ($rows as &$rw) {
  6162. if (!is_array($rw)) {
  6163. continue;
  6164. }
  6165. $mergeSids = [];
  6166. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  6167. foreach ($rw['_order_merge_rows'] as $mr) {
  6168. $mid = (int)($mr['ID'] ?? 0);
  6169. if ($this->isValidScydgyRowId($mid)) {
  6170. $mergeSids[] = $mid;
  6171. }
  6172. }
  6173. }
  6174. $rid = (int)($rw['ID'] ?? 0);
  6175. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  6176. $mergeSids[] = $rid;
  6177. }
  6178. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  6179. $issue = $pick;
  6180. $confirm = '';
  6181. $approve = '';
  6182. foreach ($mergeSids as $sid) {
  6183. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  6184. $issue = $issueBySid[$sid];
  6185. }
  6186. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  6187. $confirm = $confirmBySid[$sid];
  6188. }
  6189. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  6190. $approve = $approveBySid[$sid];
  6191. }
  6192. }
  6193. if ($issue === '' && $pick !== '') {
  6194. $issue = $pick;
  6195. }
  6196. $rw['issue_time'] = $issue;
  6197. $rw['confirm_time'] = $confirm;
  6198. $rw['approve_time'] = $approve;
  6199. }
  6200. unset($rw);
  6201. }
  6202. /**
  6203. * 按主键取一条
  6204. */
  6205. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  6206. {
  6207. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  6208. return [];
  6209. }
  6210. try {
  6211. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  6212. if (is_array($one)) {
  6213. return $one;
  6214. }
  6215. } catch (\Throwable $e) {
  6216. }
  6217. try {
  6218. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  6219. if (is_array($one)) {
  6220. return $one;
  6221. }
  6222. } catch (\Throwable $e) {
  6223. }
  6224. return [];
  6225. }
  6226. /**
  6227. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  6228. */
  6229. protected function formatProcuremenDetailTime($v): string
  6230. {
  6231. return ProcuremenFormat::detailTime($v);
  6232. }
  6233. /**
  6234. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  6235. */
  6236. protected function formatDeliveryYmd($v): string
  6237. {
  6238. return ProcuremenFormat::deliveryYmd($v);
  6239. }
  6240. /**
  6241. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  6242. */
  6243. protected function detailRowSupplierOperated(array $r): bool
  6244. {
  6245. $am = $r['amount'] ?? null;
  6246. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  6247. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  6248. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  6249. return $okAmt || $okDel;
  6250. }
  6251. /**
  6252. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  6253. */
  6254. protected function resolveDetailSupplierOperTime(array $r): string
  6255. {
  6256. if (!$this->detailRowSupplierOperated($r)) {
  6257. return '';
  6258. }
  6259. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  6260. if ($t !== '') {
  6261. return $t;
  6262. }
  6263. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  6264. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  6265. continue;
  6266. }
  6267. $t = $this->formatProcuremenDetailTime($r[$col]);
  6268. if ($t !== '') {
  6269. return $t;
  6270. }
  6271. }
  6272. return '';
  6273. }
  6274. /**
  6275. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  6276. */
  6277. protected function detailRowSupplierAccepted(array $r): bool
  6278. {
  6279. $am = $r['amount'] ?? null;
  6280. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  6281. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  6282. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  6283. return $okAmt && $okDel;
  6284. }
  6285. /**
  6286. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  6287. */
  6288. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  6289. {
  6290. if ($detailCount > 0) {
  6291. return true;
  6292. }
  6293. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  6294. return true;
  6295. }
  6296. $pickTime = trim((string)($main['pick_time'] ?? ''));
  6297. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  6298. return true;
  6299. }
  6300. return false;
  6301. }
  6302. /**
  6303. * 下发时间:优先 pick_time,其次首条下发明细时间
  6304. */
  6305. protected function resolveProcuremenIssueTime(array $main, array $details): string
  6306. {
  6307. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  6308. if ($issueTime !== '') {
  6309. return $issueTime;
  6310. }
  6311. foreach ($details as $dr) {
  6312. if (!is_array($dr)) {
  6313. continue;
  6314. }
  6315. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  6316. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  6317. $issueTime = $t;
  6318. }
  6319. }
  6320. if ($issueTime !== '') {
  6321. return $issueTime;
  6322. }
  6323. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  6324. }
  6325. /**
  6326. * 直接点「完结」时间:优先操作记录 mark_complete
  6327. */
  6328. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  6329. {
  6330. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  6331. }
  6332. /**
  6333. * 操作记录时间(取指定 action 最近一条)
  6334. *
  6335. * @param string|array<int, string> $actions
  6336. */
  6337. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  6338. {
  6339. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  6340. }
  6341. /**
  6342. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  6343. *
  6344. * @param array $main purchase_order 一行
  6345. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  6346. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  6347. */
  6348. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  6349. {
  6350. $issueCnt = count($details);
  6351. $acceptCnt = 0;
  6352. $pickedName = '';
  6353. $pickedTime = '';
  6354. foreach ($details as $dr) {
  6355. if (!is_array($dr)) {
  6356. continue;
  6357. }
  6358. if ($this->detailRowSupplierAccepted($dr)) {
  6359. $acceptCnt++;
  6360. }
  6361. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  6362. if ($pickedName === '') {
  6363. $pickedName = trim((string)($dr['company_name'] ?? ''));
  6364. }
  6365. if ($pickedTime === '') {
  6366. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  6367. if ($pickedTime === '') {
  6368. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  6369. }
  6370. }
  6371. }
  6372. }
  6373. $hasMain = $main !== [];
  6374. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  6375. if ($poTime === '') {
  6376. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  6377. }
  6378. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  6379. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  6380. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  6381. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  6382. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  6383. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  6384. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  6385. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  6386. $inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
  6387. $inboundResult = '';
  6388. if ($scydgyId > 0) {
  6389. try {
  6390. $inRow = Db::table('purchase_order_inbound_score')
  6391. ->where('scydgy_id', $scydgyId)
  6392. ->field('result,updatetime,createtime')
  6393. ->find();
  6394. } catch (\Throwable $e) {
  6395. $inRow = null;
  6396. }
  6397. if (is_array($inRow) && $inRow !== []) {
  6398. $inboundResult = trim((string)($inRow['result'] ?? ''));
  6399. if ($inboundScoreTime === '') {
  6400. $inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
  6401. }
  6402. }
  6403. }
  6404. $inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
  6405. $supplierTime = '';
  6406. if ($acceptCnt > 0) {
  6407. foreach ($details as $dr) {
  6408. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  6409. continue;
  6410. }
  6411. $t = $this->resolveDetailSupplierOperTime($dr);
  6412. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  6413. $supplierTime = $t;
  6414. }
  6415. }
  6416. }
  6417. $directComplete = ($mainCompleted && !$issued);
  6418. $doneTime = '';
  6419. if ($mainCompleted) {
  6420. if ($directComplete) {
  6421. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  6422. }
  6423. if ($doneTime === '' && $inboundScoreTime !== '') {
  6424. $doneTime = $inboundScoreTime;
  6425. }
  6426. if ($doneTime === '') {
  6427. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  6428. }
  6429. if ($doneTime === '') {
  6430. foreach ($details as $dr) {
  6431. if (!is_array($dr)) {
  6432. continue;
  6433. }
  6434. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  6435. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  6436. $doneTime = $t;
  6437. }
  6438. }
  6439. }
  6440. if ($doneTime === '') {
  6441. $doneTime = $poTime;
  6442. }
  6443. // 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
  6444. if ($doneTime === '' && $confirmApproveTime !== '') {
  6445. $doneTime = $confirmApproveTime;
  6446. }
  6447. }
  6448. if ($directComplete) {
  6449. // 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
  6450. $step1Done = $hasMain;
  6451. $step2Done = false;
  6452. $step3Done = false;
  6453. $step4Done = false;
  6454. $step5Done = false;
  6455. $stepInboundDone = $inboundScored;
  6456. $step6Done = $mainCompleted && $inboundScored;
  6457. } else {
  6458. $step1Done = $issued;
  6459. $step2Done = $issued;
  6460. $step3Done = $acceptCnt > 0;
  6461. $step4Done = $wflowPendingApproval;
  6462. if (!$step4Done) {
  6463. foreach ($details as $dr) {
  6464. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  6465. $step4Done = true;
  6466. break;
  6467. }
  6468. }
  6469. }
  6470. $step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
  6471. $stepInboundDone = $inboundScored;
  6472. // 未确认合格/不合格时,「已完结」保持未点亮(灰色)
  6473. $step6Done = $mainCompleted && $inboundScored;
  6474. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  6475. if ($mainCompleted && $issued) {
  6476. $step3Done = true;
  6477. $step4Done = true;
  6478. $step5Done = true;
  6479. // 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
  6480. if ($supplierTime === '') {
  6481. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6482. if ($fillT !== '') {
  6483. $supplierTime = $fillT;
  6484. }
  6485. }
  6486. if ($pickedTime === '') {
  6487. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6488. if ($fillT !== '') {
  6489. $pickedTime = $fillT;
  6490. }
  6491. }
  6492. if ($auditSelectTime === '') {
  6493. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6494. if ($fillT !== '') {
  6495. $auditSelectTime = $fillT;
  6496. }
  6497. }
  6498. if ($confirmApproveTime === '') {
  6499. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6500. if ($fillT !== '') {
  6501. $confirmApproveTime = $fillT;
  6502. }
  6503. }
  6504. }
  6505. }
  6506. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  6507. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  6508. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  6509. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  6510. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  6511. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  6512. $inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
  6513. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  6514. $deadlineLines = [];
  6515. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  6516. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  6517. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  6518. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  6519. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  6520. }
  6521. }
  6522. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  6523. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  6524. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  6525. if ($deliveryDisp === '') {
  6526. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  6527. }
  6528. if ($deliveryDisp !== '') {
  6529. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  6530. }
  6531. }
  6532. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  6533. $deadlineText = implode("\n", $deadlineLines);
  6534. $prefixOperTime = static function (string $t): string {
  6535. $t = trim($t);
  6536. if ($t === '' || $t === '—') {
  6537. return $t;
  6538. }
  6539. if (strpos($t, '操作时间') === 0) {
  6540. return $t;
  6541. }
  6542. return '操作时间:' . $t;
  6543. };
  6544. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  6545. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  6546. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
  6547. $stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  6548. $step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  6549. $steps = [
  6550. [
  6551. 'title' => '未发',
  6552. 'subtitle' => '',
  6553. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  6554. 'done' => $step1Done,
  6555. ],
  6556. [
  6557. 'title' => '下发',
  6558. 'subtitle' => $deadlineText,
  6559. 'time' => $prefixOperTime($step2Time),
  6560. 'done' => $step2Done,
  6561. ],
  6562. [
  6563. 'title' => '供应商接单',
  6564. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  6565. 'time' => '',
  6566. 'done' => $step3Done,
  6567. ],
  6568. [
  6569. 'title' => '待确认',
  6570. 'subtitle' => $step4Done
  6571. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  6572. : ($issued ? '待选供应商' : ''),
  6573. 'time' => $prefixOperTime($step4Time),
  6574. 'done' => $step4Done,
  6575. ],
  6576. [
  6577. 'title' => '待审批',
  6578. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  6579. 'time' => $prefixOperTime($step5Time),
  6580. 'done' => $step5Done,
  6581. ],
  6582. [
  6583. 'title' => '是否合格',
  6584. 'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
  6585. 'time' => $prefixOperTime($stepInboundTime),
  6586. 'done' => $stepInboundDone,
  6587. ],
  6588. [
  6589. 'title' => '已完结',
  6590. 'subtitle' => '',
  6591. 'time' => $prefixOperTime($step6Time),
  6592. 'done' => $step6Done,
  6593. ],
  6594. ];
  6595. $currentIdx = count($steps) - 1;
  6596. if ($directComplete) {
  6597. // 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
  6598. if (!$step6Done) {
  6599. foreach ($steps as $i => $s) {
  6600. if (($s['title'] ?? '') === '是否合格') {
  6601. $currentIdx = $i;
  6602. break;
  6603. }
  6604. }
  6605. }
  6606. } else {
  6607. foreach ($steps as $i => $s) {
  6608. if (!$s['done']) {
  6609. $currentIdx = $i;
  6610. break;
  6611. }
  6612. }
  6613. }
  6614. $nSteps = count($steps);
  6615. foreach ($steps as $idx => &$s) {
  6616. $s['current'] = ($idx === $currentIdx);
  6617. if ($idx === 0) {
  6618. $s['pdf_left_bg'] = '';
  6619. } else {
  6620. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  6621. }
  6622. if ($idx >= $nSteps - 1) {
  6623. $s['pdf_right_bg'] = '';
  6624. } else {
  6625. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  6626. }
  6627. }
  6628. unset($s);
  6629. $labelMap = [
  6630. 'CCYDH' => '订单号',
  6631. 'CYJMC' => '印件名称',
  6632. 'CCLBMMC' => '承揽部门',
  6633. 'CGYMC' => '工序名称',
  6634. 'CDW' => '单位',
  6635. 'czlyq' => '类型',
  6636. 'NGZL' => '工作量',
  6637. 'CDF' => '单价',
  6638. 'cGzzxMc' => '工作中心',
  6639. 'MBZ' => '招标备注',
  6640. 'This_quantity' => '本次数量',
  6641. 'ceilingPrice' => '最高限价',
  6642. ];
  6643. $orderSummary = [];
  6644. foreach ($labelMap as $key => $lab) {
  6645. if (!array_key_exists($key, $main)) {
  6646. continue;
  6647. }
  6648. $val = $main[$key];
  6649. if ($val === null) {
  6650. $val = '';
  6651. } elseif (!is_scalar($val)) {
  6652. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  6653. } else {
  6654. $val = (string)$val;
  6655. }
  6656. $orderSummary[] = ['label' => $lab, 'value' => $val];
  6657. }
  6658. $orderSummary[] = [
  6659. 'label' => '是否合格',
  6660. 'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
  6661. ];
  6662. $orderSummaryGrid = [];
  6663. $n = count($orderSummary);
  6664. for ($i = 0; $i < $n; $i += 2) {
  6665. $left = $orderSummary[$i];
  6666. $hasRight = ($i + 1) < $n;
  6667. $orderSummaryGrid[] = [
  6668. 'l1' => $left['label'],
  6669. 'v1' => $left['value'],
  6670. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  6671. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  6672. ];
  6673. }
  6674. return [
  6675. 'steps' => $steps,
  6676. 'orderSummary' => $orderSummary,
  6677. 'orderSummaryGrid' => $orderSummaryGrid,
  6678. 'inbound_result' => $inboundResult,
  6679. 'inbound_score_time'=> $inboundScoreTime,
  6680. 'detailRows' => $details,
  6681. ];
  6682. }
  6683. /**
  6684. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  6685. *
  6686. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  6687. */
  6688. protected function prepareProcuremenDetailsView(string $ids): array
  6689. {
  6690. $main = [];
  6691. try {
  6692. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  6693. $main = is_array($one) ? $one : [];
  6694. } catch (\Throwable $e) {
  6695. $main = [];
  6696. }
  6697. $details = [];
  6698. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  6699. if ($mergeRows === []) {
  6700. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  6701. if ($mergeRows === [] && $main !== []) {
  6702. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  6703. }
  6704. }
  6705. $detailSidList = [];
  6706. $anchorSid = (int)$ids;
  6707. if ($anchorSid !== 0) {
  6708. $detailSidList[$anchorSid] = true;
  6709. }
  6710. foreach ($mergeRows as $mr) {
  6711. if (!is_array($mr)) {
  6712. continue;
  6713. }
  6714. $sid = $this->extractScydgyRowId($mr);
  6715. if ($sid !== 0) {
  6716. $detailSidList[$sid] = true;
  6717. }
  6718. }
  6719. try {
  6720. if ($detailSidList !== []) {
  6721. $details = Db::table('purchase_order_detail')
  6722. ->where('scydgy_id', 'in', array_keys($detailSidList))
  6723. ->order('id', 'asc')
  6724. ->select();
  6725. }
  6726. } catch (\Throwable $e) {
  6727. $details = [];
  6728. }
  6729. if (!is_array($details)) {
  6730. $details = [];
  6731. }
  6732. foreach ($details as &$r) {
  6733. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  6734. $r['id'] = $r['ID'];
  6735. }
  6736. if (isset($r['createtime'])) {
  6737. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  6738. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  6739. } else {
  6740. $r['createtime_text'] = (string)$r['createtime'];
  6741. }
  6742. } else {
  6743. $r['createtime_text'] = '';
  6744. }
  6745. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  6746. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  6747. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  6748. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  6749. if (is_array($r)) {
  6750. $r = $this->maskSupplierContactFields($r);
  6751. }
  6752. }
  6753. unset($r);
  6754. $activeDetails = [];
  6755. foreach ($details as $r) {
  6756. if (is_array($r) && empty($r['is_void'])) {
  6757. $activeDetails[] = $r;
  6758. }
  6759. }
  6760. $operLogs = [];
  6761. try {
  6762. $operSidList = array_keys($detailSidList);
  6763. if ($operSidList === [] && (int)$ids !== 0) {
  6764. $operSidList = [(int)$ids];
  6765. }
  6766. if ($operSidList !== []) {
  6767. $operLogs = Db::table('purchase_order_oper_log')
  6768. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  6769. ->order('id', 'asc')
  6770. ->select();
  6771. }
  6772. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  6773. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  6774. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  6775. if ($poId > 0) {
  6776. $operLogs = Db::table('purchase_order_oper_log')
  6777. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  6778. ->order('id', 'asc')
  6779. ->select();
  6780. }
  6781. }
  6782. } catch (\Throwable $e) {
  6783. $operLogs = [];
  6784. }
  6785. if (!is_array($operLogs)) {
  6786. $operLogs = [];
  6787. }
  6788. $operLogsRaw = $operLogs;
  6789. $processNameBySid = [];
  6790. foreach ($mergeRows as $mr) {
  6791. if (!is_array($mr)) {
  6792. continue;
  6793. }
  6794. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  6795. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  6796. if ($psid !== 0 && $gymc !== '') {
  6797. $processNameBySid[$psid] = $gymc;
  6798. }
  6799. }
  6800. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  6801. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
  6802. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  6803. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  6804. if ($ccydh === '') {
  6805. foreach ($details as $r) {
  6806. if (!is_array($r)) {
  6807. continue;
  6808. }
  6809. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  6810. if ($ccydh !== '') {
  6811. break;
  6812. }
  6813. }
  6814. }
  6815. $this->view->assign('ccydh', $ccydh);
  6816. $this->view->assign('steps', $bundle['steps']);
  6817. $this->view->assign('orderSummary', $bundle['orderSummary']);
  6818. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  6819. $this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
  6820. $this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
  6821. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  6822. $this->view->assign('processCount', count($mergeRows));
  6823. $orderBatchNo = $this->resolveProcuremenOrderBatchNo($main);
  6824. if ($orderBatchNo === '' && $detailSidList !== []) {
  6825. try {
  6826. $poBn = Db::table('purchase_order')
  6827. ->where('scydgy_id', 'in', array_keys($detailSidList))
  6828. ->whereRaw("TRIM(IFNULL(`order_batch_no`,'')) <> ''")
  6829. ->order('id', 'desc')
  6830. ->find();
  6831. if (is_array($poBn)) {
  6832. $orderBatchNo = $this->resolveProcuremenOrderBatchNo($poBn);
  6833. }
  6834. } catch (\Throwable $e) {
  6835. $orderBatchNo = '';
  6836. }
  6837. }
  6838. $this->view->assign('orderBatchNo', $orderBatchNo);
  6839. $this->view->assign('detailRows', $details);
  6840. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  6841. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  6842. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  6843. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  6844. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  6845. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  6846. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  6847. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  6848. $this->view->assign('operLogs', $operLogs);
  6849. $sg = $quoteView['supplier_groups'] ?? [];
  6850. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
  6851. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  6852. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
  6853. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
  6854. return [
  6855. 'ok' => $main !== [] || $details !== [],
  6856. 'ccydh' => $ccydh,
  6857. 'steps' => $bundle['steps'],
  6858. ];
  6859. }
  6860. /**
  6861. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  6862. */
  6863. public function details()
  6864. {
  6865. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6866. if (is_array($ids)) {
  6867. $ids = isset($ids[0]) ? $ids[0] : '';
  6868. }
  6869. $ids = trim((string)$ids);
  6870. if ($ids === '') {
  6871. $this->error(__('Invalid parameters'));
  6872. }
  6873. $this->assertManualOrderDetailsViewable((int)$ids);
  6874. // 已完结:打开详情时按最新进度/操作记录重存存证 PDF(含质量/交货评分)
  6875. $sid = (int)$ids;
  6876. if ($this->isValidScydgyRowId($sid)) {
  6877. try {
  6878. $poCheck = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  6879. if (is_array($poCheck) && ProcuremenStatus::isPoCompleted($poCheck['status'] ?? '')) {
  6880. $this->refreshCompletedOrderArchivePdf($sid, true);
  6881. }
  6882. } catch (\Throwable $e) {
  6883. Log::write('详情页刷新完结存证PDF失败 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'notice');
  6884. }
  6885. }
  6886. $this->prepareProcuremenDetailsView($ids);
  6887. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  6888. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  6889. $this->view->engine->layout(false);
  6890. try {
  6891. return $this->view->fetch('procuremen/details_dialog_shell');
  6892. } finally {
  6893. if ($restoreLayout) {
  6894. $this->view->engine->layout($restoreLayout);
  6895. }
  6896. }
  6897. }
  6898. /**
  6899. * 已完结订单重生成存证 PDF(与详情页一致,含质量/交货评分与「已完结」节点)
  6900. *
  6901. * @param bool $requireCompleted true 时仅已完结才重生成;false 强制按当前详情重存
  6902. * @return string 本地 web 路径或 OSS URL,失败为空串
  6903. */
  6904. protected function refreshCompletedOrderArchivePdf(int $scydgyId, bool $requireCompleted = true): string
  6905. {
  6906. if (!$this->isValidScydgyRowId($scydgyId)) {
  6907. return '';
  6908. }
  6909. try {
  6910. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6911. } catch (\Throwable $e) {
  6912. $po = null;
  6913. }
  6914. if (!is_array($po) || $po === []) {
  6915. return '';
  6916. }
  6917. if ($requireCompleted && !ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6918. return trim((string)($po['pdf_url'] ?? ''));
  6919. }
  6920. $poId = (int)($po['id'] ?? 0);
  6921. return $this->savePurchaseConfirmDetailPdf($scydgyId, $poId);
  6922. }
  6923. /**
  6924. * CLI / 手机端评分完结后调用:无后台登录态重生成存证 PDF
  6925. */
  6926. public static function regenerateArchivePdfWithoutAuth(int $scydgyId, bool $requireCompleted = true): string
  6927. {
  6928. if ((int)$scydgyId === 0) {
  6929. return '';
  6930. }
  6931. try {
  6932. $ctl = new class extends Procuremen {
  6933. public function _initialize()
  6934. {
  6935. $this->request = \think\Request::instance();
  6936. $tpl = \think\Config::get('template');
  6937. if (!is_array($tpl)) {
  6938. $tpl = [];
  6939. }
  6940. // CLI / 跨模块调用时无 admin 视图目录
  6941. $tpl['view_path'] = APP_PATH . 'admin' . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR;
  6942. $this->view = new \think\View($tpl, \think\Config::get('view_replace_str'));
  6943. $this->model = new \app\admin\model\Procuremen();
  6944. try {
  6945. ProcuremenSchema::ensureAll();
  6946. } catch (\Throwable $e) {
  6947. }
  6948. }
  6949. public function runRegen(int $sid, bool $requireCompleted): string
  6950. {
  6951. return $this->refreshCompletedOrderArchivePdf($sid, $requireCompleted);
  6952. }
  6953. };
  6954. return $ctl->runRegen($scydgyId, $requireCompleted);
  6955. } catch (\Throwable $e) {
  6956. Log::write('regenerateArchivePdfWithoutAuth 失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'error');
  6957. return '';
  6958. }
  6959. }
  6960. /**
  6961. * 解析合并下发工序行(可跨订单,且均未协助)
  6962. *
  6963. * @return array<int, array<string, mixed>>
  6964. */
  6965. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  6966. {
  6967. $primary = json_decode($rowJson, true);
  6968. if (!is_array($primary)) {
  6969. $this->error(__('Invalid parameters'));
  6970. }
  6971. $merge = json_decode($mergeRowsJson, true);
  6972. if (!is_array($merge) || $merge === []) {
  6973. $merge = [$primary];
  6974. }
  6975. $seen = [];
  6976. $out = [];
  6977. foreach ($merge as $r) {
  6978. if (!is_array($r)) {
  6979. continue;
  6980. }
  6981. $id = $this->extractScydgyRowId($r);
  6982. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  6983. continue;
  6984. }
  6985. $seen[$id] = true;
  6986. $out[] = $r;
  6987. }
  6988. if ($out === []) {
  6989. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  6990. }
  6991. // 允许多订单同批下发:不再校验订单号一致
  6992. $ids = [];
  6993. foreach ($out as $r) {
  6994. $id = $this->extractScydgyRowId($r);
  6995. if ($this->isValidScydgyRowId($id)) {
  6996. $ids[$id] = true;
  6997. }
  6998. }
  6999. $poBySid = [];
  7000. $detCntBySid = [];
  7001. if ($ids !== []) {
  7002. $idList = array_keys($ids);
  7003. try {
  7004. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  7005. if (is_array($poList)) {
  7006. foreach ($poList as $po) {
  7007. if (!is_array($po)) {
  7008. continue;
  7009. }
  7010. $sid = (int)($po['scydgy_id'] ?? 0);
  7011. if ($this->isValidScydgyRowId($sid)) {
  7012. $poBySid[$sid] = $po;
  7013. }
  7014. }
  7015. }
  7016. } catch (\Throwable $e) {
  7017. }
  7018. try {
  7019. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  7020. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  7021. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  7022. if (is_array($detRows)) {
  7023. foreach ($detRows as $dr) {
  7024. if (!is_array($dr)) {
  7025. continue;
  7026. }
  7027. $sid = (int)($dr['scydgy_id'] ?? 0);
  7028. if ($this->isValidScydgyRowId($sid)) {
  7029. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  7030. }
  7031. }
  7032. }
  7033. } catch (\Throwable $e) {
  7034. }
  7035. }
  7036. foreach ($out as $r) {
  7037. $id = $this->extractScydgyRowId($r);
  7038. if (!$this->isValidScydgyRowId($id)) {
  7039. continue;
  7040. }
  7041. $po = $poBySid[$id] ?? null;
  7042. if (!is_array($po)) {
  7043. continue;
  7044. }
  7045. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  7046. $gymc = trim((string)($r['CGYMC'] ?? ''));
  7047. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  7048. }
  7049. $detCnt = (int)($detCntBySid[$id] ?? 0);
  7050. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  7051. $gymc = trim((string)($r['CGYMC'] ?? ''));
  7052. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  7053. }
  7054. }
  7055. return $out;
  7056. }
  7057. /**
  7058. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  7059. */
  7060. protected function maskSupplierContactFields(array $item): array
  7061. {
  7062. if (array_key_exists('email', $item)) {
  7063. $item['email'] = mask_email((string)$item['email']);
  7064. }
  7065. if (array_key_exists('phone', $item)) {
  7066. $item['phone'] = mask_phone((string)$item['phone']);
  7067. }
  7068. return $item;
  7069. }
  7070. /**
  7071. * @param array<int, array<string, mixed>> $list
  7072. * @return array<int, array<string, mixed>>
  7073. */
  7074. protected function maskSupplierContactList(array $list): array
  7075. {
  7076. $out = [];
  7077. foreach ($list as $item) {
  7078. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  7079. }
  7080. return $out;
  7081. }
  7082. /**
  7083. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  7084. *
  7085. * @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
  7086. * @return array<string, string>|null
  7087. */
  7088. protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
  7089. {
  7090. if (!is_array($row)) {
  7091. return null;
  7092. }
  7093. $norm = [];
  7094. foreach ($row as $k => $v) {
  7095. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  7096. }
  7097. $row = $norm;
  7098. $st = $row['status'] ?? '';
  7099. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  7100. return null;
  7101. }
  7102. $companyName = '';
  7103. foreach (['company_name', 'name'] as $nk) {
  7104. if (!empty($row[$nk])) {
  7105. $companyName = trim((string)$row[$nk]);
  7106. break;
  7107. }
  7108. }
  7109. if ($companyName === '') {
  7110. return null;
  7111. }
  7112. $username = '';
  7113. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  7114. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  7115. $username = trim((string)$row[$uk]);
  7116. break;
  7117. }
  7118. }
  7119. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  7120. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  7121. if ($phone === '' && isset($row['account'])) {
  7122. $phone = trim((string)$row['account']);
  7123. }
  7124. if ($phone === '' && isset($row['mobile'])) {
  7125. $phone = trim((string)$row['mobile']);
  7126. }
  7127. if ($requireContactChannels && $email === '' && $phone === '') {
  7128. return null;
  7129. }
  7130. $category = '';
  7131. foreach (['company_type', 'category', 'type_name'] as $ck) {
  7132. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  7133. $category = trim((string)$row[$ck]);
  7134. break;
  7135. }
  7136. }
  7137. return [
  7138. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  7139. 'name' => $companyName,
  7140. 'company_name' => $companyName,
  7141. 'username' => $username,
  7142. 'email' => $email,
  7143. 'phone' => $phone,
  7144. 'category' => $category,
  7145. 'company_type' => $category,
  7146. 'can_select' => ($email !== '' && $phone !== '') ? 1 : 0,
  7147. ];
  7148. }
  7149. /**
  7150. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  7151. */
  7152. protected function resolveCustomerContactById(string $id): ?array
  7153. {
  7154. $id = trim($id);
  7155. if ($id === '' || !ctype_digit($id)) {
  7156. return null;
  7157. }
  7158. try {
  7159. $row = Db::table('customer')->where('id', (int)$id)->find();
  7160. } catch (\Throwable $e) {
  7161. return null;
  7162. }
  7163. return $this->buildCustomerContactPayloadFromRow($row);
  7164. }
  7165. /**
  7166. * 按供应商名称解析联系信息(兼容旧提交数据)
  7167. *
  7168. * @param bool $requireContactChannels true 时须有邮箱或手机
  7169. */
  7170. protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
  7171. {
  7172. $name = trim($name);
  7173. if ($name === '') {
  7174. return null;
  7175. }
  7176. try {
  7177. // customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
  7178. $row = Db::table('customer')
  7179. ->where('company_name', $name)
  7180. ->order('id', 'desc')
  7181. ->find();
  7182. } catch (\Throwable $e) {
  7183. return null;
  7184. }
  7185. return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
  7186. }
  7187. /**
  7188. * 规范化下发/确认时勾选的供应商
  7189. *
  7190. * @param array<int, mixed> $companies
  7191. * @return array<int, array<string, string>>
  7192. */
  7193. protected function normalizePickCompanies(array $companies): array
  7194. {
  7195. $out = [];
  7196. foreach ($companies as $c) {
  7197. if (!is_array($c)) {
  7198. continue;
  7199. }
  7200. $resolved = null;
  7201. $cid = trim((string)($c['id'] ?? ''));
  7202. if ($cid !== '') {
  7203. $resolved = $this->resolveCustomerContactById($cid);
  7204. }
  7205. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  7206. if ($resolved === null && $name !== '') {
  7207. $resolved = $this->resolveCustomerContactByCompanyName($name);
  7208. }
  7209. if ($resolved === null) {
  7210. continue;
  7211. }
  7212. $email = trim((string)($resolved['email'] ?? ''));
  7213. $phone = trim((string)($resolved['phone'] ?? ''));
  7214. // 下发须同时有邮箱和手机号(与初选弹窗可选规则一致)
  7215. if ($email === '' || $phone === '') {
  7216. continue;
  7217. }
  7218. $out[] = $resolved;
  7219. }
  7220. return $out;
  7221. }
  7222. /**
  7223. * 同一次下发批次的时间(优先 pick_time,空则 createtime)
  7224. */
  7225. protected function procuremenIssueBatchTime(array $row): string
  7226. {
  7227. $t = $this->procuremenRowListSortTime($row, 'pick_time');
  7228. if ($t !== '') {
  7229. return $t;
  7230. }
  7231. $t = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  7232. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  7233. return $t;
  7234. }
  7235. return '';
  7236. }
  7237. /**
  7238. * 读取下发批次号(兼容旧字段 issue_batch_no)
  7239. *
  7240. * @param array<string, mixed> $row
  7241. */
  7242. protected function resolveProcuremenOrderBatchNo(array $row): string
  7243. {
  7244. foreach (['order_batch_no', 'issue_batch_no'] as $k) {
  7245. $v = trim((string)($row[$k] ?? ''));
  7246. if ($v !== '') {
  7247. return $v;
  7248. }
  7249. }
  7250. return '';
  7251. }
  7252. /**
  7253. * 从订单 bundle 取下发批次号
  7254. *
  7255. * @param array{order_batch_no?:mixed,pos?:array} $bundle
  7256. */
  7257. protected function resolveBundleOrderBatchNo(array $bundle): string
  7258. {
  7259. $direct = trim((string)($bundle['order_batch_no'] ?? ''));
  7260. if ($direct !== '') {
  7261. return $direct;
  7262. }
  7263. foreach ($bundle['pos'] ?? [] as $po) {
  7264. if (!is_array($po)) {
  7265. continue;
  7266. }
  7267. $bn = $this->resolveProcuremenOrderBatchNo($po);
  7268. if ($bn !== '') {
  7269. return $bn;
  7270. }
  7271. }
  7272. return '';
  7273. }
  7274. /**
  7275. * @param int[] $sidList
  7276. * @return array<int, string> scydgy_id => MBZ
  7277. */
  7278. protected function loadScydgyMbzByIds(array $sidList): array
  7279. {
  7280. $ids = [];
  7281. foreach ($sidList as $sid) {
  7282. $sid = (int)$sid;
  7283. if ($this->isValidScydgyRowId($sid)) {
  7284. $ids[$sid] = true;
  7285. }
  7286. }
  7287. if ($ids === []) {
  7288. return [];
  7289. }
  7290. try {
  7291. $map = Db::table('scydgy')->where('ID', 'in', array_keys($ids))->column('MBZ', 'ID');
  7292. } catch (\Throwable $e) {
  7293. return [];
  7294. }
  7295. return is_array($map) ? $map : [];
  7296. }
  7297. /**
  7298. * purchase_order / 列表行 MBZ 为空时,回退 ERP 工序表 scydgy.MBZ
  7299. *
  7300. * @param array<int, array<string, mixed>> $rows
  7301. */
  7302. protected function enrichProcuremenRowsMbz(array &$rows): void
  7303. {
  7304. if ($rows === []) {
  7305. return;
  7306. }
  7307. $need = [];
  7308. foreach ($rows as $r) {
  7309. if (!is_array($r)) {
  7310. continue;
  7311. }
  7312. if (trim((string)($r['MBZ'] ?? $r['mbz'] ?? '')) !== '') {
  7313. continue;
  7314. }
  7315. $sid = $this->extractScydgyRowId($r);
  7316. if ($this->isValidScydgyRowId($sid)) {
  7317. $need[$sid] = true;
  7318. }
  7319. }
  7320. if ($need === []) {
  7321. return;
  7322. }
  7323. $mbzMap = $this->loadScydgyMbzByIds(array_keys($need));
  7324. if ($mbzMap === []) {
  7325. return;
  7326. }
  7327. foreach ($rows as &$r) {
  7328. if (!is_array($r)) {
  7329. continue;
  7330. }
  7331. if (trim((string)($r['MBZ'] ?? $r['mbz'] ?? '')) !== '') {
  7332. continue;
  7333. }
  7334. $sid = $this->extractScydgyRowId($r);
  7335. if (!$this->isValidScydgyRowId($sid) || !isset($mbzMap[$sid])) {
  7336. continue;
  7337. }
  7338. $mbz = trim((string)$mbzMap[$sid]);
  7339. if ($mbz !== '') {
  7340. $r['MBZ'] = $mbz;
  7341. }
  7342. }
  7343. unset($r);
  7344. }
  7345. /**
  7346. * 列表/弹窗合并键:优先正式批次号 order_batch_no;
  7347. * 旧数据无批次号时回退为「同一订单号 + 同一次下发时间」。
  7348. */
  7349. protected function procuremenIssueBatchGroupKey(array $row): string
  7350. {
  7351. $batchNo = $this->resolveProcuremenOrderBatchNo($row);
  7352. if ($batchNo !== '') {
  7353. return 'bn:' . $batchNo;
  7354. }
  7355. $dh = trim((string)($row['CCYDH'] ?? ''));
  7356. $sid = (int)($row['scydgy_id'] ?? $row['ID'] ?? $row['id'] ?? 0);
  7357. if ($dh === '') {
  7358. return '_id_' . $sid;
  7359. }
  7360. $batch = $this->procuremenIssueBatchTime($row);
  7361. return $batch !== '' ? ($dh . '|' . $batch) : ($dh . '|sid:' . $sid);
  7362. }
  7363. /**
  7364. * 是否同一次下发(同批次号,或旧数据同订单号且下发时间一致)
  7365. */
  7366. protected function isSameProcuremenIssueBatch(array $anchor, array $po): bool
  7367. {
  7368. return $this->procuremenIssueBatchGroupKey($anchor) === $this->procuremenIssueBatchGroupKey($po);
  7369. }
  7370. /**
  7371. * @param array<int, mixed> $pos
  7372. * @return array<int, array<string, mixed>>
  7373. */
  7374. protected function filterPurchaseOrdersSameIssueBatch(array $pos, array $anchor): array
  7375. {
  7376. $out = [];
  7377. foreach ($pos as $po) {
  7378. if (is_array($po) && $this->isSameProcuremenIssueBatch($anchor, $po)) {
  7379. $out[] = $po;
  7380. }
  7381. }
  7382. return $out !== [] ? $out : [$anchor];
  7383. }
  7384. /**
  7385. * 确认供应商列表:同一订单号且同一次下发才合并为一行
  7386. *
  7387. * @param array<int, array<string, mixed>> $pool
  7388. * @return array<int, array<string, mixed>>
  7389. */
  7390. protected function collapseProcuremenPoolByOrder(array $pool): array
  7391. {
  7392. if ($pool === []) {
  7393. return [];
  7394. }
  7395. $groups = [];
  7396. foreach ($pool as $row) {
  7397. if (!is_array($row)) {
  7398. continue;
  7399. }
  7400. $key = $this->procuremenIssueBatchGroupKey($row);
  7401. if (!isset($groups[$key])) {
  7402. $groups[$key] = [];
  7403. }
  7404. $groups[$key][] = $row;
  7405. }
  7406. $out = [];
  7407. foreach ($groups as $ccydh => $rows) {
  7408. if ($rows === []) {
  7409. continue;
  7410. }
  7411. // 与确认/审批弹窗「本单工序」一致:按订单号 → 印件名称 → 工序名称 → 工序ID
  7412. usort($rows, function ($a, $b) {
  7413. $oa = trim((string)($a['CCYDH'] ?? ''));
  7414. $ob = trim((string)($b['CCYDH'] ?? ''));
  7415. if ($oa !== $ob) {
  7416. return strcmp($oa, $ob);
  7417. }
  7418. $na = trim((string)($a['CYJMC'] ?? ''));
  7419. $nb = trim((string)($b['CYJMC'] ?? ''));
  7420. if ($na !== $nb) {
  7421. return strcmp($na, $nb);
  7422. }
  7423. $ga = trim((string)($a['CGYMC'] ?? ''));
  7424. $gb = trim((string)($b['CGYMC'] ?? ''));
  7425. if ($ga !== $gb) {
  7426. return strcmp($ga, $gb);
  7427. }
  7428. $ida = (int)($a['ID'] ?? $a['scydgy_id'] ?? 0);
  7429. $idb = (int)($b['ID'] ?? $b['scydgy_id'] ?? 0);
  7430. return $ida <=> $idb;
  7431. });
  7432. $head = $rows[0];
  7433. $gymcList = [];
  7434. foreach ($rows as $r) {
  7435. $g = trim((string)($r['CGYMC'] ?? ''));
  7436. if ($g !== '' && !in_array($g, $gymcList, true)) {
  7437. $gymcList[] = $g;
  7438. }
  7439. }
  7440. $merged = $head;
  7441. $orderDhList = [];
  7442. $nameList = [];
  7443. foreach ($rows as $r) {
  7444. if (!is_array($r)) {
  7445. continue;
  7446. }
  7447. $odh = trim((string)($r['CCYDH'] ?? ''));
  7448. if ($odh !== '' && !in_array($odh, $orderDhList, true)) {
  7449. $orderDhList[] = $odh;
  7450. }
  7451. $onm = trim((string)($r['CYJMC'] ?? ''));
  7452. if ($onm !== '' && !in_array($onm, $nameList, true)) {
  7453. $nameList[] = $onm;
  7454. }
  7455. }
  7456. $orderDh = $orderDhList !== [] ? implode('、', $orderDhList) : trim((string)($head['CCYDH'] ?? ''));
  7457. $merged['CCYDH'] = $orderDh;
  7458. $merged['order_key'] = $orderDh;
  7459. if ($nameList !== []) {
  7460. $merged['CYJMC'] = implode('、', $nameList);
  7461. }
  7462. $merged['order_batch_no'] = $this->resolveProcuremenOrderBatchNo($head);
  7463. $merged['process_count'] = count($rows);
  7464. $merged['_order_merge_rows'] = $rows;
  7465. $qtyList = [];
  7466. $priceList = [];
  7467. foreach ($rows as $r) {
  7468. if (!is_array($r)) {
  7469. continue;
  7470. }
  7471. $qtyList[] = $this->resolveProcuremenThisQuantity($r);
  7472. $priceList[] = $this->resolveProcuremenCeilingPrice($r);
  7473. }
  7474. if (count($rows) > 1) {
  7475. $merged['CGYMC'] = implode('、', $gymcList);
  7476. // 多工序:数量/限价按有值项顿号间隔(空值不占位)
  7477. $merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  7478. $merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  7479. } else {
  7480. $merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
  7481. $merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
  7482. }
  7483. // 已选供应商:取合并行中首个非空 pick_company_name
  7484. $pickedName = '';
  7485. $manualPick = ((int)($head['manual_pick'] ?? 0) === 1) ? 1 : 0;
  7486. foreach ($rows as $r) {
  7487. if (!is_array($r)) {
  7488. continue;
  7489. }
  7490. if ((int)($r['manual_pick'] ?? 0) === 1) {
  7491. $manualPick = 1;
  7492. }
  7493. $pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
  7494. if ($pn !== '' && $pickedName === '') {
  7495. $pickedName = $pn;
  7496. }
  7497. }
  7498. $merged['manual_pick'] = $manualPick;
  7499. if ($pickedName !== '') {
  7500. $merged['pick_company_name'] = $pickedName;
  7501. $merged['picked_supplier_name'] = $pickedName;
  7502. }
  7503. $mergedPickTime = '';
  7504. foreach ($rows as $r) {
  7505. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  7506. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  7507. $mergedPickTime = $t;
  7508. }
  7509. }
  7510. if ($mergedPickTime !== '') {
  7511. $merged['pick_time'] = $mergedPickTime;
  7512. }
  7513. $out[] = $merged;
  7514. }
  7515. usort($out, function ($a, $b) {
  7516. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  7517. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  7518. if ($ta === $tb) {
  7519. $ida = (int)($a['purchase_order_id'] ?? 0);
  7520. $idb = (int)($b['purchase_order_id'] ?? 0);
  7521. if ($ida !== $idb) {
  7522. return $idb <=> $ida;
  7523. }
  7524. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  7525. }
  7526. if ($ta === '') {
  7527. return 1;
  7528. }
  7529. if ($tb === '') {
  7530. return -1;
  7531. }
  7532. return strcmp($tb, $ta);
  7533. });
  7534. return $out;
  7535. }
  7536. /**
  7537. * 待确认供应商:同一次下发批次的工序(优先 order_batch_no;旧数据回退同订单+同下发时间)
  7538. *
  7539. * @return array{ccydh:string, order_batch_no?:string, pos:array<int,array>, merge_rows:array<int,array>}
  7540. */
  7541. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  7542. {
  7543. $scydgyId = trim($scydgyId);
  7544. $empty = ['ccydh' => '', 'order_batch_no' => '', 'pos' => [], 'merge_rows' => []];
  7545. if ($scydgyId === '') {
  7546. return $empty;
  7547. }
  7548. try {
  7549. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7550. } catch (\Throwable $e) {
  7551. $anchor = null;
  7552. }
  7553. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  7554. return $empty;
  7555. }
  7556. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7557. $batchNo = $this->resolveProcuremenOrderBatchNo($anchor);
  7558. try {
  7559. if ($batchNo !== '') {
  7560. $pos = Db::table('purchase_order')
  7561. ->where('order_batch_no', $batchNo)
  7562. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())
  7563. ->order('scydgy_id', 'asc')
  7564. ->select();
  7565. } elseif ($ccydh !== '') {
  7566. $pos = Db::table('purchase_order')
  7567. ->where('CCYDH', $ccydh)
  7568. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())
  7569. ->order('scydgy_id', 'asc')
  7570. ->select();
  7571. } else {
  7572. $pos = [$anchor];
  7573. }
  7574. } catch (\Throwable $e) {
  7575. $pos = [$anchor];
  7576. }
  7577. if (!is_array($pos) || $pos === []) {
  7578. $pos = [$anchor];
  7579. }
  7580. $pos = $this->filterPurchaseOrdersSameIssueBatch($pos, $anchor);
  7581. return [
  7582. 'ccydh' => $ccydh,
  7583. 'order_batch_no' => $batchNo,
  7584. 'pos' => $pos,
  7585. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  7586. ];
  7587. }
  7588. /**
  7589. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  7590. */
  7591. protected function purchaseOrderRowInConfirmStage(array $po): bool
  7592. {
  7593. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  7594. return false;
  7595. }
  7596. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  7597. return false;
  7598. }
  7599. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  7600. return true;
  7601. }
  7602. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  7603. $sid = (int)($po['scydgy_id'] ?? 0);
  7604. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  7605. }
  7606. return false;
  7607. }
  7608. /**
  7609. * 采购确认:同一次下发批次的待审批工序(优先 order_batch_no)
  7610. *
  7611. * @return array{ccydh:string, order_batch_no?:string, pos:array<int,array>, merge_rows:array<int,array>}
  7612. */
  7613. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  7614. {
  7615. $scydgyId = trim($scydgyId);
  7616. $empty = ['ccydh' => '', 'order_batch_no' => '', 'pos' => [], 'merge_rows' => []];
  7617. if ($scydgyId === '') {
  7618. return $empty;
  7619. }
  7620. try {
  7621. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7622. } catch (\Throwable $e) {
  7623. $anchor = null;
  7624. }
  7625. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  7626. return $empty;
  7627. }
  7628. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7629. $batchNo = $this->resolveProcuremenOrderBatchNo($anchor);
  7630. try {
  7631. if ($batchNo !== '') {
  7632. $posQuery = Db::table('purchase_order')->where('order_batch_no', $batchNo);
  7633. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  7634. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  7635. } elseif ($ccydh !== '') {
  7636. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  7637. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  7638. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  7639. } else {
  7640. $pos = [$anchor];
  7641. }
  7642. } catch (\Throwable $e) {
  7643. $pos = [$anchor];
  7644. }
  7645. if (!is_array($pos) || $pos === []) {
  7646. $pos = [$anchor];
  7647. }
  7648. $pos = array_values(array_filter($pos, function ($po) {
  7649. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  7650. }));
  7651. if ($pos === []) {
  7652. $pos = [$anchor];
  7653. }
  7654. $pos = $this->filterPurchaseOrdersSameIssueBatch($pos, $anchor);
  7655. return [
  7656. 'ccydh' => $ccydh,
  7657. 'order_batch_no' => $batchNo,
  7658. 'pos' => $pos,
  7659. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  7660. ];
  7661. }
  7662. /**
  7663. * @param array<int, array<string, mixed>> $purchaseOrders
  7664. * @return array<int, array<string, mixed>>
  7665. */
  7666. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  7667. {
  7668. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  7669. $byId = [];
  7670. foreach ($pool as $r) {
  7671. if (!is_array($r)) {
  7672. continue;
  7673. }
  7674. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  7675. if ($this->isValidScydgyRowId($sid)) {
  7676. $byId[$sid] = $r;
  7677. }
  7678. }
  7679. $out = [];
  7680. foreach ($purchaseOrders as $po) {
  7681. if (!is_array($po)) {
  7682. continue;
  7683. }
  7684. $sid = (int)($po['scydgy_id'] ?? 0);
  7685. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  7686. $out[] = $byId[$sid];
  7687. }
  7688. }
  7689. $this->enrichProcuremenRowsMbz($out);
  7690. return $out;
  7691. }
  7692. /**
  7693. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  7694. *
  7695. * @return array<int, array<string, mixed>>
  7696. */
  7697. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  7698. {
  7699. $scydgyId = trim($scydgyId);
  7700. if ($scydgyId === '') {
  7701. return [];
  7702. }
  7703. try {
  7704. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7705. } catch (\Throwable $e) {
  7706. $anchor = null;
  7707. }
  7708. if (!is_array($anchor)) {
  7709. return [];
  7710. }
  7711. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  7712. return [];
  7713. }
  7714. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7715. $batchNo = $this->resolveProcuremenOrderBatchNo($anchor);
  7716. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  7717. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  7718. try {
  7719. $q = Db::table('purchase_order');
  7720. if ($batchNo !== '') {
  7721. $q->where('order_batch_no', $batchNo);
  7722. } elseif ($ccydh !== '' && $isValidPick) {
  7723. $q->where('CCYDH', $ccydh)->where('pick_time', $pickTime);
  7724. } else {
  7725. $q->where('scydgy_id', $scydgyId);
  7726. }
  7727. $pos = $q->order('scydgy_id', 'asc')->select();
  7728. } catch (\Throwable $e) {
  7729. $pos = [$anchor];
  7730. }
  7731. if (!is_array($pos) || $pos === []) {
  7732. $pos = [$anchor];
  7733. }
  7734. $pos = array_values(array_filter($pos, function ($po) {
  7735. if (!is_array($po)) {
  7736. return false;
  7737. }
  7738. $mr = $po['mod_rq'] ?? null;
  7739. if ($mr === null || $mr === '') {
  7740. return true;
  7741. }
  7742. $mrs = trim((string)$mr);
  7743. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  7744. }));
  7745. if ($pos === []) {
  7746. $pos = [$anchor];
  7747. }
  7748. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  7749. if ($rows === []) {
  7750. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  7751. }
  7752. return $rows;
  7753. }
  7754. /**
  7755. * 工序/报价明细统一排序:订单号升序 → 印件名称 → 工序名称 → 工序行ID
  7756. * (与审核弹窗上方工序表一致)
  7757. *
  7758. * @param array<int, array<string, mixed>> $mergeRows
  7759. * @return array<int, array<string, mixed>>
  7760. */
  7761. protected function sortProcuremenMergeRowsByCcydh(array $mergeRows): array
  7762. {
  7763. $list = [];
  7764. foreach ($mergeRows as $r) {
  7765. if (is_array($r)) {
  7766. $list[] = $r;
  7767. }
  7768. }
  7769. usort($list, function ($a, $b) {
  7770. $oa = trim((string)($a['CCYDH'] ?? ''));
  7771. $ob = trim((string)($b['CCYDH'] ?? ''));
  7772. if ($oa !== $ob) {
  7773. return strcmp($oa, $ob);
  7774. }
  7775. $na = trim((string)($a['CYJMC'] ?? ''));
  7776. $nb = trim((string)($b['CYJMC'] ?? ''));
  7777. if ($na !== $nb) {
  7778. return strcmp($na, $nb);
  7779. }
  7780. $ga = trim((string)($a['CGYMC'] ?? ''));
  7781. $gb = trim((string)($b['CGYMC'] ?? ''));
  7782. if ($ga !== $gb) {
  7783. return strcmp($ga, $gb);
  7784. }
  7785. $ida = $this->extractScydgyRowId($a);
  7786. $idb = $this->extractScydgyRowId($b);
  7787. return $ida <=> $idb;
  7788. });
  7789. return $list;
  7790. }
  7791. /**
  7792. * 按工序表同序得到 scydgy_id 列表(供应商报价明细行顺序用)
  7793. *
  7794. * @param array<int, array<string, mixed>> $mergeRows
  7795. * @param int[] $extraSids 合并行未覆盖时追加
  7796. * @return int[]
  7797. */
  7798. protected function orderedScydgyIdsLikeProcessDisplay(array $mergeRows, array $extraSids = []): array
  7799. {
  7800. $out = [];
  7801. $seen = [];
  7802. foreach ($this->sortProcuremenMergeRowsByCcydh($mergeRows) as $r) {
  7803. $sid = $this->extractScydgyRowId($r);
  7804. if (!$this->isValidScydgyRowId($sid) || isset($seen[$sid])) {
  7805. continue;
  7806. }
  7807. $seen[$sid] = true;
  7808. $out[] = $sid;
  7809. }
  7810. foreach ($extraSids as $sid) {
  7811. $sid = (int)$sid;
  7812. if (!$this->isValidScydgyRowId($sid) || isset($seen[$sid])) {
  7813. continue;
  7814. }
  7815. $seen[$sid] = true;
  7816. $out[] = $sid;
  7817. }
  7818. return $out;
  7819. }
  7820. /**
  7821. * 审核弹窗工序表展示行(与下发弹窗列一致;按订单号排序,同订单合并订单号/印件名称单元格)
  7822. *
  7823. * @param array<int, array<string, mixed>> $mergeRows
  7824. * @return array<int, array<string, mixed>>
  7825. */
  7826. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  7827. {
  7828. $list = $this->sortProcuremenMergeRowsByCcydh($mergeRows);
  7829. $n = count($list);
  7830. // 连续同订单号+印件名称:合并单元格 rowspan
  7831. $groupSpan = array_fill(0, $n, 1);
  7832. $groupStart = array_fill(0, $n, true);
  7833. $i = 0;
  7834. while ($i < $n) {
  7835. $key = trim((string)($list[$i]['CCYDH'] ?? '')) . "\0" . trim((string)($list[$i]['CYJMC'] ?? ''));
  7836. $j = $i + 1;
  7837. while ($j < $n) {
  7838. $key2 = trim((string)($list[$j]['CCYDH'] ?? '')) . "\0" . trim((string)($list[$j]['CYJMC'] ?? ''));
  7839. if ($key === '' || $key2 !== $key) {
  7840. break;
  7841. }
  7842. $j++;
  7843. }
  7844. $span = $j - $i;
  7845. $groupSpan[$i] = $span;
  7846. for ($k = $i + 1; $k < $j; $k++) {
  7847. $groupStart[$k] = false;
  7848. $groupSpan[$k] = 1;
  7849. }
  7850. $i = $j;
  7851. }
  7852. $out = [];
  7853. foreach ($list as $idx => $r) {
  7854. $qty = $this->resolveProcuremenThisQuantity($r);
  7855. $price = $this->resolveProcuremenCeilingPrice($r);
  7856. $sid = $this->extractScydgyRowId($r);
  7857. $out[] = [
  7858. 'seq' => $idx + 1,
  7859. 'scydgy_id' => $sid,
  7860. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  7861. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  7862. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  7863. 'CDW' => trim((string)($r['CDW'] ?? '')),
  7864. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  7865. 'NGZL' => $r['NGZL'] ?? '',
  7866. 'This_quantity' => $qty,
  7867. 'ceilingPrice' => $price,
  7868. 'CDF' => trim((string)($r['CDF'] ?? '')),
  7869. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  7870. 'show_order_cells' => !empty($groupStart[$idx]),
  7871. 'order_rowspan' => (int)($groupSpan[$idx] ?? 1),
  7872. ];
  7873. }
  7874. return $out;
  7875. }
  7876. /**
  7877. * 解析金额/数量(去千分位等非数字字符)
  7878. */
  7879. protected function parseProcuremenMoneyNumber($value): ?float
  7880. {
  7881. return ProcuremenFormat::moneyNumber($value);
  7882. }
  7883. protected function formatProcuremenMoneyDisplay(?float $amount): string
  7884. {
  7885. return ProcuremenFormat::moneyDisplay($amount);
  7886. }
  7887. /**
  7888. * 列表/详情展示:工作量为 0 时显示空
  7889. */
  7890. protected function formatProcuremenWorkloadDisplay($value): string
  7891. {
  7892. return ProcuremenFormat::workloadDisplay($value);
  7893. }
  7894. /**
  7895. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  7896. */
  7897. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  7898. {
  7899. foreach ($details as $d) {
  7900. if (!is_array($d)) {
  7901. continue;
  7902. }
  7903. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  7904. $cn = trim((string)($d['company_name'] ?? ''));
  7905. if ($cn !== '') {
  7906. return $cn;
  7907. }
  7908. }
  7909. }
  7910. return trim((string)($main['pick_company_name'] ?? ''));
  7911. }
  7912. /**
  7913. * 详情报价小计:单价 × 本工序本次数量
  7914. */
  7915. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  7916. {
  7917. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  7918. if ($unit === null) {
  7919. return null;
  7920. }
  7921. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  7922. if ($qty === null || $qty <= 0) {
  7923. return null;
  7924. }
  7925. return $unit * $qty;
  7926. }
  7927. /**
  7928. * 详情页:工序小计 + 供应商分组报价与总计
  7929. *
  7930. * @param array<int, array<string, mixed>> $mergeRows
  7931. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  7932. * @return array{
  7933. * process_rows: array,
  7934. * supplier_groups: array,
  7935. * order_total_text: string,
  7936. * order_total_has: bool,
  7937. * selected_company: string
  7938. * }
  7939. */
  7940. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  7941. {
  7942. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  7943. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  7944. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
  7945. || ((int)($main['manual_pick'] ?? 0) === 1);
  7946. $orderMbz = trim((string)($main['MBZ'] ?? $main['mbz'] ?? ''));
  7947. if ($orderMbz === '') {
  7948. $orderMbz = $this->resolveBundleOrderMbz(['pos' => [$main], 'merge_rows' => $mergeRows]);
  7949. }
  7950. $qtyBySid = [];
  7951. $ceilingBySid = [];
  7952. $gymcBySid = [];
  7953. $ccydhBySid = [];
  7954. foreach ($mergeRows as $mr) {
  7955. if (!is_array($mr)) {
  7956. continue;
  7957. }
  7958. $sid = $this->extractScydgyRowId($mr);
  7959. if (!$this->isValidScydgyRowId($sid)) {
  7960. continue;
  7961. }
  7962. $qtyBySid[$sid] = $this->resolveProcuremenThisQuantity($mr);
  7963. $ceilingBySid[$sid] = $this->resolveProcuremenCeilingPrice($mr);
  7964. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  7965. $dh = trim((string)($mr['CCYDH'] ?? ''));
  7966. if ($dh !== '') {
  7967. $ccydhBySid[$sid] = $dh;
  7968. }
  7969. }
  7970. // 与上方工序表一致:按订单号升序
  7971. $orderedSids = $this->orderedScydgyIdsLikeProcessDisplay($mergeRows);
  7972. $mainCcydh = trim((string)($main['CCYDH'] ?? $ccydh));
  7973. if ($mainCcydh !== '') {
  7974. foreach ($orderedSids as $sid) {
  7975. if (empty($ccydhBySid[$sid])) {
  7976. $ccydhBySid[$sid] = $mainCcydh;
  7977. }
  7978. }
  7979. }
  7980. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  7981. $detailByCompanySid = [];
  7982. foreach ($details as $d) {
  7983. if (!is_array($d)) {
  7984. continue;
  7985. }
  7986. $cn = trim((string)($d['company_name'] ?? ''));
  7987. $sid = (int)($d['scydgy_id'] ?? 0);
  7988. if ($cn === '' || $sid === 0) {
  7989. continue;
  7990. }
  7991. if (!isset($detailByCompanySid[$cn])) {
  7992. $detailByCompanySid[$cn] = [];
  7993. }
  7994. $detailByCompanySid[$cn][$sid] = $d;
  7995. }
  7996. $supplierGroups = [];
  7997. foreach ($detailByCompanySid as $cn => $bySid) {
  7998. $lines = [];
  7999. $groupTotal = 0.0;
  8000. $groupHas = false;
  8001. $groupVoid = true;
  8002. $usedSids = [];
  8003. $appendLine = function (int $sid, array $d) use (
  8004. &$lines,
  8005. &$groupTotal,
  8006. &$groupHas,
  8007. &$groupVoid,
  8008. $qtyBySid,
  8009. $ceilingBySid,
  8010. $gymcBySid,
  8011. $ccydhBySid,
  8012. $quoteVisible
  8013. ) {
  8014. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  8015. if (!$isVoid) {
  8016. $groupVoid = false;
  8017. }
  8018. $qtyStr = $qtyBySid[$sid] ?? '';
  8019. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  8020. $am = trim((string)($d['amount'] ?? ''));
  8021. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  8022. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  8023. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  8024. $sub = null;
  8025. if (!$isVoid && $amountNum !== null) {
  8026. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  8027. }
  8028. $ct = $this->resolveDetailSupplierOperTime($d);
  8029. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  8030. $leadFilled = ($leadDays !== null);
  8031. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  8032. $processName = $this->buildSupplierProcessNameFields(
  8033. (string)($ccydhBySid[$sid] ?? ''),
  8034. (string)($gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')))
  8035. );
  8036. $line = array_merge($processName, [
  8037. 'scydgy_id' => $sid,
  8038. 'This_quantity' => (string)$qtyStr,
  8039. 'ceilingPrice' => (string)($ceilingBySid[$sid] ?? ''),
  8040. 'amount' => $am,
  8041. 'unit_price_text' => $amountFilled
  8042. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  8043. : '未填写',
  8044. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  8045. 'delivery_ymd' => $deliveryYmd,
  8046. 'amount_filled' => $amountFilled,
  8047. 'delivery_filled' => $deliveryFilled,
  8048. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  8049. 'lead_days' => $leadFilled ? $leadDays : '',
  8050. 'lead_days_filled'=> $leadFilled,
  8051. 'lead_days_show' => $leadText,
  8052. 'lead_days_text' => $leadText,
  8053. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  8054. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  8055. 'is_void' => $isVoid,
  8056. 'oper_time_text' => $ct,
  8057. ]);
  8058. if (!$quoteVisible && !$isVoid) {
  8059. $this->maskSupplierQuoteLineBeforeDeadline($line);
  8060. } elseif ($sub !== null) {
  8061. $groupTotal += $sub;
  8062. $groupHas = true;
  8063. }
  8064. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  8065. };
  8066. foreach ($orderedSids as $sid) {
  8067. if (!isset($bySid[$sid])) {
  8068. continue;
  8069. }
  8070. $usedSids[$sid] = true;
  8071. $appendLine($sid, $bySid[$sid]);
  8072. }
  8073. foreach ($bySid as $sid => $d) {
  8074. if (isset($usedSids[$sid])) {
  8075. continue;
  8076. }
  8077. $appendLine((int)$sid, $d);
  8078. }
  8079. $firstDetail = null;
  8080. foreach ($bySid as $d) {
  8081. if (is_array($d)) {
  8082. $firstDetail = $d;
  8083. break;
  8084. }
  8085. }
  8086. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  8087. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  8088. if ($username === '' && $ph !== '') {
  8089. $username = $this->resolveCustomerContactName($ph, $cn);
  8090. }
  8091. $remark = '';
  8092. foreach ($bySid as $d) {
  8093. if (!is_array($d)) {
  8094. continue;
  8095. }
  8096. $rm = '';
  8097. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  8098. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  8099. $rm = trim((string)$d[$rk]);
  8100. break;
  8101. }
  8102. }
  8103. if ($rm !== '') {
  8104. $remark = $rm;
  8105. break;
  8106. }
  8107. }
  8108. $lineCount = count($lines);
  8109. $supplierGroup = [
  8110. 'company_name' => $cn,
  8111. 'username' => $username,
  8112. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  8113. 'phone' => $ph,
  8114. 'remark' => $remark,
  8115. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  8116. 'is_void' => $groupVoid,
  8117. 'lines' => $lines,
  8118. 'line_count' => $lineCount,
  8119. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  8120. 'has_total' => $lineCount > 0,
  8121. ];
  8122. $this->finalizeSupplierRemarkDisplay($supplierGroup, $orderMbz, $quoteVisible);
  8123. $supplierGroups[] = $supplierGroup;
  8124. }
  8125. usort($supplierGroups, function ($a, $b) {
  8126. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  8127. return ($a['is_void'] ?? false) ? 1 : -1;
  8128. }
  8129. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  8130. return ($a['is_selected'] ?? false) ? -1 : 1;
  8131. }
  8132. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  8133. });
  8134. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  8135. return [
  8136. 'process_rows' => $processRows,
  8137. 'supplier_groups' => $supplierGroups,
  8138. 'order_total_text' => '',
  8139. 'order_total_has' => false,
  8140. 'selected_company' => $selectedCompany,
  8141. ];
  8142. }
  8143. /**
  8144. * 短信用工序明细。
  8145. * 单订单:仅工序行(订单号/印件名称由模版 {ccydh}{cyjmc} 排版);
  8146. * 多订单同批:每个订单各自输出「订单号 + 印件名称 + 工序列表」,组间空行。
  8147. */
  8148. protected function buildProcessLinesPlain(array $mergeRows): string
  8149. {
  8150. $groups = [];
  8151. foreach ($mergeRows as $r) {
  8152. if (!is_array($r)) {
  8153. continue;
  8154. }
  8155. $dh = trim((string)($r['CCYDH'] ?? ''));
  8156. $key = $dh !== '' ? $dh : ('__sid_' . (int)($r['ID'] ?? $r['id'] ?? $r['scydgy_id'] ?? 0));
  8157. if (!isset($groups[$key])) {
  8158. $groups[$key] = [
  8159. 'ccydh' => $dh,
  8160. 'cyjmc' => trim((string)($r['CYJMC'] ?? '')),
  8161. 'rows' => [],
  8162. ];
  8163. } elseif ($groups[$key]['cyjmc'] === '') {
  8164. $groups[$key]['cyjmc'] = trim((string)($r['CYJMC'] ?? ''));
  8165. }
  8166. $groups[$key]['rows'][] = $r;
  8167. }
  8168. if ($groups === []) {
  8169. return '';
  8170. }
  8171. $multiOrder = count($groups) > 1;
  8172. $blocks = [];
  8173. foreach ($groups as $g) {
  8174. $lines = [];
  8175. if ($multiOrder) {
  8176. if ($g['ccydh'] !== '') {
  8177. $lines[] = '订单号:' . $g['ccydh'];
  8178. }
  8179. if ($g['cyjmc'] !== '') {
  8180. $lines[] = '印件名称:' . $g['cyjmc'];
  8181. }
  8182. }
  8183. foreach ($g['rows'] as $r) {
  8184. if (!is_array($r)) {
  8185. continue;
  8186. }
  8187. $gymc = trim((string)($r['CGYMC'] ?? ''));
  8188. if ($gymc === '') {
  8189. $gymc = '—';
  8190. }
  8191. $dw = trim((string)($r['CDW'] ?? ''));
  8192. // 下发通知展示「本次数量」(优先 This_quantity,空则回退 NGZL),与确认/审批弹窗一致
  8193. $qty = $this->resolveProcuremenThisQuantity($r);
  8194. $parts = ['工序名称:' . $gymc];
  8195. if ($dw !== '') {
  8196. $parts[] = '单位:' . $dw;
  8197. }
  8198. if ($qty !== '') {
  8199. $parts[] = '本次数量:' . $qty;
  8200. }
  8201. $lines[] = implode(' ', $parts);
  8202. }
  8203. if ($lines !== []) {
  8204. $blocks[] = implode("\n", $lines);
  8205. }
  8206. }
  8207. return implode("\n\n", $blocks);
  8208. }
  8209. /** 中文友好显示宽度(全角约 2,半角 1) */
  8210. protected function mbDisplayWidth(string $s): int
  8211. {
  8212. if ($s === '') {
  8213. return 0;
  8214. }
  8215. if (function_exists('mb_strwidth')) {
  8216. return (int)mb_strwidth($s, 'UTF-8');
  8217. }
  8218. if (function_exists('mb_strlen')) {
  8219. return (int)mb_strlen($s, 'UTF-8');
  8220. }
  8221. return strlen($s);
  8222. }
  8223. /** 按显示宽度右侧补空格,便于短信/邮件工序行对齐 */
  8224. protected function mbPadRight(string $s, int $width): string
  8225. {
  8226. $cur = $this->mbDisplayWidth($s);
  8227. if ($cur >= $width) {
  8228. return $s;
  8229. }
  8230. return $s . str_repeat(' ', $width - $cur);
  8231. }
  8232. /**
  8233. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  8234. *
  8235. * @return array<string, string>
  8236. */
  8237. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  8238. {
  8239. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  8240. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  8241. }
  8242. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  8243. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  8244. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  8245. $cyjmc = '';
  8246. foreach ($mergeRows as $mr) {
  8247. if (!is_array($mr)) {
  8248. continue;
  8249. }
  8250. if ($ccydh === '') {
  8251. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  8252. }
  8253. if ($cyjmc === '') {
  8254. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  8255. }
  8256. }
  8257. if ($pos !== []) {
  8258. $firstPo = $pos[0];
  8259. if (is_array($firstPo)) {
  8260. if ($ccydh === '') {
  8261. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  8262. }
  8263. if ($cyjmc === '') {
  8264. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  8265. }
  8266. }
  8267. }
  8268. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  8269. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  8270. if (is_array($any)) {
  8271. if ($ccydh === '') {
  8272. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  8273. }
  8274. if ($cyjmc === '') {
  8275. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  8276. }
  8277. }
  8278. }
  8279. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  8280. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  8281. $cgymc = '';
  8282. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  8283. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  8284. }
  8285. return [
  8286. 'ccydh' => $ccydh,
  8287. 'cyjmc' => $cyjmc,
  8288. 'cgymc' => $cgymc,
  8289. 'process_lines' => $processLines,
  8290. 'process_lines_html' => '',
  8291. ];
  8292. }
  8293. /**
  8294. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  8295. * 多订单时 processPlain 已含各订单头,不再重复拼订单号/印件名称。
  8296. */
  8297. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  8298. {
  8299. $processPlain = trim($processPlain);
  8300. if ($processPlain !== '' && preg_match('/^订单号:/u', $processPlain)) {
  8301. return $processPlain;
  8302. }
  8303. $lines = [];
  8304. if ($ccydh !== '') {
  8305. $lines[] = '订单号:' . $ccydh;
  8306. }
  8307. if ($cyjmc !== '') {
  8308. $lines[] = '印件名称:' . $cyjmc;
  8309. }
  8310. if ($processPlain !== '') {
  8311. $lines[] = $processPlain;
  8312. }
  8313. return implode("\n", $lines);
  8314. }
  8315. /**
  8316. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  8317. *
  8318. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  8319. */
  8320. protected function buildPlatformLinksPlain(array $detailLinks): string
  8321. {
  8322. $lines = [];
  8323. $i = 1;
  8324. foreach ($detailLinks as $lk) {
  8325. if (!is_array($lk)) {
  8326. continue;
  8327. }
  8328. $url = trim((string)($lk['url'] ?? ''));
  8329. if ($url === '') {
  8330. continue;
  8331. }
  8332. $label = trim((string)($lk['cgymc'] ?? ''));
  8333. if ($label === '') {
  8334. $label = '工序' . $i;
  8335. }
  8336. $lines[] = $label . ':' . $url;
  8337. $i++;
  8338. }
  8339. return implode("\n", $lines);
  8340. }
  8341. /**
  8342. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  8343. *
  8344. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  8345. */
  8346. protected function buildPlatformLinksHtml(array $detailLinks): string
  8347. {
  8348. $parts = [];
  8349. $i = 1;
  8350. foreach ($detailLinks as $lk) {
  8351. if (!is_array($lk)) {
  8352. continue;
  8353. }
  8354. $url = trim((string)($lk['url'] ?? ''));
  8355. if ($url === '') {
  8356. continue;
  8357. }
  8358. $label = trim((string)($lk['cgymc'] ?? ''));
  8359. if ($label === '') {
  8360. $label = '工序' . $i;
  8361. }
  8362. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  8363. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  8364. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  8365. $i++;
  8366. }
  8367. return implode("<br>\n", $parts);
  8368. }
  8369. /**
  8370. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  8371. *
  8372. * @return array<string, mixed>
  8373. */
  8374. protected function loadMailerConfig(): array
  8375. {
  8376. try {
  8377. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  8378. } catch (\Throwable $e) {
  8379. $cfg = [];
  8380. }
  8381. return is_array($cfg) ? $cfg : [];
  8382. }
  8383. protected function loadNotifyTemplateRow(string $scene): ?array
  8384. {
  8385. if (in_array($scene, ['confirm_ok_email', 'confirm_fail_email'], true)) {
  8386. $this->ensureConfirmResultEmailTemplates();
  8387. }
  8388. if (in_array($scene, ['review_email', 'review_sms'], true)) {
  8389. $this->ensureReviewEmailTemplate();
  8390. $this->ensureReviewSmsTemplate();
  8391. }
  8392. try {
  8393. $row = Db::table('purchase_sms_template')
  8394. ->where('scene', $scene)
  8395. ->where(function ($q) {
  8396. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  8397. })
  8398. ->order('id', 'asc')
  8399. ->find();
  8400. } catch (\Throwable $e) {
  8401. return null;
  8402. }
  8403. if (!is_array($row) || $row === []) {
  8404. return null;
  8405. }
  8406. return [
  8407. 'title' => trim((string)($row['title'] ?? '')),
  8408. 'content' => trim((string)($row['content'] ?? '')),
  8409. ];
  8410. }
  8411. /**
  8412. * 邮件用工序明细 HTML。
  8413. * 多订单同批时按订单分组;单订单保持原表格/单行样式。
  8414. */
  8415. protected function buildProcessLinesHtml(array $mergeRows): string
  8416. {
  8417. $groups = [];
  8418. foreach ($mergeRows as $r) {
  8419. if (!is_array($r)) {
  8420. continue;
  8421. }
  8422. $dh = trim((string)($r['CCYDH'] ?? ''));
  8423. $key = $dh !== '' ? $dh : ('__sid_' . (int)($r['ID'] ?? $r['id'] ?? $r['scydgy_id'] ?? 0));
  8424. if (!isset($groups[$key])) {
  8425. $groups[$key] = [
  8426. 'ccydh' => $dh,
  8427. 'cyjmc' => trim((string)($r['CYJMC'] ?? '')),
  8428. 'rows' => [],
  8429. ];
  8430. } elseif ($groups[$key]['cyjmc'] === '') {
  8431. $groups[$key]['cyjmc'] = trim((string)($r['CYJMC'] ?? ''));
  8432. }
  8433. $groups[$key]['rows'][] = $r;
  8434. }
  8435. if ($groups === []) {
  8436. return '';
  8437. }
  8438. $multiOrder = count($groups) > 1;
  8439. $flatRows = [];
  8440. foreach ($groups as $g) {
  8441. foreach ($g['rows'] as $r) {
  8442. $flatRows[] = $r;
  8443. }
  8444. }
  8445. if (!$multiOrder && count($flatRows) <= 1) {
  8446. $r = $flatRows[0] ?? [];
  8447. if (!is_array($r)) {
  8448. return '';
  8449. }
  8450. $gymc = trim((string)($r['CGYMC'] ?? ''));
  8451. $dw = trim((string)($r['CDW'] ?? ''));
  8452. $qty = $this->resolveProcuremenThisQuantity($r);
  8453. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  8454. if ($dw !== '') {
  8455. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  8456. }
  8457. if ($qty !== '') {
  8458. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  8459. }
  8460. return $html;
  8461. }
  8462. $blocks = [];
  8463. foreach ($groups as $g) {
  8464. $head = '';
  8465. if ($multiOrder) {
  8466. if ($g['ccydh'] !== '') {
  8467. $head .= '<div style="margin:10px 0 4px;font-weight:700;">订单号:'
  8468. . htmlspecialchars($g['ccydh'], ENT_QUOTES, 'UTF-8') . '</div>';
  8469. }
  8470. if ($g['cyjmc'] !== '') {
  8471. $head .= '<div style="margin:0 0 6px;color:#333;">印件名称:'
  8472. . htmlspecialchars($g['cyjmc'], ENT_QUOTES, 'UTF-8') . '</div>';
  8473. }
  8474. }
  8475. $rows = '';
  8476. $i = 1;
  8477. foreach ($g['rows'] as $r) {
  8478. if (!is_array($r)) {
  8479. continue;
  8480. }
  8481. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  8482. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  8483. $qty = htmlspecialchars($this->resolveProcuremenThisQuantity($r), ENT_QUOTES, 'UTF-8');
  8484. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  8485. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  8486. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  8487. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  8488. $i++;
  8489. }
  8490. if ($rows === '') {
  8491. continue;
  8492. }
  8493. $table = '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:4px 0 12px;font-size:14px;width:100%;max-width:560px;">'
  8494. . '<thead><tr style="background:#f5f5f5;">'
  8495. . '<th style="padding:6px 8px;border:1px solid #ddd;width:48px;">序号</th>'
  8496. . '<th style="padding:6px 8px;border:1px solid #ddd;text-align:left;">工序名称</th>'
  8497. . '<th style="padding:6px 8px;border:1px solid #ddd;width:64px;">单位</th>'
  8498. . '<th style="padding:6px 8px;border:1px solid #ddd;width:88px;">本次数量</th>'
  8499. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  8500. $blocks[] = $head . $table;
  8501. }
  8502. return implode('', $blocks);
  8503. }
  8504. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  8505. {
  8506. $sysRq = trim($sysRq);
  8507. if ($sysRq === '') {
  8508. if ($required) {
  8509. $this->error('请选择招标截止日期');
  8510. }
  8511. return '';
  8512. }
  8513. $ts = strtotime($sysRq);
  8514. if ($ts === false || $ts <= 0) {
  8515. $this->error('招标截止日期格式无效');
  8516. }
  8517. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  8518. if (!$allowPast) {
  8519. $ymd = date('Y-m-d', $ts);
  8520. if ($ymd < date('Y-m-d')) {
  8521. $this->error('招标截止日期不能早于今天');
  8522. }
  8523. if ($ts <= time()) {
  8524. $this->error('招标截止时间不能早于当前时间');
  8525. }
  8526. }
  8527. return date('Y-m-d H:i:s', $ts);
  8528. }
  8529. /**
  8530. * 确保 purchase_order.czlyq(类型)存在
  8531. */
  8532. protected function ensurePurchaseOrderCzlyqColumn(): void
  8533. {
  8534. static $done = false;
  8535. if ($done) {
  8536. return;
  8537. }
  8538. $done = true;
  8539. try {
  8540. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  8541. if (empty($cols)) {
  8542. Db::execute(
  8543. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  8544. );
  8545. }
  8546. } catch (\Throwable $e) {
  8547. // ignore
  8548. }
  8549. }
  8550. /**
  8551. * 确保 purchase_order.delivery_deadline 存在
  8552. */
  8553. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  8554. {
  8555. static $done = false;
  8556. if ($done) {
  8557. return;
  8558. }
  8559. $done = true;
  8560. try {
  8561. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  8562. if (empty($cols)) {
  8563. Db::execute(
  8564. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  8565. );
  8566. }
  8567. } catch (\Throwable $e) {
  8568. // ignore
  8569. }
  8570. }
  8571. /**
  8572. * 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
  8573. */
  8574. protected function ensurePurchaseOrderScoreRuleIdColumn(): void
  8575. {
  8576. static $done = false;
  8577. if ($done) {
  8578. return;
  8579. }
  8580. $done = true;
  8581. // 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
  8582. $adds = [
  8583. 'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
  8584. 'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
  8585. 'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
  8586. 'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
  8587. 'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
  8588. ];
  8589. $changed = false;
  8590. foreach ($adds as $col => $ddl) {
  8591. try {
  8592. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  8593. if (!is_array($cols) || $cols === []) {
  8594. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  8595. $changed = true;
  8596. }
  8597. } catch (\Throwable $e) {
  8598. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  8599. }
  8600. }
  8601. if ($changed) {
  8602. $this->clearPurchaseOrderTableFieldsCache();
  8603. }
  8604. }
  8605. /**
  8606. * 确保 purchase_order.order_batch_no(下发批次号)存在
  8607. */
  8608. protected function ensurePurchaseOrderOrderBatchNoColumn(): void
  8609. {
  8610. static $done = false;
  8611. if ($done) {
  8612. return;
  8613. }
  8614. $done = true;
  8615. try {
  8616. $hasNew = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'order_batch_no'");
  8617. if (is_array($hasNew) && $hasNew !== []) {
  8618. return;
  8619. }
  8620. $hasOld = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'issue_batch_no'");
  8621. if (is_array($hasOld) && $hasOld !== []) {
  8622. Db::execute(
  8623. "ALTER TABLE `purchase_order` CHANGE COLUMN `issue_batch_no` `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号(如XH202608240001)'"
  8624. );
  8625. try {
  8626. Db::execute('ALTER TABLE `purchase_order` DROP INDEX `idx_issue_batch_no`');
  8627. } catch (\Throwable $eDrop) {
  8628. }
  8629. try {
  8630. Db::execute('ALTER TABLE `purchase_order` ADD INDEX `idx_order_batch_no` (`order_batch_no`)');
  8631. } catch (\Throwable $eIdx) {
  8632. }
  8633. } else {
  8634. Db::execute(
  8635. "ALTER TABLE `purchase_order` ADD COLUMN `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号(如XH202608240001)'"
  8636. );
  8637. try {
  8638. Db::execute('ALTER TABLE `purchase_order` ADD INDEX `idx_order_batch_no` (`order_batch_no`)');
  8639. } catch (\Throwable $eIdx) {
  8640. }
  8641. }
  8642. $this->clearPurchaseOrderTableFieldsCache();
  8643. } catch (\Throwable $e) {
  8644. Log::write('purchase_order.order_batch_no: ' . $e->getMessage(), 'error');
  8645. }
  8646. }
  8647. /** @deprecated 兼容旧调用 */
  8648. protected function ensurePurchaseOrderIssueBatchNoColumn(): void
  8649. {
  8650. $this->ensurePurchaseOrderOrderBatchNoColumn();
  8651. }
  8652. /**
  8653. * 批次号日流水表:取号时立刻落库递增,避免并发下发撞号
  8654. */
  8655. protected function ensurePurchaseIssueBatchSeqTable(): void
  8656. {
  8657. static $done = false;
  8658. if ($done) {
  8659. return;
  8660. }
  8661. $done = true;
  8662. try {
  8663. Db::execute(
  8664. "CREATE TABLE IF NOT EXISTS `purchase_issue_batch_seq` (
  8665. `ymd` char(8) NOT NULL COMMENT '日期Ymd',
  8666. `last_no` int unsigned NOT NULL DEFAULT 0 COMMENT '当日已分配最大流水',
  8667. `updatetime` datetime DEFAULT NULL,
  8668. PRIMARY KEY (`ymd`)
  8669. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助下发批次号日流水'"
  8670. );
  8671. } catch (\Throwable $e) {
  8672. Log::write('purchase_issue_batch_seq: ' . $e->getMessage(), 'error');
  8673. }
  8674. }
  8675. /**
  8676. * 生成下发批次号:XH + Ymd + 当日4位流水(如 XH202608240001)
  8677. * 必须拿到日锁后先递增流水表再返回,避免两笔下发同时取到同一号。
  8678. *
  8679. * @throws \RuntimeException
  8680. */
  8681. protected function allocateProcuremenIssueBatchNo(): string
  8682. {
  8683. $this->ensurePurchaseOrderOrderBatchNoColumn();
  8684. $this->ensurePurchaseIssueBatchSeqTable();
  8685. $ymd = date('Ymd');
  8686. $prefix = 'XH' . $ymd;
  8687. $lockName = 'procuremen_issue_batch_' . $ymd;
  8688. if (!$this->acquireProcuremenNamedLock($lockName, 15)) {
  8689. throw new \RuntimeException('批次号生成繁忙,请稍后重试');
  8690. }
  8691. try {
  8692. $last = 0;
  8693. $hasSeqRow = false;
  8694. try {
  8695. $row = Db::table('purchase_issue_batch_seq')->where('ymd', $ymd)->find();
  8696. if (is_array($row) && $row !== []) {
  8697. $hasSeqRow = true;
  8698. $last = (int)($row['last_no'] ?? 0);
  8699. }
  8700. } catch (\Throwable $e) {
  8701. $last = 0;
  8702. }
  8703. // 兼容:流水表为空时,用已有 purchase_order.order_batch_no 最大值对齐
  8704. try {
  8705. $maxPo = Db::table('purchase_order')
  8706. ->where('order_batch_no', 'like', $prefix . '%')
  8707. ->order('order_batch_no', 'desc')
  8708. ->value('order_batch_no');
  8709. if (is_string($maxPo) && preg_match('/^XH\d{8}(\d{4})$/', $maxPo, $m)) {
  8710. $last = max($last, (int)$m[1]);
  8711. }
  8712. } catch (\Throwable $e) {
  8713. }
  8714. $seq = $last + 1;
  8715. if ($seq < 1) {
  8716. $seq = 1;
  8717. }
  8718. if ($seq > 9999) {
  8719. throw new \RuntimeException('当日批次号已用尽,请联系管理员');
  8720. }
  8721. $now = date('Y-m-d H:i:s');
  8722. try {
  8723. if ($hasSeqRow) {
  8724. Db::table('purchase_issue_batch_seq')->where('ymd', $ymd)->update([
  8725. 'last_no' => $seq,
  8726. 'updatetime' => $now,
  8727. ]);
  8728. } else {
  8729. try {
  8730. Db::table('purchase_issue_batch_seq')->insert([
  8731. 'ymd' => $ymd,
  8732. 'last_no' => $seq,
  8733. 'updatetime' => $now,
  8734. ]);
  8735. } catch (\Throwable $eIns) {
  8736. Db::table('purchase_issue_batch_seq')->where('ymd', $ymd)->update([
  8737. 'last_no' => $seq,
  8738. 'updatetime' => $now,
  8739. ]);
  8740. }
  8741. }
  8742. } catch (\Throwable $e) {
  8743. throw new \RuntimeException('批次号写入失败,请重试');
  8744. }
  8745. return $prefix . str_pad((string)$seq, 4, '0', STR_PAD_LEFT);
  8746. } finally {
  8747. $this->releaseProcuremenNamedLock($lockName);
  8748. }
  8749. }
  8750. /**
  8751. * ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
  8752. */
  8753. protected function clearPurchaseOrderTableFieldsCache(): void
  8754. {
  8755. try {
  8756. $db = (string)Config::get('database.database');
  8757. $key = $db . '.purchase_order';
  8758. $ref = new \ReflectionProperty(\think\db\Query::class, 'info');
  8759. $ref->setAccessible(true);
  8760. $info = $ref->getValue();
  8761. if (is_array($info) && isset($info[$key])) {
  8762. unset($info[$key]);
  8763. $ref->setValue(null, $info);
  8764. }
  8765. } catch (\Throwable $e) {
  8766. }
  8767. try {
  8768. $db = (string)Config::get('database.database');
  8769. $schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
  8770. if (is_file($schemaFile)) {
  8771. @unlink($schemaFile);
  8772. }
  8773. } catch (\Throwable $e) {
  8774. }
  8775. }
  8776. /**
  8777. * @return array<string, bool>
  8778. */
  8779. protected function loadPurchaseOrderColumnSet(): array
  8780. {
  8781. static $set = null;
  8782. if (is_array($set)) {
  8783. return $set;
  8784. }
  8785. $set = [];
  8786. try {
  8787. $cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
  8788. } catch (\Throwable $e) {
  8789. return $set;
  8790. }
  8791. if (!is_array($cols)) {
  8792. return $set;
  8793. }
  8794. foreach ($cols as $c) {
  8795. if (!is_array($c)) {
  8796. continue;
  8797. }
  8798. $f = (string)($c['Field'] ?? $c['field'] ?? '');
  8799. if ($f !== '') {
  8800. $set[$f] = true;
  8801. }
  8802. }
  8803. return $set;
  8804. }
  8805. /**
  8806. * 解析交货截止日期(仅年月日)
  8807. */
  8808. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  8809. {
  8810. $raw = trim($raw);
  8811. if ($raw === '') {
  8812. if ($required) {
  8813. $this->error('请选择交货截止日期');
  8814. }
  8815. return '';
  8816. }
  8817. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  8818. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  8819. } else {
  8820. $ts = strtotime(str_replace('/', '-', $raw));
  8821. if ($ts === false || $ts <= 0) {
  8822. $this->error('交货截止日期格式无效');
  8823. }
  8824. $ymd = date('Y-m-d', $ts);
  8825. }
  8826. if ($ymd < date('Y-m-d')) {
  8827. $this->error('交货截止日期不能早于今天');
  8828. }
  8829. return $ymd;
  8830. }
  8831. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  8832. {
  8833. return ProcuremenFormat::deliveryDeadlineForInput($value);
  8834. }
  8835. /**
  8836. * @param array{pos?:array} $bundle
  8837. * @return array<string, string> CCYDH => Y-m-d
  8838. */
  8839. protected function buildBundleOrderDeliveryDeadlineMap(array $bundle): array
  8840. {
  8841. $map = [];
  8842. foreach ($bundle['pos'] ?? [] as $po) {
  8843. if (!is_array($po)) {
  8844. continue;
  8845. }
  8846. $dh = trim((string)($po['CCYDH'] ?? ''));
  8847. if ($dh === '' || isset($map[$dh])) {
  8848. continue;
  8849. }
  8850. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  8851. if ($d !== '') {
  8852. $map[$dh] = $d;
  8853. }
  8854. }
  8855. return $map;
  8856. }
  8857. /**
  8858. * @param array{pos?:array} $bundle
  8859. */
  8860. protected function resolveBundleDeliveryDeadline(array $bundle): string
  8861. {
  8862. $map = $this->buildBundleOrderDeliveryDeadlineMap($bundle);
  8863. if ($map !== []) {
  8864. $firstDeadline = reset($map);
  8865. return (string)$firstDeadline;
  8866. }
  8867. return '';
  8868. }
  8869. protected function formatProcuremenSysRqForInput($sysRq): string
  8870. {
  8871. return ProcuremenFormat::sysRqForInput($sysRq);
  8872. }
  8873. protected function formatProcuremenSysRqForDisplay($sysRq): string
  8874. {
  8875. return ProcuremenFormat::sysRqForDisplay($sysRq);
  8876. }
  8877. /**
  8878. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  8879. *
  8880. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  8881. * @return array{ccydh?:string,pos:array,merge_rows:array}
  8882. */
  8883. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  8884. {
  8885. return $bundle;
  8886. }
  8887. /**
  8888. * 写入/更新 purchase_order(单道工序行)
  8889. *
  8890. * @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
  8891. */
  8892. protected function upsertPurchaseOrderFromRow(
  8893. array $row,
  8894. string $sysRqDb,
  8895. $wflowStatus = null,
  8896. ?string $pickTime = null,
  8897. ?array $exists = null,
  8898. ?string $deliveryDeadline = null,
  8899. $scoreRuleId = null,
  8900. ?string $issueBatchNo = null
  8901. ): void {
  8902. $ids = $this->extractScydgyRowId($row);
  8903. if (!$this->isValidScydgyRowId($ids)) {
  8904. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  8905. }
  8906. if ($exists === null) {
  8907. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  8908. }
  8909. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  8910. $this->ensurePurchaseOrderScoreRuleIdColumn();
  8911. $this->ensurePurchaseOrderOrderBatchNoColumn();
  8912. $this->ensurePurchaseOrderCzlyqColumn();
  8913. $data = $this->normalizePurchaseOrderWritePayload([
  8914. 'scydgy_id' => $ids,
  8915. 'CCYDH' => $row['CCYDH'] ?? null,
  8916. 'CYJMC' => $row['CYJMC'] ?? null,
  8917. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  8918. 'CDXMC' => $row['CDXMC'] ?? null,
  8919. 'CGYBH' => $row['CGYBH'] ?? null,
  8920. 'CGYMC' => $row['CGYMC'] ?? null,
  8921. 'CDW' => $row['CDW'] ?? null,
  8922. 'czlyq' => $row['czlyq'] ?? null,
  8923. 'NGZL' => $row['NGZL'] ?? null,
  8924. 'CDF' => $row['CDF'] ?? null,
  8925. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  8926. 'MBZ' => trim((string)($row['MBZ'] ?? $row['mbz'] ?? '')),
  8927. 'bwjg' => $row['bwjg'] ?? null,
  8928. 'iStatus' => $row['iStatus'] ?? null,
  8929. 'dStamp' => $row['dStamp'] ?? null,
  8930. 'dputrecord' => $row['dputrecord'] ?? null,
  8931. 'cywyxm' => $row['cywyxm'] ?? null,
  8932. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  8933. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  8934. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  8935. 'sys_rq' => $sysRqDb,
  8936. ], $row);
  8937. // 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
  8938. $qtyUp = trim((string)($data['This_quantity'] ?? ''));
  8939. if ($qtyUp === '') {
  8940. $qtyFallback = $this->resolveProcuremenThisQuantity([
  8941. 'This_quantity' => '',
  8942. 'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
  8943. ]);
  8944. if ($qtyFallback !== '') {
  8945. $data['This_quantity'] = $qtyFallback;
  8946. }
  8947. }
  8948. if ($deliveryDeadline !== null) {
  8949. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  8950. }
  8951. // 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
  8952. $scoreRule = null;
  8953. if (is_array($scoreRuleId)) {
  8954. $scoreRule = $scoreRuleId;
  8955. $scoreRuleId = (int)($scoreRule['id'] ?? 0);
  8956. } else {
  8957. $scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
  8958. }
  8959. if ($scoreRuleId !== null && $scoreRuleId > 0) {
  8960. $poCols = $this->loadPurchaseOrderColumnSet();
  8961. if (!empty($poCols['score_rule_id'])) {
  8962. $data['score_rule_id'] = $scoreRuleId;
  8963. if (is_array($scoreRule)) {
  8964. if (!empty($poCols['score_rule_name'])) {
  8965. $data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
  8966. }
  8967. if (!empty($poCols['score_quality_weight'])) {
  8968. $data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
  8969. }
  8970. if (!empty($poCols['score_price_weight'])) {
  8971. $data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
  8972. }
  8973. if (!empty($poCols['score_lead_weight'])) {
  8974. $data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
  8975. }
  8976. }
  8977. }
  8978. }
  8979. if ($wflowStatus !== null && $wflowStatus !== '') {
  8980. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  8981. }
  8982. if ($pickTime !== null && $pickTime !== '') {
  8983. $data['pick_time'] = $pickTime;
  8984. $data['pick_company_name'] = '';
  8985. // 新下发批次:清空「指定供应商」,避免沿用上轮免开标状态导致提前可见报价
  8986. $this->ensurePurchaseOrderManualPickColumns();
  8987. $data['manual_pick'] = 0;
  8988. $data['manual_pick_reason'] = '';
  8989. // 同订单重新下发后需重新开标(按订单号 + 批次号);并软删同订单其它旧批
  8990. $dh = trim((string)($data['CCYDH'] ?? $row['CCYDH'] ?? ''));
  8991. $bn = trim((string)($issueBatchNo ?? ''));
  8992. if ($bn === '') {
  8993. $bn = $this->resolveProcuremenOrderBatchNo(array_merge(is_array($exists) ? $exists : [], $data, $row));
  8994. }
  8995. $this->clearProcuremenBidOpenRecords($dh !== '' ? [$dh] : [], $bn !== '' ? [$bn] : []);
  8996. if ($dh !== '') {
  8997. // 新下发只清开标/评分;软删其它批仅在「重新下发」入口做,避免正常补发工序误伤并行单
  8998. $this->clearProcuremenSupplierScoresForCcydhs([$dh]);
  8999. }
  9000. }
  9001. if ($issueBatchNo !== null) {
  9002. $batchNo = trim($issueBatchNo);
  9003. $poCols = $this->loadPurchaseOrderColumnSet();
  9004. if (!empty($poCols['order_batch_no'])) {
  9005. $data['order_batch_no'] = $batchNo;
  9006. }
  9007. }
  9008. if ($exists) {
  9009. $upd = $data;
  9010. unset($upd['scydgy_id']);
  9011. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  9012. } else {
  9013. $data['createtime'] = date('Y-m-d H:i:s');
  9014. Db::table('purchase_order')->insert($data);
  9015. }
  9016. }
  9017. /**
  9018. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  9019. *
  9020. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  9021. */
  9022. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
  9023. {
  9024. $toDb = function ($value) {
  9025. if ($value === null) {
  9026. return null;
  9027. }
  9028. if (is_scalar($value)) {
  9029. return $value;
  9030. }
  9031. return json_encode($value, JSON_UNESCAPED_UNICODE);
  9032. };
  9033. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  9034. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  9035. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  9036. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  9037. if ($username === '') {
  9038. $username = $this->resolveCustomerContactName($phone, $companyName);
  9039. }
  9040. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  9041. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  9042. }
  9043. if ($requirePhone && $phone === '') {
  9044. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  9045. }
  9046. $detailLinks = [];
  9047. foreach ($mergeRows as $row) {
  9048. if (!is_array($row)) {
  9049. continue;
  9050. }
  9051. $sid = $this->extractScydgyRowId($row);
  9052. $detailId = 0;
  9053. if ($skipExisting) {
  9054. try {
  9055. $existsQuery = Db::table('purchase_order_detail')
  9056. ->where('scydgy_id', $sid)
  9057. ->where('company_name', $companyName);
  9058. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  9059. $exists = $existsQuery->find();
  9060. } catch (\Throwable $e) {
  9061. $exists = null;
  9062. }
  9063. if (is_array($exists)) {
  9064. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  9065. }
  9066. }
  9067. if ($detailId <= 0) {
  9068. $one = [
  9069. 'scydgy_id' => $toDb($sid),
  9070. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  9071. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  9072. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  9073. 'username' => $username !== '' ? $username : null,
  9074. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  9075. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  9076. 'createtime' => date('Y-m-d H:i:s'),
  9077. 'status' => ProcuremenStatus::POD_UNPICKED,
  9078. 'status_name' => '未提交',
  9079. ];
  9080. // 新下发/重新下发均不继承历史报价,供应商需对本批次重新填报
  9081. Db::table('purchase_order_detail')->insert($one);
  9082. $detailId = (int)Db::getLastInsID();
  9083. }
  9084. $mprocUrl = '';
  9085. if ($buildMobileLinks && $detailId > 0) {
  9086. // 手工询价 → 待报价;协助下发 → 未提交
  9087. $listTab = ($sid < 0) ? 'rfq' : 'draft';
  9088. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId, $listTab);
  9089. }
  9090. $detailLinks[] = [
  9091. 'detail_id' => $detailId,
  9092. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  9093. 'url' => $mprocUrl,
  9094. ];
  9095. }
  9096. $this->invalidatePickHiddenScydgyCache();
  9097. return $detailLinks;
  9098. }
  9099. /**
  9100. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  9101. * @return array<string, mixed>
  9102. */
  9103. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks, string $emailTplScene = 'review_email'): array
  9104. {
  9105. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  9106. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  9107. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  9108. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  9109. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  9110. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  9111. $isMerge = !empty($ctx['is_merge']);
  9112. $contactName = trim((string)($c['username'] ?? ''));
  9113. if ($contactName === '') {
  9114. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  9115. }
  9116. $notifyVars = [
  9117. 'company_name' => $companyName,
  9118. 'contact_name' => $contactName,
  9119. 'phone' => $phone,
  9120. 'email' => $toEmail,
  9121. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  9122. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  9123. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  9124. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  9125. 'deadline' => (string)($ctx['deadline'] ?? ''),
  9126. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  9127. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  9128. 'order_type' => (string)($ctx['order_type'] ?? ''),
  9129. 'score_weights' => (string)($ctx['score_weights'] ?? ''),
  9130. 'platform_url' => $platformUrl,
  9131. 'platform_links' => $platformLinksPlain,
  9132. 'platform_links_html' => $platformLinksHtml,
  9133. ];
  9134. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  9135. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  9136. $mailPlain = $this->renderNotifyTemplate($emailTplScene, $notifyVars);
  9137. if (!empty($ctx['multi_order'])) {
  9138. $smsContent = $this->stripEmptyOrderHeaderLines($smsContent);
  9139. $mailPlain = $this->stripEmptyOrderHeaderLines($mailPlain);
  9140. }
  9141. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  9142. // 邮件:用表格替换纯文本工序块,列对齐更整齐
  9143. $processHtml = trim((string)($ctx['process_html'] ?? ''));
  9144. $processPlain = trim((string)($ctx['process_plain'] ?? ''));
  9145. if ($processHtml !== '' && $processPlain !== '') {
  9146. $plainBlockHtml = $this->plainTextToHtmlEmailBody($processPlain);
  9147. if ($plainBlockHtml !== '' && strpos($mailBody, $plainBlockHtml) !== false) {
  9148. $mailBody = str_replace($plainBlockHtml, $processHtml, $mailBody);
  9149. }
  9150. }
  9151. return [
  9152. 'company_name' => $companyName,
  9153. 'phone' => $phone,
  9154. 'email' => $toEmail,
  9155. 'sms_content' => $smsContent,
  9156. 'mail_plain' => $mailPlain,
  9157. 'mail_body' => $mailBody,
  9158. 'notify_vars' => $notifyVars,
  9159. 'detail_links' => $detailLinks,
  9160. ];
  9161. }
  9162. /**
  9163. * 多订单下发时模版里「订单号:{ccydh}」可能变成空行,去掉以免重复
  9164. */
  9165. protected function stripEmptyOrderHeaderLines(string $text): string
  9166. {
  9167. $text = str_replace(["\r\n", "\r"], "\n", $text);
  9168. $text = preg_replace('/^订单号:\s*\n/mu', '', $text);
  9169. $text = preg_replace('/^印件名称:\s*\n/mu', '', $text);
  9170. $text = preg_replace("/\n{3,}/", "\n\n", (string)$text);
  9171. return (string)$text;
  9172. }
  9173. /**
  9174. * @param array<string, mixed> $chosen
  9175. * @param array<int, array<string, mixed>> $mergeRows
  9176. * @param array{ccydh:string, pos:array} $bundle
  9177. */
  9178. /**
  9179. * 先把成功 JSON 回给浏览器,再继续后台任务(发短信/邮件)。
  9180. * 避免多家供应商通知串行导致页面一直转圈、网关超时被当成系统失败。
  9181. *
  9182. * @param array<string, mixed>|string|null $data
  9183. */
  9184. protected function respondSuccessThenContinue(string $msg, $data = null): void
  9185. {
  9186. $result = [
  9187. 'code' => 1,
  9188. 'msg' => $msg,
  9189. 'data' => $data,
  9190. 'url' => '',
  9191. 'wait' => 3,
  9192. ];
  9193. $json = json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  9194. if ($json === false) {
  9195. $json = '{"code":1,"msg":"操作成功","data":null,"url":"","wait":3}';
  9196. }
  9197. while (ob_get_level() > 0) {
  9198. @ob_end_clean();
  9199. }
  9200. if (!headers_sent()) {
  9201. header('Content-Type: application/json; charset=utf-8');
  9202. header('Cache-Control: no-store, no-cache, must-revalidate');
  9203. header('Connection: close');
  9204. header('Content-Length: ' . strlen($json));
  9205. }
  9206. echo $json;
  9207. if (session_status() === PHP_SESSION_ACTIVE) {
  9208. @session_write_close();
  9209. }
  9210. if (function_exists('fastcgi_finish_request')) {
  9211. @fastcgi_finish_request();
  9212. } else {
  9213. @flush();
  9214. }
  9215. @ignore_user_abort(true);
  9216. @set_time_limit(300);
  9217. @ini_set('max_execution_time', '300');
  9218. }
  9219. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue', string $emailTplScene = 'review_email'): void
  9220. {
  9221. if (!$sendSms && !$sendEmail) {
  9222. return;
  9223. }
  9224. $companyName = trim((string)($chosen['name'] ?? ''));
  9225. $phone = trim((string)($chosen['phone'] ?? ''));
  9226. $toEmail = trim((string)($chosen['email'] ?? ''));
  9227. if ($companyName === '') {
  9228. throw new \Exception('供应商名称无效');
  9229. }
  9230. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  9231. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  9232. }
  9233. if ($sendSms && $phone === '') {
  9234. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  9235. }
  9236. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  9237. $linkListTab = (strpos($emailTplScene, 'rfq_') === 0) ? 'rfq' : 'draft';
  9238. $sids = [];
  9239. foreach ($mergeRows as $mr) {
  9240. if (!is_array($mr)) {
  9241. continue;
  9242. }
  9243. $sid = $this->extractScydgyRowId($mr);
  9244. if ($this->isValidScydgyRowId($sid)) {
  9245. $sids[$sid] = true;
  9246. }
  9247. }
  9248. if ($sids === []) {
  9249. throw new \Exception('未找到工序行,无法发送通知');
  9250. }
  9251. $sysRqNotify = '';
  9252. $pos = $bundle['pos'] ?? [];
  9253. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  9254. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  9255. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  9256. $ts = strtotime($sr);
  9257. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  9258. }
  9259. }
  9260. try {
  9261. $detailsQuery = Db::table('purchase_order_detail')
  9262. ->where('scydgy_id', 'in', array_keys($sids))
  9263. ->where('company_name', $companyName);
  9264. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  9265. $details = $detailsQuery->order('id', 'asc')->select();
  9266. } catch (\Throwable $e) {
  9267. $details = [];
  9268. }
  9269. if (!is_array($details) || $details === []) {
  9270. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  9271. try {
  9272. $detailsQuery = Db::table('purchase_order_detail')
  9273. ->where('scydgy_id', 'in', array_keys($sids))
  9274. ->where('company_name', $companyName);
  9275. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  9276. $details = $detailsQuery->order('id', 'asc')->select();
  9277. } catch (\Throwable $e) {
  9278. $details = [];
  9279. }
  9280. }
  9281. if (!is_array($details) || $details === []) {
  9282. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  9283. }
  9284. $detailLinks = [];
  9285. foreach ($details as $d) {
  9286. if (!is_array($d)) {
  9287. continue;
  9288. }
  9289. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  9290. if ($detailId <= 0) {
  9291. continue;
  9292. }
  9293. $sid = (int)($d['scydgy_id'] ?? 0);
  9294. $gymc = '';
  9295. foreach ($mergeRows as $mr) {
  9296. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  9297. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  9298. break;
  9299. }
  9300. }
  9301. $detailLinks[] = [
  9302. 'detail_id' => $detailId,
  9303. 'cgymc' => $gymc,
  9304. // 询价邮件 → 待报价;下发报价 → 未提交
  9305. 'url' => $this->buildMprocMobileOrderUrl(
  9306. $detailId,
  9307. ($linkListTab === 'rfq' || $sid < 0) ? 'rfq' : 'draft'
  9308. ),
  9309. ];
  9310. }
  9311. if ($detailLinks === []) {
  9312. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  9313. }
  9314. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  9315. $orderTypeCtx = $this->resolveIssueNotifyOrderTypeFromBundle($bundle);
  9316. $ctx['order_type'] = (string)($orderTypeCtx['order_type'] ?? '');
  9317. $ctx['score_weights'] = (string)($orderTypeCtx['score_weights'] ?? '');
  9318. $this->ensureReviewEmailTemplate();
  9319. $this->ensureReviewSmsTemplate();
  9320. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks, $emailTplScene);
  9321. $notifyBundle['email_log_scene'] = $emailLogScene;
  9322. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  9323. $poIdLog = 0;
  9324. $pos = $bundle['pos'] ?? [];
  9325. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  9326. $poIdLog = (int)($pos[0]['id'] ?? 0);
  9327. }
  9328. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  9329. // 日志单独记订单号/批次号:多订单下发时模版变量 ccydh 会刻意留空,不能沿用到日志
  9330. $notifyBundle['email_log_ccydh'] = $this->collectCcydhListForEmailLog($mergeRows, $pos);
  9331. $notifyBundle['email_log_order_batch_no'] = $this->resolveBundleOrderBatchNo($bundle);
  9332. if ($sendEmail) {
  9333. $mailTplRow = $this->loadNotifyTemplateRow($emailTplScene);
  9334. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  9335. throw new \Exception($this->notifyTemplateMissingMessage($emailTplScene));
  9336. }
  9337. $mailSubject = $this->resolveProcuremenEmailSubject($emailTplScene);
  9338. $mailConfig = $this->loadMailerConfig();
  9339. if (!$this->isProcuremenNotifyDryRun()) {
  9340. if (empty($mailConfig['host'])) {
  9341. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9342. }
  9343. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9344. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9345. }
  9346. }
  9347. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  9348. }
  9349. if ($sendSms) {
  9350. $this->issueSendSupplierSms($notifyBundle);
  9351. }
  9352. }
  9353. /**
  9354. * @param array<int, array<string, mixed>> $quoteGroups
  9355. * @return array<int, array<string, mixed>>
  9356. */
  9357. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  9358. {
  9359. $names = [];
  9360. if (is_string($companiesJson) && $companiesJson !== '') {
  9361. $decoded = json_decode($companiesJson, true);
  9362. if (is_array($decoded)) {
  9363. foreach ($decoded as $nm) {
  9364. $nm = trim((string)$nm);
  9365. if ($nm !== '') {
  9366. $names[] = $nm;
  9367. }
  9368. }
  9369. }
  9370. }
  9371. $names = array_values(array_unique($names));
  9372. if ($names === [] && $selectedCompany !== '') {
  9373. $names = [$selectedCompany];
  9374. }
  9375. if ($names === []) {
  9376. return $quoteGroups;
  9377. }
  9378. $targets = [];
  9379. foreach ($quoteGroups as $g) {
  9380. if (!is_array($g)) {
  9381. continue;
  9382. }
  9383. $cn = trim((string)($g['name'] ?? ''));
  9384. if ($cn !== '' && in_array($cn, $names, true)) {
  9385. $targets[] = $g;
  9386. }
  9387. }
  9388. return $targets;
  9389. }
  9390. /**
  9391. * @return array{pos:array, merge_rows:array, bundle:array}
  9392. */
  9393. protected function loadAuditResendBundle(string $scydgyId): array
  9394. {
  9395. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  9396. $pos = $bundle['pos'];
  9397. $mergeRows = $bundle['merge_rows'];
  9398. if ($pos === [] || $mergeRows === []) {
  9399. $this->error('该订单不在待确认供应商状态');
  9400. }
  9401. $sysRqDb = '';
  9402. if (isset($pos[0]) && is_array($pos[0])) {
  9403. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  9404. }
  9405. foreach ($pos as $i => $poRow) {
  9406. if (is_array($pos[$i]) && $sysRqDb !== '') {
  9407. $pos[$i]['sys_rq'] = $sysRqDb;
  9408. }
  9409. }
  9410. $bundle['pos'] = $pos;
  9411. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  9412. }
  9413. /**
  9414. * @param array<int, array<string, mixed>> $targets
  9415. */
  9416. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  9417. {
  9418. if ($targets === []) {
  9419. $this->error('未找到可通知的供应商');
  9420. }
  9421. $notifyErrors = [];
  9422. try {
  9423. $this->notifyDryRunPreview = [];
  9424. foreach ($targets as $g) {
  9425. if (!is_array($g)) {
  9426. continue;
  9427. }
  9428. $cname = trim((string)($g['name'] ?? ''));
  9429. if ($cname === '') {
  9430. continue;
  9431. }
  9432. $chosen = [
  9433. 'name' => $cname,
  9434. 'company_name' => $cname,
  9435. 'email' => trim((string)($g['email'] ?? '')),
  9436. 'phone' => trim((string)($g['phone'] ?? '')),
  9437. 'username' => trim((string)($g['username'] ?? '')),
  9438. ];
  9439. try {
  9440. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  9441. } catch (\Throwable $e) {
  9442. $notifyErrors[] = $cname . ':' . $e->getMessage();
  9443. }
  9444. }
  9445. } catch (\Throwable $e) {
  9446. Log::write('procuremen auditResend notify fatal: ' . $e->getMessage(), 'error');
  9447. $this->success('重发未全部完成,请核对联系方式后稍后再试', '', [
  9448. 'notify_failed' => 1,
  9449. ]);
  9450. }
  9451. if ($notifyErrors !== []) {
  9452. Log::write('procuremen auditResend partial fail: ' . implode(';', $notifyErrors), 'error');
  9453. $ok = max(0, count($targets) - count($notifyErrors));
  9454. $this->success(
  9455. '已向 ' . $ok . ' 家发送成功;',
  9456. '',
  9457. [
  9458. 'notify_failed' => 1,
  9459. 'notify_fail_detail' => $notifyErrors,
  9460. ]
  9461. );
  9462. }
  9463. if ($this->isProcuremenNotifyDryRun()) {
  9464. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  9465. 'notify_dry_run' => true,
  9466. 'notify_preview' => $this->notifyDryRunPreview,
  9467. ]);
  9468. }
  9469. $nameLabels = [];
  9470. foreach ($targets as $g) {
  9471. if (!is_array($g)) {
  9472. continue;
  9473. }
  9474. $n = trim((string)($g['name'] ?? ''));
  9475. if ($n !== '') {
  9476. $nameLabels[] = $n;
  9477. }
  9478. }
  9479. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  9480. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  9481. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  9482. $seenLogSid = [];
  9483. foreach ($bundle['pos'] ?? [] as $poRow) {
  9484. if (!is_array($poRow)) {
  9485. continue;
  9486. }
  9487. $sid = (int)($poRow['scydgy_id'] ?? 0);
  9488. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  9489. continue;
  9490. }
  9491. $seenLogSid[$sid] = true;
  9492. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  9493. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  9494. }
  9495. if ($seenLogSid === []) {
  9496. foreach ($mergeRows as $mr) {
  9497. if (!is_array($mr)) {
  9498. continue;
  9499. }
  9500. $sid = $this->extractScydgyRowId($mr);
  9501. if ($this->isValidScydgyRowId($sid)) {
  9502. $this->addOrderLog($sid, $logAction, $logMsg, null);
  9503. break;
  9504. }
  9505. }
  9506. }
  9507. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  9508. }
  9509. /**
  9510. * 协助下发 — 发送短信(一家供应商)
  9511. *
  9512. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  9513. */
  9514. protected function issueSendSupplierSms(array $bundle): void
  9515. {
  9516. $companyName = (string)($bundle['company_name'] ?? '');
  9517. $phone = (string)($bundle['phone'] ?? '');
  9518. $smsContent = (string)($bundle['sms_content'] ?? '');
  9519. $this->logIssueNotifyDebug('短信', [
  9520. 'company' => $companyName,
  9521. 'phone' => $phone,
  9522. 'sms_content' => $smsContent,
  9523. ]);
  9524. if ($this->isProcuremenNotifyDryRun()) {
  9525. $this->recordNotifyDryRunPreview([
  9526. 'scene' => 'issue_sms',
  9527. 'company_name' => $companyName,
  9528. 'phone' => $phone,
  9529. 'sms_content' => $smsContent,
  9530. ]);
  9531. return;
  9532. }
  9533. $this->smsbao($phone, $smsContent);
  9534. }
  9535. /**
  9536. * 协助下发 — 发送邮件(一家供应商)
  9537. *
  9538. * @param array<string, mixed> $bundle
  9539. * @param array<string, mixed> $mailConfig
  9540. */
  9541. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  9542. {
  9543. $companyName = (string)($bundle['company_name'] ?? '');
  9544. $toEmail = (string)($bundle['email'] ?? '');
  9545. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  9546. $mailBody = (string)($bundle['mail_body'] ?? '');
  9547. $this->logIssueNotifyDebug('邮件', [
  9548. 'company' => $companyName,
  9549. 'email' => $toEmail,
  9550. 'cc_email' => $this->resolveMprocNotifyCcEmails($toEmail),
  9551. 'mail_subject' => $mailSubject,
  9552. 'mail_body' => $mailPlain,
  9553. ]);
  9554. if ($this->isProcuremenNotifyDryRun()) {
  9555. $this->recordNotifyDryRunPreview([
  9556. 'scene' => 'issue_email',
  9557. 'company_name' => $companyName,
  9558. 'email' => $toEmail,
  9559. 'cc_email' => $this->resolveMprocNotifyCcEmails($toEmail),
  9560. 'mail_subject' => $mailSubject,
  9561. 'mail_body' => $mailPlain,
  9562. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  9563. 'notify_vars' => $bundle['notify_vars'] ?? [],
  9564. 'detail_links' => $bundle['detail_links'] ?? [],
  9565. ]);
  9566. return;
  9567. }
  9568. $mail = new PHPMailer(true);
  9569. $mail->isSMTP();
  9570. $mail->Host = $mailConfig['host'];
  9571. $mail->SMTPAuth = true;
  9572. $mail->Username = $mailConfig['addr'];
  9573. $mail->Password = $mailConfig['pass'];
  9574. $mail->SMTPSecure = $mailConfig['security'];
  9575. $mail->Port = $mailConfig['port'];
  9576. $mail->CharSet = $mailConfig['charset'];
  9577. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  9578. $mail->addAddress($toEmail, $companyName);
  9579. $ccList = $this->resolveMprocNotifyCcEmails($toEmail);
  9580. foreach ($ccList as $cc) {
  9581. $mail->addCC($cc);
  9582. }
  9583. $mail->isHTML(true);
  9584. $mail->Subject = $mailSubject;
  9585. $mail->Body = $mailBody;
  9586. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  9587. $sendOk = true;
  9588. $failReason = '';
  9589. $logCcydh = trim((string)($bundle['email_log_ccydh'] ?? ''));
  9590. if ($logCcydh === '') {
  9591. $logCcydh = trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? '')));
  9592. }
  9593. $logBatchNo = trim((string)($bundle['email_log_order_batch_no'] ?? ($bundle['order_batch_no'] ?? '')));
  9594. $logCommon = [
  9595. 'from_email' => $fromEmail,
  9596. 'to_email' => $toEmail,
  9597. 'send_time' => date('Y-m-d H:i:s'),
  9598. 'scene' => (string)($bundle['email_log_scene'] ?? '初选下发'),
  9599. 'order_batch_no' => $logBatchNo,
  9600. 'ccydh' => $logCcydh,
  9601. 'company_name' => $companyName,
  9602. 'mail_subject' => $mailSubject,
  9603. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  9604. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  9605. ];
  9606. try {
  9607. $mail->send();
  9608. } catch (\Throwable $e) {
  9609. $sendOk = false;
  9610. $failReason = $e->getMessage();
  9611. $this->persistEmailSendLog(array_merge($logCommon, [
  9612. 'status' => 0,
  9613. 'fail_reason' => $failReason,
  9614. ]));
  9615. throw $e;
  9616. }
  9617. $this->persistEmailSendLog(array_merge($logCommon, [
  9618. 'status' => 1,
  9619. 'fail_reason' => '',
  9620. ]));
  9621. }
  9622. /**
  9623. * 协助通知抄送:读取 mproc.cc_email(逗号分隔),排除与主收件人相同的地址
  9624. *
  9625. * @return array<int, string>
  9626. */
  9627. protected function resolveMprocNotifyCcEmails(string $toEmail = ''): array
  9628. {
  9629. $raw = trim((string)config('mproc.cc_email'));
  9630. if ($raw === '') {
  9631. return [];
  9632. }
  9633. $toNorm = strtolower(trim($toEmail));
  9634. $out = [];
  9635. $seen = [];
  9636. foreach (preg_split('/[,;,;\s]+/', $raw) ?: [] as $piece) {
  9637. $email = strtolower(trim((string)$piece));
  9638. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9639. continue;
  9640. }
  9641. if ($toNorm !== '' && $email === $toNorm) {
  9642. continue;
  9643. }
  9644. if (isset($seen[$email])) {
  9645. continue;
  9646. }
  9647. $seen[$email] = true;
  9648. $out[] = $email;
  9649. }
  9650. return $out;
  9651. }
  9652. /**
  9653. * 下发通知:解析订单类型名称与评分比例文案
  9654. *
  9655. * @param array<string, mixed> $bundle
  9656. * @return array{order_type:string,score_weights:string}
  9657. */
  9658. protected function resolveIssueNotifyOrderTypeFromBundle(array $bundle): array
  9659. {
  9660. $orderType = '';
  9661. $scoreWeights = '';
  9662. $rule = null;
  9663. Log::write('procuremen resolveOrderType bundle: ' . json_encode([
  9664. 'score_rule' => isset($bundle['score_rule']) ? $bundle['score_rule'] : 'NOT_SET',
  9665. 'pos0_score_rule_id' => isset($bundle['pos'][0]['score_rule_id']) ? $bundle['pos'][0]['score_rule_id'] : 'NOT_SET',
  9666. ], JSON_UNESCAPED_UNICODE), 'notice');
  9667. if (!empty($bundle['score_rule']) && is_array($bundle['score_rule'])) {
  9668. $rule = $bundle['score_rule'];
  9669. }
  9670. $pos = $bundle['pos'] ?? [];
  9671. $po0 = (is_array($pos) && isset($pos[0]) && is_array($pos[0])) ? $pos[0] : null;
  9672. if ($rule === null && is_array($po0)) {
  9673. $ruleId = (int)($po0['score_rule_id'] ?? 0);
  9674. if ($ruleId > 0) {
  9675. try {
  9676. $rule = ProcuremenSupplierScore::getRuleById($ruleId);
  9677. Log::write('procuremen resolveOrderType via pos ruleId=' . $ruleId . ' result: ' . json_encode($rule, JSON_UNESCAPED_UNICODE), 'notice');
  9678. } catch (\Throwable $e) {
  9679. $rule = null;
  9680. Log::write('procuremen resolveOrderType getRuleById exception: ' . $e->getMessage(), 'error');
  9681. }
  9682. }
  9683. if (!is_array($rule) || (int)($rule['id'] ?? 0) <= 0) {
  9684. $qw = (int)($po0['score_quality_weight'] ?? 0);
  9685. $pw = (int)($po0['score_price_weight'] ?? 0);
  9686. $lw = (int)($po0['score_lead_weight'] ?? 0);
  9687. if ($qw > 0 || $pw > 0 || $lw > 0) {
  9688. $rule = [
  9689. 'name' => trim((string)($po0['score_rule_name'] ?? '')),
  9690. 'quality_weight' => $qw,
  9691. 'price_weight' => $pw,
  9692. 'lead_weight' => $lw,
  9693. ];
  9694. }
  9695. }
  9696. }
  9697. if (is_array($rule)) {
  9698. $orderType = trim((string)($rule['name'] ?? ''));
  9699. $scoreWeights = $this->formatScoreRuleWeightsText($rule);
  9700. }
  9701. if ($orderType === '' && is_array($po0)) {
  9702. $orderType = trim((string)($po0['score_rule_name'] ?? ''));
  9703. }
  9704. Log::write('procuremen resolveOrderType result: orderType=' . $orderType . ', scoreWeights=' . $scoreWeights, 'notice');
  9705. return [
  9706. 'order_type' => $orderType,
  9707. 'score_weights' => $scoreWeights,
  9708. ];
  9709. }
  9710. /**
  9711. * 评分比例文案:质量30%、价格50%、交货20%
  9712. *
  9713. * @param array{quality_weight?:mixed,price_weight?:mixed,lead_weight?:mixed} $rule
  9714. */
  9715. protected function formatScoreRuleWeightsText(array $rule): string
  9716. {
  9717. return ProcuremenFormat::scoreRuleWeightsText($rule);
  9718. }
  9719. /**
  9720. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  9721. *
  9722. * @param array<int, array<string, mixed>> $mergeRows
  9723. * @return array<string, mixed>
  9724. */
  9725. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  9726. {
  9727. $head = $mergeRows[0] ?? [];
  9728. $isMerge = count($mergeRows) > 1;
  9729. $orderSet = [];
  9730. foreach ($mergeRows as $r) {
  9731. if (!is_array($r)) {
  9732. continue;
  9733. }
  9734. $dh = trim((string)($r['CCYDH'] ?? ''));
  9735. if ($dh !== '') {
  9736. $orderSet[$dh] = true;
  9737. }
  9738. }
  9739. $multiOrder = count($orderSet) > 1;
  9740. // 多订单:明细块自带各订单头,避免模版里 {ccydh}/{cyjmc} 只显示第一单
  9741. $ccydh = $multiOrder ? '' : (isset($head['CCYDH']) ? (string)$head['CCYDH'] : '');
  9742. $cyjmc = $multiOrder ? '' : (isset($head['CYJMC']) ? (string)$head['CYJMC'] : '');
  9743. return [
  9744. 'ccydh' => $ccydh,
  9745. 'cyjmc' => $cyjmc,
  9746. 'cgymc_single' => $multiOrder ? '' : trim((string)($head['CGYMC'] ?? '')),
  9747. 'is_merge' => $isMerge,
  9748. 'multi_order' => $multiOrder,
  9749. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  9750. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  9751. 'deadline' => $sysRqNotify,
  9752. 'order_type' => '',
  9753. 'score_weights' => '',
  9754. ];
  9755. }
  9756. /**
  9757. * 邮件发送日志用的订单号列表(多单逗号分隔;与模版变量是否留空无关)
  9758. *
  9759. * @param array<int, array<string, mixed>> $mergeRows
  9760. * @param array<int, array<string, mixed>> $pos
  9761. */
  9762. protected function collectCcydhListForEmailLog(array $mergeRows, array $pos = []): string
  9763. {
  9764. $set = [];
  9765. foreach ($mergeRows as $r) {
  9766. if (!is_array($r)) {
  9767. continue;
  9768. }
  9769. foreach (['CCYDH', 'ccydh'] as $k) {
  9770. $dh = trim((string)($r[$k] ?? ''));
  9771. if ($dh !== '') {
  9772. $set[$dh] = true;
  9773. break;
  9774. }
  9775. }
  9776. }
  9777. if ($set === []) {
  9778. foreach ($pos as $po) {
  9779. if (!is_array($po)) {
  9780. continue;
  9781. }
  9782. foreach (['CCYDH', 'ccydh'] as $k) {
  9783. $dh = trim((string)($po[$k] ?? ''));
  9784. if ($dh !== '') {
  9785. $set[$dh] = true;
  9786. break;
  9787. }
  9788. }
  9789. }
  9790. }
  9791. return implode(',', array_keys($set));
  9792. }
  9793. /**
  9794. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  9795. *
  9796. * @param array<string, mixed> $data
  9797. */
  9798. protected function logIssueNotifyDebug(string $type, array $data): void
  9799. {
  9800. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  9801. return;
  9802. }
  9803. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  9804. }
  9805. protected function ensurePurchaseEmailSendLogTableOnce(): void
  9806. {
  9807. try {
  9808. Db::query('SELECT `id`,`order_batch_no`,`ccydh` FROM `purchase_email_send_log` LIMIT 1');
  9809. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  9810. return;
  9811. } catch (\Throwable $e) {
  9812. }
  9813. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  9814. if (is_file($sqlFile)) {
  9815. $sql = file_get_contents($sqlFile);
  9816. if (is_string($sql) && $sql !== '') {
  9817. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  9818. $stmt = trim($stmt);
  9819. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  9820. continue;
  9821. }
  9822. try {
  9823. Db::execute($stmt);
  9824. } catch (\Throwable $ignore) {
  9825. }
  9826. }
  9827. }
  9828. }
  9829. try {
  9830. $cols = Db::query("SHOW COLUMNS FROM `purchase_email_send_log` LIKE 'order_batch_no'");
  9831. if (!is_array($cols) || $cols === []) {
  9832. Db::execute(
  9833. "ALTER TABLE `purchase_email_send_log` ADD COLUMN `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号' AFTER `scene`"
  9834. );
  9835. }
  9836. } catch (\Throwable $ignore) {
  9837. }
  9838. try {
  9839. $cols = Db::query("SHOW COLUMNS FROM `purchase_email_send_log` LIKE 'ccydh'");
  9840. if (is_array($cols) && $cols !== []) {
  9841. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  9842. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 500) {
  9843. Db::execute(
  9844. "ALTER TABLE `purchase_email_send_log` MODIFY COLUMN `ccydh` varchar(500) NOT NULL DEFAULT '' COMMENT '订单号(多单逗号分隔)'"
  9845. );
  9846. }
  9847. }
  9848. } catch (\Throwable $ignore) {
  9849. }
  9850. try {
  9851. $idx = Db::query("SHOW INDEX FROM `purchase_email_send_log` WHERE Key_name = 'idx_order_batch_no'");
  9852. if (!is_array($idx) || $idx === []) {
  9853. Db::execute('ALTER TABLE `purchase_email_send_log` ADD INDEX `idx_order_batch_no` (`order_batch_no`)');
  9854. }
  9855. } catch (\Throwable $ignore) {
  9856. }
  9857. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  9858. }
  9859. /**
  9860. * @param array<string, mixed> $row
  9861. */
  9862. protected function persistEmailSendLog(array $row): void
  9863. {
  9864. try {
  9865. $this->ensurePurchaseEmailSendLogTableOnce();
  9866. } catch (\Throwable $e) {
  9867. return;
  9868. }
  9869. list($adminId, $adminName) = $this->GetUseName();
  9870. $cut = function ($s, $max) {
  9871. $s = (string)$s;
  9872. if (function_exists('mb_substr')) {
  9873. return mb_substr($s, 0, $max, 'UTF-8');
  9874. }
  9875. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  9876. };
  9877. $data = [
  9878. 'from_email' => $cut($row['from_email'] ?? '', 128),
  9879. 'to_email' => $cut($row['to_email'] ?? '', 128),
  9880. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  9881. 'scene' => $cut($this->normalizeEmailLogSceneForStore((string)($row['scene'] ?? '')), 64),
  9882. 'order_batch_no' => $cut($row['order_batch_no'] ?? '', 32),
  9883. 'ccydh' => $cut($row['ccydh'] ?? '', 500),
  9884. 'company_name' => $cut($row['company_name'] ?? '', 128),
  9885. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  9886. 'status' => !empty($row['status']) ? 1 : 0,
  9887. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  9888. 'admin_id' => (int)$adminId,
  9889. 'admin_name' => $cut($adminName, 64),
  9890. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  9891. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  9892. 'createtime' => date('Y-m-d H:i:s'),
  9893. ];
  9894. try {
  9895. Db::table('purchase_email_send_log')->insert($data);
  9896. } catch (\Throwable $e) {
  9897. // 兼容尚未自动补列的旧库:去掉批次号再试一次
  9898. if (stripos($e->getMessage(), 'order_batch_no') !== false) {
  9899. try {
  9900. unset($data['order_batch_no']);
  9901. Db::table('purchase_email_send_log')->insert($data);
  9902. return;
  9903. } catch (\Throwable $e2) {
  9904. Log::write('persistEmailSendLog: ' . $e2->getMessage(), 'error');
  9905. return;
  9906. }
  9907. }
  9908. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  9909. }
  9910. }
  9911. /**
  9912. * 邮件日志场景:库内统一存中文;兼容历史英文码
  9913. *
  9914. * @return array<string, string>
  9915. */
  9916. protected function emailLogSceneLabelMap(): array
  9917. {
  9918. return ProcuremenFormat::emailLogSceneLabelMap();
  9919. }
  9920. /** 写入邮件日志前:英文场景码转中文;已是中文则原样 */
  9921. protected function normalizeEmailLogSceneForStore(string $scene): string
  9922. {
  9923. return ProcuremenFormat::normalizeEmailLogSceneForStore($scene);
  9924. }
  9925. protected function formatEmailLogSceneText(string $scene): string
  9926. {
  9927. return ProcuremenFormat::emailLogSceneText($scene);
  9928. }
  9929. /**
  9930. * 邮件发送日志列表
  9931. */
  9932. public function emailLog()
  9933. {
  9934. $this->relationSearch = false;
  9935. $this->searchFields = 'from_email,to_email,ccydh,order_batch_no,company_name,admin_name,mail_subject';
  9936. $this->request->filter(['strip_tags', 'trim']);
  9937. $bakModel = $this->model;
  9938. $this->model = new \app\admin\model\Purchaseemailsendlog;
  9939. if ($this->request->isAjax()) {
  9940. $this->ensurePurchaseEmailSendLogTableOnce();
  9941. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  9942. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  9943. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  9944. $list = $this->model
  9945. ->where($where)
  9946. ->order($sortField, $orderDir)
  9947. ->paginate($limit);
  9948. $rows = [];
  9949. $needEnrichPoIds = [];
  9950. foreach ($list->items() as $item) {
  9951. $row = is_array($item) ? $item : $item->toArray();
  9952. $scene = trim((string)($row['scene'] ?? ''));
  9953. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  9954. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  9955. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  9956. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  9957. $row['order_batch_no'] = trim((string)($row['order_batch_no'] ?? ''));
  9958. $row['ccydh'] = trim((string)($row['ccydh'] ?? ''));
  9959. $poId = (int)($row['purchase_order_id'] ?? 0);
  9960. if ($poId > 0 && ($row['ccydh'] === '' || $row['order_batch_no'] === '')) {
  9961. $needEnrichPoIds[$poId] = true;
  9962. }
  9963. $rows[] = $row;
  9964. }
  9965. if ($needEnrichPoIds !== []) {
  9966. $poMap = $this->loadEmailLogEnrichPoMap(array_keys($needEnrichPoIds));
  9967. foreach ($rows as &$row) {
  9968. $poId = (int)($row['purchase_order_id'] ?? 0);
  9969. if ($poId <= 0 || !isset($poMap[$poId])) {
  9970. continue;
  9971. }
  9972. $info = $poMap[$poId];
  9973. if ($row['order_batch_no'] === '' && $info['order_batch_no'] !== '') {
  9974. $row['order_batch_no'] = $info['order_batch_no'];
  9975. }
  9976. if ($row['ccydh'] === '') {
  9977. if ($info['order_batch_no'] !== '' && isset($info['batch_ccydhs']) && $info['batch_ccydhs'] !== '') {
  9978. $row['ccydh'] = $info['batch_ccydhs'];
  9979. } elseif ($info['ccydh'] !== '') {
  9980. $row['ccydh'] = $info['ccydh'];
  9981. }
  9982. }
  9983. }
  9984. unset($row);
  9985. }
  9986. $this->model = $bakModel;
  9987. return json(['total' => $list->total(), 'rows' => $rows]);
  9988. }
  9989. $this->model = $bakModel;
  9990. return $this->view->fetch('procuremen/emaillog');
  9991. }
  9992. /**
  9993. * 历史邮件日志缺订单号/批次号时,按 purchase_order_id 回填展示
  9994. *
  9995. * @param array<int, int> $poIds
  9996. * @return array<int, array{ccydh:string,order_batch_no:string,batch_ccydhs:string}>
  9997. */
  9998. protected function loadEmailLogEnrichPoMap(array $poIds): array
  9999. {
  10000. $out = [];
  10001. $poIds = array_values(array_unique(array_filter(array_map('intval', $poIds))));
  10002. if ($poIds === []) {
  10003. return $out;
  10004. }
  10005. try {
  10006. $pos = Db::table('purchase_order')->where('id', 'in', $poIds)->field('id,CCYDH,order_batch_no')->select();
  10007. } catch (\Throwable $e) {
  10008. try {
  10009. $pos = Db::table('purchase_order')->where('id', 'in', $poIds)->field('id,CCYDH')->select();
  10010. } catch (\Throwable $e2) {
  10011. return $out;
  10012. }
  10013. }
  10014. $batchSet = [];
  10015. foreach ($pos as $po) {
  10016. if (!is_array($po)) {
  10017. continue;
  10018. }
  10019. $id = (int)($po['id'] ?? 0);
  10020. if ($id <= 0) {
  10021. continue;
  10022. }
  10023. $bn = $this->resolveProcuremenOrderBatchNo($po);
  10024. $out[$id] = [
  10025. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  10026. 'order_batch_no' => $bn,
  10027. 'batch_ccydhs' => '',
  10028. ];
  10029. if ($bn !== '') {
  10030. $batchSet[$bn] = true;
  10031. }
  10032. }
  10033. if ($batchSet === []) {
  10034. return $out;
  10035. }
  10036. try {
  10037. $batchRows = Db::table('purchase_order')
  10038. ->where('order_batch_no', 'in', array_keys($batchSet))
  10039. ->field('CCYDH,order_batch_no')
  10040. ->select();
  10041. } catch (\Throwable $e) {
  10042. return $out;
  10043. }
  10044. $byBatch = [];
  10045. foreach ($batchRows as $br) {
  10046. if (!is_array($br)) {
  10047. continue;
  10048. }
  10049. $bn = trim((string)($br['order_batch_no'] ?? ''));
  10050. $dh = trim((string)($br['CCYDH'] ?? ''));
  10051. if ($bn === '' || $dh === '') {
  10052. continue;
  10053. }
  10054. $byBatch[$bn][$dh] = true;
  10055. }
  10056. foreach ($out as $id => $info) {
  10057. $bn = $info['order_batch_no'];
  10058. if ($bn !== '' && isset($byBatch[$bn])) {
  10059. $out[$id]['batch_ccydhs'] = implode(',', array_keys($byBatch[$bn]));
  10060. }
  10061. }
  10062. return $out;
  10063. }
  10064. /**
  10065. * 协助下发弹窗(选多家供应商并通知)
  10066. */
  10067. public function pickReview()
  10068. {
  10069. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  10070. $this->error(__('You have no permission'));
  10071. }
  10072. if ($this->request->isPost()) {
  10073. $this->error('请使用弹窗内「确认下发」提交');
  10074. }
  10075. $this->view->assign('pickMode', 1);
  10076. $this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
  10077. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  10078. }
  10079. /**
  10080. * 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
  10081. */
  10082. protected function ensurePurchaseOrderNotifySalesmanColumn(): void
  10083. {
  10084. static $done = false;
  10085. if ($done) {
  10086. return;
  10087. }
  10088. $done = true;
  10089. try {
  10090. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'notify_salesman'");
  10091. if (empty($cols)) {
  10092. Db::execute(
  10093. "ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
  10094. );
  10095. } else {
  10096. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  10097. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
  10098. Db::execute(
  10099. "ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
  10100. );
  10101. }
  10102. }
  10103. } catch (\Throwable $e) {
  10104. // ignore
  10105. }
  10106. }
  10107. /**
  10108. * 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
  10109. */
  10110. protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
  10111. {
  10112. static $done = false;
  10113. if ($done) {
  10114. return;
  10115. }
  10116. $done = true;
  10117. try {
  10118. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
  10119. if (empty($cols)) {
  10120. Db::execute(
  10121. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
  10122. );
  10123. }
  10124. } catch (\Throwable $e) {
  10125. // ignore
  10126. }
  10127. try {
  10128. $cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
  10129. if (empty($cols2)) {
  10130. Db::execute(
  10131. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
  10132. );
  10133. }
  10134. } catch (\Throwable $e) {
  10135. // ignore
  10136. }
  10137. }
  10138. /**
  10139. * 确保「采购确认通过/未通过」邮箱模版存在。
  10140. * title=说明;remark=邮箱通知;邮件主题由 resolveProcuremenEmailSubject 固定,不用 title。
  10141. */
  10142. protected function ensureConfirmResultEmailTemplates(): void
  10143. {
  10144. static $done = false;
  10145. if ($done) {
  10146. return;
  10147. }
  10148. $done = true;
  10149. $now = date('Y-m-d H:i:s');
  10150. $seeds = [
  10151. 'confirm_ok_email' => [
  10152. 'title' => '确认已通过通知',
  10153. 'content' => "您好,{company_name}:\n\n您参与的订单采购确认结果:已通过 已中标。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  10154. 'remark' => '邮箱通知',
  10155. ],
  10156. 'confirm_fail_email' => [
  10157. 'title' => '确认未通过通知',
  10158. 'content' => "您好,{company_name}:\n\n您参与的订单采购确认结果:未通过 未中标。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  10159. 'remark' => '邮箱通知',
  10160. ],
  10161. ];
  10162. try {
  10163. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  10164. } catch (\Throwable $e) {
  10165. return;
  10166. }
  10167. $colNames = [];
  10168. foreach ($cols as $c) {
  10169. if (!is_array($c)) {
  10170. continue;
  10171. }
  10172. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  10173. if ($n !== '') {
  10174. $colNames[$n] = true;
  10175. }
  10176. }
  10177. foreach ($seeds as $scene => $seed) {
  10178. try {
  10179. $row = Db::table('purchase_sms_template')->where('scene', $scene)->find();
  10180. } catch (\Throwable $e) {
  10181. continue;
  10182. }
  10183. if (is_array($row) && $row !== []) {
  10184. continue;
  10185. }
  10186. $data = [
  10187. 'scene' => $scene,
  10188. 'title' => $seed['title'],
  10189. 'content' => $seed['content'],
  10190. 'remark' => $seed['remark'],
  10191. 'status' => 1,
  10192. ];
  10193. if (isset($colNames['updatetime'])) {
  10194. $data['updatetime'] = $now;
  10195. }
  10196. if (isset($colNames['createtime'])) {
  10197. $data['createtime'] = $now;
  10198. }
  10199. try {
  10200. Db::table('purchase_sms_template')->insert($data);
  10201. } catch (\Throwable $e) {
  10202. // ignore
  10203. }
  10204. }
  10205. }
  10206. /**
  10207. * 确保「协助下发-邮箱」模版存在(含 {order_type};可在短信模版配置中修改)
  10208. */
  10209. protected function ensureReviewEmailTemplate(): void
  10210. {
  10211. static $done = false;
  10212. if ($done) {
  10213. return;
  10214. }
  10215. $done = true;
  10216. $content = "您好,{company_name}:\n\n"
  10217. . "您有新的协助加工订单,请登录平台查看并报价。\n\n"
  10218. . "需求编号:{ccydh}\n"
  10219. . "印件名称:{cyjmc}\n"
  10220. . "业务分类:{category}\n"
  10221. . "订单类型:{order_type}\n"
  10222. . "{process_lines}\n\n"
  10223. . "请在 {deadline} 前完成报价。\n\n"
  10224. . "平台链接:{platform_url}\n";
  10225. try {
  10226. $row = Db::table('purchase_sms_template')
  10227. ->where('scene', 'review_email')
  10228. ->find();
  10229. } catch (\Throwable $e) {
  10230. return;
  10231. }
  10232. $now = date('Y-m-d H:i:s');
  10233. if (is_array($row) && $row !== []) {
  10234. return;
  10235. }
  10236. try {
  10237. $data = [
  10238. 'scene' => 'review_email',
  10239. 'title' => '协助加工订单通知',
  10240. 'content' => $content,
  10241. 'remark' => '协助下发-邮箱;可在短信模版配置中修改',
  10242. 'status' => 1,
  10243. ];
  10244. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  10245. $colNames = [];
  10246. foreach ($cols as $c) {
  10247. if (!is_array($c)) {
  10248. continue;
  10249. }
  10250. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  10251. if ($n !== '') {
  10252. $colNames[$n] = true;
  10253. }
  10254. }
  10255. if (isset($colNames['updatetime'])) {
  10256. $data['updatetime'] = $now;
  10257. }
  10258. if (isset($colNames['createtime'])) {
  10259. $data['createtime'] = $now;
  10260. }
  10261. Db::table('purchase_sms_template')->insert($data);
  10262. } catch (\Throwable $e) {
  10263. // ignore
  10264. }
  10265. }
  10266. /**
  10267. * 确保「协助下发-短信」模版存在(含 {order_type};可在短信模版配置中修改)
  10268. */
  10269. protected function ensureReviewSmsTemplate(): void
  10270. {
  10271. static $done = false;
  10272. if ($done) {
  10273. return;
  10274. }
  10275. $done = true;
  10276. $content = "您好,{company_name}:\n\n"
  10277. . "您有新的协助加工订单,请登录平台查看并报价。\n\n"
  10278. . "需求编号:{ccydh}\n"
  10279. . "印件名称:{cyjmc}\n"
  10280. . "订单类型:{order_type}\n"
  10281. . "{process_lines}\n\n"
  10282. . "请在 {deadline} 前完成报价。\n\n"
  10283. . "平台链接:{platform_url}\n";
  10284. try {
  10285. $row = Db::table('purchase_sms_template')
  10286. ->where('scene', 'review_sms')
  10287. ->find();
  10288. } catch (\Throwable $e) {
  10289. return;
  10290. }
  10291. $now = date('Y-m-d H:i:s');
  10292. if (is_array($row) && $row !== []) {
  10293. return;
  10294. }
  10295. try {
  10296. $data = [
  10297. 'scene' => 'review_sms',
  10298. 'title' => '协助加工订单通知',
  10299. 'content' => $content,
  10300. 'remark' => '协助下发-短信;可在短信模版配置中修改',
  10301. 'status' => 1,
  10302. ];
  10303. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  10304. $colNames = [];
  10305. foreach ($cols as $c) {
  10306. if (!is_array($c)) {
  10307. continue;
  10308. }
  10309. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  10310. if ($n !== '') {
  10311. $colNames[$n] = true;
  10312. }
  10313. }
  10314. if (isset($colNames['updatetime'])) {
  10315. $data['updatetime'] = $now;
  10316. }
  10317. if (isset($colNames['createtime'])) {
  10318. $data['createtime'] = $now;
  10319. }
  10320. Db::table('purchase_sms_template')->insert($data);
  10321. } catch (\Throwable $e) {
  10322. // ignore
  10323. }
  10324. }
  10325. /**
  10326. * 确保「供应商询价通知」邮箱模版存在(查询询价-询价/发邮件;可在短信模版配置中修改)
  10327. */
  10328. protected function ensureRfqSupplierEmailTemplate(): void
  10329. {
  10330. static $done = false;
  10331. if ($done) {
  10332. return;
  10333. }
  10334. $done = true;
  10335. $content = "您好,{company_name}:\n\n"
  10336. . "您有新的协助采购询价需求,请登录平台查看并处理。\n\n"
  10337. . "需求编号:{ccydh}\n"
  10338. . "印件名称:{cyjmc}\n"
  10339. . "{process_lines}\n\n"
  10340. . "请在 {deadline} 前完成回复。\n\n"
  10341. . "平台链接:{platform_url}\n";
  10342. try {
  10343. $row = Db::table('purchase_sms_template')
  10344. ->where('scene', 'rfq_supplier_email')
  10345. ->find();
  10346. } catch (\Throwable $e) {
  10347. return;
  10348. }
  10349. $now = date('Y-m-d H:i:s');
  10350. if (is_array($row) && $row !== []) {
  10351. return;
  10352. }
  10353. try {
  10354. $data = [
  10355. 'scene' => 'rfq_supplier_email',
  10356. 'title' => '供应商询价通知',
  10357. 'content' => $content,
  10358. 'remark' => '查询询价-询价/发邮件通知供应商;模版名称作邮件主题',
  10359. 'status' => 1,
  10360. ];
  10361. try {
  10362. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  10363. } catch (\Throwable $e) {
  10364. $cols = [];
  10365. }
  10366. $colNames = [];
  10367. foreach ($cols as $c) {
  10368. if (!is_array($c)) {
  10369. continue;
  10370. }
  10371. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  10372. if ($n !== '') {
  10373. $colNames[$n] = true;
  10374. }
  10375. }
  10376. if (isset($colNames['updatetime'])) {
  10377. $data['updatetime'] = $now;
  10378. }
  10379. if (isset($colNames['createtime'])) {
  10380. $data['createtime'] = $now;
  10381. }
  10382. Db::table('purchase_sms_template')->insert($data);
  10383. } catch (\Throwable $e) {
  10384. // ignore
  10385. }
  10386. }
  10387. /**
  10388. * 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
  10389. */
  10390. protected function ensureRfqSalesmanEmailTemplate(): void
  10391. {
  10392. static $done = false;
  10393. if ($done) {
  10394. return;
  10395. }
  10396. $done = true;
  10397. $content = "您好,{contact_name}:\n\n"
  10398. . "有新的协助采购询价需求,请知悉。\n"
  10399. . "印件名称:{cyjmc}\n"
  10400. . "工序名称:{cgymc}\n"
  10401. . "本次数量:{this_quantity}\n"
  10402. . "供应商报价:\n{supplier_quotes}\n"
  10403. . "平台链接:{platform_url}\n"
  10404. . "需求发起人:{cywyxm}\n";
  10405. try {
  10406. $row = Db::table('purchase_sms_template')
  10407. ->where('scene', 'rfq_salesman_email')
  10408. ->find();
  10409. } catch (\Throwable $e) {
  10410. return;
  10411. }
  10412. $now = date('Y-m-d H:i:s');
  10413. if (is_array($row) && $row !== []) {
  10414. $old = (string)($row['content'] ?? '');
  10415. // 无报价表格 / 无平台链接 / 链接不在「需求发起人」上方时,同步默认文案
  10416. $urlPos = strpos($old, '{platform_url}');
  10417. $cywyPos = strpos($old, '需求发起人');
  10418. $linkNotAboveStarter = ($urlPos === false)
  10419. || ($cywyPos !== false && $urlPos > $cywyPos);
  10420. $needMigrate = (strpos($old, '{supplier_quotes}') === false)
  10421. || (strpos($old, '供应商:{supplier_name}') !== false)
  10422. || $linkNotAboveStarter;
  10423. if ($needMigrate) {
  10424. $data = ['content' => $content];
  10425. if (trim((string)($row['title'] ?? '')) === '' || trim((string)($row['title'] ?? '')) === '询价通知') {
  10426. $data['title'] = '业务员询价通知';
  10427. }
  10428. try {
  10429. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
  10430. if (!empty($cols)) {
  10431. $data['updatetime'] = $now;
  10432. }
  10433. } catch (\Throwable $e) {
  10434. }
  10435. try {
  10436. Db::table('purchase_sms_template')
  10437. ->where('id', (int)($row['id'] ?? 0))
  10438. ->update($data);
  10439. } catch (\Throwable $e) {
  10440. }
  10441. }
  10442. return;
  10443. }
  10444. try {
  10445. $data = [
  10446. 'scene' => 'rfq_salesman_email',
  10447. 'title' => '业务员询价通知',
  10448. 'content' => $content,
  10449. 'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
  10450. 'status' => 1,
  10451. ];
  10452. try {
  10453. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  10454. } catch (\Throwable $e) {
  10455. $cols = [];
  10456. }
  10457. $colNames = [];
  10458. foreach ($cols as $c) {
  10459. if (!is_array($c)) {
  10460. continue;
  10461. }
  10462. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  10463. if ($n !== '') {
  10464. $colNames[$n] = true;
  10465. }
  10466. }
  10467. if (isset($colNames['updatetime'])) {
  10468. $data['updatetime'] = $now;
  10469. }
  10470. if (isset($colNames['createtime'])) {
  10471. $data['createtime'] = $now;
  10472. }
  10473. Db::table('purchase_sms_template')->insert($data);
  10474. } catch (\Throwable $e) {
  10475. // ignore
  10476. }
  10477. }
  10478. /**
  10479. * 通知业务员邮件:供应商报价明细行(仅名称+单价)
  10480. *
  10481. * @return array<int, array{name:string,amount:string}>
  10482. */
  10483. protected function loadRfqSalesmanSupplierQuoteRows(int $sid, string $supplierRaw = ''): array
  10484. {
  10485. $list = [];
  10486. $seen = [];
  10487. try {
  10488. $rows = Db::table('purchase_order_detail')
  10489. ->where('scydgy_id', $sid)
  10490. ->field('company_name,amount')
  10491. ->order('id', 'asc')
  10492. ->select();
  10493. if (is_array($rows)) {
  10494. foreach ($rows as $r) {
  10495. if (!is_array($r)) {
  10496. continue;
  10497. }
  10498. $cn = trim((string)($r['company_name'] ?? ''));
  10499. if ($cn === '' || isset($seen[$cn])) {
  10500. continue;
  10501. }
  10502. $seen[$cn] = true;
  10503. $amount = trim((string)($r['amount'] ?? ''));
  10504. $list[] = [
  10505. 'name' => $cn,
  10506. 'amount' => $amount !== '' ? $amount : '未报价',
  10507. ];
  10508. }
  10509. }
  10510. } catch (\Throwable $e) {
  10511. }
  10512. if ($list === [] && $supplierRaw !== '') {
  10513. foreach ($this->splitRfqSalesmanNames($supplierRaw) as $cn) {
  10514. if ($cn === '' || isset($seen[$cn])) {
  10515. continue;
  10516. }
  10517. $seen[$cn] = true;
  10518. $list[] = [
  10519. 'name' => $cn,
  10520. 'amount' => '未报价',
  10521. ];
  10522. }
  10523. }
  10524. return $list;
  10525. }
  10526. /**
  10527. * 通知业务员邮件:供应商报价 HTML 表格(名称+单价,不含时间)
  10528. */
  10529. protected function buildRfqSalesmanSupplierQuotesHtml(int $sid, string $supplierRaw = ''): string
  10530. {
  10531. $rows = $this->loadRfqSalesmanSupplierQuoteRows($sid, $supplierRaw);
  10532. if ($rows === []) {
  10533. return '<p style="margin:8px 0;color:#888;">暂无报价</p>';
  10534. }
  10535. $html = '<table cellpadding="0" cellspacing="0" border="1" '
  10536. . 'style="border-collapse:collapse;border-color:#ddd;width:100%;max-width:560px;font-size:14px;margin:8px 0;">'
  10537. . '<thead><tr style="background:#f5f5f5;">'
  10538. . '<th style="padding:8px 10px;text-align:center;width:56px;">序号</th>'
  10539. . '<th style="padding:8px 10px;text-align:left;">供应商名称</th>'
  10540. . '<th style="padding:8px 10px;text-align:center;width:100px;">单价</th>'
  10541. . '</tr></thead><tbody>';
  10542. foreach ($rows as $i => $row) {
  10543. $html .= '<tr>'
  10544. . '<td style="padding:8px 10px;text-align:center;">' . ($i + 1) . '</td>'
  10545. . '<td style="padding:8px 10px;">' . htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8') . '</td>'
  10546. . '<td style="padding:8px 10px;text-align:center;">' . htmlspecialchars($row['amount'], ENT_QUOTES, 'UTF-8') . '</td>'
  10547. . '</tr>';
  10548. }
  10549. $html .= '</tbody></table>';
  10550. return $html;
  10551. }
  10552. /**
  10553. * 询价多选字段:数组或字符串统一为顿号拼接
  10554. *
  10555. * @param mixed $raw
  10556. */
  10557. protected function joinRfqMultiSelectValues($raw): string
  10558. {
  10559. $parts = [];
  10560. if (is_array($raw)) {
  10561. foreach ($raw as $item) {
  10562. if (is_array($item)) {
  10563. continue;
  10564. }
  10565. $v = trim((string)$item);
  10566. if ($v !== '') {
  10567. $parts[] = $v;
  10568. }
  10569. }
  10570. } else {
  10571. $s = trim((string)$raw);
  10572. if ($s !== '') {
  10573. foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
  10574. $v = trim((string)$piece);
  10575. if ($v !== '') {
  10576. $parts[] = $v;
  10577. }
  10578. }
  10579. }
  10580. }
  10581. $parts = array_values(array_unique($parts));
  10582. return implode('、', $parts);
  10583. }
  10584. /**
  10585. * 新增询价:可选供应商名称(仅落库记录,不发通知)
  10586. *
  10587. * @return string[]
  10588. */
  10589. protected function loadRfqSupplierNameOptions(): array
  10590. {
  10591. $out = [];
  10592. try {
  10593. $rows = Db::table('customer')
  10594. ->where(function ($q) {
  10595. $q->where('status', 1)
  10596. ->whereOr('status', '1')
  10597. ->whereOr('status', '')
  10598. ->whereNull('status');
  10599. })
  10600. ->order('id', 'desc')
  10601. ->column('company_name');
  10602. } catch (\Throwable $e) {
  10603. return [];
  10604. }
  10605. if (!is_array($rows)) {
  10606. return [];
  10607. }
  10608. foreach ($rows as $name) {
  10609. $name = trim((string)$name);
  10610. if ($name === '' || isset($out[$name])) {
  10611. continue;
  10612. }
  10613. $out[$name] = $name;
  10614. }
  10615. return array_values($out);
  10616. }
  10617. /**
  10618. * 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
  10619. */
  10620. protected function rfqNotifySalesmanAuthGroupId(): int
  10621. {
  10622. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  10623. if ($id > 0) {
  10624. return $id;
  10625. }
  10626. try {
  10627. $found = Db::name('auth_group')
  10628. ->where('name', '业务员')
  10629. ->where('status', 'normal')
  10630. ->order('id', 'asc')
  10631. ->value('id');
  10632. $id = (int)$found;
  10633. } catch (\Throwable $e) {
  10634. $id = 0;
  10635. }
  10636. return $id > 0 ? $id : 12;
  10637. }
  10638. /**
  10639. * 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
  10640. *
  10641. * @return string[]
  10642. */
  10643. protected function loadRfqSalesmanNameOptions(): array
  10644. {
  10645. $out = [];
  10646. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  10647. $name = trim((string)($row['name'] ?? ''));
  10648. if ($name !== '') {
  10649. $out[] = $name;
  10650. }
  10651. }
  10652. return $out;
  10653. }
  10654. /**
  10655. * 业务员角色组下管理员:姓名、邮箱、手机
  10656. *
  10657. * @return array<int, array{name:string,email:string,mobile:string}>
  10658. */
  10659. protected function loadRfqSalesmanContactOptions(): array
  10660. {
  10661. $out = [];
  10662. $seen = [];
  10663. $groupId = $this->rfqNotifySalesmanAuthGroupId();
  10664. if ($groupId <= 0) {
  10665. return [];
  10666. }
  10667. try {
  10668. $adminIds = Db::name('auth_group_access')
  10669. ->where('group_id', $groupId)
  10670. ->column('uid');
  10671. } catch (\Throwable $e) {
  10672. return [];
  10673. }
  10674. $adminIds = is_array($adminIds)
  10675. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  10676. : [];
  10677. if ($adminIds === []) {
  10678. return [];
  10679. }
  10680. try {
  10681. $rows = Db::name('admin')
  10682. ->where('status', 'normal')
  10683. ->where('id', 'in', $adminIds)
  10684. ->order('id', 'asc')
  10685. ->field('id,nickname,username,email,mobile')
  10686. ->select();
  10687. } catch (\Throwable $e) {
  10688. return [];
  10689. }
  10690. if (!is_array($rows)) {
  10691. return [];
  10692. }
  10693. foreach ($rows as $row) {
  10694. if (!is_array($row)) {
  10695. continue;
  10696. }
  10697. $name = trim((string)($row['nickname'] ?? ''));
  10698. if ($name === '') {
  10699. $name = trim((string)($row['username'] ?? ''));
  10700. }
  10701. if ($name === '' || isset($seen[$name])) {
  10702. continue;
  10703. }
  10704. $seen[$name] = true;
  10705. $out[] = [
  10706. 'name' => $name,
  10707. 'email' => trim((string)($row['email'] ?? '')),
  10708. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  10709. ];
  10710. }
  10711. return $out;
  10712. }
  10713. /**
  10714. * 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
  10715. *
  10716. * @return string[]
  10717. */
  10718. protected function loadRfqDeptNameOptions(): array
  10719. {
  10720. $out = [];
  10721. // ERP 承揽部门(主来源)
  10722. try {
  10723. $vals = Db::table('mcyd')
  10724. ->where('CCLBMMC', '<>', '')
  10725. ->whereNotNull('CCLBMMC')
  10726. ->distinct(true)
  10727. ->limit(300)
  10728. ->column('CCLBMMC');
  10729. } catch (\Throwable $e) {
  10730. $vals = [];
  10731. }
  10732. if (is_array($vals)) {
  10733. foreach ($vals as $v) {
  10734. $v = trim((string)$v);
  10735. if ($v === '' || isset($out[$v])) {
  10736. continue;
  10737. }
  10738. $out[$v] = $v;
  10739. }
  10740. }
  10741. // 手工询价历史部门补全
  10742. try {
  10743. $poVals = Db::table('purchase_order')
  10744. ->where('CCLBMMC', '<>', '')
  10745. ->whereNotNull('CCLBMMC')
  10746. ->distinct(true)
  10747. ->limit(200)
  10748. ->column('CCLBMMC');
  10749. } catch (\Throwable $e) {
  10750. $poVals = [];
  10751. }
  10752. if (is_array($poVals)) {
  10753. foreach ($poVals as $v) {
  10754. $v = trim((string)$v);
  10755. if ($v === '' || isset($out[$v])) {
  10756. continue;
  10757. }
  10758. $out[$v] = $v;
  10759. }
  10760. }
  10761. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  10762. if (!isset($out[$preset])) {
  10763. $out[$preset] = $preset;
  10764. }
  10765. }
  10766. $list = array_values($out);
  10767. // 常用部门靠前
  10768. usort($list, static function ($a, $b) {
  10769. $weight = [
  10770. '营销中心' => 1,
  10771. '业务部' => 2,
  10772. '市场部' => 3,
  10773. '外贸部' => 4,
  10774. '新华技术业务部' => 5,
  10775. ];
  10776. $wa = $weight[$a] ?? 100;
  10777. $wb = $weight[$b] ?? 100;
  10778. if ($wa !== $wb) {
  10779. return $wa <=> $wb;
  10780. }
  10781. return strcmp((string)$a, (string)$b);
  10782. });
  10783. return $list;
  10784. }
  10785. /**
  10786. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  10787. */
  10788. public function add()
  10789. {
  10790. if ($this->request->isPost()) {
  10791. $params = $this->request->post('row/a');
  10792. if (!is_array($params)) {
  10793. $this->error(__('Parameter %s can not be empty', ''));
  10794. }
  10795. [, $adminName] = $this->GetUseName();
  10796. $params['cywyxm'] = $adminName;
  10797. try {
  10798. $sid = $this->saveManualPickOrder($params);
  10799. } catch (\InvalidArgumentException $e) {
  10800. $this->error($e->getMessage());
  10801. } catch (\Throwable $e) {
  10802. $this->error($e->getMessage());
  10803. }
  10804. $this->success('新增成功', '', [
  10805. 'scydgy_id' => $sid,
  10806. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  10807. ]);
  10808. }
  10809. $this->ensurePurchaseOrderNotifySalesmanColumn();
  10810. [, $adminName] = $this->GetUseName();
  10811. $this->view->assign('adminNickname', $adminName);
  10812. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  10813. $this->view->assign('defaultCclbmmc', '营销中心');
  10814. $this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
  10815. $this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
  10816. $this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
  10817. return $this->view->fetch();
  10818. }
  10819. /**
  10820. * 业务员新增进度查询(手工询价;有查询权限看全部,含手机端新增且未通知业务员的)
  10821. */
  10822. public function rfqlist()
  10823. {
  10824. $this->relationSearch = false;
  10825. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ';
  10826. $this->request->filter(['strip_tags', 'trim']);
  10827. $this->ensurePurchaseOrderNotifySalesmanColumn();
  10828. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  10829. $this->ensureRfqSalesmanEmailTemplate();
  10830. $this->ensureRfqSupplierEmailTemplate();
  10831. if ($this->request->isAjax()) {
  10832. try {
  10833. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  10834. $limit = max(10, min(500, (int)$limit));
  10835. $filterYm = trim((string)$this->request->param('filter_ym', ''));
  10836. if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
  10837. $filterYm = date('Y-m');
  10838. }
  10839. $applyFilters = function ($query) use ($where, $filterYm) {
  10840. $query->where('scydgy_id', '<', 0);
  10841. $this->applyPurchaseOrderNotDeletedWhere($query);
  10842. // 查询询价:有菜单权限即可看全部手工单(含手机端新增、尚未通知业务员的)
  10843. $this->applyRfqListMonthFilter($query, $filterYm);
  10844. if (!empty($where)) {
  10845. // 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
  10846. $safeWhere = [];
  10847. $skipFields = [
  10848. 'supplier_name' => true,
  10849. 'progress_text' => true,
  10850. 'createtime_text' => true,
  10851. 'notify_time_text' => true,
  10852. 'can_notify_salesman' => true,
  10853. 'has_issued' => true,
  10854. 'has_quoted' => true,
  10855. ];
  10856. foreach ((array)$where as $cond) {
  10857. if (!is_array($cond) || !isset($cond[0])) {
  10858. continue;
  10859. }
  10860. $field = (string)$cond[0];
  10861. $fieldBase = (string)preg_replace('/\|.*$/', '', $field);
  10862. $fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
  10863. if (isset($skipFields[$fieldBase])) {
  10864. continue;
  10865. }
  10866. if ($fieldBase === 'supplier_name') {
  10867. continue;
  10868. }
  10869. $safeWhere[] = $cond;
  10870. }
  10871. if ($safeWhere !== []) {
  10872. $query->where($safeWhere);
  10873. }
  10874. }
  10875. };
  10876. $countQuery = Db::table('purchase_order');
  10877. $applyFilters($countQuery);
  10878. $total = (int)$countQuery->count();
  10879. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  10880. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  10881. $listQuery = Db::table('purchase_order');
  10882. $applyFilters($listQuery);
  10883. $rows = $listQuery
  10884. ->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')
  10885. ->order($sortField, $orderDir)
  10886. ->limit($offset, $limit)
  10887. ->select();
  10888. if (!is_array($rows)) {
  10889. $rows = [];
  10890. }
  10891. $sidList = [];
  10892. foreach ($rows as $r) {
  10893. if (!is_array($r)) {
  10894. continue;
  10895. }
  10896. $sid = (int)($r['scydgy_id'] ?? 0);
  10897. if ($sid < 0) {
  10898. $sidList[$sid] = true;
  10899. }
  10900. }
  10901. $issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
  10902. $quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
  10903. $out = [];
  10904. foreach ($rows as $r) {
  10905. if (!is_array($r)) {
  10906. continue;
  10907. }
  10908. $sid = (int)($r['scydgy_id'] ?? 0);
  10909. if ($sid >= 0) {
  10910. continue;
  10911. }
  10912. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  10913. if ($createdText === '') {
  10914. $createdText = trim((string)($r['dStamp'] ?? ''));
  10915. }
  10916. $notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
  10917. $supplier = trim((string)($r['cGzzxMc'] ?? ''));
  10918. if ($supplier === '') {
  10919. $supplier = trim((string)($r['pick_company_name'] ?? ''));
  10920. }
  10921. $hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
  10922. || isset($issuedSidSet[$sid]);
  10923. $hasQuoted = isset($quotedSidSet[$sid]);
  10924. $salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
  10925. $canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
  10926. $out[] = [
  10927. 'id' => (int)($r['id'] ?? 0),
  10928. 'scydgy_id' => $sid,
  10929. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  10930. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  10931. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  10932. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  10933. 'CDW' => trim((string)($r['CDW'] ?? '')),
  10934. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  10935. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  10936. 'CDF' => trim((string)($r['CDF'] ?? '')),
  10937. 'supplier_name' => $supplier,
  10938. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  10939. 'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
  10940. 'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
  10941. 'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
  10942. 'notify_time_text' => $notifyTimeText,
  10943. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  10944. 'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
  10945. 'has_issued' => $hasIssued ? 1 : 0,
  10946. 'has_quoted' => $hasQuoted ? 1 : 0,
  10947. 'can_notify_salesman' => $canNotifySalesman,
  10948. 'createtime' => $r['createtime'] ?? null,
  10949. 'createtime_text' => $createdText,
  10950. ];
  10951. }
  10952. return json(['total' => $total, 'rows' => $out]);
  10953. } catch (\Throwable $e) {
  10954. Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
  10955. return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
  10956. }
  10957. }
  10958. $sidebar = $this->loadRfqSidebarYearMonths();
  10959. $defaultYm = $this->resolveRfqListDefaultYm($sidebar);
  10960. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  10961. [, $adminName] = $this->GetUseName();
  10962. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  10963. $this->view->assign('adminNickname', $adminName);
  10964. $this->view->assign('defaultYm', $defaultYm);
  10965. $this->view->assign('sidebarYearMonths', $sidebar);
  10966. return $this->view->fetch('procuremen/rfqlist');
  10967. }
  10968. /**
  10969. * 列表默认月份:当月有数据用当月,否则取最近有数据的月份
  10970. *
  10971. * @param array<int, array{year:string, months:array}> $sidebar
  10972. */
  10973. protected function resolveRfqListDefaultYm(array $sidebar): string
  10974. {
  10975. $current = date('Y-m');
  10976. $yms = $this->flattenProcuremenSidebarYms($sidebar);
  10977. if (in_array($current, $yms, true)) {
  10978. return $current;
  10979. }
  10980. if ($yms !== []) {
  10981. rsort($yms, SORT_STRING);
  10982. return (string)$yms[0];
  10983. }
  10984. return $current;
  10985. }
  10986. /**
  10987. * 手工询价列表左侧月份(按 createtime / dStamp)
  10988. *
  10989. * @return array<int, array{year:string, months:array}>
  10990. */
  10991. protected function loadRfqSidebarYearMonths(): array
  10992. {
  10993. $ymSet = [];
  10994. try {
  10995. $q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
  10996. $this->applyPurchaseOrderNotDeletedWhere($q);
  10997. $rows = $q->field('createtime,dStamp')->limit(5000)->select();
  10998. } catch (\Throwable $e) {
  10999. $rows = [];
  11000. }
  11001. if (!is_array($rows)) {
  11002. $rows = [];
  11003. }
  11004. foreach ($rows as $r) {
  11005. if (!is_array($r)) {
  11006. continue;
  11007. }
  11008. $t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  11009. if ($t === '') {
  11010. $t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
  11011. }
  11012. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  11013. $ymSet[$m[1] . '-' . $m[2]] = true;
  11014. }
  11015. }
  11016. return $this->buildYearMonthSidebar(array_keys($ymSet));
  11017. }
  11018. /**
  11019. * 手工询价可见范围(用于详情/操作校验):
  11020. * 超管、具备「查询询价」权限、需求发起人、通知业务员 → 可见
  11021. * 列表页本身不再按发起人/通知过滤,避免手机端新增后后台看不到。
  11022. */
  11023. protected function applyManualRfqViewerWhere($query): void
  11024. {
  11025. if ($this->auth->isSuperAdmin() || $this->hasProcuremenPerm(['rfqlist'])) {
  11026. return;
  11027. }
  11028. [, $adminName] = $this->GetUseName();
  11029. $adminName = trim((string)$adminName);
  11030. if ($adminName === '') {
  11031. $query->whereRaw('1 = 0');
  11032. return;
  11033. }
  11034. // 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
  11035. $query->where(function ($q) use ($adminName) {
  11036. $q->where('cywyxm', $adminName)
  11037. ->whereOr('notify_salesman', $adminName)
  11038. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  11039. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  11040. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  11041. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  11042. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  11043. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  11044. });
  11045. }
  11046. /**
  11047. * 当前用户是否可查看/操作该手工询价单
  11048. */
  11049. protected function canViewManualRfqOrder(array $po): bool
  11050. {
  11051. if ($this->auth->isSuperAdmin()) {
  11052. return true;
  11053. }
  11054. // 有查询询价权限则可操作全部手工询价(询价/查看报价/通知业务员等)
  11055. if ($this->hasProcuremenPerm(['rfqlist'])) {
  11056. return true;
  11057. }
  11058. [, $adminName] = $this->GetUseName();
  11059. $adminName = trim((string)$adminName);
  11060. if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
  11061. return true;
  11062. }
  11063. if ($adminName !== '') {
  11064. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  11065. if ($n === $adminName) {
  11066. return true;
  11067. }
  11068. }
  11069. }
  11070. return false;
  11071. }
  11072. /**
  11073. * 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
  11074. */
  11075. protected function applyRfqListMonthFilter($query, string $ym): void
  11076. {
  11077. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  11078. $ym = date('Y-m');
  11079. }
  11080. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  11081. // 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
  11082. $query->whereRaw(
  11083. "("
  11084. . "CASE "
  11085. . "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  11086. . "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
  11087. . "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
  11088. . "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  11089. . "THEN TRIM(CAST(createtime AS CHAR(32))) "
  11090. . "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
  11091. . "END"
  11092. . ") LIKE '{$ymEsc}-%'"
  11093. );
  11094. }
  11095. /**
  11096. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  11097. */
  11098. public function rfqlistDetails()
  11099. {
  11100. return $this->details();
  11101. }
  11102. /**
  11103. * 查询询价 — 弹窗:可选通知业务员名单(勾选后确认通知)
  11104. */
  11105. public function rfqnotifysalesmen()
  11106. {
  11107. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman'])) {
  11108. $this->error(__('You have no permission'));
  11109. }
  11110. $this->ensurePurchaseOrderNotifySalesmanColumn();
  11111. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  11112. $sid = (int)$this->request->param('scydgy_id', 0);
  11113. if ($sid >= 0) {
  11114. $this->error('仅支持手工新增询价单');
  11115. }
  11116. $po = $this->loadManualRfqOrderForNotify($sid);
  11117. $selectedMap = [];
  11118. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  11119. $selectedMap[$n] = true;
  11120. }
  11121. $list = [];
  11122. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  11123. $name = trim((string)($row['name'] ?? ''));
  11124. if ($name === '') {
  11125. continue;
  11126. }
  11127. $email = trim((string)($row['email'] ?? ''));
  11128. $mobile = trim((string)($row['mobile'] ?? ''));
  11129. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  11130. $list[] = [
  11131. 'name' => $name,
  11132. 'email' => $email,
  11133. 'mobile' => $mobile,
  11134. 'can_select' => $hasEmail ? 1 : 0,
  11135. 'checked' => (!empty($selectedMap[$name]) && $hasEmail) ? 1 : 0,
  11136. ];
  11137. }
  11138. $canNotify = $this->canRfqNotifySalesman($po);
  11139. $this->success('', null, [
  11140. 'scydgy_id' => $sid,
  11141. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  11142. 'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
  11143. 'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
  11144. 'can_notify_salesman' => $canNotify ? 1 : 0,
  11145. 'list' => $list,
  11146. ]);
  11147. }
  11148. /**
  11149. * 查询询价 — 补加通知业务员可选名单
  11150. */
  11151. public function rfqsalesmanoptions()
  11152. {
  11153. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen'])) {
  11154. $this->error(__('You have no permission'));
  11155. }
  11156. $out = [];
  11157. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  11158. $email = trim((string)($row['email'] ?? ''));
  11159. $mobile = trim((string)($row['mobile'] ?? ''));
  11160. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  11161. $out[] = [
  11162. 'name' => (string)($row['name'] ?? ''),
  11163. 'email' => $email,
  11164. 'mobile' => $mobile,
  11165. 'can_select' => $hasEmail ? 1 : 0,
  11166. ];
  11167. }
  11168. $this->success('', null, ['list' => $out]);
  11169. }
  11170. /**
  11171. * 查询询价 — 补加通知业务员(合并更新 notify_salesman)
  11172. */
  11173. public function rfqappendsalesmen()
  11174. {
  11175. if (!$this->request->isPost()) {
  11176. $this->error(__('Invalid parameters'));
  11177. }
  11178. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen'])) {
  11179. $this->error(__('You have no permission'));
  11180. }
  11181. $this->ensurePurchaseOrderNotifySalesmanColumn();
  11182. $sid = (int)$this->request->post('scydgy_id', 0);
  11183. if ($sid >= 0) {
  11184. $this->error('仅支持手工新增询价单');
  11185. }
  11186. $po = $this->loadManualRfqOrderForNotify($sid);
  11187. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  11188. $this->error('订单已完结,无法添加业务员');
  11189. }
  11190. $raw = $this->request->post('salesmen/a', []);
  11191. if (!is_array($raw) || $raw === []) {
  11192. $salesmenJson = $this->request->post('salesmen_json', '');
  11193. if (is_string($salesmenJson) && $salesmenJson !== '') {
  11194. $decoded = json_decode($salesmenJson, true);
  11195. $raw = is_array($decoded) ? $decoded : [];
  11196. }
  11197. }
  11198. $addNames = [];
  11199. foreach ((array)$raw as $item) {
  11200. if (is_array($item)) {
  11201. $n = trim((string)($item['name'] ?? ''));
  11202. } else {
  11203. $n = trim((string)$item);
  11204. }
  11205. if ($n !== '') {
  11206. $addNames[] = $n;
  11207. }
  11208. }
  11209. $addNames = array_values(array_unique($addNames));
  11210. if ($addNames === []) {
  11211. $this->error('请选择要添加的业务员');
  11212. }
  11213. $allowedOptions = $this->loadRfqSalesmanContactOptions();
  11214. $allowedMap = [];
  11215. foreach ($allowedOptions as $opt) {
  11216. $n = trim((string)($opt['name'] ?? ''));
  11217. if ($n === '') {
  11218. continue;
  11219. }
  11220. $email = trim((string)($opt['email'] ?? ''));
  11221. $allowedMap[$n] = ($email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL));
  11222. }
  11223. foreach ($addNames as $n) {
  11224. if (!array_key_exists($n, $allowedMap)) {
  11225. $this->error('业务员不在可选名单中:' . $n);
  11226. }
  11227. if (!$allowedMap[$n]) {
  11228. $this->error('业务员未填写有效邮箱,无法添加:' . $n);
  11229. }
  11230. }
  11231. $existingRaw = trim((string)($po['notify_salesman'] ?? ''));
  11232. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  11233. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  11234. try {
  11235. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['notify_salesman' => $mergedStr]);
  11236. } catch (\Throwable $e) {
  11237. $this->error('保存失败:' . $e->getMessage());
  11238. }
  11239. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11240. $this->addOrderLog($sid, 'rfq_append_salesman', '添加通知业务员:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  11241. $this->success('已添加业务员', null, [
  11242. 'scydgy_id' => $sid,
  11243. 'notify_salesman' => $mergedStr,
  11244. 'added_count' => count($addNames),
  11245. ]);
  11246. }
  11247. /**
  11248. * 查询询价 — 勾选业务员后邮箱通知(salesmen_json)
  11249. */
  11250. public function rfqnotifysalesman()
  11251. {
  11252. if (!$this->request->isPost()) {
  11253. $this->error(__('Invalid parameters'));
  11254. }
  11255. if (!$this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen'])) {
  11256. $this->error(__('You have no permission'));
  11257. }
  11258. $this->ensurePurchaseOrderNotifySalesmanColumn();
  11259. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  11260. $sid = (int)$this->request->post('scydgy_id', 0);
  11261. if ($sid >= 0) {
  11262. $this->error('仅支持手工新增询价单');
  11263. }
  11264. $po = $this->loadManualRfqOrderForNotify($sid);
  11265. $this->assertRfqCanNotifySalesman($po);
  11266. $raw = $this->request->post('salesmen/a', []);
  11267. if (!is_array($raw) || $raw === []) {
  11268. $salesmenJson = $this->request->post('salesmen_json', '');
  11269. if (is_string($salesmenJson) && $salesmenJson !== '') {
  11270. $decoded = json_decode($salesmenJson, true);
  11271. $raw = is_array($decoded) ? $decoded : [];
  11272. }
  11273. }
  11274. // 兼容旧参数:notify_all / 单人 name
  11275. if ((!is_array($raw) || $raw === []) && (int)$this->request->post('notify_all', 0) === 1) {
  11276. $raw = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  11277. }
  11278. if ((!is_array($raw) || $raw === [])) {
  11279. $oneName = trim((string)$this->request->post('name', ''));
  11280. if ($oneName !== '') {
  11281. $raw = [$oneName];
  11282. }
  11283. }
  11284. $selectedNames = [];
  11285. foreach ((array)$raw as $item) {
  11286. if (is_array($item)) {
  11287. $n = trim((string)($item['name'] ?? ''));
  11288. } else {
  11289. $n = trim((string)$item);
  11290. }
  11291. if ($n !== '') {
  11292. $selectedNames[] = $n;
  11293. }
  11294. }
  11295. $selectedNames = array_values(array_unique($selectedNames));
  11296. if ($selectedNames === []) {
  11297. $this->error('请选择要通知的业务员');
  11298. }
  11299. $optionMap = [];
  11300. foreach ($this->loadRfqSalesmanContactOptions() as $opt) {
  11301. $n = trim((string)($opt['name'] ?? ''));
  11302. if ($n === '') {
  11303. continue;
  11304. }
  11305. $optionMap[$n] = $opt;
  11306. }
  11307. $targets = [];
  11308. foreach ($selectedNames as $n) {
  11309. if (!isset($optionMap[$n])) {
  11310. $this->error('业务员不在可选名单中:' . $n);
  11311. }
  11312. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  11313. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  11314. $this->error('业务员未填写有效邮箱,无法通知:' . $n);
  11315. }
  11316. $resolved = $this->resolveRfqSalesmanContactRows([$n]);
  11317. $targets[] = $resolved[0] ?? [
  11318. 'admin_id' => 0,
  11319. 'name' => $n,
  11320. 'email' => $email,
  11321. ];
  11322. }
  11323. $mergedStr = $this->joinRfqMultiSelectValues($selectedNames);
  11324. try {
  11325. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11326. 'notify_salesman' => $mergedStr,
  11327. ]);
  11328. } catch (\Throwable $e) {
  11329. $this->error('保存通知业务员失败:' . $e->getMessage());
  11330. }
  11331. $po['notify_salesman'] = $mergedStr;
  11332. $mailConfig = $this->loadMailerConfig();
  11333. if (empty($mailConfig['host'])) {
  11334. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  11335. }
  11336. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  11337. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  11338. }
  11339. $this->ensureRfqSalesmanEmailTemplate();
  11340. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  11341. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  11342. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  11343. $cdw = trim((string)($po['CDW'] ?? ''));
  11344. $qty = trim((string)$this->resolveProcuremenThisQuantity($po));
  11345. $ceiling = trim((string)$this->resolveProcuremenCeilingPrice($po));
  11346. $mbz = trim((string)($po['MBZ'] ?? ''));
  11347. $cywyxm = trim((string)($po['cywyxm'] ?? ''));
  11348. $supplier = trim((string)($po['cGzzxMc'] ?? ''));
  11349. if ($supplier === '') {
  11350. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  11351. }
  11352. $supplierQuotesHtml = $this->buildRfqSalesmanSupplierQuotesHtml($sid, $supplier);
  11353. try {
  11354. $platformUrl = $this->buildMprocMobileRfqAddUrl($sid, 'pending');
  11355. } catch (\Throwable $e) {
  11356. $platformUrl = '';
  11357. }
  11358. try {
  11359. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
  11360. } catch (\Throwable $e) {
  11361. $this->error($e->getMessage());
  11362. }
  11363. $okNames = [];
  11364. $failMsgs = [];
  11365. foreach ($targets as $contact) {
  11366. $toEmail = trim((string)($contact['email'] ?? ''));
  11367. $toName = trim((string)($contact['name'] ?? ''));
  11368. $notifyVars = [
  11369. 'contact_name' => $toName,
  11370. 'salesman_name' => $toName,
  11371. 'company_name' => $toName,
  11372. 'email' => $toEmail,
  11373. 'ccydh' => $ccydh,
  11374. 'cyjmc' => $cyjmc,
  11375. 'cgymc' => $cgymc,
  11376. 'cdw' => $cdw,
  11377. 'this_quantity' => $qty,
  11378. 'ceilingPrice' => $ceiling,
  11379. 'MBZ' => $mbz,
  11380. 'supplier_name' => $supplier,
  11381. // 占位符,转 HTML 后再替换成表格,避免被 htmlspecialchars 转义
  11382. 'supplier_quotes' => '__RFQ_SUPPLIER_QUOTES_TABLE__',
  11383. 'cywyxm' => $cywyxm,
  11384. 'platform_url' => $platformUrl,
  11385. ];
  11386. try {
  11387. $mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
  11388. $mailSubject = $mailSubjectTpl;
  11389. foreach ($notifyVars as $k => $v) {
  11390. if ($k === 'supplier_quotes') {
  11391. continue;
  11392. }
  11393. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  11394. }
  11395. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  11396. $mailSubject = trim((string)$mailSubject);
  11397. if ($mailSubject === '') {
  11398. $mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  11399. }
  11400. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  11401. $mailBody = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', $supplierQuotesHtml, $mailBody);
  11402. $mailPlainForLog = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', strip_tags(str_replace(['</tr>', '</p>'], "\n", $supplierQuotesHtml)), $mailPlain);
  11403. $bundle = [
  11404. 'company_name' => $toName,
  11405. 'email' => $toEmail,
  11406. 'mail_plain' => $mailPlainForLog,
  11407. 'mail_body' => $mailBody,
  11408. 'ccydh' => $ccydh,
  11409. 'email_log_scene' => 'rfq_salesman',
  11410. 'email_log_scydgy_id' => $sid,
  11411. 'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
  11412. 'email_log_ccydh' => $ccydh,
  11413. 'email_log_order_batch_no' => $this->resolveProcuremenOrderBatchNo(is_array($po) ? $po : []),
  11414. 'notify_vars' => $notifyVars,
  11415. ];
  11416. $this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
  11417. $okNames[] = $toName . '(' . $toEmail . ')';
  11418. } catch (\Throwable $e) {
  11419. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  11420. }
  11421. }
  11422. if ($okNames === []) {
  11423. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  11424. }
  11425. $now = date('Y-m-d H:i:s');
  11426. try {
  11427. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11428. 'rfq_salesman_notified' => 1,
  11429. 'rfq_salesman_notify_time' => $now,
  11430. ]);
  11431. } catch (\Throwable $e) {
  11432. // ignore
  11433. }
  11434. $this->addOrderLog(
  11435. $sid,
  11436. 'rfq_notify_salesman',
  11437. '邮箱通知业务员:' . implode('、', $okNames),
  11438. (int)($po['id'] ?? 0)
  11439. );
  11440. $msg = '已通知 ' . count($okNames) . ' 人';
  11441. if ($failMsgs !== []) {
  11442. $msg .= ';部分失败:' . implode(';', $failMsgs);
  11443. }
  11444. $this->success($msg, null, [
  11445. 'scydgy_id' => $sid,
  11446. 'notify_salesman' => $mergedStr,
  11447. 'rfq_salesman_notified' => 1,
  11448. 'rfq_salesman_notify_time' => $now,
  11449. 'notify_time_text' => $now,
  11450. 'ok_count' => count($okNames),
  11451. 'fail_count' => count($failMsgs),
  11452. ]);
  11453. }
  11454. /**
  11455. * 生产部角色组 id(mproc.mobile_delivery_group_id,缺省按组名「生产部/生产员」查找)
  11456. */
  11457. protected function deliveryNotifyAuthGroupId(): int
  11458. {
  11459. static $mprocCfgLoaded = false;
  11460. if (!$mprocCfgLoaded) {
  11461. $mprocCfgLoaded = true;
  11462. if (is_file(APP_PATH . 'extra/mproc.php')) {
  11463. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  11464. }
  11465. }
  11466. $id = (int)Config::get('mproc.mobile_delivery_group_id');
  11467. if ($id > 0) {
  11468. return $id;
  11469. }
  11470. try {
  11471. foreach (['生产部', '生产员'] as $name) {
  11472. $gid = (int)Db::name('auth_group')->where('name', $name)->value('id');
  11473. if ($gid > 0) {
  11474. return $gid;
  11475. }
  11476. }
  11477. } catch (\Throwable $e) {
  11478. }
  11479. return 0;
  11480. }
  11481. /**
  11482. * 生产部人员:姓名、邮箱、手机
  11483. *
  11484. * @return array<int, array{name:string,email:string,mobile:string,admin_id:int}>
  11485. */
  11486. protected function loadDeliveryStaffContactOptions(): array
  11487. {
  11488. $out = [];
  11489. $seen = [];
  11490. $groupId = $this->deliveryNotifyAuthGroupId();
  11491. if ($groupId <= 0) {
  11492. return [];
  11493. }
  11494. try {
  11495. $adminIds = Db::name('auth_group_access')
  11496. ->where('group_id', $groupId)
  11497. ->column('uid');
  11498. } catch (\Throwable $e) {
  11499. return [];
  11500. }
  11501. $adminIds = is_array($adminIds)
  11502. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  11503. : [];
  11504. if ($adminIds === []) {
  11505. return [];
  11506. }
  11507. try {
  11508. $rows = Db::name('admin')
  11509. ->where('status', 'normal')
  11510. ->where('id', 'in', $adminIds)
  11511. ->order('id', 'asc')
  11512. ->field('id,nickname,username,email,mobile')
  11513. ->select();
  11514. } catch (\Throwable $e) {
  11515. return [];
  11516. }
  11517. if (!is_array($rows)) {
  11518. return [];
  11519. }
  11520. foreach ($rows as $row) {
  11521. if (!is_array($row)) {
  11522. continue;
  11523. }
  11524. $name = trim((string)($row['nickname'] ?? ''));
  11525. if ($name === '') {
  11526. $name = trim((string)($row['username'] ?? ''));
  11527. }
  11528. if ($name === '' || isset($seen[$name])) {
  11529. continue;
  11530. }
  11531. $seen[$name] = true;
  11532. $out[] = [
  11533. 'admin_id' => (int)($row['id'] ?? 0),
  11534. 'name' => $name,
  11535. 'email' => trim((string)($row['email'] ?? '')),
  11536. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  11537. ];
  11538. }
  11539. return $out;
  11540. }
  11541. /**
  11542. * 交货情况页直达链接(邮件用,单参数避免邮箱客户端拆坏)
  11543. */
  11544. protected function buildMprocMobileDeliveryscoreUrl(string $ccydh): string
  11545. {
  11546. static $mprocCfgLoaded = false;
  11547. if (!$mprocCfgLoaded) {
  11548. $mprocCfgLoaded = true;
  11549. if (is_file(APP_PATH . 'extra/mproc.php')) {
  11550. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  11551. }
  11552. }
  11553. $base = $this->resolveMprocMobilePublicBaseUrl();
  11554. if ($base === '') {
  11555. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  11556. }
  11557. $path = '/index.php/index/index/deliveryscore';
  11558. $ccydh = trim($ccydh);
  11559. if ($ccydh === '') {
  11560. return $base . $path;
  11561. }
  11562. return $base . $path . '?ccydh=' . rawurlencode($ccydh);
  11563. }
  11564. /**
  11565. * 按订单号取已审核外发单(合并工序字段)
  11566. *
  11567. * @return array<string, mixed>|null
  11568. */
  11569. protected function loadApprovedOrderForDeliveryNotify(string $ccydh, int $sid = 0): ?array
  11570. {
  11571. $ccydh = trim($ccydh);
  11572. if ($ccydh === '' && $sid > 0) {
  11573. try {
  11574. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
  11575. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  11576. } catch (\Throwable $e) {
  11577. $ccydh = '';
  11578. }
  11579. }
  11580. if ($ccydh === '') {
  11581. return null;
  11582. }
  11583. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  11584. $approvedIn = implode(',', array_map(static function ($v) {
  11585. return "'" . str_replace("'", "''", (string)$v) . "'";
  11586. }, $approvedVals));
  11587. try {
  11588. $rows = Db::table('purchase_order')
  11589. ->where('CCYDH', $ccydh)
  11590. ->where('scydgy_id', '>', 0)
  11591. ->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%\')')
  11592. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  11593. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  11594. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,CDW,This_quantity,NGZL,pick_company_name,delivery_deadline,MBZ,cywyxm,wflow_status,status')
  11595. ->order('id', 'asc')
  11596. ->select();
  11597. } catch (\Throwable $e) {
  11598. $rows = [];
  11599. }
  11600. if (!is_array($rows) || $rows === []) {
  11601. return null;
  11602. }
  11603. $gymc = [];
  11604. $qty = [];
  11605. $first = null;
  11606. foreach ($rows as $r) {
  11607. if (!is_array($r)) {
  11608. continue;
  11609. }
  11610. if ($first === null) {
  11611. $first = $r;
  11612. }
  11613. $g = trim((string)($r['CGYMC'] ?? ''));
  11614. if ($g !== '' && !in_array($g, $gymc, true)) {
  11615. $gymc[] = $g;
  11616. }
  11617. $q = trim((string)$this->resolveProcuremenThisQuantity($r));
  11618. if ($q !== '' && !in_array($q, $qty, true)) {
  11619. $qty[] = $q;
  11620. }
  11621. }
  11622. if (!is_array($first)) {
  11623. return null;
  11624. }
  11625. $first['CGYMC'] = $gymc !== [] ? implode('、', $gymc) : '';
  11626. $first['This_quantity'] = $qty !== [] ? implode('、', $qty) : '';
  11627. $first['delivery_deadline'] = $this->mprocFormatYmdForNotify($first['delivery_deadline'] ?? '');
  11628. return $first;
  11629. }
  11630. protected function mprocFormatYmdForNotify($raw): string
  11631. {
  11632. return ProcuremenFormat::mprocYmdForNotify($raw);
  11633. }
  11634. /**
  11635. * 确保「交货情况通知生产部-邮箱」模版存在
  11636. */
  11637. protected function ensureDeliveryNotifyEmailTemplate(): void
  11638. {
  11639. static $done = false;
  11640. if ($done) {
  11641. return;
  11642. }
  11643. $done = true;
  11644. $content = "您好,{contact_name}:\n\n"
  11645. . "有订单已中标外发,需要您在手机端确认交货情况(填写库位、交货情况、交货日期等)。\n\n"
  11646. . "订单号:{ccydh}\n"
  11647. . "印件名称:{cyjmc}\n"
  11648. . "工序名称:{cgymc}\n"
  11649. . "订单数量:{this_quantity}\n"
  11650. . "中标供应商:{supplier_name}\n"
  11651. . "交货截止日期:{delivery_deadline}\n\n"
  11652. . "请点击下方链接登录后,找到该订单进行填写:\n"
  11653. . "{platform_url}\n";
  11654. try {
  11655. $row = Db::table('purchase_sms_template')
  11656. ->where('scene', 'delivery_notify_email')
  11657. ->find();
  11658. } catch (\Throwable $e) {
  11659. return;
  11660. }
  11661. $now = date('Y-m-d H:i:s');
  11662. if (is_array($row) && $row !== []) {
  11663. return;
  11664. }
  11665. try {
  11666. $data = [
  11667. 'scene' => 'delivery_notify_email',
  11668. 'title' => '交货情况确认通知 - {ccydh}',
  11669. 'content' => $content,
  11670. 'remark' => '审批通过后通知生产部填写交货情况;模版名称作邮件主题,支持变量',
  11671. 'status' => 1,
  11672. ];
  11673. try {
  11674. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  11675. } catch (\Throwable $e) {
  11676. $cols = [];
  11677. }
  11678. $colNames = [];
  11679. foreach ($cols as $c) {
  11680. if (!is_array($c)) {
  11681. continue;
  11682. }
  11683. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  11684. if ($n !== '') {
  11685. $colNames[$n] = true;
  11686. }
  11687. }
  11688. if (isset($colNames['updatetime'])) {
  11689. $data['updatetime'] = $now;
  11690. }
  11691. if (isset($colNames['createtime'])) {
  11692. $data['createtime'] = $now;
  11693. }
  11694. Db::table('purchase_sms_template')->insert($data);
  11695. } catch (\Throwable $e) {
  11696. // ignore
  11697. }
  11698. }
  11699. /**
  11700. * 通知生产部 — 可选人员名单
  11701. */
  11702. public function deliverynotifymen()
  11703. {
  11704. if (!$this->hasProcuremenPerm(['deliverynotifymen', 'deliverynotify', 'outward_detail', 'outwarddetail', 'purchaseconfirmpick', 'details'])) {
  11705. $this->error(__('You have no permission'));
  11706. }
  11707. $this->ensureDeliveryNotifyEmailTemplate();
  11708. $sid = (int)$this->request->request('scydgy_id', 0);
  11709. $ccydh = trim((string)$this->request->request('ccydh', ''));
  11710. $po = $this->loadApprovedOrderForDeliveryNotify($ccydh, $sid);
  11711. if ($po === null) {
  11712. $this->error('未找到已审核且已中标的订单,无法通知生产部');
  11713. }
  11714. $list = [];
  11715. foreach ($this->loadDeliveryStaffContactOptions() as $opt) {
  11716. $email = trim((string)($opt['email'] ?? ''));
  11717. $list[] = [
  11718. 'name' => (string)($opt['name'] ?? ''),
  11719. 'email' => $email,
  11720. 'mobile' => (string)($opt['mobile'] ?? ''),
  11721. 'can_select' => ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) ? 1 : 0,
  11722. 'checked' => 0,
  11723. ];
  11724. }
  11725. $this->success('', null, [
  11726. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  11727. 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
  11728. 'cgymc' => trim((string)($po['CGYMC'] ?? '')),
  11729. 'this_quantity' => trim((string)($po['This_quantity'] ?? '')),
  11730. 'supplier_name' => trim((string)($po['pick_company_name'] ?? '')),
  11731. 'delivery_deadline' => trim((string)($po['delivery_deadline'] ?? '')),
  11732. 'list' => $list,
  11733. ]);
  11734. }
  11735. /**
  11736. * 通知生产部 — 勾选后发邮件(staff_json / names)
  11737. */
  11738. public function deliverynotify()
  11739. {
  11740. if (!$this->request->isPost()) {
  11741. $this->error(__('Invalid parameters'));
  11742. }
  11743. if (!$this->hasProcuremenPerm(['deliverynotify', 'deliverynotifymen', 'outward_detail', 'outwarddetail', 'purchaseconfirmpick', 'details'])) {
  11744. $this->error(__('You have no permission'));
  11745. }
  11746. $this->ensureDeliveryNotifyEmailTemplate();
  11747. $sid = (int)$this->request->post('scydgy_id', 0);
  11748. $ccydh = trim((string)$this->request->post('ccydh', ''));
  11749. $po = $this->loadApprovedOrderForDeliveryNotify($ccydh, $sid);
  11750. if ($po === null) {
  11751. $this->error('未找到已审核且已中标的订单,无法通知生产部');
  11752. }
  11753. $ccydh = trim((string)($po['CCYDH'] ?? $ccydh));
  11754. $raw = $this->request->post('staff/a', []);
  11755. if (!is_array($raw) || $raw === []) {
  11756. $staffJson = $this->request->post('staff_json', '');
  11757. if (is_string($staffJson) && $staffJson !== '') {
  11758. $decoded = json_decode($staffJson, true);
  11759. $raw = is_array($decoded) ? $decoded : [];
  11760. }
  11761. }
  11762. $selectedNames = [];
  11763. foreach ((array)$raw as $item) {
  11764. if (is_array($item)) {
  11765. $n = trim((string)($item['name'] ?? ''));
  11766. } else {
  11767. $n = trim((string)$item);
  11768. }
  11769. if ($n !== '') {
  11770. $selectedNames[] = $n;
  11771. }
  11772. }
  11773. $selectedNames = array_values(array_unique($selectedNames));
  11774. if ($selectedNames === []) {
  11775. $this->error('请选择要通知的生产部人员');
  11776. }
  11777. $optionMap = [];
  11778. foreach ($this->loadDeliveryStaffContactOptions() as $opt) {
  11779. $n = trim((string)($opt['name'] ?? ''));
  11780. if ($n === '') {
  11781. continue;
  11782. }
  11783. $optionMap[$n] = $opt;
  11784. }
  11785. $targets = [];
  11786. foreach ($selectedNames as $n) {
  11787. if (!isset($optionMap[$n])) {
  11788. $this->error('人员不在生产部可选名单中:' . $n);
  11789. }
  11790. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  11791. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  11792. $this->error('未填写有效邮箱,无法通知:' . $n);
  11793. }
  11794. $targets[] = $optionMap[$n];
  11795. }
  11796. $mailConfig = $this->loadMailerConfig();
  11797. if (empty($mailConfig['host'])) {
  11798. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  11799. }
  11800. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  11801. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  11802. }
  11803. try {
  11804. $platformUrl = $this->buildMprocMobileDeliveryscoreUrl($ccydh);
  11805. } catch (\Throwable $e) {
  11806. $this->error($e->getMessage());
  11807. }
  11808. try {
  11809. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('delivery_notify_email');
  11810. } catch (\Throwable $e) {
  11811. $this->error($e->getMessage());
  11812. }
  11813. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  11814. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  11815. $qty = trim((string)($po['This_quantity'] ?? ''));
  11816. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  11817. $deadline = trim((string)($po['delivery_deadline'] ?? ''));
  11818. $firstSid = (int)($po['scydgy_id'] ?? 0);
  11819. $firstPoId = (int)($po['id'] ?? 0);
  11820. $okNames = [];
  11821. $failMsgs = [];
  11822. foreach ($targets as $contact) {
  11823. $toEmail = trim((string)($contact['email'] ?? ''));
  11824. $toName = trim((string)($contact['name'] ?? ''));
  11825. $notifyVars = [
  11826. 'contact_name' => $toName,
  11827. 'company_name' => $toName,
  11828. 'email' => $toEmail,
  11829. 'ccydh' => $ccydh,
  11830. 'cyjmc' => $cyjmc,
  11831. 'cgymc' => $cgymc,
  11832. 'this_quantity' => $qty,
  11833. 'supplier_name' => $supplier,
  11834. 'delivery_deadline' => $deadline,
  11835. 'platform_url' => $platformUrl,
  11836. ];
  11837. try {
  11838. $mailPlain = $this->renderNotifyTemplate('delivery_notify_email', $notifyVars);
  11839. $mailSubject = $mailSubjectTpl;
  11840. foreach ($notifyVars as $k => $v) {
  11841. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  11842. }
  11843. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  11844. $mailSubject = trim((string)$mailSubject);
  11845. if ($mailSubject === '') {
  11846. $mailSubject = '交货情况确认通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  11847. }
  11848. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  11849. $this->issueSendSupplierEmail([
  11850. 'company_name' => $toName,
  11851. 'email' => $toEmail,
  11852. 'mail_plain' => $mailPlain,
  11853. 'mail_body' => $mailBody,
  11854. 'ccydh' => $ccydh,
  11855. 'email_log_scene' => 'delivery_notify',
  11856. 'email_log_scydgy_id' => $firstSid,
  11857. 'email_log_purchase_order_id' => $firstPoId,
  11858. 'email_log_ccydh' => $ccydh,
  11859. 'email_log_order_batch_no' => $this->resolveProcuremenOrderBatchNo(is_array($po) ? $po : []),
  11860. 'notify_vars' => $notifyVars,
  11861. ], $mailConfig, $mailSubject);
  11862. $okNames[] = $toName . '(' . $toEmail . ')';
  11863. } catch (\Throwable $e) {
  11864. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  11865. }
  11866. }
  11867. if ($okNames === []) {
  11868. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  11869. }
  11870. if ($firstSid > 0) {
  11871. $this->addOrderLog(
  11872. $firstSid,
  11873. 'delivery_notify',
  11874. '邮箱通知生产部:' . implode('、', $okNames),
  11875. $firstPoId > 0 ? $firstPoId : null
  11876. );
  11877. }
  11878. $msg = '已通知 ' . count($okNames) . ' 人';
  11879. if ($failMsgs !== []) {
  11880. $msg .= ';部分失败:' . implode(';', $failMsgs);
  11881. }
  11882. $this->success($msg, null, [
  11883. 'ccydh' => $ccydh,
  11884. 'ok_count' => count($okNames),
  11885. 'fail_count'=> count($failMsgs),
  11886. 'platform_url' => $platformUrl,
  11887. ]);
  11888. }
  11889. /**
  11890. * 查询询价 — 下发前:返回将通知的供应商表格数据
  11891. */
  11892. public function rfqissuesuppliers()
  11893. {
  11894. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers'])) {
  11895. $this->error(__('You have no permission'));
  11896. }
  11897. $sid = (int)$this->request->param('scydgy_id', 0);
  11898. if ($sid >= 0) {
  11899. $this->error('仅支持手工新增询价单');
  11900. }
  11901. $po = $this->loadManualRfqOrderForNotify($sid);
  11902. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  11903. if ($supplierRaw === '') {
  11904. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  11905. }
  11906. $names = $this->splitRfqSalesmanNames($supplierRaw);
  11907. // 已成功发过询价邮件的供应商(含历史 pick_issue 场景)
  11908. $notifiedMap = [];
  11909. try {
  11910. $this->ensurePurchaseEmailSendLogTableOnce();
  11911. $logRows = Db::table('purchase_email_send_log')
  11912. ->where('scydgy_id', $sid)
  11913. ->where('status', 1)
  11914. ->where('scene', 'in', [
  11915. 'rfq_supplier', 'pick_issue',
  11916. '供应商询价通知', '初选下发',
  11917. ])
  11918. ->field('company_name')
  11919. ->select();
  11920. if (is_array($logRows)) {
  11921. foreach ($logRows as $lr) {
  11922. if (!is_array($lr)) {
  11923. continue;
  11924. }
  11925. $cn = trim((string)($lr['company_name'] ?? ''));
  11926. if ($cn !== '') {
  11927. $notifiedMap[$cn] = true;
  11928. }
  11929. }
  11930. }
  11931. } catch (\Throwable $e) {
  11932. }
  11933. // 兼容:明细已生成(曾下发)也视为已通知
  11934. try {
  11935. $detRows = Db::table('purchase_order_detail')
  11936. ->where('scydgy_id', $sid)
  11937. ->field('company_name')
  11938. ->select();
  11939. if (is_array($detRows)) {
  11940. foreach ($detRows as $dr) {
  11941. if (!is_array($dr)) {
  11942. continue;
  11943. }
  11944. $cn = trim((string)($dr['company_name'] ?? ''));
  11945. if ($cn !== '') {
  11946. $notifiedMap[$cn] = true;
  11947. }
  11948. }
  11949. }
  11950. } catch (\Throwable $e) {
  11951. }
  11952. $list = [];
  11953. foreach ($names as $name) {
  11954. // 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
  11955. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  11956. $email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
  11957. $phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
  11958. $username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
  11959. $okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
  11960. $notified = !empty($notifiedMap[$name]) ? 1 : 0;
  11961. $list[] = [
  11962. 'name' => $name,
  11963. 'username' => $username,
  11964. 'email' => $email,
  11965. 'phone' => $phone,
  11966. 'can_notify' => $okEmail ? 1 : 0,
  11967. 'found' => is_array($contact) ? 1 : 0,
  11968. 'notified' => $notified,
  11969. 'notify_status_text' => $notified ? '已通知' : '未通知',
  11970. ];
  11971. }
  11972. $this->success('', null, [
  11973. 'scydgy_id' => $sid,
  11974. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  11975. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  11976. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  11977. 'CDW' => trim((string)($po['CDW'] ?? '')),
  11978. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  11979. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  11980. 'CDF' => trim((string)($po['CDF'] ?? '')),
  11981. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  11982. 'list' => $list,
  11983. ]);
  11984. }
  11985. /**
  11986. * 查询询价 — 补加供应商可选名单
  11987. */
  11988. public function rfqsupplieroptions()
  11989. {
  11990. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
  11991. $this->error(__('You have no permission'));
  11992. }
  11993. $names = array_values($this->loadRfqSupplierNameOptions());
  11994. $out = [];
  11995. foreach ($names as $name) {
  11996. $out[] = ['name' => $name];
  11997. }
  11998. $this->success('', null, ['list' => $out]);
  11999. }
  12000. /**
  12001. * 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
  12002. */
  12003. public function rfqappendsuppliers()
  12004. {
  12005. if (!$this->request->isPost()) {
  12006. $this->error(__('Invalid parameters'));
  12007. }
  12008. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers'])) {
  12009. $this->error(__('You have no permission'));
  12010. }
  12011. $sid = (int)$this->request->post('scydgy_id', 0);
  12012. if ($sid >= 0) {
  12013. $this->error('仅支持手工新增询价单');
  12014. }
  12015. $po = $this->loadManualRfqOrderForNotify($sid);
  12016. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  12017. $this->error('订单已完结,无法补加供应商');
  12018. }
  12019. $raw = $this->request->post('suppliers/a', []);
  12020. if (!is_array($raw) || $raw === []) {
  12021. $suppliersJson = $this->request->post('suppliers_json', '');
  12022. if (is_string($suppliersJson) && $suppliersJson !== '') {
  12023. $decoded = json_decode($suppliersJson, true);
  12024. $raw = is_array($decoded) ? $decoded : [];
  12025. }
  12026. }
  12027. $addNames = [];
  12028. foreach ((array)$raw as $item) {
  12029. if (is_array($item)) {
  12030. $n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
  12031. } else {
  12032. $n = trim((string)$item);
  12033. }
  12034. if ($n !== '') {
  12035. $addNames[] = $n;
  12036. }
  12037. }
  12038. $addNames = array_values(array_unique($addNames));
  12039. if ($addNames === []) {
  12040. $this->error('请选择要补加的供应商');
  12041. }
  12042. $existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
  12043. if ($existingRaw === '') {
  12044. $existingRaw = trim((string)($po['pick_company_name'] ?? ''));
  12045. }
  12046. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  12047. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  12048. try {
  12049. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
  12050. } catch (\Throwable $e) {
  12051. $this->error('保存失败:' . $e->getMessage());
  12052. }
  12053. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  12054. $this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  12055. $this->success('已补加供应商', null, [
  12056. 'scydgy_id' => $sid,
  12057. 'cGzzxMc' => $mergedStr,
  12058. 'added_count' => count($addNames),
  12059. ]);
  12060. }
  12061. /**
  12062. * 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
  12063. */
  12064. public function rfqissue()
  12065. {
  12066. if (!$this->request->isPost()) {
  12067. $this->error(__('Invalid parameters'));
  12068. }
  12069. if (!$this->hasProcuremenPerm(['rfqissue'])) {
  12070. $this->error(__('You have no permission'));
  12071. }
  12072. $this->ensureRfqSupplierEmailTemplate();
  12073. $sid = (int)$this->request->post('scydgy_id', 0);
  12074. if ($sid >= 0) {
  12075. $this->error('仅支持手工新增询价单');
  12076. }
  12077. $po = $this->loadManualRfqOrderForNotify($sid);
  12078. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  12079. $this->error('订单已完结,无法下发');
  12080. }
  12081. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  12082. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  12083. $this->error('订单已进入后续流程,无法再下发');
  12084. }
  12085. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  12086. if ($supplierRaw === '') {
  12087. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  12088. }
  12089. $supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
  12090. if ($supplierNames === []) {
  12091. $this->error('请先在新增询价时选择供应商');
  12092. }
  12093. $companies = [];
  12094. $missing = [];
  12095. $noEmail = [];
  12096. foreach ($supplierNames as $name) {
  12097. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  12098. if ($contact === null) {
  12099. $missing[] = $name;
  12100. continue;
  12101. }
  12102. $em = trim((string)($contact['email'] ?? ''));
  12103. if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
  12104. $noEmail[] = $name;
  12105. continue;
  12106. }
  12107. $companies[] = $contact;
  12108. }
  12109. if ($missing !== []) {
  12110. $this->error('未找到供应商档案:' . implode('、', $missing));
  12111. }
  12112. if ($noEmail !== []) {
  12113. $this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
  12114. }
  12115. if ($companies === []) {
  12116. $this->error('没有可通知的供应商');
  12117. }
  12118. $mailConfig = $this->loadMailerConfig();
  12119. if (empty($mailConfig['host'])) {
  12120. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  12121. }
  12122. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  12123. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  12124. }
  12125. $mergeRow = $po;
  12126. $mergeRow['ID'] = $sid;
  12127. $mergeRow['id'] = $sid;
  12128. $mergeRows = [$mergeRow];
  12129. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  12130. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  12131. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  12132. }
  12133. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  12134. $issueTime = date('Y-m-d H:i:s');
  12135. $nameLabels = [];
  12136. foreach ($companies as $c) {
  12137. $nameLabels[] = trim((string)($c['name'] ?? ''));
  12138. }
  12139. $logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
  12140. Db::startTrans();
  12141. try {
  12142. $this->upsertPurchaseOrderFromRow(
  12143. $mergeRow,
  12144. $sysRqDb,
  12145. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  12146. $issueTime,
  12147. $po,
  12148. null,
  12149. $scoreRule
  12150. );
  12151. foreach ($companies as $c) {
  12152. $this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
  12153. }
  12154. Db::commit();
  12155. } catch (\Throwable $e) {
  12156. Db::rollback();
  12157. $this->error($e->getMessage());
  12158. }
  12159. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  12160. if ($poId <= 0) {
  12161. try {
  12162. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  12163. } catch (\Throwable $e) {
  12164. $poId = 0;
  12165. }
  12166. }
  12167. $this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
  12168. $posNotify = [];
  12169. try {
  12170. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  12171. if (is_array($fresh)) {
  12172. $fresh['sys_rq'] = $sysRqDb;
  12173. $posNotify = [$fresh];
  12174. }
  12175. } catch (\Throwable $e) {
  12176. $posNotify = [$po];
  12177. $posNotify[0]['sys_rq'] = $sysRqDb;
  12178. }
  12179. $notifyBundle = [
  12180. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  12181. 'pos' => $posNotify,
  12182. 'merge_rows' => $mergeRows,
  12183. ];
  12184. $notifyErrors = [];
  12185. foreach ($companies as $c) {
  12186. $cname = trim((string)($c['name'] ?? ''));
  12187. try {
  12188. // 询价下发:仅邮箱通知供应商
  12189. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  12190. } catch (\Throwable $e) {
  12191. $notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
  12192. }
  12193. }
  12194. if ($notifyErrors !== []) {
  12195. Log::write('procuremen rfq issue notify fail sid=' . $sid . ': ' . implode(';', $notifyErrors), 'error');
  12196. $this->success('询价下发成功。部分供应商邮件未送达,可稍后重发。', null, [
  12197. 'scydgy_id' => $sid,
  12198. 'progress_text' => '待报价',
  12199. 'supplier_count' => count($companies),
  12200. 'notify_failed' => 1,
  12201. 'notify_fail_detail' => $notifyErrors,
  12202. ]);
  12203. }
  12204. $this->success('已询价并邮件通知供应商', null, [
  12205. 'scydgy_id' => $sid,
  12206. 'progress_text' => '待报价',
  12207. 'supplier_count' => count($companies),
  12208. 'notify_failed' => 0,
  12209. ]);
  12210. }
  12211. /**
  12212. * 查询询价 — 弹窗内向单个供应商发送询价邮件
  12213. */
  12214. public function rfqissuesendmail()
  12215. {
  12216. if (!$this->request->isPost()) {
  12217. $this->error(__('Invalid parameters'));
  12218. }
  12219. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail'])) {
  12220. $this->error(__('You have no permission'));
  12221. }
  12222. $this->ensureRfqSupplierEmailTemplate();
  12223. $sid = (int)$this->request->post('scydgy_id', 0);
  12224. $companyName = trim((string)$this->request->post('company_name', ''));
  12225. if ($sid >= 0) {
  12226. $this->error('仅支持手工新增询价单');
  12227. }
  12228. if ($companyName === '') {
  12229. $this->error('请选择供应商');
  12230. }
  12231. $po = $this->loadManualRfqOrderForNotify($sid);
  12232. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  12233. $this->error('订单已完结,无法发送');
  12234. }
  12235. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  12236. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  12237. $this->error('订单已进入后续流程,无法再发送');
  12238. }
  12239. $contact = $this->resolveCustomerContactByCompanyName($companyName, false);
  12240. if ($contact === null) {
  12241. $this->error('未找到供应商档案:' . $companyName);
  12242. }
  12243. $email = trim((string)($contact['email'] ?? ''));
  12244. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  12245. $this->error('该供应商未填写有效邮箱');
  12246. }
  12247. $mailConfig = $this->loadMailerConfig();
  12248. if (empty($mailConfig['host'])) {
  12249. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  12250. }
  12251. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  12252. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  12253. }
  12254. $mergeRow = $po;
  12255. $mergeRow['ID'] = $sid;
  12256. $mergeRow['id'] = $sid;
  12257. $mergeRows = [$mergeRow];
  12258. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  12259. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  12260. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  12261. }
  12262. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  12263. $issueTime = date('Y-m-d H:i:s');
  12264. Db::startTrans();
  12265. try {
  12266. $this->upsertPurchaseOrderFromRow(
  12267. $mergeRow,
  12268. $sysRqDb,
  12269. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  12270. $issueTime,
  12271. $po,
  12272. null,
  12273. $scoreRule
  12274. );
  12275. $this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
  12276. Db::commit();
  12277. } catch (\Throwable $e) {
  12278. Db::rollback();
  12279. $this->error($e->getMessage());
  12280. }
  12281. $posNotify = [];
  12282. try {
  12283. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  12284. if (is_array($fresh)) {
  12285. $fresh['sys_rq'] = $sysRqDb;
  12286. $posNotify = [$fresh];
  12287. }
  12288. } catch (\Throwable $e) {
  12289. $posNotify = [$po];
  12290. $posNotify[0]['sys_rq'] = $sysRqDb;
  12291. }
  12292. $notifyBundle = [
  12293. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  12294. 'pos' => $posNotify,
  12295. 'merge_rows' => $mergeRows,
  12296. ];
  12297. $mailFail = '';
  12298. try {
  12299. $this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  12300. } catch (\Throwable $e) {
  12301. $mailFail = $e->getMessage();
  12302. Log::write('procuremen rfqissuesendmail fail sid=' . $sid . ' company=' . $companyName . ': ' . $mailFail, 'error');
  12303. }
  12304. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  12305. if ($poId <= 0) {
  12306. try {
  12307. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  12308. } catch (\Throwable $e) {
  12309. $poId = 0;
  12310. }
  12311. }
  12312. $this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
  12313. if ($mailFail !== '') {
  12314. $this->success('询价已保存。邮件未送达「' . $companyName . '」:' . $mailFail . '。可稍后重发。', null, [
  12315. 'scydgy_id' => $sid,
  12316. 'notify_failed' => 1,
  12317. ]);
  12318. }
  12319. $this->success('已向「' . $companyName . '」发送询价邮件', null, [
  12320. 'scydgy_id' => $sid,
  12321. 'company_name' => $companyName,
  12322. ]);
  12323. }
  12324. /**
  12325. * 查询询价 — 查看各供应商报价(单价)
  12326. */
  12327. public function rfqquotes()
  12328. {
  12329. if (!$this->hasProcuremenPerm(['rfqquotes', 'rfqissue'])) {
  12330. $this->error(__('You have no permission'));
  12331. }
  12332. $sid = (int)$this->request->param('scydgy_id', 0);
  12333. if ($sid >= 0) {
  12334. $this->error('仅支持手工新增询价单');
  12335. }
  12336. $po = $this->loadManualRfqOrderForNotify($sid);
  12337. $rows = [];
  12338. try {
  12339. // 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
  12340. $q = Db::table('purchase_order_detail')
  12341. ->where('scydgy_id', $sid)
  12342. ->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
  12343. ->order('id', 'asc');
  12344. $this->applyActivePurchaseOrderDetailWhere($q);
  12345. $rows = $q->select();
  12346. } catch (\Throwable $e) {
  12347. try {
  12348. $q = Db::table('purchase_order_detail')
  12349. ->where('scydgy_id', $sid)
  12350. ->order('id', 'asc');
  12351. $this->applyActivePurchaseOrderDetailWhere($q);
  12352. $rows = $q->select();
  12353. } catch (\Throwable $e2) {
  12354. $rows = [];
  12355. }
  12356. }
  12357. if (!is_array($rows)) {
  12358. $rows = [];
  12359. }
  12360. $list = [];
  12361. foreach ($rows as $row) {
  12362. if (!is_array($row)) {
  12363. continue;
  12364. }
  12365. $amount = trim((string)($row['amount'] ?? ''));
  12366. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  12367. // 未报价不显示时间(createtime 是下发时间,不是报价时间)
  12368. $oper = '';
  12369. if ($isQuoted) {
  12370. $oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
  12371. if ($oper === '') {
  12372. $oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  12373. }
  12374. }
  12375. $list[] = [
  12376. 'id' => (int)($row['id'] ?? 0),
  12377. 'company_name' => trim((string)($row['company_name'] ?? '')),
  12378. 'amount' => $amount,
  12379. 'amount_text' => $isQuoted ? $amount : '',
  12380. 'is_quoted' => $isQuoted,
  12381. 'quote_label' => $isQuoted ? '已报价' : '未报价',
  12382. 'status_name' => trim((string)($row['status_name'] ?? '')),
  12383. 'oper_time' => $oper,
  12384. ];
  12385. }
  12386. $this->success('', null, [
  12387. 'scydgy_id' => $sid,
  12388. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  12389. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  12390. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  12391. 'CDW' => trim((string)($po['CDW'] ?? '')),
  12392. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  12393. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  12394. 'CDF' => trim((string)($po['CDF'] ?? '')),
  12395. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  12396. 'list' => $list,
  12397. ]);
  12398. }
  12399. /**
  12400. * 手工询价是否已下发(有下发明细或已进入待确认及之后)
  12401. */
  12402. protected function isRfqOrderIssued(array $po): bool
  12403. {
  12404. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  12405. return true;
  12406. }
  12407. $sid = (int)($po['scydgy_id'] ?? 0);
  12408. if ($sid >= 0) {
  12409. return false;
  12410. }
  12411. try {
  12412. $q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  12413. $this->applyActivePurchaseOrderDetailWhere($q);
  12414. return (int)$q->count() > 0;
  12415. } catch (\Throwable $e) {
  12416. return false;
  12417. }
  12418. }
  12419. /**
  12420. * 批量:已有下发明细的手工询价 scydgy_id
  12421. *
  12422. * @param int[] $scydgyIds
  12423. * @return array<int, bool>
  12424. */
  12425. protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
  12426. {
  12427. $set = [];
  12428. $ids = [];
  12429. foreach ($scydgyIds as $sid) {
  12430. $sid = (int)$sid;
  12431. if ($sid < 0) {
  12432. $ids[$sid] = true;
  12433. }
  12434. }
  12435. if ($ids === []) {
  12436. return $set;
  12437. }
  12438. try {
  12439. $q = Db::table('purchase_order_detail')
  12440. ->where('scydgy_id', 'in', array_keys($ids))
  12441. ->field('scydgy_id');
  12442. $this->applyActivePurchaseOrderDetailWhere($q);
  12443. $rows = $q->select();
  12444. } catch (\Throwable $e) {
  12445. return $set;
  12446. }
  12447. if (!is_array($rows)) {
  12448. return $set;
  12449. }
  12450. foreach ($rows as $row) {
  12451. if (!is_array($row)) {
  12452. continue;
  12453. }
  12454. $sid = (int)($row['scydgy_id'] ?? 0);
  12455. if ($sid < 0) {
  12456. $set[$sid] = true;
  12457. }
  12458. }
  12459. return $set;
  12460. }
  12461. /**
  12462. * 批量:已填单价(已报价)的手工询价 scydgy_id
  12463. *
  12464. * @param int[] $scydgyIds
  12465. * @return array<int, bool>
  12466. */
  12467. protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
  12468. {
  12469. $set = [];
  12470. $ids = [];
  12471. foreach ($scydgyIds as $sid) {
  12472. $sid = (int)$sid;
  12473. if ($sid < 0) {
  12474. $ids[$sid] = true;
  12475. }
  12476. }
  12477. if ($ids === []) {
  12478. return $set;
  12479. }
  12480. try {
  12481. $q = Db::table('purchase_order_detail')
  12482. ->where('scydgy_id', 'in', array_keys($ids))
  12483. ->field('scydgy_id,amount');
  12484. $this->applyActivePurchaseOrderDetailWhere($q);
  12485. $rows = $q->select();
  12486. } catch (\Throwable $e) {
  12487. return $set;
  12488. }
  12489. if (!is_array($rows)) {
  12490. return $set;
  12491. }
  12492. foreach ($rows as $row) {
  12493. if (!is_array($row)) {
  12494. continue;
  12495. }
  12496. $amount = trim((string)($row['amount'] ?? ''));
  12497. if ($amount === '' || $amount === '0' || $amount === '0.00') {
  12498. continue;
  12499. }
  12500. $sid = (int)($row['scydgy_id'] ?? 0);
  12501. if ($sid < 0) {
  12502. $set[$sid] = true;
  12503. }
  12504. }
  12505. return $set;
  12506. }
  12507. /**
  12508. * 已下发且至少一家供应商已报价,才允许通知业务员
  12509. */
  12510. protected function canRfqNotifySalesman(array $po): bool
  12511. {
  12512. if (!$this->isRfqOrderIssued($po)) {
  12513. return false;
  12514. }
  12515. $sid = (int)($po['scydgy_id'] ?? 0);
  12516. if ($sid >= 0) {
  12517. return false;
  12518. }
  12519. $quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
  12520. return isset($quoted[$sid]);
  12521. }
  12522. protected function assertRfqCanNotifySalesman(array $po): void
  12523. {
  12524. if (!$this->isRfqOrderIssued($po)) {
  12525. $this->error('请先询价并等待供应商报价后再通知业务员');
  12526. }
  12527. if (!$this->canRfqNotifySalesman($po)) {
  12528. $this->error('供应商尚未报价,暂不能通知业务员');
  12529. }
  12530. }
  12531. /**
  12532. * 加载手工询价单(含可见性校验)
  12533. *
  12534. * @return array<string, mixed>
  12535. */
  12536. protected function loadManualRfqOrderForNotify(int $scydgyId): array
  12537. {
  12538. try {
  12539. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  12540. } catch (\Throwable $e) {
  12541. $po = null;
  12542. }
  12543. if (!is_array($po)) {
  12544. $this->error('订单不存在');
  12545. }
  12546. $modRq = trim((string)($po['mod_rq'] ?? ''));
  12547. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  12548. $this->error('订单不存在');
  12549. }
  12550. if ($this->auth->isSuperAdmin()) {
  12551. return $po;
  12552. }
  12553. if ($this->canViewManualRfqOrder($po)) {
  12554. return $po;
  12555. }
  12556. $this->error('无权操作该订单');
  12557. }
  12558. /**
  12559. * @return string[]
  12560. */
  12561. protected function splitRfqSalesmanNames(string $raw): array
  12562. {
  12563. $parts = [];
  12564. $raw = trim($raw);
  12565. if ($raw === '') {
  12566. return [];
  12567. }
  12568. foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
  12569. $v = trim((string)$piece);
  12570. if ($v !== '' && !in_array($v, $parts, true)) {
  12571. $parts[] = $v;
  12572. }
  12573. }
  12574. return $parts;
  12575. }
  12576. /**
  12577. * 按姓名匹配 fa_admin 邮箱
  12578. *
  12579. * @param string[] $names
  12580. * @return array<int, array{admin_id:int,name:string,email:string}>
  12581. */
  12582. protected function resolveRfqSalesmanContactRows(array $names): array
  12583. {
  12584. $out = [];
  12585. foreach ($names as $name) {
  12586. $name = trim((string)$name);
  12587. if ($name === '') {
  12588. continue;
  12589. }
  12590. $adminId = 0;
  12591. $email = '';
  12592. try {
  12593. $row = Db::name('admin')
  12594. ->where(function ($q) use ($name) {
  12595. $q->where('nickname', $name)->whereOr('username', $name);
  12596. })
  12597. ->where('status', 'normal')
  12598. ->order('id', 'asc')
  12599. ->field('id,nickname,username,email')
  12600. ->find();
  12601. } catch (\Throwable $e) {
  12602. $row = null;
  12603. }
  12604. if (is_array($row)) {
  12605. $adminId = (int)($row['id'] ?? 0);
  12606. $email = trim((string)($row['email'] ?? ''));
  12607. $disp = trim((string)($row['nickname'] ?? ''));
  12608. if ($disp === '') {
  12609. $disp = trim((string)($row['username'] ?? ''));
  12610. }
  12611. if ($disp !== '') {
  12612. $name = $disp;
  12613. }
  12614. }
  12615. $out[] = [
  12616. 'admin_id' => $adminId,
  12617. 'name' => $name,
  12618. 'email' => $email,
  12619. ];
  12620. }
  12621. return $out;
  12622. }
  12623. /**
  12624. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  12625. */
  12626. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  12627. {
  12628. if ($scydgyId >= 0) {
  12629. return;
  12630. }
  12631. try {
  12632. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  12633. } catch (\Throwable $e) {
  12634. $po = null;
  12635. }
  12636. if (!is_array($po)) {
  12637. $this->error('订单不存在');
  12638. }
  12639. $modRq = trim((string)($po['mod_rq'] ?? ''));
  12640. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  12641. $this->error('订单不存在');
  12642. }
  12643. if ($this->auth->isSuperAdmin()) {
  12644. return;
  12645. }
  12646. [, $adminName] = $this->GetUseName();
  12647. $cywy = trim((string)($po['cywyxm'] ?? ''));
  12648. if ($cywy !== '' && $cywy === $adminName) {
  12649. return;
  12650. }
  12651. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  12652. try {
  12653. if ($this->auth->check($rule)) {
  12654. return;
  12655. }
  12656. } catch (\Throwable $e) {
  12657. }
  12658. }
  12659. $this->error('无权查看该订单');
  12660. }
  12661. /**
  12662. * 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
  12663. */
  12664. protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
  12665. {
  12666. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  12667. return ProcuremenStatus::PO_COMPLETED;
  12668. }
  12669. $sid = (int)($row['scydgy_id'] ?? 0);
  12670. if ($sid < 0) {
  12671. if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
  12672. return '已通知业务员';
  12673. }
  12674. if ($hasQuoted) {
  12675. return '供应商已报价';
  12676. }
  12677. if ($hasIssued
  12678. || ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
  12679. || ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
  12680. return '待报价';
  12681. }
  12682. try {
  12683. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  12684. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  12685. if ((int)$detCntQuery->count() > 0) {
  12686. return '待报价';
  12687. }
  12688. } catch (\Throwable $e) {
  12689. }
  12690. return '待询价';
  12691. }
  12692. if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
  12693. return '待入库评分';
  12694. }
  12695. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  12696. return '待采购确认';
  12697. }
  12698. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  12699. return '待确认供应商';
  12700. }
  12701. return '待协助下发';
  12702. }
  12703. /**
  12704. * 协助初选列表 — 批量软删除
  12705. */
  12706. public function pickDelete()
  12707. {
  12708. if (!$this->request->isPost() || !$this->request->isAjax()) {
  12709. $this->error(__('Invalid parameters'));
  12710. }
  12711. if (!$this->procuremenCanPickDelete()) {
  12712. $this->error(__('You have no permission'));
  12713. }
  12714. $rowsRaw = $this->request->post('rows_json', '[]');
  12715. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  12716. if (!is_array($rows) || $rows === []) {
  12717. $this->error('请至少勾选一条工序');
  12718. }
  12719. $done = 0;
  12720. Db::startTrans();
  12721. try {
  12722. foreach ($rows as $row) {
  12723. if (!is_array($row)) {
  12724. continue;
  12725. }
  12726. $this->softDeleteProcuremenPickRow($row);
  12727. $done++;
  12728. }
  12729. if ($done < 1) {
  12730. throw new \Exception('没有可删除的工序');
  12731. }
  12732. Db::commit();
  12733. } catch (\InvalidArgumentException $e) {
  12734. Db::rollback();
  12735. $this->error($e->getMessage());
  12736. } catch (\Throwable $e) {
  12737. Db::rollback();
  12738. $this->error($e->getMessage());
  12739. }
  12740. $this->pickHiddenScydgySetCache = null;
  12741. $this->success('已删除 ' . $done . ' 条工序');
  12742. }
  12743. /**
  12744. * 下发 — 手工新增工序(弹窗)
  12745. */
  12746. public function pickAdd()
  12747. {
  12748. if ($this->request->isPost()) {
  12749. $params = $this->request->post('row/a');
  12750. if (!is_array($params)) {
  12751. $this->error(__('Parameter %s can not be empty', ''));
  12752. }
  12753. try {
  12754. $sid = $this->saveManualPickOrder($params);
  12755. } catch (\InvalidArgumentException $e) {
  12756. $this->error($e->getMessage());
  12757. } catch (\Throwable $e) {
  12758. $this->error($e->getMessage());
  12759. }
  12760. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  12761. }
  12762. return $this->view->fetch('procuremen/pick_add');
  12763. }
  12764. /**
  12765. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  12766. */
  12767. public function pickSubmit()
  12768. {
  12769. if (!$this->request->isPost()) {
  12770. $this->error(__('Invalid parameters'));
  12771. }
  12772. // ---------- 接口订单数据 ----------
  12773. $rowJson = $this->request->post('row_json', '');
  12774. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  12775. $companiesJson = $this->request->post('companies_json', '[]');
  12776. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  12777. $companies = json_decode($companiesJson, true);
  12778. if (!is_array($companies)) {
  12779. $this->error('供应商数据无效');
  12780. }
  12781. $postedCompanyCount = 0;
  12782. $skippedCompanyCount = 0;
  12783. foreach ($companies as $c) {
  12784. if (is_array($c) && (trim((string)($c['name'] ?? $c['company_name'] ?? '')) !== '' || trim((string)($c['id'] ?? '')) !== '')) {
  12785. $postedCompanyCount++;
  12786. }
  12787. }
  12788. $issueCompanies = $this->normalizePickCompanies($companies);
  12789. if ($issueCompanies === []) {
  12790. $this->error('请至少选择一家合作供应商(须同时具备有效手机号与邮箱)');
  12791. }
  12792. // 不可用供应商静默跳过,不向操作员报错;成功提示中说明实际下发家数
  12793. if ($postedCompanyCount > 0 && count($issueCompanies) < $postedCompanyCount) {
  12794. $skippedCompanyCount = $postedCompanyCount - count($issueCompanies);
  12795. Log::write(
  12796. 'procuremen pickSubmit skip companies: posted=' . $postedCompanyCount
  12797. . ' issued=' . count($issueCompanies),
  12798. 'notice'
  12799. );
  12800. }
  12801. $issueNameLabels = [];
  12802. foreach ($issueCompanies as $pc) {
  12803. $issueNameLabels[] = $pc['name'];
  12804. }
  12805. $issueNamesSummary = implode('、', $issueNameLabels);
  12806. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  12807. if ($sysRq === '') {
  12808. $this->error('请选择招标截止日期');
  12809. }
  12810. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  12811. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  12812. (string)$this->request->post('delivery_deadline', ''),
  12813. true
  12814. );
  12815. $scoreRuleId = (int)$this->request->post('score_rule_id', 0);
  12816. if ($scoreRuleId <= 0) {
  12817. $this->error('请选择订单类型');
  12818. }
  12819. $scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
  12820. if ((int)($scoreRule['id'] ?? 0) <= 0) {
  12821. $this->error('订单类型无效,请刷新后重选');
  12822. }
  12823. $scoreRuleId = (int)$scoreRule['id'];
  12824. $this->ensurePurchaseOrderScoreRuleIdColumn();
  12825. $logMsg = '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  12826. $bidDispForLog = $this->formatProcuremenSysRqForDisplay($sysRqDb);
  12827. $delDispForLog = $this->formatProcuremenDeliveryDeadlineForInput($deliveryDeadlineDb);
  12828. if ($delDispForLog === '') {
  12829. $delDispForLog = $this->formatDeliveryYmd($deliveryDeadlineDb);
  12830. }
  12831. $orderTypeForLog = trim((string)($scoreRule['name'] ?? ''));
  12832. $logExtra = [];
  12833. if ($bidDispForLog !== '' && $bidDispForLog !== '—') {
  12834. $logExtra[] = '招标截止日期:' . $bidDispForLog;
  12835. }
  12836. if ($delDispForLog !== '') {
  12837. $logExtra[] = '交货截止日期:' . $delDispForLog;
  12838. }
  12839. if ($orderTypeForLog !== '') {
  12840. $logExtra[] = '订单类型:' . $orderTypeForLog;
  12841. }
  12842. if ($logExtra !== []) {
  12843. $logMsg .= ';' . implode(';', $logExtra);
  12844. }
  12845. $issueTime = date('Y-m-d H:i:s');
  12846. try {
  12847. $issueBatchNo = $this->allocateProcuremenIssueBatchNo();
  12848. } catch (\Throwable $e) {
  12849. $this->error($e->getMessage() !== '' ? $e->getMessage() : '批次号生成失败,请重试');
  12850. }
  12851. $logSidList = [];
  12852. foreach ($mergeRows as $row) {
  12853. if (!is_array($row)) {
  12854. continue;
  12855. }
  12856. $sid = $this->extractScydgyRowId($row);
  12857. if ($this->isValidScydgyRowId($sid)) {
  12858. $logSidList[$sid] = true;
  12859. }
  12860. }
  12861. if ($logSidList === []) {
  12862. $this->error('未找到有效工序,无法下发');
  12863. }
  12864. // 防连点/并发:同一批工序加命名锁,已下发则直接拒绝(避免重复短信邮件)
  12865. $sidKeys = array_keys($logSidList);
  12866. sort($sidKeys, SORT_NUMERIC);
  12867. $pickLockName = 'procuremen_pick_submit_' . md5(implode(',', $sidKeys));
  12868. if (!$this->acquireProcuremenNamedLock($pickLockName, 15)) {
  12869. $this->error('下发处理中,请勿重复点击');
  12870. }
  12871. $existingBySid = [];
  12872. try {
  12873. try {
  12874. $existingRows = Db::table('purchase_order')
  12875. ->where('scydgy_id', 'in', $sidKeys)
  12876. ->select();
  12877. if (is_array($existingRows)) {
  12878. foreach ($existingRows as $poRow) {
  12879. if (!is_array($poRow)) {
  12880. continue;
  12881. }
  12882. $sid = (int)($poRow['scydgy_id'] ?? 0);
  12883. if ($this->isValidScydgyRowId($sid)) {
  12884. $existingBySid[$sid] = $poRow;
  12885. }
  12886. }
  12887. }
  12888. } catch (\Throwable $e) {
  12889. $existingBySid = [];
  12890. }
  12891. foreach ($sidKeys as $sid) {
  12892. $poRow = $existingBySid[$sid] ?? null;
  12893. if (!is_array($poRow)) {
  12894. continue;
  12895. }
  12896. if ($this->isPurchaseOrderSoftDeleted($poRow['mod_rq'] ?? null)) {
  12897. continue;
  12898. }
  12899. $label = $this->formatProcuremenRowLabel(['CCYDH' => $poRow['CCYDH'] ?? '', 'CGYMC' => $poRow['CGYMC'] ?? '']);
  12900. if (ProcuremenStatus::isPoCompleted($poRow['status'] ?? '')) {
  12901. $this->error(($label !== '' ? $label : ('工序#' . $sid)) . '已完结,无法再次下发');
  12902. }
  12903. if (!ProcuremenStatus::isWflowPendingIssue($poRow['wflow_status'] ?? '')) {
  12904. $this->error(($label !== '' ? $label : ('工序#' . $sid)) . '已下发或进入后续流程,请勿重复提交');
  12905. }
  12906. }
  12907. Db::startTrans();
  12908. try {
  12909. $this->enrichProcuremenRowsMbz($mergeRows);
  12910. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  12911. foreach ($mergeRows as $row) {
  12912. if (!is_array($row)) {
  12913. continue;
  12914. }
  12915. $sid = $this->extractScydgyRowId($row);
  12916. $this->upsertPurchaseOrderFromRow(
  12917. $row,
  12918. $sysRqDb,
  12919. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  12920. $issueTime,
  12921. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  12922. $deliveryDeadlineDb,
  12923. $scoreRule,
  12924. $issueBatchNo
  12925. );
  12926. }
  12927. foreach ($issueCompanies as $c) {
  12928. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  12929. }
  12930. Db::commit();
  12931. } catch (\Throwable $e) {
  12932. Db::rollback();
  12933. $this->error($e->getMessage());
  12934. }
  12935. } finally {
  12936. $this->releaseProcuremenNamedLock($pickLockName);
  12937. }
  12938. $poIdBySid = [];
  12939. if ($logSidList !== []) {
  12940. try {
  12941. $poIdBySid = Db::table('purchase_order')
  12942. ->where('scydgy_id', 'in', array_keys($logSidList))
  12943. ->column('id', 'scydgy_id');
  12944. } catch (\Throwable $e) {
  12945. $poIdBySid = [];
  12946. }
  12947. }
  12948. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  12949. if ($logSidList !== []) {
  12950. list($adminId, $adminName) = $this->GetUseName();
  12951. $logRows = [];
  12952. $seenLogSid = [];
  12953. foreach ($mergeRows as $row) {
  12954. if (!is_array($row)) {
  12955. continue;
  12956. }
  12957. $ids = $this->extractScydgyRowId($row);
  12958. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  12959. continue;
  12960. }
  12961. $seenLogSid[$ids] = true;
  12962. $poIdLog = null;
  12963. if (isset($poIdBySid[$ids])) {
  12964. $tid = (int)$poIdBySid[$ids];
  12965. $poIdLog = $tid > 0 ? $tid : null;
  12966. }
  12967. $logRows[] = ProcuremenOperLog::buildInsertRow(
  12968. $ids,
  12969. 'issue_submit',
  12970. $logMsg,
  12971. $poIdLog,
  12972. (int)$adminId,
  12973. (string)$adminName
  12974. );
  12975. }
  12976. if ($logRows !== []) {
  12977. try {
  12978. Db::table('purchase_order_oper_log')->insertAll($logRows);
  12979. } catch (\Throwable $e) {
  12980. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  12981. }
  12982. }
  12983. }
  12984. $posNotify = [];
  12985. if ($logSidList !== []) {
  12986. try {
  12987. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  12988. } catch (\Throwable $e) {
  12989. $posNotify = [];
  12990. }
  12991. }
  12992. if (!is_array($posNotify)) {
  12993. $posNotify = [];
  12994. }
  12995. foreach ($posNotify as $i => $prow) {
  12996. if (is_array($posNotify[$i])) {
  12997. $posNotify[$i]['sys_rq'] = $sysRqDb;
  12998. }
  12999. }
  13000. $ccydhPick = '';
  13001. foreach ($mergeRows as $row) {
  13002. if (!is_array($row)) {
  13003. continue;
  13004. }
  13005. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  13006. if ($ccydhPick !== '') {
  13007. break;
  13008. }
  13009. }
  13010. $notifyBundleBase = [
  13011. 'ccydh' => $ccydhPick,
  13012. 'pos' => $posNotify,
  13013. 'merge_rows' => $mergeRows,
  13014. 'score_rule' => is_array($scoreRule) ? $scoreRule : null,
  13015. ];
  13016. // 写库已成功:先立刻回成功给前端,再后台发短信/邮件(避免多家串行超时转圈/误报失败)
  13017. $okCount = count($issueCompanies);
  13018. $skipHint = '';
  13019. if (!empty($skippedCompanyCount) && (int)$skippedCompanyCount > 0) {
  13020. $skipHint = '(已自动跳过 ' . (int)$skippedCompanyCount . ' 家资料不完整的供应商)';
  13021. }
  13022. $payload = [
  13023. 'issued' => 1,
  13024. 'supplier_count' => $okCount,
  13025. 'notify_pending' => 1,
  13026. 'notify_failed' => 0,
  13027. ];
  13028. $successMsg = '下发成功' . $skipHint . ',已向 ' . $okCount
  13029. . ' 家供应商发起通知。';
  13030. if ($this->isProcuremenNotifyDryRun()) {
  13031. $this->notifyDryRunPreview = [];
  13032. $notifyErrors = [];
  13033. foreach ($issueCompanies as $c) {
  13034. if (!is_array($c)) {
  13035. continue;
  13036. }
  13037. $cname = trim((string)($c['name'] ?? ''));
  13038. if ($cname === '') {
  13039. continue;
  13040. }
  13041. try {
  13042. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  13043. } catch (\Throwable $e) {
  13044. $notifyErrors[] = $cname . ':' . $e->getMessage();
  13045. }
  13046. }
  13047. $this->success('【演练模式】已保存并生成通知预览', '', [
  13048. 'notify_dry_run' => true,
  13049. 'notify_preview' => $this->notifyDryRunPreview,
  13050. 'notify_fail_detail' => $notifyErrors,
  13051. ]);
  13052. }
  13053. $this->respondSuccessThenContinue($successMsg, $payload);
  13054. @set_time_limit(300);
  13055. @ini_set('max_execution_time', '300');
  13056. $notifyOk = 0;
  13057. $notifyErrors = [];
  13058. foreach ($issueCompanies as $c) {
  13059. if (!is_array($c)) {
  13060. continue;
  13061. }
  13062. $cname = trim((string)($c['name'] ?? ''));
  13063. if ($cname === '') {
  13064. continue;
  13065. }
  13066. try {
  13067. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  13068. $notifyOk++;
  13069. } catch (\Throwable $e) {
  13070. $notifyErrors[] = $cname . ':' . $e->getMessage();
  13071. Log::write('procuremen pickSubmit background notify fail ' . $cname . ': ' . $e->getMessage(), 'error');
  13072. }
  13073. }
  13074. if ($notifyErrors !== []) {
  13075. Log::write(
  13076. 'procuremen pickSubmit background notify summary ok=' . $notifyOk
  13077. . ' fail=' . count($notifyErrors) . ' ' . implode(';', $notifyErrors),
  13078. 'error'
  13079. );
  13080. }
  13081. exit;
  13082. }
  13083. /**
  13084. * 确认供应商弹窗
  13085. */
  13086. public function auditIssue()
  13087. {
  13088. $ids = $this->request->param('ids', $this->request->param('id', ''));
  13089. if (is_array($ids)) {
  13090. $ids = isset($ids[0]) ? $ids[0] : '';
  13091. }
  13092. $ids = trim((string)$ids);
  13093. if ($ids === '') {
  13094. $this->error(__('Invalid parameters'));
  13095. }
  13096. if ($this->request->isPost()) {
  13097. $this->error('请使用弹窗内「确认」提交');
  13098. }
  13099. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  13100. $pos = $bundle['pos'];
  13101. if ($pos === []) {
  13102. $this->error('该订单不在待确认供应商状态');
  13103. }
  13104. $po = $pos[0];
  13105. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13106. if ($quoteGroups === []) {
  13107. $toastMsg = '暂无下发明细,请确认该订单已在「供应商初选」完成下发';
  13108. // 弹层内不要走整页跳转提示,仅 Toastr 后关闭
  13109. $this->view->assign('toastMsg', $toastMsg);
  13110. return $this->view->fetch('procuremen/toast_close');
  13111. }
  13112. $pickedName = '';
  13113. foreach ($pos as $poRow) {
  13114. if (!is_array($poRow)) {
  13115. continue;
  13116. }
  13117. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  13118. if ($pn !== '') {
  13119. $pickedName = $pn;
  13120. break;
  13121. }
  13122. }
  13123. $this->view->assign('po', $po);
  13124. $this->view->assign('scydgyId', $ids);
  13125. $this->view->assign('orderCcydh', $bundle['ccydh']);
  13126. $mergeRows = $bundle['merge_rows'];
  13127. $this->view->assign('processRows', $mergeRows);
  13128. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  13129. $this->view->assign('processCount', count($mergeRows));
  13130. $this->view->assign('orderBatchNo', $this->resolveBundleOrderBatchNo($bundle));
  13131. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  13132. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  13133. $this->view->assign('pickedCompanyName', $pickedName);
  13134. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  13135. if ($sysRqForView === '') {
  13136. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  13137. }
  13138. $this->view->assign('sysRq', $sysRqForView);
  13139. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  13140. if ($deliveryDeadlineForView === '') {
  13141. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  13142. }
  13143. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  13144. $this->ensurePurchaseOrderManualPickColumns();
  13145. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
  13146. $manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
  13147. $manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
  13148. $isRejected = 0;
  13149. foreach ($pos as $poRow) {
  13150. if (!is_array($poRow)) {
  13151. continue;
  13152. }
  13153. if (ProcuremenStatus::isWflowRejected($poRow['wflow_status'] ?? '')) {
  13154. $isRejected = 1;
  13155. break;
  13156. }
  13157. }
  13158. $quoteVisible = ($bidOpenVerified || $manualPicked || $isRejected) ? 1 : 0;
  13159. if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
  13160. $pickedName = $manualPickInfo['company'];
  13161. }
  13162. // 驳回后:仅一家供应商时自动选定,便于直接确认;多家则留空供用户选择
  13163. $quoteGroupCount = 0;
  13164. $onlyQuoteCompany = '';
  13165. foreach ($quoteGroups as $g) {
  13166. if (!is_array($g)) {
  13167. continue;
  13168. }
  13169. $nm = trim((string)($g['name'] ?? ''));
  13170. if ($nm === '') {
  13171. continue;
  13172. }
  13173. $quoteGroupCount++;
  13174. if ($onlyQuoteCompany === '') {
  13175. $onlyQuoteCompany = $nm;
  13176. }
  13177. }
  13178. if ($isRejected) {
  13179. // 驳回需重新选定:清空锁定用的已选名;仅一家时再自动勾选
  13180. $pickedName = ($quoteGroupCount === 1) ? $onlyQuoteCompany : '';
  13181. }
  13182. $this->view->assign('pickedCompanyName', $pickedName);
  13183. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  13184. $this->view->assign('manualPicked', $manualPicked);
  13185. $this->view->assign('isRejected', $isRejected);
  13186. $this->view->assign('quoteGroupCount', $quoteGroupCount);
  13187. $this->view->assign('manualPickReason', $manualPickInfo['reason']);
  13188. $this->view->assign('quoteVisible', $quoteVisible);
  13189. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
  13190. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  13191. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
  13192. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
  13193. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  13194. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  13195. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  13196. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  13197. return $this->view->fetch('procuremen/audit_issue');
  13198. }
  13199. /**
  13200. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  13201. *
  13202. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  13203. */
  13204. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  13205. {
  13206. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13207. return false;
  13208. }
  13209. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13210. return false;
  13211. }
  13212. return true;
  13213. }
  13214. /**
  13215. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  13216. *
  13217. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  13218. */
  13219. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  13220. {
  13221. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13222. return false;
  13223. }
  13224. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13225. return false;
  13226. }
  13227. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  13228. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  13229. return true;
  13230. }
  13231. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  13232. }
  13233. /**
  13234. * 确认页 — 补加供应商弹窗
  13235. */
  13236. public function auditAppend()
  13237. {
  13238. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  13239. $this->error(__('You have no permission'));
  13240. }
  13241. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  13242. if (is_array($ids)) {
  13243. $ids = isset($ids[0]) ? $ids[0] : '';
  13244. }
  13245. $ids = trim((string)$ids);
  13246. if ($ids === '') {
  13247. $this->error(__('Invalid parameters'));
  13248. }
  13249. if ($this->request->isPost()) {
  13250. $this->error('请使用弹窗内「确认」提交');
  13251. }
  13252. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  13253. if (($bundle['pos'] ?? []) === []) {
  13254. $this->error('该订单不在待确认供应商状态');
  13255. }
  13256. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  13257. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13258. $this->error('已开标验证,不能再补加供应商');
  13259. }
  13260. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13261. $this->error('已指定供应商,不能再补加供应商');
  13262. }
  13263. $this->error('已经超过了招标截止日期,不可操作');
  13264. }
  13265. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13266. $existingNames = [];
  13267. foreach ($quoteGroups as $g) {
  13268. if (!is_array($g)) {
  13269. continue;
  13270. }
  13271. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  13272. if ($n !== '') {
  13273. $existingNames[$n] = true;
  13274. }
  13275. }
  13276. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  13277. $mergeRows = $bundle['merge_rows'] ?? [];
  13278. $this->view->assign('scydgyId', $ids);
  13279. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  13280. $this->view->assign('po', $po);
  13281. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  13282. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  13283. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  13284. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  13285. if ($sysRqForView === '') {
  13286. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  13287. }
  13288. $this->view->assign('sysRq', $sysRqForView);
  13289. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  13290. if ($deliveryDeadlineForView === '') {
  13291. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  13292. }
  13293. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  13294. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  13295. }
  13296. /**
  13297. * 确认页 — 补加供应商提交
  13298. */
  13299. public function auditAppendSubmit()
  13300. {
  13301. if (!$this->request->isPost()) {
  13302. $this->error(__('Invalid parameters'));
  13303. }
  13304. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  13305. $this->error(__('You have no permission'));
  13306. }
  13307. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  13308. if ($ids === '') {
  13309. $this->error(__('Invalid parameters'));
  13310. }
  13311. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  13312. if (($bundle['pos'] ?? []) === []) {
  13313. $this->error('该订单不在待确认供应商状态');
  13314. }
  13315. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  13316. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13317. $this->error('已开标验证,不能再补加供应商');
  13318. }
  13319. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13320. $this->error('已指定供应商,不能再补加供应商');
  13321. }
  13322. $this->error('已经超过了招标截止日期,不可操作');
  13323. }
  13324. $companiesJson = $this->request->post('companies_json', '[]');
  13325. $companies = json_decode((string)$companiesJson, true);
  13326. if (!is_array($companies)) {
  13327. $this->error('供应商数据无效');
  13328. }
  13329. $issueCompanies = $this->normalizePickCompanies($companies);
  13330. if ($issueCompanies === []) {
  13331. $this->error('请至少选择一家合作供应商');
  13332. }
  13333. $mergeRows = $bundle['merge_rows'] ?? [];
  13334. if (!is_array($mergeRows) || $mergeRows === []) {
  13335. $this->error('未找到工序行,无法补加');
  13336. }
  13337. $existingNames = [];
  13338. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  13339. if (!is_array($g)) {
  13340. continue;
  13341. }
  13342. $n = trim((string)($g['company_name'] ?? ''));
  13343. if ($n !== '') {
  13344. $existingNames[$n] = true;
  13345. }
  13346. }
  13347. $toAdd = [];
  13348. foreach ($issueCompanies as $c) {
  13349. if (!is_array($c)) {
  13350. continue;
  13351. }
  13352. $n = trim((string)($c['name'] ?? ''));
  13353. if ($n === '' || isset($existingNames[$n])) {
  13354. continue;
  13355. }
  13356. $toAdd[] = $c;
  13357. }
  13358. if ($toAdd === []) {
  13359. $this->error('所选供应商均已在本单中,请选择新的供应商');
  13360. }
  13361. $addedNames = [];
  13362. Db::startTrans();
  13363. try {
  13364. foreach ($toAdd as $c) {
  13365. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  13366. $addedNames[] = trim((string)($c['name'] ?? ''));
  13367. }
  13368. Db::commit();
  13369. } catch (\Throwable $e) {
  13370. Db::rollback();
  13371. $this->error($e->getMessage());
  13372. }
  13373. $notifyBundleBase = [
  13374. 'ccydh' => $bundle['ccydh'] ?? '',
  13375. 'pos' => $bundle['pos'] ?? [],
  13376. 'merge_rows' => $mergeRows,
  13377. ];
  13378. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  13379. $seenLogSid = [];
  13380. foreach ($bundle['pos'] ?? [] as $poRow) {
  13381. if (!is_array($poRow)) {
  13382. continue;
  13383. }
  13384. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13385. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  13386. continue;
  13387. }
  13388. $seenLogSid[$sid] = true;
  13389. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  13390. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  13391. }
  13392. if ($seenLogSid === []) {
  13393. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  13394. if ($this->isValidScydgyRowId($logSid)) {
  13395. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  13396. }
  13397. }
  13398. if ($this->isProcuremenNotifyDryRun()) {
  13399. $this->notifyDryRunPreview = [];
  13400. $notifyErrors = [];
  13401. foreach ($toAdd as $c) {
  13402. if (!is_array($c)) {
  13403. continue;
  13404. }
  13405. $cname = trim((string)($c['name'] ?? ''));
  13406. if ($cname === '') {
  13407. continue;
  13408. }
  13409. try {
  13410. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  13411. } catch (\Throwable $e) {
  13412. $notifyErrors[] = $cname . ':' . $e->getMessage();
  13413. }
  13414. }
  13415. $this->success('【演练模式】已补加并生成通知预览', '', [
  13416. 'append_ok' => 1,
  13417. 'notify_dry_run' => true,
  13418. 'notify_preview' => $this->notifyDryRunPreview,
  13419. 'notify_fail_detail' => $notifyErrors,
  13420. ]);
  13421. }
  13422. $this->respondSuccessThenContinue(
  13423. '已补加 ' . count($toAdd) . ' 家供应商并发起通知。',
  13424. ['append_ok' => 1, 'notify_pending' => 1, 'notify_failed' => 0]
  13425. );
  13426. $notifyErrors = [];
  13427. foreach ($toAdd as $c) {
  13428. if (!is_array($c)) {
  13429. continue;
  13430. }
  13431. $cname = trim((string)($c['name'] ?? ''));
  13432. if ($cname === '') {
  13433. continue;
  13434. }
  13435. try {
  13436. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  13437. } catch (\Throwable $e) {
  13438. $notifyErrors[] = $cname . ':' . $e->getMessage();
  13439. Log::write('procuremen auditAppend background notify fail ' . $cname . ': ' . $e->getMessage(), 'error');
  13440. }
  13441. }
  13442. if ($notifyErrors !== []) {
  13443. Log::write('procuremen auditAppend background notify summary: ' . implode(';', $notifyErrors), 'error');
  13444. }
  13445. exit;
  13446. }
  13447. /**
  13448. * 开标双重验证 — 可选验证人列表
  13449. */
  13450. public function bidOpenUsers()
  13451. {
  13452. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  13453. $this->error('无权限');
  13454. }
  13455. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  13456. if ($scydgyId !== '') {
  13457. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13458. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13459. $this->success('已完成开标验证', null, [
  13460. 'verified' => 1,
  13461. 'users' => [],
  13462. ]);
  13463. }
  13464. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13465. $this->error('本单已指定供应商,无需再开标');
  13466. }
  13467. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  13468. }
  13469. $this->success('', null, [
  13470. 'verified' => 0,
  13471. 'users' => $this->listBidOpenVerifierCandidates(),
  13472. ]);
  13473. }
  13474. /**
  13475. * 开标双重验证 — 向指定管理员发送短信验证码
  13476. */
  13477. public function bidOpenSendCode()
  13478. {
  13479. if (!$this->request->isPost()) {
  13480. $this->error(__('Invalid parameters'));
  13481. }
  13482. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  13483. $this->error('无权限');
  13484. }
  13485. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13486. $adminId = (int)$this->request->post('admin_id', 0);
  13487. if ($scydgyId === '' || $adminId <= 0) {
  13488. $this->error('参数无效');
  13489. }
  13490. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13491. if ($bundle['pos'] === []) {
  13492. $this->error('该订单不在待确认供应商状态');
  13493. }
  13494. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13495. $this->success('已完成开标验证,无需重复发送');
  13496. }
  13497. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13498. $this->error('本单已指定供应商,无需再开标');
  13499. }
  13500. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  13501. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  13502. if ($ccydh === '') {
  13503. $this->error('订单号无效');
  13504. }
  13505. $admin = $this->loadBidOpenAdminUser($adminId);
  13506. if ($admin === null) {
  13507. $this->error('验证人无效或未绑定手机号');
  13508. }
  13509. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  13510. $cd = max(30, min(120, $cd));
  13511. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  13512. $this->error('发送过于频繁,请稍后再试');
  13513. }
  13514. $code = (string)random_int(100000, 999999);
  13515. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  13516. $ttl = max(60, min(600, $ttl));
  13517. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  13518. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  13519. try {
  13520. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  13521. } catch (\Throwable $e) {
  13522. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  13523. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  13524. $this->error($e->getMessage());
  13525. }
  13526. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  13527. }
  13528. /**
  13529. * 开标双重验证 — 两人验证码校验并记录
  13530. */
  13531. public function bidOpenVerify()
  13532. {
  13533. if (!$this->request->isPost()) {
  13534. $this->error(__('Invalid parameters'));
  13535. }
  13536. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  13537. $this->error('无权限');
  13538. }
  13539. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13540. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  13541. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  13542. $code1 = trim((string)$this->request->post('code1', ''));
  13543. $code2 = trim((string)$this->request->post('code2', ''));
  13544. if ($scydgyId === '') {
  13545. $this->error('参数无效');
  13546. }
  13547. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  13548. $this->error('请选择两位验证人');
  13549. }
  13550. if ($verifier1Id === $verifier2Id) {
  13551. $this->error('两位验证人不能相同');
  13552. }
  13553. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  13554. $this->error('请输入6位短信验证码');
  13555. }
  13556. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13557. if ($bundle['pos'] === []) {
  13558. $this->error('该订单不在待确认供应商状态');
  13559. }
  13560. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  13561. if ($ccydh === '') {
  13562. $this->error('订单号无效');
  13563. }
  13564. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13565. $this->success('已完成开标验证');
  13566. }
  13567. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13568. $this->error('本单已指定供应商,无需再开标');
  13569. }
  13570. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  13571. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  13572. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  13573. if ($verifier1 === null || $verifier2 === null) {
  13574. $this->error('验证人无效或未绑定手机号');
  13575. }
  13576. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  13577. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  13578. }
  13579. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  13580. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  13581. }
  13582. try {
  13583. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  13584. } catch (\Throwable $e) {
  13585. $this->error($e->getMessage());
  13586. }
  13587. $this->success('开标验证成功,可查看供应商报价与交货日期');
  13588. }
  13589. /**
  13590. * 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
  13591. */
  13592. public function auditManualPick()
  13593. {
  13594. if (!$this->request->isPost()) {
  13595. $this->error(__('Invalid parameters'));
  13596. }
  13597. if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
  13598. $this->error('无权限');
  13599. }
  13600. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13601. if ($scydgyId === '') {
  13602. $this->error('参数无效');
  13603. }
  13604. $companyName = trim((string)$this->request->post('selected_company', ''));
  13605. $reason = trim((string)$this->request->post('pick_reason', ''));
  13606. if ($companyName === '') {
  13607. $this->error('请选择一家供应商');
  13608. }
  13609. if ($reason === '') {
  13610. $this->error('请填写选择说明');
  13611. }
  13612. if (mb_strlen($reason) > 500) {
  13613. $this->error('选择说明不能超过500字');
  13614. }
  13615. $this->ensurePurchaseOrderManualPickColumns();
  13616. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13617. $pos = $bundle['pos'];
  13618. if ($pos === []) {
  13619. $this->error('该订单不在待确认供应商状态');
  13620. }
  13621. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13622. $this->error('本单已开标验证,请直接在列表中选定供应商后确认');
  13623. }
  13624. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13625. if ($quoteGroups === []) {
  13626. $this->error('暂无供应商,请确认已完成协助初选通知');
  13627. }
  13628. $matched = null;
  13629. foreach ($quoteGroups as $g) {
  13630. if (!is_array($g)) {
  13631. continue;
  13632. }
  13633. if (trim((string)($g['name'] ?? '')) === $companyName) {
  13634. $matched = $g;
  13635. break;
  13636. }
  13637. }
  13638. if ($matched === null) {
  13639. $this->error('所选供应商不在本单报价列表中');
  13640. }
  13641. $logMsg = '指定供应商:' . $companyName . ';说明:' . $reason;
  13642. Db::startTrans();
  13643. try {
  13644. foreach ($pos as $poRow) {
  13645. if (!is_array($poRow)) {
  13646. continue;
  13647. }
  13648. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13649. if (!$this->isValidScydgyRowId($sid)) {
  13650. continue;
  13651. }
  13652. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  13653. 'pick_company_name' => $companyName,
  13654. 'manual_pick' => 1,
  13655. 'manual_pick_reason' => $reason,
  13656. ]);
  13657. }
  13658. Db::commit();
  13659. } catch (\Throwable $e) {
  13660. Db::rollback();
  13661. $this->error($e->getMessage());
  13662. }
  13663. foreach ($pos as $poRow) {
  13664. if (!is_array($poRow)) {
  13665. continue;
  13666. }
  13667. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13668. if (!$this->isValidScydgyRowId($sid)) {
  13669. continue;
  13670. }
  13671. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  13672. $this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  13673. }
  13674. // 自选后可见报价:按本批各订单分别计算评分(与开标后一致)
  13675. try {
  13676. $bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13677. $this->saveProcuremenSupplierScoresForBundle($bundleFresh, date('Y-m'));
  13678. } catch (\Throwable $e) {
  13679. Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
  13680. }
  13681. $this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
  13682. }
  13683. /**
  13684. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  13685. */
  13686. public function auditSubmit()
  13687. {
  13688. if (!$this->request->isPost()) {
  13689. $this->error(__('Invalid parameters'));
  13690. }
  13691. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13692. if ($scydgyId === '') {
  13693. $this->error('参数无效');
  13694. }
  13695. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13696. $pos = $bundle['pos'];
  13697. $mergeRows = $bundle['merge_rows'];
  13698. if ($pos === [] || $mergeRows === []) {
  13699. $this->error('该订单不在待确认供应商状态');
  13700. }
  13701. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13702. if ($quoteGroups === []) {
  13703. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  13704. }
  13705. $companyName = trim((string)$this->request->post('selected_company', ''));
  13706. if ($companyName === '') {
  13707. $this->error('请选择一家供应商');
  13708. }
  13709. $matched = null;
  13710. foreach ($quoteGroups as $g) {
  13711. if (!is_array($g)) {
  13712. continue;
  13713. }
  13714. if (trim((string)($g['name'] ?? '')) === $companyName) {
  13715. $matched = $g;
  13716. break;
  13717. }
  13718. }
  13719. if ($matched === null) {
  13720. $this->error('所选供应商不在本单报价列表中');
  13721. }
  13722. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  13723. if ($sysRqDb === '') {
  13724. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  13725. } else {
  13726. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  13727. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  13728. }
  13729. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  13730. $this->error('未到招标截止日期,暂不可确认');
  13731. }
  13732. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
  13733. && !$this->isProcuremenManualPickedForBundle($bundle)
  13734. ) {
  13735. $this->error('请先完成开标双重验证或指定供应商后再确认');
  13736. }
  13737. $logMsg = '确认供应商:' . $companyName;
  13738. Db::startTrans();
  13739. try {
  13740. foreach ($pos as $poRow) {
  13741. if (!is_array($poRow)) {
  13742. continue;
  13743. }
  13744. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13745. if (!$this->isValidScydgyRowId($sid)) {
  13746. continue;
  13747. }
  13748. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  13749. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  13750. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  13751. 'pick_company_name' => $companyName,
  13752. 'sys_rq' => $sysRqDb,
  13753. ]);
  13754. }
  13755. Db::commit();
  13756. } catch (\Throwable $e) {
  13757. Db::rollback();
  13758. $this->error($e->getMessage());
  13759. }
  13760. foreach ($pos as $poRow) {
  13761. if (!is_array($poRow)) {
  13762. continue;
  13763. }
  13764. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13765. if (!$this->isValidScydgyRowId($sid)) {
  13766. continue;
  13767. }
  13768. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  13769. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  13770. }
  13771. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  13772. }
  13773. /**
  13774. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  13775. */
  13776. public function auditResendSms()
  13777. {
  13778. if (!$this->request->isPost()) {
  13779. $this->error(__('Invalid parameters'));
  13780. }
  13781. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13782. if ($scydgyId === '') {
  13783. $this->error('参数无效');
  13784. }
  13785. $loaded = $this->loadAuditResendBundle($scydgyId);
  13786. $mergeRows = $loaded['merge_rows'];
  13787. $bundle = $loaded['bundle'];
  13788. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  13789. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13790. if ($quoteGroups === []) {
  13791. $this->error('暂无可通知的供应商');
  13792. }
  13793. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  13794. $companiesJson = (string)$this->request->post('companies_json', '');
  13795. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  13796. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  13797. }
  13798. /**
  13799. * 确认供应商 — 二次发送邮件(可选单家/批量)
  13800. */
  13801. public function auditResendEmail()
  13802. {
  13803. if (!$this->request->isPost()) {
  13804. $this->error(__('Invalid parameters'));
  13805. }
  13806. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13807. if ($scydgyId === '') {
  13808. $this->error('参数无效');
  13809. }
  13810. $loaded = $this->loadAuditResendBundle($scydgyId);
  13811. $mergeRows = $loaded['merge_rows'];
  13812. $bundle = $loaded['bundle'];
  13813. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  13814. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13815. if ($quoteGroups === []) {
  13816. $this->error('暂无可通知的供应商');
  13817. }
  13818. $companiesJson = (string)$this->request->post('companies_json', '');
  13819. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  13820. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  13821. if ($companiesJson === '' && $selectedCompany === '') {
  13822. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  13823. }
  13824. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  13825. }
  13826. /**
  13827. * 废弃单个订单 bundle(退回供应商初选,明细归档留痕)
  13828. *
  13829. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  13830. * @return array<int, true> 已处理的 scydgy_id 集合
  13831. */
  13832. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回供应商初选'): array
  13833. {
  13834. $pos = $bundle['pos'] ?? [];
  13835. if (!is_array($pos) || $pos === []) {
  13836. return [];
  13837. }
  13838. $sids = [];
  13839. $poIdBySid = [];
  13840. foreach ($pos as $poRow) {
  13841. if (!is_array($poRow)) {
  13842. continue;
  13843. }
  13844. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13845. if ($this->isValidScydgyRowId($sid)) {
  13846. $sids[$sid] = true;
  13847. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  13848. if ($poId > 0) {
  13849. $poIdBySid[$sid] = $poId;
  13850. }
  13851. }
  13852. }
  13853. if ($sids === []) {
  13854. return [];
  13855. }
  13856. $logMsg = '重新下发';
  13857. $suffix = trim((string)$logSuffix, ',, ');
  13858. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  13859. $logMsg .= ':从历史存证退回供应商初选';
  13860. } else {
  13861. $logMsg .= ':退回供应商初选';
  13862. }
  13863. Db::table('purchase_order')
  13864. ->where('scydgy_id', 'in', array_keys($sids))
  13865. ->update([
  13866. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  13867. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  13868. 'pick_company_name' => '',
  13869. 'pick_time' => null,
  13870. 'sys_rq' => null,
  13871. 'mod_rq' => null,
  13872. 'manual_pick' => 0,
  13873. 'manual_pick_reason' => '',
  13874. ]);
  13875. // 重新下发后需重新开标;清掉本批按订单号/批次号记录的开标验证
  13876. $ccydhSet = [];
  13877. $batchSet = [];
  13878. $cgySet = [];
  13879. foreach ($pos as $poRow) {
  13880. if (!is_array($poRow)) {
  13881. continue;
  13882. }
  13883. foreach ($this->expandProcuremenCcydhTokens($poRow['CCYDH'] ?? '') as $dh) {
  13884. $ccydhSet[$dh] = true;
  13885. }
  13886. $bn = $this->resolveProcuremenOrderBatchNo($poRow);
  13887. if ($bn !== '') {
  13888. $batchSet[$bn] = true;
  13889. }
  13890. $cgy = trim((string)($poRow['CGYMC'] ?? ''));
  13891. if ($cgy !== '') {
  13892. $cgySet[$cgy] = true;
  13893. }
  13894. }
  13895. $this->clearProcuremenBidOpenRecords(array_keys($ccydhSet), array_keys($batchSet));
  13896. $this->clearProcuremenSupplierScoresForCcydhs(array_keys($ccydhSet));
  13897. // 同订单其它旧批次(有明确批次号、未完结)软删除,避免列表/弹窗仍读到旧批「已开标/已指定」
  13898. $keepBatch = '';
  13899. if ($batchSet !== []) {
  13900. $batchKeys = array_keys($batchSet);
  13901. $keepBatch = (string)reset($batchKeys);
  13902. }
  13903. // 返回被软删的旧批次 scydgy_id,用于废弃其明细
  13904. $voidedSids = $this->softDeleteOtherBatchPurchaseOrders(array_keys($ccydhSet), array_keys($sids), $keepBatch, array_keys($cgySet));
  13905. // 废弃本批次新工序的明细(重新下发后重新招标)
  13906. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  13907. // 废弃被软删旧批次的明细(防止卡在"已提交"状态)
  13908. if ($voidedSids !== []) {
  13909. $this->voidPurchaseOrderDetailsForScydgyIds($voidedSids);
  13910. // 旧批次被重新下发流程软删,记录日志便于追溯
  13911. foreach ($voidedSids as $oldSid) {
  13912. $oldSidInt = (int)$oldSid;
  13913. if ($this->isValidScydgyRowId($oldSidInt)) {
  13914. $this->addOrderLog($oldSidInt, $logAction, '重新下发:同批次工序旧数据软删', null);
  13915. }
  13916. }
  13917. }
  13918. foreach (array_keys($sids) as $sid) {
  13919. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  13920. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  13921. }
  13922. return $sids;
  13923. }
  13924. /**
  13925. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  13926. *
  13927. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  13928. */
  13929. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  13930. {
  13931. $scydgyId = trim($scydgyId);
  13932. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  13933. if ($scydgyId === '') {
  13934. return $empty;
  13935. }
  13936. try {
  13937. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  13938. } catch (\Throwable $e) {
  13939. $anchor = null;
  13940. }
  13941. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  13942. return $empty;
  13943. }
  13944. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  13945. if ($ccydh === '') {
  13946. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  13947. }
  13948. try {
  13949. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  13950. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  13951. $pos = $query->order('scydgy_id', 'asc')->select();
  13952. } catch (\Throwable $e) {
  13953. $pos = [$anchor];
  13954. }
  13955. if (!is_array($pos) || $pos === []) {
  13956. $pos = [$anchor];
  13957. }
  13958. return [
  13959. 'ccydh' => $ccydh,
  13960. 'pos' => $pos,
  13961. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  13962. ];
  13963. }
  13964. protected function purchaseOrderRowIsCompleted(array $po): bool
  13965. {
  13966. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  13967. }
  13968. /**
  13969. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  13970. *
  13971. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  13972. */
  13973. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  13974. {
  13975. $scydgyId = trim($scydgyId);
  13976. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  13977. if ($scydgyId === '') {
  13978. return $empty;
  13979. }
  13980. try {
  13981. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  13982. } catch (\Throwable $e) {
  13983. $anchor = null;
  13984. }
  13985. if (!is_array($anchor)) {
  13986. return $empty;
  13987. }
  13988. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  13989. if ($ccydh === '') {
  13990. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  13991. }
  13992. try {
  13993. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  13994. } catch (\Throwable $e) {
  13995. $pos = [$anchor];
  13996. }
  13997. if (!is_array($pos) || $pos === []) {
  13998. $pos = [$anchor];
  13999. }
  14000. $pos = $this->filterPurchaseOrdersSameIssueBatch($pos, $anchor);
  14001. return [
  14002. 'ccydh' => $ccydh,
  14003. 'pos' => $pos,
  14004. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  14005. ];
  14006. }
  14007. /**
  14008. * 废弃订单 — 退回供应商初选重新询价(支持单条或批量)
  14009. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  14010. */
  14011. public function auditAbandon()
  14012. {
  14013. if (!$this->request->isPost()) {
  14014. $this->error(__('Invalid parameters'));
  14015. }
  14016. $anchorIds = [];
  14017. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  14018. if ($batchRaw !== '') {
  14019. $decoded = json_decode($batchRaw, true);
  14020. if (is_array($decoded)) {
  14021. foreach ($decoded as $id) {
  14022. $s = trim((string)$id);
  14023. if ($s !== '') {
  14024. $anchorIds[] = $s;
  14025. }
  14026. }
  14027. }
  14028. }
  14029. if ($anchorIds === []) {
  14030. $single = trim((string)$this->request->post('scydgy_id', ''));
  14031. if ($single !== '') {
  14032. $anchorIds[] = $single;
  14033. }
  14034. }
  14035. if ($anchorIds === []) {
  14036. $this->error('请至少选择一条订单');
  14037. }
  14038. $processedCcydh = [];
  14039. $doneOrders = 0;
  14040. $allSids = [];
  14041. Db::startTrans();
  14042. try {
  14043. foreach ($anchorIds as $anchorId) {
  14044. $fromArchive = false;
  14045. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  14046. if (($bundle['pos'] ?? []) === []) {
  14047. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  14048. $fromArchive = ($bundle['pos'] ?? []) !== [];
  14049. }
  14050. if (($bundle['pos'] ?? []) === []) {
  14051. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  14052. $fromArchive = ($bundle['pos'] ?? []) !== [];
  14053. }
  14054. if (($bundle['pos'] ?? []) === []) {
  14055. continue;
  14056. }
  14057. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  14058. $batchTime = '';
  14059. if (!empty($bundle['pos'][0]) && is_array($bundle['pos'][0])) {
  14060. $batchTime = $this->procuremenIssueBatchTime($bundle['pos'][0]);
  14061. }
  14062. $dedupeKey = $ccydh !== '' ? ($ccydh . '|' . $batchTime) : ('sid:' . $anchorId);
  14063. if (isset($processedCcydh[$dedupeKey])) {
  14064. continue;
  14065. }
  14066. $processedCcydh[$dedupeKey] = true;
  14067. $sids = $fromArchive
  14068. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回供应商初选')
  14069. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  14070. if ($sids === []) {
  14071. continue;
  14072. }
  14073. $doneOrders++;
  14074. foreach (array_keys($sids) as $sid) {
  14075. $allSids[(int)$sid] = true;
  14076. }
  14077. }
  14078. if ($doneOrders < 1) {
  14079. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  14080. }
  14081. Db::commit();
  14082. } catch (\Throwable $e) {
  14083. Db::rollback();
  14084. $this->error($e->getMessage());
  14085. }
  14086. $this->pickHiddenScydgySetCache = null;
  14087. $msg = $doneOrders > 1
  14088. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回供应商初选,历史下发与操作记录已保留')
  14089. : '已退回供应商初选,请重新选择供应商下发(历史记录已保留)';
  14090. $this->success($msg);
  14091. }
  14092. /**
  14093. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  14094. */
  14095. public function archiveAbandon()
  14096. {
  14097. return $this->auditAbandon();
  14098. }
  14099. /**
  14100. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  14101. */
  14102. public function purchaseApprovalReject()
  14103. {
  14104. if (!$this->request->isPost() || !$this->request->isAjax()) {
  14105. $this->error(__('Invalid parameters'));
  14106. }
  14107. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  14108. $this->error(__('You have no permission'));
  14109. }
  14110. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  14111. $decoded = json_decode($batchRaw, true);
  14112. if (!is_array($decoded) || $decoded === []) {
  14113. $this->error('提交数据无效');
  14114. }
  14115. $done = 0;
  14116. Db::startTrans();
  14117. try {
  14118. foreach ($decoded as $item) {
  14119. if (!is_array($item)) {
  14120. continue;
  14121. }
  14122. $sid = (int)($item['scydgy_id'] ?? 0);
  14123. if (!$this->isValidScydgyRowId($sid)) {
  14124. continue;
  14125. }
  14126. $this->runPurchaseApprovalRejectForSid($sid);
  14127. $done++;
  14128. }
  14129. if ($done < 1) {
  14130. throw new \Exception('所选订单均不在待审批状态');
  14131. }
  14132. Db::commit();
  14133. } catch (\Throwable $e) {
  14134. Db::rollback();
  14135. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  14136. }
  14137. $this->pickHiddenScydgySetCache = null;
  14138. $this->success('已驳回并退回「确认供应商」');
  14139. }
  14140. /**
  14141. * @throws \Exception
  14142. */
  14143. protected function runPurchaseApprovalRejectForSid(int $sid): void
  14144. {
  14145. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  14146. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  14147. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  14148. $allIds = $this->purchaseOrderDetail($sid);
  14149. if ($allIds === []) {
  14150. throw new \Exception('未找到下发明细');
  14151. }
  14152. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  14153. 'wflow_status' => ProcuremenStatus::WFLOW_REJECTED,
  14154. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  14155. 'pick_company_name' => '',
  14156. ]);
  14157. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  14158. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  14159. $poId = 0;
  14160. try {
  14161. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  14162. if (is_array($po)) {
  14163. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  14164. }
  14165. } catch (\Throwable $e) {
  14166. }
  14167. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  14168. }
  14169. /**
  14170. * 审核弹窗(旧入口,POST 已关闭)
  14171. */
  14172. public function review()
  14173. {
  14174. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  14175. $this->error(__('You have no permission'));
  14176. }
  14177. if ($this->request->isPost()) {
  14178. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  14179. }
  14180. $this->view->assign('pickMode', 0);
  14181. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  14182. }
  14183. /**
  14184. * 审核弹窗获取公司列表
  14185. */
  14186. public function reviewCompanies()
  14187. {
  14188. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  14189. $this->error(__('You have no permission'));
  14190. }
  14191. if (!$this->request->isAjax()) {
  14192. $this->error(__('Invalid parameters'));
  14193. }
  14194. $list = [];
  14195. try {
  14196. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  14197. $rows = Db::table('customer')
  14198. ->where(function ($q) {
  14199. $q->where('status', 1)
  14200. ->whereOr('status', '1')
  14201. ->whereOr('status', '')
  14202. ->whereNull('status');
  14203. })
  14204. ->order('id', 'desc')
  14205. ->select();
  14206. } catch (\Throwable $e) {
  14207. $this->success('', '', []);
  14208. return;
  14209. }
  14210. if (!is_array($rows)) {
  14211. $this->success('', '', []);
  14212. return;
  14213. }
  14214. $detailColCandidates = [
  14215. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  14216. 'company_detail', 'company_desc', 'address',
  14217. ];
  14218. foreach ($rows as $row) {
  14219. if (!is_array($row)) {
  14220. continue;
  14221. }
  14222. $norm = [];
  14223. foreach ($row as $k => $v) {
  14224. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  14225. }
  14226. $row = $norm;
  14227. $st = $row['status'] ?? '';
  14228. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  14229. continue;
  14230. }
  14231. $payload = $this->buildCustomerContactPayloadFromRow($row, false);
  14232. if ($payload === null) {
  14233. continue;
  14234. }
  14235. $detail = '';
  14236. foreach ($detailColCandidates as $dk) {
  14237. if (!isset($row[$dk])) {
  14238. continue;
  14239. }
  14240. $dv = trim((string)$row[$dk]);
  14241. if ($dv !== '') {
  14242. $detail = $dv;
  14243. break;
  14244. }
  14245. }
  14246. $payload['detail'] = $detail;
  14247. $list[] = $this->maskSupplierContactFields($payload);
  14248. }
  14249. $this->success('', '', $list);
  14250. }
  14251. /**
  14252. * 采购确认-下发明细弹窗:
  14253. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  14254. */
  14255. public function outward_detail()
  14256. {
  14257. $ids = $this->request->param('ids', $this->request->param('id', ''));
  14258. if (is_array($ids)) {
  14259. $ids = isset($ids[0]) ? $ids[0] : '';
  14260. }
  14261. $ids = trim((string)$ids);
  14262. if ($ids === '') {
  14263. $this->error(__('Invalid parameters'));
  14264. }
  14265. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  14266. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  14267. $wffTab = 'all';
  14268. }
  14269. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  14270. $purchaseOrderId = 0;
  14271. $po = null;
  14272. try {
  14273. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  14274. if (is_array($po)) {
  14275. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  14276. }
  14277. } catch (\Throwable $e) {
  14278. $purchaseOrderId = 0;
  14279. $po = null;
  14280. }
  14281. if (!$isPurchaseConfirm && is_array($po)) {
  14282. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  14283. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  14284. $isPurchaseConfirm = true;
  14285. }
  14286. }
  14287. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  14288. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  14289. $confirmProcessCount = 1;
  14290. $confirmPickGroups = [];
  14291. $processDisplayRows = [];
  14292. $allDetailsBySid = [];
  14293. $requiredSidList = [];
  14294. $sidList = [$ids];
  14295. if ($isPurchaseConfirm) {
  14296. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  14297. if (!$this->canViewProcuremenSupplierQuotesForBundle($confirmBundle)) {
  14298. $this->error('本单尚未开标或指定供应商,不能审批');
  14299. }
  14300. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  14301. if ($mergeRows !== []) {
  14302. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  14303. }
  14304. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  14305. if ($confirmBundle['pos'] !== []) {
  14306. $sidList = [];
  14307. foreach ($confirmBundle['pos'] as $poRow) {
  14308. if (!is_array($poRow)) {
  14309. continue;
  14310. }
  14311. $sid = (int)($poRow['scydgy_id'] ?? 0);
  14312. if (!$this->isValidScydgyRowId($sid)) {
  14313. continue;
  14314. }
  14315. $sidList[] = (string)$sid;
  14316. $requiredSidList[] = $sid;
  14317. }
  14318. }
  14319. if ($sidList === []) {
  14320. $sidList = [$ids];
  14321. $requiredSidList = [(int)$ids];
  14322. }
  14323. $confirmProcessCount = max(1, count($requiredSidList));
  14324. if (is_array($po) && $purchaseOrderId <= 0) {
  14325. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  14326. }
  14327. }
  14328. $rows = [];
  14329. try {
  14330. if (count($sidList) === 1) {
  14331. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  14332. } else {
  14333. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  14334. }
  14335. } catch (\Throwable $e) {
  14336. $rows = [];
  14337. }
  14338. if ($isPurchaseConfirm) {
  14339. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  14340. }
  14341. foreach ($rows as &$r) {
  14342. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  14343. $r['id'] = $r['ID'];
  14344. }
  14345. if (isset($r['createtime'])) {
  14346. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  14347. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  14348. } else {
  14349. $r['createtime_text'] = (string)$r['createtime'];
  14350. }
  14351. } else {
  14352. $r['createtime_text'] = '';
  14353. }
  14354. if (is_array($r)) {
  14355. $r = $this->maskSupplierContactFields($r);
  14356. }
  14357. }
  14358. unset($r);
  14359. $pickedCompanyName = '';
  14360. $manualPicked = 0;
  14361. $manualPickReason = '';
  14362. $quoteVisible = 0;
  14363. $bidOpenVerified = 0;
  14364. if ($isPurchaseConfirm) {
  14365. // 确认包为空时,用当前主单兜底,避免指定说明读不到
  14366. if (($confirmBundle['ccydh'] ?? '') === '' && is_array($po)) {
  14367. $confirmBundle['ccydh'] = trim((string)($po['CCYDH'] ?? ''));
  14368. }
  14369. if (($confirmBundle['pos'] ?? []) === [] && is_array($po)) {
  14370. $confirmBundle['pos'] = [$po];
  14371. }
  14372. $manualPickInfo = $this->resolveProcuremenManualPickInfo($confirmBundle);
  14373. $manualPicked = $this->isProcuremenManualPickedForBundle($confirmBundle) ? 1 : 0;
  14374. $manualPickReason = (string)($manualPickInfo['reason'] ?? '');
  14375. if ($manualPickInfo['company'] !== '') {
  14376. $pickedCompanyName = $manualPickInfo['company'];
  14377. }
  14378. if ($pickedCompanyName === '') {
  14379. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  14380. if (!is_array($poRow)) {
  14381. continue;
  14382. }
  14383. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  14384. if ($pn !== '') {
  14385. $pickedCompanyName = $pn;
  14386. break;
  14387. }
  14388. }
  14389. }
  14390. // 再兜底:直接读当前主单字段
  14391. if (is_array($po) && (int)($po['manual_pick'] ?? 0) === 1) {
  14392. $manualPicked = 1;
  14393. if ($manualPickReason === '') {
  14394. $manualPickReason = trim((string)($po['manual_pick_reason'] ?? ''));
  14395. }
  14396. if ($pickedCompanyName === '') {
  14397. $pickedCompanyName = trim((string)($po['pick_company_name'] ?? ''));
  14398. }
  14399. }
  14400. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle) ? 1 : 0;
  14401. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  14402. }
  14403. $this->view->assign('rows', $rows ?: []);
  14404. $this->view->assign('rowCount', count($rows ?: []));
  14405. $this->view->assign('scydgyId', $ids);
  14406. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  14407. $this->view->assign('headTitle', $headTitle);
  14408. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  14409. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  14410. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  14411. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  14412. $this->view->assign('orderBatchNo', $this->resolveBundleOrderBatchNo($confirmBundle));
  14413. $this->view->assign('processDisplayRows', $processDisplayRows);
  14414. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  14415. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  14416. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  14417. $this->view->assign('manualPicked', $manualPicked);
  14418. $this->view->assign('manualPickReason', $manualPickReason);
  14419. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  14420. $this->view->assign('quoteVisible', $quoteVisible);
  14421. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
  14422. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  14423. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
  14424. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
  14425. $sysRqDisplay = '—';
  14426. if ($isPurchaseConfirm) {
  14427. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  14428. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  14429. );
  14430. }
  14431. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  14432. $this->view->assign('sysRq', $isPurchaseConfirm
  14433. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  14434. : '');
  14435. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  14436. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  14437. : '');
  14438. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  14439. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  14440. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  14441. if ($isPurchaseConfirm) {
  14442. return $this->view->fetch();
  14443. }
  14444. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  14445. $this->view->engine->layout(false);
  14446. try {
  14447. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  14448. $this->view->assign('dialogBody', $bodyHtml);
  14449. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  14450. } finally {
  14451. if ($restoreLayout) {
  14452. $this->view->engine->layout($restoreLayout);
  14453. }
  14454. }
  14455. }
  14456. /**
  14457. * 月度导出记录表(不存在时自动创建)
  14458. */
  14459. protected function ensurePurchaseMonthExportLogTable(): void
  14460. {
  14461. try {
  14462. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  14463. } catch (\Throwable $e) {
  14464. Db::execute(
  14465. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  14466. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  14467. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  14468. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  14469. `admin_name` varchar(64) NOT NULL DEFAULT '',
  14470. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  14471. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  14472. `createtime` int(10) unsigned DEFAULT NULL,
  14473. PRIMARY KEY (`id`),
  14474. KEY `idx_ym` (`ym`),
  14475. KEY `idx_ct` (`createtime`)
  14476. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  14477. );
  14478. }
  14479. }
  14480. /**
  14481. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  14482. *
  14483. * @param array<int, mixed> $dbRows
  14484. * @return array<int, array<string, mixed>>
  14485. */
  14486. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  14487. {
  14488. $keyword = trim((string)$this->request->get('search', ''));
  14489. if ($keyword === '') {
  14490. $keyword = trim((string)$this->request->request('search', ''));
  14491. }
  14492. $filter = $this->request->get('filter', '');
  14493. $op = $this->request->get('op', '');
  14494. if (is_string($filter) && $filter !== '') {
  14495. $filterArr = (array)json_decode($filter, true);
  14496. } else {
  14497. $filterArr = is_array($filter) ? $filter : [];
  14498. }
  14499. if (is_string($op) && $op !== '') {
  14500. $opArr = (array)json_decode($op, true);
  14501. } else {
  14502. $opArr = is_array($op) ? $op : [];
  14503. }
  14504. if ($keyword === '' && $filterArr === []) {
  14505. return array_values(array_filter($dbRows, 'is_array'));
  14506. }
  14507. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  14508. $out = [];
  14509. foreach ($dbRows as $row) {
  14510. if (!is_array($row)) {
  14511. continue;
  14512. }
  14513. if ($keyword !== '') {
  14514. $hit = false;
  14515. foreach ($searchFields as $f) {
  14516. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  14517. $hit = true;
  14518. break;
  14519. }
  14520. }
  14521. if (!$hit) {
  14522. continue;
  14523. }
  14524. }
  14525. $passFilter = true;
  14526. foreach ($filterArr as $field => $val) {
  14527. $field = (string)$field;
  14528. $val = trim((string)$val);
  14529. if ($field === '' || $val === '') {
  14530. continue;
  14531. }
  14532. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  14533. continue;
  14534. }
  14535. $cell = (string)($row[$field] ?? '');
  14536. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  14537. if ($mode === '=' || $mode === 'EQUAL') {
  14538. if (strcasecmp($cell, $val) !== 0) {
  14539. $passFilter = false;
  14540. break;
  14541. }
  14542. } elseif (mb_stripos($cell, $val) === false) {
  14543. $passFilter = false;
  14544. break;
  14545. }
  14546. }
  14547. if (!$passFilter) {
  14548. continue;
  14549. }
  14550. $out[] = $row;
  14551. }
  14552. return $out;
  14553. }
  14554. /**
  14555. * 按月份导出:审批通过订单(与月度列表一致),按审批月份筛选。
  14556. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  14557. */
  14558. public function export_month_outward()
  14559. {
  14560. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  14561. $this->error(__('You have no permission'));
  14562. }
  14563. $bundle = $this->prepareMonthOutwardExportBundle();
  14564. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  14565. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  14566. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  14567. $spreadsheet = new Spreadsheet();
  14568. $sheet = $spreadsheet->getActiveSheet();
  14569. $sheet->setTitle('外协加工明细');
  14570. $mon = (int)substr($ym, 5, 2);
  14571. $sheet->mergeCells('A1:H1');
  14572. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  14573. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  14574. $sheet->getStyle('A1')->getAlignment()
  14575. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  14576. ->setVertical(Alignment::VERTICAL_CENTER);
  14577. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  14578. $col = 'A';
  14579. foreach ($headers as $h) {
  14580. $sheet->setCellValue($col . '2', $h);
  14581. $col++;
  14582. }
  14583. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  14584. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  14585. $rowNum = 3;
  14586. $sumSubtotalCounts = 0;
  14587. $grandAmount = 0.0;
  14588. $globalSeq = 0;
  14589. if ($groups === []) {
  14590. $sheet->mergeCells('A3:H3');
  14591. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  14592. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  14593. $rowNum = 4;
  14594. } else {
  14595. foreach ($groups as $items) {
  14596. if ($items === []) {
  14597. continue;
  14598. }
  14599. $groupLineCount = count($items);
  14600. $subAmount = 0.0;
  14601. foreach ($items as $line) {
  14602. $globalSeq++;
  14603. $dr = $line['detail'];
  14604. $amt = $this->procuremenExportAmount($dr);
  14605. $subAmount += $amt;
  14606. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  14607. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  14608. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  14609. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  14610. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  14611. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  14612. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  14613. $sheet->setCellValue('H' . $rowNum, $amt);
  14614. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  14615. $rowNum++;
  14616. }
  14617. $sumSubtotalCounts += $groupLineCount;
  14618. $grandAmount += $subAmount;
  14619. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  14620. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  14621. $sheet->getStyle('G' . $rowNum)->getAlignment()
  14622. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  14623. ->setVertical(Alignment::VERTICAL_CENTER);
  14624. $rowNum++;
  14625. }
  14626. }
  14627. $sheet->setCellValue('A' . $rowNum, '总计');
  14628. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  14629. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  14630. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  14631. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  14632. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  14633. $lastRow = $rowNum;
  14634. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  14635. 'borders' => [
  14636. 'allBorders' => [
  14637. 'borderStyle' => Border::BORDER_THIN,
  14638. 'color' => ['rgb' => '000000'],
  14639. ],
  14640. ],
  14641. ]);
  14642. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  14643. if ($lastRow >= 3) {
  14644. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14645. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14646. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14647. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14648. }
  14649. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  14650. $sheet->getColumnDimension('A')->setWidth(7);
  14651. $sheet->getColumnDimension('B')->setWidth(16);
  14652. $sheet->getColumnDimension('C')->setWidth(52);
  14653. $sheet->getColumnDimension('D')->setWidth(32);
  14654. $sheet->getColumnDimension('E')->setWidth(12);
  14655. $sheet->getColumnDimension('F')->setWidth(44);
  14656. $sheet->getColumnDimension('G')->setWidth(26);
  14657. $sheet->getColumnDimension('H')->setWidth(13);
  14658. $sheet->getRowDimension(1)->setRowHeight(28);
  14659. $ymCompact = str_replace('-', '', $ym);
  14660. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  14661. $filename = $fileBase . '.xlsx';
  14662. try {
  14663. $this->ensurePurchaseMonthExportLogTable();
  14664. list($adminId, $adminName) = $this->GetUseName();
  14665. Db::table('purchase_month_export_log')->insert([
  14666. 'ym' => $ym,
  14667. 'admin_id' => (int)$adminId,
  14668. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  14669. 'row_count' => count($exportLines),
  14670. 'total_amount' => round($grandAmount, 2),
  14671. 'createtime' => time(),
  14672. ]);
  14673. } catch (\Throwable $e) {
  14674. Log::write('month export log: ' . $e->getMessage(), 'error');
  14675. }
  14676. if (ob_get_length()) {
  14677. ob_end_clean();
  14678. }
  14679. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  14680. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  14681. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  14682. header('Cache-Control: max-age=0');
  14683. $writer = new Xlsx($spreadsheet);
  14684. $writer->save('php://output');
  14685. $spreadsheet->disconnectWorksheets();
  14686. unset($spreadsheet);
  14687. exit;
  14688. }
  14689. /**
  14690. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  14691. */
  14692. public function export_month_quote()
  14693. {
  14694. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  14695. $this->error(__('You have no permission'));
  14696. }
  14697. $bundle = $this->prepareMonthOutwardExportBundle();
  14698. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  14699. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  14700. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  14701. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  14702. $spreadsheet = new Spreadsheet();
  14703. $sheet = $spreadsheet->getActiveSheet();
  14704. $sheet->setTitle('供应商报价明细');
  14705. $mon = (int)substr($ym, 5, 2);
  14706. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  14707. $sheet->getColumnDimension('A')->setWidth(7);
  14708. $sheet->getColumnDimension('B')->setWidth(16);
  14709. $sheet->getColumnDimension('C')->setWidth(52);
  14710. $sheet->getColumnDimension('D')->setWidth(26);
  14711. $sheet->getColumnDimension('E')->setWidth(32);
  14712. $sheet->getColumnDimension('F')->setWidth(12);
  14713. $sheet->getColumnDimension('G')->setWidth(14);
  14714. $sheet->getColumnDimension('H')->setWidth(12);
  14715. if ($quoteLastRow < 1) {
  14716. $quoteLastRow = 3;
  14717. }
  14718. $ymCompact = str_replace('-', '', $ym);
  14719. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  14720. if (ob_get_length()) {
  14721. ob_end_clean();
  14722. }
  14723. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  14724. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  14725. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  14726. header('Cache-Control: max-age=0');
  14727. $writer = new Xlsx($spreadsheet);
  14728. $writer->save('php://output');
  14729. $spreadsheet->disconnectWorksheets();
  14730. unset($spreadsheet);
  14731. exit;
  14732. }
  14733. /**
  14734. * 月度导出公共数据:审批通过订单按月份/搜索筛选后的主表与明细(不要求已完结)
  14735. *
  14736. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  14737. */
  14738. protected function prepareMonthOutwardExportBundle(): array
  14739. {
  14740. $this->request->filter(['strip_tags', 'trim']);
  14741. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  14742. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  14743. $ym = date('Y-m');
  14744. }
  14745. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  14746. $softDel = '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')';
  14747. $dbRows = [];
  14748. try {
  14749. $dbRows = Db::table('purchase_order')
  14750. ->where('wflow_status', 'in', $approvedVals)
  14751. ->whereRaw($softDel)
  14752. ->select();
  14753. } catch (\Throwable $e) {
  14754. $dbRows = [];
  14755. }
  14756. if (!is_array($dbRows)) {
  14757. $dbRows = [];
  14758. }
  14759. $completeTsMap = [];
  14760. $sidList = [];
  14761. foreach ($dbRows as $dbRow) {
  14762. if (!is_array($dbRow)) {
  14763. continue;
  14764. }
  14765. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  14766. if ($sid > 0) {
  14767. $sidList[$sid] = true;
  14768. }
  14769. }
  14770. if ($sidList !== []) {
  14771. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  14772. }
  14773. // 导出按「查看月份」取当月审批通过单;搜索只在当月内再缩小
  14774. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  14775. if (!is_array($dbRow)) {
  14776. return false;
  14777. }
  14778. if (!ProcuremenStatus::isWflowApproved($dbRow['wflow_status'] ?? '')) {
  14779. return false;
  14780. }
  14781. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  14782. if ($done['ts'] <= 0) {
  14783. return false;
  14784. }
  14785. return date('Y-m', $done['ts']) === $ym;
  14786. }));
  14787. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  14788. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  14789. $mainBySid = [];
  14790. foreach ($pool as $rw) {
  14791. if (!is_array($rw)) {
  14792. continue;
  14793. }
  14794. $rid = (int)($rw['ID'] ?? 0);
  14795. if ($rid > 0) {
  14796. $mainBySid[$rid] = $rw;
  14797. }
  14798. }
  14799. if ($mainBySid === []) {
  14800. $detailRows = [];
  14801. } else {
  14802. try {
  14803. $detailRows = Db::table('purchase_order_detail')
  14804. ->where('scydgy_id', 'in', array_keys($mainBySid))
  14805. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  14806. ->order('status', 'desc')
  14807. ->order('CCYDH', 'asc')
  14808. ->order('company_name', 'asc')
  14809. ->order('id', 'asc')
  14810. ->select();
  14811. } catch (\Throwable $e) {
  14812. try {
  14813. $detailRows = Db::table('purchase_order_detail')
  14814. ->where('scydgy_id', 'in', array_keys($mainBySid))
  14815. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  14816. ->order('status', 'desc')
  14817. ->order('CCYDH', 'asc')
  14818. ->order('company_name', 'asc')
  14819. ->order('ID', 'asc')
  14820. ->select();
  14821. } catch (\Throwable $e2) {
  14822. $detailRows = [];
  14823. }
  14824. }
  14825. }
  14826. if (!is_array($detailRows)) {
  14827. $detailRows = [];
  14828. }
  14829. $exportLines = [];
  14830. $detailSidSeen = [];
  14831. foreach ($detailRows as $dr) {
  14832. if (!is_array($dr)) {
  14833. continue;
  14834. }
  14835. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  14836. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  14837. continue;
  14838. }
  14839. if (isset($detailSidSeen[$sid])) {
  14840. continue;
  14841. }
  14842. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  14843. continue;
  14844. }
  14845. $detailSidSeen[$sid] = true;
  14846. $m = $mainBySid[$sid];
  14847. $company = trim((string)($m['pick_company_name'] ?? ''));
  14848. if ($company === '') {
  14849. $company = trim((string)($dr['company_name'] ?? ''));
  14850. }
  14851. $exportLines[] = [
  14852. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  14853. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  14854. 'company_name' => $company,
  14855. 'CDF' => (string)($m['CDF'] ?? ''),
  14856. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  14857. 'gx' => $this->procuremenExportGxText($m),
  14858. 'detail' => $dr,
  14859. ];
  14860. }
  14861. foreach ($detailRows as $dr) {
  14862. if (!is_array($dr)) {
  14863. continue;
  14864. }
  14865. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  14866. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  14867. continue;
  14868. }
  14869. $detailSidSeen[$sid] = true;
  14870. $m = $mainBySid[$sid];
  14871. $company = trim((string)($m['pick_company_name'] ?? ''));
  14872. if ($company === '') {
  14873. $company = trim((string)($dr['company_name'] ?? ''));
  14874. }
  14875. $exportLines[] = [
  14876. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  14877. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  14878. 'company_name' => $company,
  14879. 'CDF' => (string)($m['CDF'] ?? ''),
  14880. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  14881. 'gx' => $this->procuremenExportGxText($m),
  14882. 'detail' => $dr,
  14883. ];
  14884. }
  14885. foreach ($mainBySid as $sid => $m) {
  14886. if (isset($detailSidSeen[$sid])) {
  14887. continue;
  14888. }
  14889. $company = trim((string)($m['pick_company_name'] ?? ''));
  14890. $exportLines[] = [
  14891. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  14892. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  14893. 'company_name' => $company,
  14894. 'CDF' => (string)($m['CDF'] ?? ''),
  14895. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  14896. 'gx' => $this->procuremenExportGxText($m),
  14897. 'detail' => [],
  14898. ];
  14899. }
  14900. $groups = [];
  14901. foreach ($exportLines as $line) {
  14902. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  14903. if (!isset($groups[$k])) {
  14904. $groups[$k] = [];
  14905. }
  14906. $groups[$k][] = $line;
  14907. }
  14908. ksort($groups, SORT_STRING);
  14909. return [
  14910. 'ym' => $ym,
  14911. 'mainBySid' => $mainBySid,
  14912. 'detailRows' => $detailRows,
  14913. 'exportLines' => $exportLines,
  14914. 'groups' => $groups,
  14915. ];
  14916. }
  14917. /**
  14918. * 导出用:工序列文案
  14919. */
  14920. protected function procuremenExportGxText(array $r)
  14921. {
  14922. return ProcuremenFormat::exportGxText($r);
  14923. }
  14924. /**
  14925. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  14926. */
  14927. protected function procuremenExportAmount(array $r)
  14928. {
  14929. return ProcuremenFormat::exportAmount($r);
  14930. }
  14931. /**
  14932. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  14933. *
  14934. * @param array<int, array<string, mixed>> $detailRows
  14935. * @param array<int, array<string, mixed>> $mainBySid
  14936. * @return array<int, array<string, mixed>>
  14937. */
  14938. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  14939. {
  14940. $lines = [];
  14941. foreach ($detailRows as $dr) {
  14942. if (!is_array($dr)) {
  14943. continue;
  14944. }
  14945. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  14946. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  14947. continue;
  14948. }
  14949. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  14950. continue;
  14951. }
  14952. $cn = trim((string)($dr['company_name'] ?? ''));
  14953. if ($cn === '') {
  14954. continue;
  14955. }
  14956. $m = $mainBySid[$sid];
  14957. $am = trim((string)($dr['amount'] ?? ''));
  14958. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  14959. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  14960. $amountText = $amountFilled
  14961. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  14962. : '未填写';
  14963. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  14964. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  14965. if ($deliveryShow === '' && $deliveryRaw !== '') {
  14966. $deliveryShow = $deliveryRaw;
  14967. }
  14968. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  14969. ? $deliveryShow
  14970. : '未填写';
  14971. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  14972. $lines[] = [
  14973. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  14974. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  14975. 'gx' => $this->procuremenExportGxText($m),
  14976. 'company_name' => $cn,
  14977. 'amount_text' => $amountText,
  14978. 'amount_num' => $amountFilled ? $amountNum : null,
  14979. 'delivery_text' => $deliveryText,
  14980. 'picked_text' => $picked ? '中标' : '未中标',
  14981. 'picked' => $picked,
  14982. ];
  14983. }
  14984. $winnerSupplierByOrder = [];
  14985. foreach ($lines as $line) {
  14986. $dh = trim((string)($line['CCYDH'] ?? ''));
  14987. $cn = trim((string)($line['company_name'] ?? ''));
  14988. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  14989. $winnerSupplierByOrder[$dh][$cn] = true;
  14990. }
  14991. }
  14992. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  14993. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  14994. if ($c !== 0) {
  14995. return $c;
  14996. }
  14997. $dh = trim((string)($a['CCYDH'] ?? ''));
  14998. $aCn = trim((string)($a['company_name'] ?? ''));
  14999. $bCn = trim((string)($b['company_name'] ?? ''));
  15000. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  15001. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  15002. if ($aSupplierWin !== $bSupplierWin) {
  15003. return $aSupplierWin ? -1 : 1;
  15004. }
  15005. $c = strcmp($aCn, $bCn);
  15006. if ($c !== 0) {
  15007. return $c;
  15008. }
  15009. if (!empty($a['picked']) !== !empty($b['picked'])) {
  15010. return !empty($a['picked']) ? -1 : 1;
  15011. }
  15012. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  15013. if ($c !== 0) {
  15014. return $c;
  15015. }
  15016. return 0;
  15017. });
  15018. return $lines;
  15019. }
  15020. /**
  15021. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  15022. *
  15023. * @param array<int, array<string, mixed>> $quoteLines
  15024. */
  15025. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  15026. {
  15027. $mon = (int)substr($ym, 5, 2);
  15028. $titleRow = $startRow;
  15029. $headerRow = $startRow + 1;
  15030. $dataStartRow = $startRow + 2;
  15031. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  15032. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  15033. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  15034. $sheet->getStyle('A' . $titleRow)->getAlignment()
  15035. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  15036. ->setVertical(Alignment::VERTICAL_CENTER);
  15037. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  15038. $col = 'A';
  15039. foreach ($headers as $h) {
  15040. $sheet->setCellValue($col . $headerRow, $h);
  15041. $col++;
  15042. }
  15043. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  15044. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  15045. $rowNum = $dataStartRow;
  15046. if ($quoteLines === []) {
  15047. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  15048. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  15049. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  15050. $rowNum = $dataStartRow + 1;
  15051. } else {
  15052. $i = 0;
  15053. foreach ($quoteLines as $line) {
  15054. $i++;
  15055. $sheet->setCellValue('A' . $rowNum, $i);
  15056. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  15057. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  15058. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  15059. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  15060. if ($line['amount_num'] !== null) {
  15061. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  15062. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  15063. } else {
  15064. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  15065. }
  15066. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  15067. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  15068. if (!empty($line['picked'])) {
  15069. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  15070. }
  15071. $rowNum++;
  15072. }
  15073. }
  15074. $lastRow = $rowNum - 1;
  15075. if ($lastRow >= $headerRow) {
  15076. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  15077. 'borders' => [
  15078. 'allBorders' => [
  15079. 'borderStyle' => Border::BORDER_THIN,
  15080. 'color' => ['rgb' => '000000'],
  15081. ],
  15082. ],
  15083. ]);
  15084. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  15085. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  15086. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  15087. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  15088. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  15089. if ($lastRow >= $dataStartRow) {
  15090. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  15091. }
  15092. }
  15093. return $lastRow;
  15094. }
  15095. /**
  15096. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  15097. */
  15098. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  15099. {
  15100. if ($lastRow < $dataStartRow || $headerRow < 1) {
  15101. return;
  15102. }
  15103. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  15104. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  15105. ->setVertical(Alignment::VERTICAL_CENTER);
  15106. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  15107. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  15108. ->setVertical(Alignment::VERTICAL_CENTER);
  15109. if ($lastCol > 'B') {
  15110. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  15111. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  15112. ->setVertical(Alignment::VERTICAL_CENTER);
  15113. }
  15114. }
  15115. /**
  15116. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  15117. */
  15118. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  15119. {
  15120. return ProcuremenFormat::sanitizePdfOrderKey($ccydh);
  15121. }
  15122. /**
  15123. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  15124. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  15125. *
  15126. * @return array{objectKey: string, webPath: string}
  15127. */
  15128. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  15129. {
  15130. return ProcuremenFormat::buildConfirmPdfPaths($scydgyId, $ccydhRaw);
  15131. }
  15132. /**
  15133. * 采购确认成功后 / 已完结刷新:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  15134. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  15135. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  15136. * 说明:审批通过时会先存一版;质量+交货评分使订单「已完结」后,详情页打开或评分保存完成时会再重存,以含最终步骤与操作记录。
  15137. *
  15138. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  15139. */
  15140. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  15141. {
  15142. if (!$this->isValidScydgyRowId($scydgyId)) {
  15143. return '';
  15144. }
  15145. $ids = trim((string)$scydgyId);
  15146. $prep = $this->prepareProcuremenDetailsView($ids);
  15147. if (!$prep['ok']) {
  15148. return '';
  15149. }
  15150. $ccydh = $prep['ccydh'];
  15151. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  15152. $objectKey = $paths['objectKey'];
  15153. $webPath = $paths['webPath'];
  15154. $cyjmc = '';
  15155. try {
  15156. $poMeta = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->field('CYJMC')->find();
  15157. if (is_array($poMeta)) {
  15158. $cyjmc = trim((string)($poMeta['CYJMC'] ?? ''));
  15159. }
  15160. } catch (\Throwable $e) {
  15161. $cyjmc = '';
  15162. }
  15163. $genTime = date('Y-m-d H:i:s');
  15164. $metaIds = '工序行ID ' . $ids . ' | 主表订单ID ' . (int)$purchaseOrderId;
  15165. $metaLeft = $metaIds . ($cyjmc !== '' ? ' | ' . $cyjmc : '');
  15166. // PDF 进度:去掉「未发」;节点用纯色圆点(不用图片,避免 mPDF 破图)
  15167. $pdfSteps = [];
  15168. $viewSteps = $prep['steps'] ?? [];
  15169. if (is_array($viewSteps)) {
  15170. foreach ($viewSteps as $st) {
  15171. if (!is_array($st)) {
  15172. continue;
  15173. }
  15174. if (trim((string)($st['title'] ?? '')) === '未发') {
  15175. continue;
  15176. }
  15177. $pdfSteps[] = $st;
  15178. }
  15179. }
  15180. $pdfStepW = count($pdfSteps) > 0 ? (round(100 / count($pdfSteps), 2) . '%') : '16.66%';
  15181. $nPdf = count($pdfSteps);
  15182. foreach ($pdfSteps as $idx => &$pst) {
  15183. if ($idx === 0) {
  15184. $pst['pdf_left_bg'] = '';
  15185. } else {
  15186. $pst['pdf_left_bg'] = !empty($pdfSteps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  15187. }
  15188. if ($idx >= $nPdf - 1) {
  15189. $pst['pdf_right_bg'] = '';
  15190. } else {
  15191. $pst['pdf_right_bg'] = !empty($pst['done']) ? '#1890ff' : '#e0e0e0';
  15192. }
  15193. }
  15194. unset($pst);
  15195. $this->view->assign([
  15196. 'pdf_export' => 1,
  15197. 'pdfMetaLine' => $metaLeft,
  15198. 'pdfMetaLeft' => $metaLeft,
  15199. 'pdfMetaIds' => $metaIds,
  15200. 'pdfMetaTitle' => $cyjmc,
  15201. 'pdfMetaTime' => 'PDF生成时间 ' . $genTime,
  15202. 'pdfSteps' => $pdfSteps,
  15203. 'pdfStepWidth' => $pdfStepW,
  15204. ]);
  15205. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  15206. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  15207. $this->view->engine->layout(false);
  15208. try {
  15209. $html = $this->view->fetch('procuremen/details_pdf_shell');
  15210. } catch (\Throwable $e) {
  15211. if ($restoreLayout) {
  15212. $this->view->engine->layout($restoreLayout);
  15213. }
  15214. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  15215. $this->view->assign([
  15216. 'pdf_export' => '', 'pdfMetaLine' => '', 'pdfMetaLeft' => '',
  15217. 'pdfMetaIds' => '', 'pdfMetaTitle' => '', 'pdfMetaTime' => '',
  15218. 'pdfSteps' => [], 'pdfStepWidth' => '',
  15219. ]);
  15220. return '';
  15221. }
  15222. if ($restoreLayout) {
  15223. $this->view->engine->layout($restoreLayout);
  15224. }
  15225. $this->view->assign([
  15226. 'pdf_export' => '', 'pdfMetaLine' => '', 'pdfMetaLeft' => '',
  15227. 'pdfMetaIds' => '', 'pdfMetaTitle' => '', 'pdfMetaTime' => '',
  15228. 'pdfSteps' => [], 'pdfStepWidth' => '',
  15229. ]);
  15230. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  15231. if (!is_dir($tempDir)) {
  15232. @mkdir($tempDir, 0755, true);
  15233. }
  15234. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  15235. try {
  15236. $mpdf = new \Mpdf\Mpdf([
  15237. 'mode' => 'utf-8',
  15238. 'format' => 'A4',
  15239. 'margin_left' => 12,
  15240. 'margin_right' => 12,
  15241. 'margin_top' => 14,
  15242. 'margin_bottom' => 14,
  15243. 'tempDir' => $tempDir,
  15244. 'autoScriptToLang' => true,
  15245. 'autoLangToFont' => true,
  15246. ]);
  15247. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  15248. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  15249. $mpdf->SetBasePath('http://127.0.0.1/');
  15250. $mpdf->WriteHTML($html);
  15251. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  15252. } catch (\Throwable $e) {
  15253. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  15254. if (is_file($tempPdf)) {
  15255. @unlink($tempPdf);
  15256. }
  15257. return '';
  15258. }
  15259. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  15260. if ($ossUrl !== '') {
  15261. @unlink($tempPdf);
  15262. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  15263. return $ossUrl;
  15264. }
  15265. $pi = pathinfo($objectKey);
  15266. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  15267. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  15268. if ($baseFile === '') {
  15269. @unlink($tempPdf);
  15270. return '';
  15271. }
  15272. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  15273. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  15274. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  15275. @unlink($tempPdf);
  15276. return '';
  15277. }
  15278. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  15279. if (!@copy($tempPdf, $fullPath)) {
  15280. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  15281. @unlink($tempPdf);
  15282. return '';
  15283. }
  15284. @unlink($tempPdf);
  15285. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  15286. return $webPath;
  15287. }
  15288. /**
  15289. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  15290. */
  15291. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  15292. {
  15293. if ($scydgyId <= 0 || $webPath === '') {
  15294. return;
  15295. }
  15296. try {
  15297. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  15298. } catch (\Throwable $e) {
  15299. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  15300. }
  15301. }
  15302. /**
  15303. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  15304. *
  15305. * @param array<string, string> $vars
  15306. * @return array<string, string>
  15307. */
  15308. protected function normalizeSmsTemplateVars(array $vars): array
  15309. {
  15310. return ProcuremenFormat::normalizeSmsTemplateVars($vars);
  15311. }
  15312. /**
  15313. * 按手机号或公司名称查 customer 表联系人姓名
  15314. */
  15315. protected function resolveCustomerContactName(string $phone, string $companyName): string
  15316. {
  15317. $phone = trim($phone);
  15318. $companyName = trim($companyName);
  15319. try {
  15320. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  15321. $row = Db::table('customer')
  15322. ->where(function ($q) use ($phone) {
  15323. $q->where('phone', $phone)->whereOr('account', $phone);
  15324. })
  15325. ->order('id', 'asc')
  15326. ->find();
  15327. if (is_array($row)) {
  15328. $nm = trim((string)($row['username'] ?? ''));
  15329. if ($nm !== '') {
  15330. return $nm;
  15331. }
  15332. }
  15333. }
  15334. if ($companyName !== '') {
  15335. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  15336. if (is_array($row)) {
  15337. return trim((string)($row['username'] ?? ''));
  15338. }
  15339. }
  15340. } catch (\Throwable $e) {
  15341. }
  15342. return '';
  15343. }
  15344. /**
  15345. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;;http(s) 链接做成可点的 &lt;a&gt;(微信 QQ 邮箱提醒纯文本 URL 常不可点)
  15346. */
  15347. protected function plainTextToHtmlEmailBody(string $text): string
  15348. {
  15349. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  15350. $parts = explode("\n", $text);
  15351. $out = [];
  15352. foreach ($parts as $line) {
  15353. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  15354. $out[] = $line;
  15355. } else {
  15356. $esc = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  15357. // 保留工序行空格,便于「单位/工作量」列对齐
  15358. $esc = str_replace(' ', '&nbsp;', $esc);
  15359. $esc = preg_replace(
  15360. '#(https?://[^\s<>"\']+)#iu',
  15361. '<a href="$1" style="color:#1565c0;text-decoration:underline;word-break:break-all;">$1</a>',
  15362. $esc
  15363. );
  15364. $out[] = $esc;
  15365. }
  15366. }
  15367. return implode("<br>\n", $out);
  15368. }
  15369. /**
  15370. * 短信场景:去掉链接类变量,避免误填 URL
  15371. *
  15372. * @param array<string, string> $vars
  15373. * @return array<string, string>
  15374. */
  15375. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  15376. {
  15377. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  15378. return $vars;
  15379. }
  15380. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  15381. $vars[$k] = '';
  15382. }
  15383. return $vars;
  15384. }
  15385. /**
  15386. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  15387. *
  15388. * @param array<string, string> $vars
  15389. */
  15390. protected function renderNotifyTemplate(string $scene, array $vars): string
  15391. {
  15392. $vars = $this->normalizeSmsTemplateVars($vars);
  15393. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  15394. $row = $this->loadNotifyTemplateRow($scene);
  15395. if ($row === null) {
  15396. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  15397. }
  15398. $tpl = trim((string)($row['content'] ?? ''));
  15399. if ($tpl === '') {
  15400. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  15401. }
  15402. foreach ($vars as $k => $v) {
  15403. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  15404. }
  15405. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  15406. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  15407. return $tpl;
  15408. }
  15409. protected function resolveProcuremenEmailSubject(string $scene): string
  15410. {
  15411. // 采购确认结果邮箱:title 仅作说明,邮件主题用固定文案(不用 title)
  15412. if (in_array($scene, ['confirm_ok_email', 'confirm_fail_email'], true)) {
  15413. $this->ensureConfirmResultEmailTemplates();
  15414. $fallback = [
  15415. 'confirm_ok_email' => '采购确认结果:已通过',
  15416. 'confirm_fail_email' => '采购确认结果:未通过',
  15417. ];
  15418. return $fallback[$scene] ?? '协助采购通知';
  15419. }
  15420. // 询价 / 交货确认邮箱:沿用模版 title 作邮件主题(与历史配置一致)
  15421. if (in_array($scene, ['rfq_salesman_email', 'rfq_supplier_email', 'delivery_notify_email'], true)) {
  15422. $row = $this->loadNotifyTemplateRow($scene);
  15423. $title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
  15424. if ($title !== '') {
  15425. return $title;
  15426. }
  15427. $fallback = [
  15428. 'rfq_supplier_email' => '供应商询价通知',
  15429. 'rfq_salesman_email' => '协助采购询价通知',
  15430. 'delivery_notify_email' => '交货情况确认通知',
  15431. ];
  15432. return $fallback[$scene] ?? '协助采购通知';
  15433. }
  15434. $map = [
  15435. 'review_email' => '您有新的协助加工订单',
  15436. ];
  15437. $subject = trim((string)($map[$scene] ?? ''));
  15438. if ($subject === '') {
  15439. $this->error('未配置邮件主题:' . $scene);
  15440. }
  15441. return $subject;
  15442. }
  15443. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  15444. {
  15445. $map = [
  15446. 'review_email' => '协助下发-邮箱',
  15447. 'review_sms' => '协助下发-短信',
  15448. 'confirm_ok' => '采购确认-通过',
  15449. 'confirm_fail' => '采购确认-未通过',
  15450. 'confirm_ok_email' => '采购确认通过-邮箱',
  15451. 'confirm_fail_email' => '采购确认未通过-邮箱',
  15452. 'bid_open' => '开标双重验证',
  15453. 'rfq_salesman_email' => '询价通知业务员-邮箱',
  15454. 'rfq_supplier_email' => '供应商询价通知',
  15455. 'delivery_notify_email'=> '交货情况通知生产部-邮箱',
  15456. ];
  15457. $label = $map[$scene] ?? $scene;
  15458. if ($titleRequired) {
  15459. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  15460. }
  15461. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  15462. }
  15463. /**
  15464. * 是否开启协助通知演练(不发真实短信/邮件)
  15465. */
  15466. protected function isProcuremenNotifyDryRun(): bool
  15467. {
  15468. return (bool)Config::get('procuremen_notify_dry_run');
  15469. }
  15470. /**
  15471. * @param array<string, mixed> $payload
  15472. */
  15473. protected function recordNotifyDryRunPreview(array $payload): void
  15474. {
  15475. $this->notifyDryRunPreview[] = $payload;
  15476. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  15477. }
  15478. /**
  15479. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  15480. * @throws \Exception
  15481. */
  15482. protected function smsbao($phone, $content)
  15483. {
  15484. if ($this->isProcuremenNotifyDryRun()) {
  15485. $this->recordNotifyDryRunPreview([
  15486. 'scene' => 'sms_only',
  15487. 'phone' => $phone,
  15488. 'sms_content' => $content,
  15489. ]);
  15490. return;
  15491. }
  15492. $statusStr = [
  15493. '0' => '短信发送成功',
  15494. '-1' => '参数不全',
  15495. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  15496. '30' => '密码错误',
  15497. '40' => '账号不存在',
  15498. '41' => '余额不足',
  15499. '42' => '帐户已过期',
  15500. '43' => 'IP地址限制',
  15501. '50' => '内容含有敏感词',
  15502. ];
  15503. $smsapi = 'http://api.smsbao.com/';
  15504. $user = 'zhuwei123';
  15505. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  15506. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  15507. $result = @file_get_contents($sendurl);
  15508. if ($result === false) {
  15509. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  15510. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  15511. }
  15512. $result = trim((string)$result);
  15513. if ($result !== '0') {
  15514. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  15515. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  15516. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  15517. }
  15518. }
  15519. }