Procuremen.php 631 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483
  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,b.order_batch_no,a.issue_time';
  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. /* audit/confirm 列表需先填充 issue_time 再搜索,否则搜索不到下发时间 */
  1602. $this->hydrateProcuremenListIssueSortTimes($pool);
  1603. if ($wffTab === 'confirm' && $pool === []) {
  1604. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1605. }
  1606. } else {
  1607. // 初选:按月直查 ERP(不解整包 Redis,避免长时间转圈)
  1608. if ($applyMonthRange) {
  1609. $pool = $this->loadPickPoolForYm($ym);
  1610. } else {
  1611. $pool = $this->procuremenEnsureRedisPool();
  1612. }
  1613. if (!is_array($pool)) {
  1614. $pool = [];
  1615. }
  1616. // 只针对本页候选 ID 查隐藏集,避免全表扫 purchase_order_detail
  1617. $hideSet = $this->loadPickHiddenScydgySetForIds($this->extractScydgyIdsFromPool($pool));
  1618. if ($pool !== [] && $hideSet !== []) {
  1619. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1620. if (!is_array($r)) {
  1621. return false;
  1622. }
  1623. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1624. return $id <= 0 || !isset($hideSet[$id]);
  1625. }));
  1626. }
  1627. // 手工新增(YW / scydgy_id<0)只走「新增询价/查询询价」,不进初选表格
  1628. if ($pool === []) {
  1629. return json([
  1630. 'total' => 0,
  1631. 'rows' => [],
  1632. 'activeYm' => $ym,
  1633. 'filterOptions' => (
  1634. (int)$offset === 0
  1635. && !$hasActiveSearch
  1636. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1637. )
  1638. ? $this->extractProcuremenFilterOptionsFromRows([])
  1639. : new \stdClass(),
  1640. ]);
  1641. }
  1642. }
  1643. $filtered = $this->filterProcuremenIndexPool(
  1644. $pool,
  1645. $monthStart,
  1646. $monthEnd,
  1647. $applyMonthRange,
  1648. $search,
  1649. $filterArr,
  1650. $opArr,
  1651. $listTimePrimary
  1652. );
  1653. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1654. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1655. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1656. }
  1657. if (in_array($wffTab, ['audit', 'confirm'], true) && $bidOpenStatusFilter !== '') {
  1658. $filtered = $this->filterProcuremenPoolByBidOpenStatus($filtered, $bidOpenStatusFilter);
  1659. }
  1660. if (in_array($wffTab, ['audit', 'confirm'], true) && $orderStatusFilter !== '') {
  1661. $filtered = $this->filterProcuremenPoolByOrderStatus($filtered, $orderStatusFilter);
  1662. }
  1663. $sortField = 'ID';
  1664. if (is_string($sort) && $sort !== '') {
  1665. $parts = explode(',', $sort);
  1666. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1667. if ($sortField === '') {
  1668. $sortField = 'ID';
  1669. }
  1670. }
  1671. // 列表「下发时间」列字段为 issue_time,与 pick_time 同义
  1672. if ($sortField === 'issue_time') {
  1673. $sortField = 'pick_time';
  1674. }
  1675. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1676. $nFiltered = count($filtered);
  1677. if (in_array($wffTab, ['audit', 'confirm'], true) && $nFiltered > 1) {
  1678. // 确认/审批:状态分组优先;同状态内固定按下发时间倒序(最新在上,不跟前端 ASC/DESC 翻转)
  1679. // 先补齐下发时间,避免 pick_time 空时回退到提交日导致顺序错乱
  1680. $this->hydrateProcuremenListIssueSortTimes($filtered);
  1681. usort($filtered, function ($a, $b) use ($wffTab) {
  1682. if (!is_array($a)) {
  1683. return 1;
  1684. }
  1685. if (!is_array($b)) {
  1686. return -1;
  1687. }
  1688. $statusKeyA = $a['order_status_text'] ?? $a['wflow_status'] ?? '';
  1689. if (trim((string)$statusKeyA) === '') {
  1690. $statusKeyA = $a['wflow_status'] ?? '';
  1691. }
  1692. $statusKeyB = $b['order_status_text'] ?? $b['wflow_status'] ?? '';
  1693. if (trim((string)$statusKeyB) === '') {
  1694. $statusKeyB = $b['wflow_status'] ?? '';
  1695. }
  1696. $wa = ProcuremenStatus::orderStatusSortWeight($wffTab, $statusKeyA);
  1697. $wb = ProcuremenStatus::orderStatusSortWeight($wffTab, $statusKeyB);
  1698. if ($wa !== $wb) {
  1699. return $wa <=> $wb;
  1700. }
  1701. $ta = trim((string)($a['_issue_sort_time'] ?? ''));
  1702. if ($ta === '') {
  1703. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  1704. }
  1705. $tb = trim((string)($b['_issue_sort_time'] ?? ''));
  1706. if ($tb === '') {
  1707. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  1708. }
  1709. if ($ta !== $tb) {
  1710. if ($ta === '') {
  1711. return 1;
  1712. }
  1713. if ($tb === '') {
  1714. return -1;
  1715. }
  1716. // 倒序:新的在前
  1717. return strcmp($tb, $ta);
  1718. }
  1719. return ((int)($b['ID'] ?? 0) <=> (int)($a['ID'] ?? 0));
  1720. });
  1721. } elseif ($nFiltered > 1) {
  1722. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1723. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1724. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1725. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1726. if ($ta === $tb) {
  1727. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1728. }
  1729. if ($ta === '') {
  1730. return 1;
  1731. }
  1732. if ($tb === '') {
  1733. return -1;
  1734. }
  1735. return strcmp($ta, $tb) * $ord;
  1736. });
  1737. } elseif ($sortField === 'ID') {
  1738. $sortKeys = [];
  1739. foreach ($filtered as $i => $row) {
  1740. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1741. }
  1742. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1743. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1744. } elseif ($sortField === 'CCYDH') {
  1745. usort($filtered, function ($a, $b) use ($ord) {
  1746. $sa = trim((string)($a['CCYDH'] ?? ''));
  1747. $sb = trim((string)($b['CCYDH'] ?? ''));
  1748. if ($sa === $sb) {
  1749. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1750. }
  1751. if ($sa === '') {
  1752. return 1;
  1753. }
  1754. if ($sb === '') {
  1755. return -1;
  1756. }
  1757. return strcmp($sa, $sb) * $ord;
  1758. });
  1759. } else {
  1760. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1761. $va = $a[$sortField] ?? null;
  1762. $vb = $b[$sortField] ?? null;
  1763. $sa = (string)$va;
  1764. $sb = (string)$vb;
  1765. if ($sa === $sb) {
  1766. return 0;
  1767. }
  1768. return strcmp($sa, $sb) * $ord;
  1769. });
  1770. }
  1771. }
  1772. $offset = max(0, (int)$offset);
  1773. $limit = max(1, (int)$limit);
  1774. $rows = array_slice($filtered, $offset, $limit);
  1775. foreach ($rows as &$rw) {
  1776. if (!is_array($rw)) {
  1777. continue;
  1778. }
  1779. $rid = (int)($rw['ID'] ?? 0);
  1780. $rw['_iss_out'] = ($wffTab !== 'pick');
  1781. }
  1782. unset($rw);
  1783. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1784. $idList = [];
  1785. foreach ($rows as $rw) {
  1786. if (!is_array($rw)) {
  1787. continue;
  1788. }
  1789. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1790. foreach ($rw['_order_merge_rows'] as $mr) {
  1791. $mid = (int)($mr['ID'] ?? 0);
  1792. if ($this->isValidScydgyRowId($mid)) {
  1793. $idList[$mid] = true;
  1794. }
  1795. }
  1796. }
  1797. $id = (int)($rw['ID'] ?? 0);
  1798. if ($this->isValidScydgyRowId($id)) {
  1799. $idList[$id] = true;
  1800. }
  1801. }
  1802. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1803. foreach ($rows as &$rw) {
  1804. if (!is_array($rw)) {
  1805. continue;
  1806. }
  1807. $mergeIds = [];
  1808. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1809. foreach ($rw['_order_merge_rows'] as $mr) {
  1810. $mid = (int)($mr['ID'] ?? 0);
  1811. if ($this->isValidScydgyRowId($mid)) {
  1812. $mergeIds[$mid] = true;
  1813. }
  1814. }
  1815. }
  1816. $rid = (int)($rw['ID'] ?? 0);
  1817. if ($this->isValidScydgyRowId($rid)) {
  1818. $mergeIds[$rid] = true;
  1819. }
  1820. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1821. $rw['po_detail_count'] = $s['cnt'];
  1822. $rw['po_amount_fill_cnt'] = $s['amt'];
  1823. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1824. }
  1825. unset($rw);
  1826. }
  1827. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1828. $idList = [];
  1829. foreach ($rows as $rw) {
  1830. if (!is_array($rw)) {
  1831. continue;
  1832. }
  1833. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1834. foreach ($rw['_order_merge_rows'] as $mr) {
  1835. $mid = (int)($mr['ID'] ?? 0);
  1836. if ($this->isValidScydgyRowId($mid)) {
  1837. $idList[$mid] = true;
  1838. }
  1839. }
  1840. }
  1841. $id = (int)($rw['ID'] ?? 0);
  1842. if ($this->isValidScydgyRowId($id)) {
  1843. $idList[$id] = true;
  1844. }
  1845. }
  1846. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1847. $bidOpenSet = [];
  1848. $manualPickSet = [];
  1849. $bidOpenBatchSet = [];
  1850. $ccydhList = [];
  1851. $batchList = [];
  1852. foreach ($rows as $rw0) {
  1853. if (!is_array($rw0)) {
  1854. continue;
  1855. }
  1856. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1857. if ($c0 !== '') {
  1858. $ccydhList[] = $c0;
  1859. }
  1860. $b0 = $this->resolveProcuremenOrderBatchNo($rw0);
  1861. if ($b0 !== '') {
  1862. $batchList[] = $b0;
  1863. }
  1864. if (!empty($rw0['_order_merge_rows']) && is_array($rw0['_order_merge_rows'])) {
  1865. foreach ($rw0['_order_merge_rows'] as $mr0) {
  1866. if (!is_array($mr0)) {
  1867. continue;
  1868. }
  1869. $cm = trim((string)($mr0['CCYDH'] ?? ''));
  1870. if ($cm !== '') {
  1871. $ccydhList[] = $cm;
  1872. }
  1873. $bm = $this->resolveProcuremenOrderBatchNo($mr0);
  1874. if ($bm !== '') {
  1875. $batchList[] = $bm;
  1876. }
  1877. }
  1878. }
  1879. }
  1880. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1881. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  1882. $bidOpenBatchSet = $this->loadProcuremenBidOpenVerifiedBatchSet($batchList);
  1883. foreach ($rows as &$rw) {
  1884. if (!is_array($rw)) {
  1885. continue;
  1886. }
  1887. $mergeIds = [];
  1888. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1889. foreach ($rw['_order_merge_rows'] as $mr) {
  1890. $mid = (int)($mr['ID'] ?? 0);
  1891. if ($this->isValidScydgyRowId($mid)) {
  1892. $mergeIds[$mid] = true;
  1893. }
  1894. }
  1895. }
  1896. $rid = (int)($rw['ID'] ?? 0);
  1897. if ($this->isValidScydgyRowId($rid)) {
  1898. $mergeIds[$rid] = true;
  1899. }
  1900. $buckets = [];
  1901. foreach (array_keys($mergeIds) as $mid) {
  1902. if (isset($quoteBucket[$mid])) {
  1903. $buckets[] = $quoteBucket[$mid];
  1904. }
  1905. }
  1906. $supplierText = $buckets !== []
  1907. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1908. : '';
  1909. $picked = trim((string)($rw['pick_company_name'] ?? $rw['picked_supplier_name'] ?? ''));
  1910. if ($picked === '') {
  1911. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1912. foreach ($rw['_order_merge_rows'] as $mr) {
  1913. if (!is_array($mr)) {
  1914. continue;
  1915. }
  1916. $pn = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  1917. if ($pn !== '') {
  1918. $picked = $pn;
  1919. break;
  1920. }
  1921. }
  1922. }
  1923. }
  1924. $rw['picked_supplier_name'] = $picked;
  1925. $rw['notify_supplier_text'] = $supplierText;
  1926. $wflowRaw = trim((string)($rw['wflow_status'] ?? ''));
  1927. if ($wflowRaw === '' && !empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1928. foreach ($rw['_order_merge_rows'] as $mr) {
  1929. if (!is_array($mr)) {
  1930. continue;
  1931. }
  1932. $wf = trim((string)($mr['wflow_status'] ?? ''));
  1933. if ($wf !== '') {
  1934. $wflowRaw = $wf;
  1935. break;
  1936. }
  1937. }
  1938. }
  1939. $rw['wflow_status'] = $wflowRaw;
  1940. $rw['order_status_text'] = ProcuremenStatus::orderStatusLabelForList($wflowRaw);
  1941. $bidState = $this->resolveProcuremenListBidOpenState($rw, $bidOpenSet, $manualPickSet, $bidOpenBatchSet);
  1942. $rw['bid_open_verified'] = !empty($bidState['verified']) ? 1 : 0;
  1943. $rw['manual_picked'] = !empty($bidState['manual']) ? 1 : 0;
  1944. $rw['bid_open_status_text'] = (string)($bidState['text'] ?? '待开标');
  1945. }
  1946. unset($rw);
  1947. }
  1948. if (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
  1949. $this->enrichProcuremenListMilestoneTimes($rows);
  1950. $this->syncCollapsedOrderQtyPriceForList($rows);
  1951. }
  1952. if ($wffTab === 'all' && count($rows) > 0) {
  1953. $this->mergePurchaseOrder($rows);
  1954. }
  1955. if ($wffTab === 'pick' && count($rows) > 0) {
  1956. $this->mergePurchaseOrder($rows);
  1957. }
  1958. foreach ($rows as &$rwClean) {
  1959. if (is_array($rwClean)) {
  1960. unset($rwClean['_order_merge_rows']);
  1961. if (array_key_exists('NGZL', $rwClean)) {
  1962. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1963. }
  1964. }
  1965. }
  1966. unset($rwClean);
  1967. return json([
  1968. 'total' => count($filtered),
  1969. 'rows' => $rows,
  1970. 'activeYm' => $ym,
  1971. // 初选:把有数据的月份带回,替换「空月份日历」侧栏
  1972. 'sidebarYms' => (in_array($wffTab, ['pick', 'audit', 'confirm'], true) && (int)$offset === 0)
  1973. ? (
  1974. $wffTab === 'pick'
  1975. ? $this->ensureProcuremenPickSidebarYmList()
  1976. : $this->flattenProcuremenSidebarYms($this->GetIssuedOrderYearMonths($wffTab))
  1977. )
  1978. : [],
  1979. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1980. 'filterOptions' => (
  1981. (int)$offset === 0
  1982. && !$hasActiveSearch
  1983. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1984. )
  1985. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1986. : new \stdClass(),
  1987. ]);
  1988. } catch (\Throwable $e) {
  1989. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1990. return json([
  1991. 'total' => 0,
  1992. 'rows' => [],
  1993. ]);
  1994. }
  1995. }
  1996. /**
  1997. * @param array<int, array<string, mixed>> $pool
  1998. * @return int[]
  1999. */
  2000. protected function extractScydgyIdsFromPool(array $pool): array
  2001. {
  2002. $ids = [];
  2003. foreach ($pool as $r) {
  2004. if (!is_array($r)) {
  2005. continue;
  2006. }
  2007. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  2008. if ($id > 0) {
  2009. $ids[$id] = $id;
  2010. }
  2011. }
  2012. return array_values($ids);
  2013. }
  2014. /**
  2015. * 仅查询指定工序 ID 是否已下发/进入后续流程(初选列表加速)
  2016. *
  2017. * @param int[] $scydgyIds
  2018. * @return array<int, true>
  2019. */
  2020. protected function loadPickHiddenScydgySetForIds(array $scydgyIds): array
  2021. {
  2022. $hideSet = [];
  2023. $scydgyIds = array_values(array_filter(array_map('intval', $scydgyIds), function ($id) {
  2024. return $id > 0;
  2025. }));
  2026. if ($scydgyIds === []) {
  2027. return $hideSet;
  2028. }
  2029. // 分批,避免 whereIn 过长
  2030. foreach (array_chunk($scydgyIds, 500) as $chunk) {
  2031. try {
  2032. $poIds = Db::table('purchase_order')
  2033. ->where('scydgy_id', 'in', $chunk)
  2034. ->where(function ($q) {
  2035. $q->whereIn('wflow_status', array_merge(
  2036. ProcuremenStatus::wflowPendingConfirmValues(),
  2037. ProcuremenStatus::wflowPendingApprovalValues()
  2038. ))
  2039. ->whereOr(function ($q1) {
  2040. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  2041. })
  2042. ->whereOr(function ($q2) {
  2043. $q2->whereNotNull('pick_time')
  2044. ->where('pick_time', '<>', '')
  2045. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  2046. })
  2047. ->whereOr(function ($q3) {
  2048. $q3->whereNotNull('mod_rq')
  2049. ->where('mod_rq', '<>', '')
  2050. ->where('mod_rq', 'not like', '0000-00-00%');
  2051. });
  2052. })
  2053. ->column('scydgy_id');
  2054. if (is_array($poIds)) {
  2055. foreach ($poIds as $pid) {
  2056. $k = (int)$pid;
  2057. if ($k !== 0) {
  2058. $hideSet[$k] = true;
  2059. }
  2060. }
  2061. }
  2062. } catch (\Throwable $e) {
  2063. }
  2064. try {
  2065. $detIdsQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $chunk);
  2066. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  2067. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  2068. if (is_array($detIds)) {
  2069. foreach ($detIds as $pid) {
  2070. $k = (int)$pid;
  2071. if ($this->isValidScydgyRowId($k)) {
  2072. $hideSet[$k] = true;
  2073. }
  2074. }
  2075. }
  2076. } catch (\Throwable $e) {
  2077. }
  2078. }
  2079. return $hideSet;
  2080. }
  2081. /**
  2082. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  2083. *
  2084. * @return array<int, true>
  2085. */
  2086. protected function loadPickHiddenScydgySet(): array
  2087. {
  2088. if ($this->pickHiddenScydgySetCache !== null) {
  2089. return $this->pickHiddenScydgySetCache;
  2090. }
  2091. $cacheKey = 'procuremen_pick_hidden_scydgy_v1';
  2092. try {
  2093. $raw = redis()->get($cacheKey);
  2094. if ($raw !== false && $raw !== null && $raw !== '') {
  2095. $ids = json_decode((string)$raw, true);
  2096. if (is_array($ids)) {
  2097. $hideSet = [];
  2098. foreach ($ids as $pid) {
  2099. $k = (int)$pid;
  2100. if ($k !== 0) {
  2101. $hideSet[$k] = true;
  2102. }
  2103. }
  2104. $this->pickHiddenScydgySetCache = $hideSet;
  2105. return $hideSet;
  2106. }
  2107. }
  2108. } catch (\Throwable $e) {
  2109. }
  2110. $hideSet = [];
  2111. try {
  2112. $poIds = Db::table('purchase_order')
  2113. ->where(function ($q) {
  2114. $q->whereIn('wflow_status', array_merge(
  2115. ProcuremenStatus::wflowPendingConfirmValues(),
  2116. ProcuremenStatus::wflowPendingApprovalValues()
  2117. ))
  2118. ->whereOr(function ($q1) {
  2119. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  2120. })
  2121. ->whereOr(function ($q2) {
  2122. $q2->whereNotNull('pick_time')
  2123. ->where('pick_time', '<>', '')
  2124. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  2125. })
  2126. ->whereOr(function ($q3) {
  2127. $q3->whereNotNull('mod_rq')
  2128. ->where('mod_rq', '<>', '')
  2129. ->where('mod_rq', 'not like', '0000-00-00%');
  2130. });
  2131. })
  2132. ->column('scydgy_id');
  2133. if (is_array($poIds)) {
  2134. foreach ($poIds as $pid) {
  2135. $k = (int)$pid;
  2136. if ($k !== 0) {
  2137. $hideSet[$k] = true;
  2138. }
  2139. }
  2140. }
  2141. } catch (\Throwable $e) {
  2142. }
  2143. try {
  2144. $detIdsQuery = Db::table('purchase_order_detail');
  2145. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  2146. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  2147. if (is_array($detIds)) {
  2148. foreach ($detIds as $pid) {
  2149. $k = (int)$pid;
  2150. if ($this->isValidScydgyRowId($k)) {
  2151. $hideSet[$k] = true;
  2152. }
  2153. }
  2154. }
  2155. } catch (\Throwable $e) {
  2156. }
  2157. $this->pickHiddenScydgySetCache = $hideSet;
  2158. try {
  2159. redis()->setex($cacheKey, 90, json_encode(array_map('intval', array_keys($hideSet))));
  2160. } catch (\Throwable $e) {
  2161. }
  2162. return $hideSet;
  2163. }
  2164. /**
  2165. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  2166. *
  2167. * @return array<int, array<string, mixed>>
  2168. */
  2169. protected function loadPickManualOrderRows(): array
  2170. {
  2171. try {
  2172. $dbRows = Db::table('purchase_order')
  2173. ->where('scydgy_id', '<', 0)
  2174. ->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%\')')
  2175. ->order('scydgy_id', 'asc')
  2176. ->select();
  2177. } catch (\Throwable $e) {
  2178. try {
  2179. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  2180. } catch (\Throwable $e2) {
  2181. return [];
  2182. }
  2183. }
  2184. if (!is_array($dbRows) || $dbRows === []) {
  2185. return [];
  2186. }
  2187. $detailSidSet = [];
  2188. try {
  2189. $negIds = [];
  2190. foreach ($dbRows as $dbRow) {
  2191. if (!is_array($dbRow)) {
  2192. continue;
  2193. }
  2194. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2195. if ($sid < 0) {
  2196. $negIds[$sid] = true;
  2197. }
  2198. }
  2199. if ($negIds !== []) {
  2200. $detQuery = Db::table('purchase_order_detail')
  2201. ->where('scydgy_id', 'in', array_keys($negIds));
  2202. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  2203. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  2204. if (is_array($detRows)) {
  2205. foreach ($detRows as $did) {
  2206. $detailSidSet[(int)$did] = true;
  2207. }
  2208. }
  2209. }
  2210. } catch (\Throwable $e) {
  2211. }
  2212. $pool = [];
  2213. foreach ($dbRows as $dbRow) {
  2214. if (!is_array($dbRow)) {
  2215. continue;
  2216. }
  2217. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2218. if ($sid >= 0) {
  2219. continue;
  2220. }
  2221. // 已进入确认/审批的不进初选;仅废弃明细残留的仍算可下发
  2222. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  2223. continue;
  2224. }
  2225. // 仅排除已完结;空 status / 「进行中」/ 0 均保留(新建手工单)
  2226. if (ProcuremenStatus::isPoCompleted($dbRow['status'] ?? '')) {
  2227. continue;
  2228. }
  2229. if (isset($detailSidSet[$sid])) {
  2230. continue;
  2231. }
  2232. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  2233. $r['_is_manual'] = 1;
  2234. $pool[] = $r;
  2235. }
  2236. return $pool;
  2237. }
  2238. /**
  2239. * 确认/审批列表排序:补齐下发时间(pick_time + 下发操作日志)
  2240. *
  2241. * @param array<int, array<string, mixed>> $rows
  2242. */
  2243. protected function hydrateProcuremenListIssueSortTimes(array &$rows): void
  2244. {
  2245. if ($rows === []) {
  2246. return;
  2247. }
  2248. $sidList = [];
  2249. foreach ($rows as $rw) {
  2250. if (!is_array($rw)) {
  2251. continue;
  2252. }
  2253. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  2254. foreach ($rw['_order_merge_rows'] as $mr) {
  2255. if (!is_array($mr)) {
  2256. continue;
  2257. }
  2258. $mid = (int)($mr['ID'] ?? 0);
  2259. if ($this->isValidScydgyRowId($mid)) {
  2260. $sidList[$mid] = true;
  2261. }
  2262. }
  2263. }
  2264. $id = (int)($rw['ID'] ?? 0);
  2265. if ($this->isValidScydgyRowId($id)) {
  2266. $sidList[$id] = true;
  2267. }
  2268. }
  2269. $issueBySid = [];
  2270. $sids = array_keys($sidList);
  2271. if ($sids !== []) {
  2272. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  2273. if ($issueActs !== []) {
  2274. try {
  2275. $logs = Db::table('purchase_order_oper_log')
  2276. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  2277. ->where(ProcuremenOperLog::COL_ACTION, 'in', $issueActs)
  2278. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_TIME)
  2279. ->order('id', 'asc')
  2280. ->select();
  2281. } catch (\Throwable $e) {
  2282. $logs = [];
  2283. }
  2284. if (is_array($logs)) {
  2285. foreach ($logs as $lg) {
  2286. if (!is_array($lg)) {
  2287. continue;
  2288. }
  2289. $lg = ProcuremenOperLog::normalizeRow($lg);
  2290. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  2291. if ($sid === 0) {
  2292. continue;
  2293. }
  2294. $tm = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  2295. if ($tm === '') {
  2296. continue;
  2297. }
  2298. if (!isset($issueBySid[$sid]) || strcmp($tm, $issueBySid[$sid]) > 0) {
  2299. $issueBySid[$sid] = $tm;
  2300. }
  2301. }
  2302. }
  2303. }
  2304. }
  2305. foreach ($rows as &$rw) {
  2306. if (!is_array($rw)) {
  2307. continue;
  2308. }
  2309. $mergeSids = [];
  2310. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  2311. foreach ($rw['_order_merge_rows'] as $mr) {
  2312. if (!is_array($mr)) {
  2313. continue;
  2314. }
  2315. $mid = (int)($mr['ID'] ?? 0);
  2316. if ($this->isValidScydgyRowId($mid)) {
  2317. $mergeSids[] = $mid;
  2318. }
  2319. }
  2320. }
  2321. $rid = (int)($rw['ID'] ?? 0);
  2322. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  2323. $mergeSids[] = $rid;
  2324. }
  2325. $best = $this->procuremenRowListSortTime($rw, 'pick_time');
  2326. foreach ($mergeSids as $sid) {
  2327. if (isset($issueBySid[$sid]) && ($best === '' || strcmp($issueBySid[$sid], $best) > 0)) {
  2328. $best = $issueBySid[$sid];
  2329. }
  2330. }
  2331. $rw['_issue_sort_time'] = $best;
  2332. if ($best !== '') {
  2333. $pickOut = trim((string)($rw['pick_time'] ?? ''));
  2334. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  2335. $rw['pick_time'] = $best;
  2336. }
  2337. $rw['issue_time'] = $best;
  2338. }
  2339. }
  2340. unset($rw);
  2341. }
  2342. /**
  2343. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  2344. */
  2345. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  2346. {
  2347. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  2348. foreach ($keys as $k) {
  2349. $t = trim((string)($row[$k] ?? ''));
  2350. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2351. return $t;
  2352. }
  2353. }
  2354. return '';
  2355. }
  2356. /**
  2357. * 分配手工新增工序行 ID(负数递减)
  2358. * 调用方须在命名锁内执行,避免并发重复
  2359. */
  2360. protected function allocateManualScydgyId(): int
  2361. {
  2362. try {
  2363. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  2364. $min = (int)$min;
  2365. return $min < 0 ? $min - 1 : -1;
  2366. } catch (\Throwable $e) {
  2367. return -1;
  2368. }
  2369. }
  2370. /**
  2371. * 手工新增订单号:YW + 年月日 + 当日序号(如 YW20260618001)
  2372. * 调用方须在命名锁内执行,避免并发重复
  2373. */
  2374. protected function allocateManualOrderCcydh(): string
  2375. {
  2376. $prefix = 'YW' . date('Ymd');
  2377. $maxSeq = 0;
  2378. try {
  2379. $rows = Db::table('purchase_order')
  2380. ->where('CCYDH', 'like', $prefix . '%')
  2381. ->column('CCYDH');
  2382. if (is_array($rows)) {
  2383. foreach ($rows as $ccydh) {
  2384. $ccydh = trim((string)$ccydh);
  2385. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3,})$/', $ccydh, $m)) {
  2386. $maxSeq = max($maxSeq, (int)$m[1]);
  2387. }
  2388. }
  2389. }
  2390. } catch (\Throwable $e) {
  2391. }
  2392. $next = $maxSeq + 1;
  2393. $width = $next > 999 ? strlen((string)$next) : 3;
  2394. return $prefix . str_pad((string)$next, $width, '0', STR_PAD_LEFT);
  2395. }
  2396. /**
  2397. * MySQL 命名锁(跨连接防并发撞号)
  2398. */
  2399. protected function acquireProcuremenNamedLock(string $name, int $timeoutSec = 10): bool
  2400. {
  2401. $name = trim($name);
  2402. if ($name === '') {
  2403. return false;
  2404. }
  2405. try {
  2406. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2407. $rows = Db::query('SELECT GET_LOCK(\'' . $nameSql . '\', ' . max(1, $timeoutSec) . ') AS locked');
  2408. if (!is_array($rows) || $rows === []) {
  2409. return false;
  2410. }
  2411. $v = $rows[0]['locked'] ?? $rows[0]['LOCKED'] ?? null;
  2412. return (int)$v === 1;
  2413. } catch (\Throwable $e) {
  2414. return false;
  2415. }
  2416. }
  2417. protected function releaseProcuremenNamedLock(string $name): void
  2418. {
  2419. $name = trim($name);
  2420. if ($name === '') {
  2421. return;
  2422. }
  2423. try {
  2424. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2425. Db::query('SELECT RELEASE_LOCK(\'' . $nameSql . '\')');
  2426. } catch (\Throwable $e) {
  2427. }
  2428. }
  2429. /**
  2430. * purchase_order.mod_rq 是否有有效软删除时间
  2431. */
  2432. protected function isPurchaseOrderSoftDeleted($modRq): bool
  2433. {
  2434. $t = trim((string)$modRq);
  2435. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  2436. }
  2437. /**
  2438. * 列表行 → purchase_order 写入字段
  2439. *
  2440. * @return array<string, mixed>
  2441. */
  2442. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  2443. {
  2444. return $this->normalizePurchaseOrderWritePayload([
  2445. 'scydgy_id' => $scydgyId,
  2446. 'CCYDH' => $row['CCYDH'] ?? null,
  2447. 'CYJMC' => $row['CYJMC'] ?? null,
  2448. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2449. 'CDXMC' => $row['CDXMC'] ?? null,
  2450. 'CGYBH' => $row['CGYBH'] ?? null,
  2451. 'CGYMC' => $row['CGYMC'] ?? null,
  2452. 'CDW' => $row['CDW'] ?? null,
  2453. 'czlyq' => $row['czlyq'] ?? null,
  2454. 'NGZL' => $row['NGZL'] ?? null,
  2455. 'CDF' => $row['CDF'] ?? null,
  2456. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2457. 'MBZ' => $row['MBZ'] ?? null,
  2458. 'bwjg' => $row['bwjg'] ?? null,
  2459. 'iStatus' => $row['iStatus'] ?? null,
  2460. 'dStamp' => $row['dStamp'] ?? null,
  2461. 'dputrecord' => $row['dputrecord'] ?? null,
  2462. 'cywyxm' => $row['cywyxm'] ?? null,
  2463. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2464. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2465. ], $row);
  2466. }
  2467. /**
  2468. * purchase_order 写入前规范化:NOT NULL 列勿显式传 null(会绕过 DEFAULT 触发 1048)
  2469. *
  2470. * @param array<string, mixed> $data
  2471. * @param array<string, mixed> $row 原始列表行(可用于补齐 czlyq)
  2472. * @return array<string, mixed>
  2473. */
  2474. protected function normalizePurchaseOrderWritePayload(array $data, array $row = []): array
  2475. {
  2476. $this->ensurePurchaseOrderCzlyqColumn();
  2477. $cz = '';
  2478. foreach (['czlyq', 'CZLYQ'] as $k) {
  2479. if (isset($data[$k]) && trim((string)$data[$k]) !== '') {
  2480. $cz = trim((string)$data[$k]);
  2481. break;
  2482. }
  2483. if (isset($row[$k]) && trim((string)$row[$k]) !== '') {
  2484. $cz = trim((string)$row[$k]);
  2485. break;
  2486. }
  2487. }
  2488. if ($cz === '') {
  2489. $ccydh = trim((string)($data['CCYDH'] ?? $row['CCYDH'] ?? ''));
  2490. if ($ccydh !== '') {
  2491. try {
  2492. $fromMcyd = Db::table('mcyd')->where('CCYDH', $ccydh)->value('czlyq');
  2493. $cz = trim((string)$fromMcyd);
  2494. } catch (\Throwable $e) {
  2495. $cz = '';
  2496. }
  2497. }
  2498. }
  2499. $data['czlyq'] = $cz;
  2500. // 显式 NULL 的字符串 NOT NULL 列改为空串
  2501. foreach (['czlyq', 'notify_salesman', 'manual_pick_reason', 'score_rule_name'] as $col) {
  2502. if (!array_key_exists($col, $data)) {
  2503. continue;
  2504. }
  2505. if ($data[$col] === null || !is_scalar($data[$col])) {
  2506. $data[$col] = '';
  2507. } else {
  2508. $data[$col] = (string)$data[$col];
  2509. }
  2510. }
  2511. foreach (['rfq_salesman_notified', 'manual_pick', 'score_rule_id', 'score_quality_weight', 'score_price_weight', 'score_lead_weight'] as $col) {
  2512. if (array_key_exists($col, $data) && $data[$col] === null) {
  2513. $data[$col] = 0;
  2514. }
  2515. }
  2516. return $data;
  2517. }
  2518. /**
  2519. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  2520. *
  2521. * @return array{po:?array<string,mixed>, hidden:bool}
  2522. */
  2523. protected function resolvePickRowPoContext(int $sid): array
  2524. {
  2525. $po = null;
  2526. try {
  2527. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2528. if (is_array($found)) {
  2529. $po = $found;
  2530. }
  2531. } catch (\Throwable $e) {
  2532. }
  2533. $hideSet = $this->loadPickHiddenScydgySet();
  2534. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  2535. }
  2536. /**
  2537. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  2538. */
  2539. protected function assertPickRowCanDelete(int $sid, array $row): void
  2540. {
  2541. $ctx = $this->resolvePickRowPoContext($sid);
  2542. $po = $ctx['po'];
  2543. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2544. return;
  2545. }
  2546. if (is_array($po)) {
  2547. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2548. throw new \InvalidArgumentException('该工序已完结,无法删除');
  2549. }
  2550. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2551. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  2552. }
  2553. }
  2554. if ($ctx['hidden']) {
  2555. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2556. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  2557. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  2558. }
  2559. }
  2560. /**
  2561. * 初选直接完结前校验
  2562. */
  2563. protected function assertPickRowCanComplete(int $sid, array $row): void
  2564. {
  2565. $ctx = $this->resolvePickRowPoContext($sid);
  2566. $po = $ctx['po'];
  2567. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2568. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  2569. }
  2570. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2571. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  2572. }
  2573. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  2574. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  2575. }
  2576. }
  2577. /**
  2578. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  2579. */
  2580. protected function softDeleteProcuremenPickRow(array $row): void
  2581. {
  2582. $sid = $this->extractScydgyRowId($row);
  2583. if (!$this->isValidScydgyRowId($sid)) {
  2584. throw new \InvalidArgumentException('无效的行主键');
  2585. }
  2586. $this->assertPickRowCanDelete($sid, $row);
  2587. $po = $this->resolvePickRowPoContext($sid)['po'];
  2588. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2589. return;
  2590. }
  2591. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2592. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  2593. }
  2594. $now = date('Y-m-d H:i:s');
  2595. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2596. if (is_array($exists)) {
  2597. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  2598. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  2599. } else {
  2600. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  2601. $data['mod_rq'] = $now;
  2602. $data['createtime'] = $now;
  2603. Db::table('purchase_order')->insert($data);
  2604. $poIdLog = (int)Db::getLastInsID();
  2605. }
  2606. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  2607. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  2608. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  2609. if ($gymcLog !== '') {
  2610. $logTail .= ' / ' . $gymcLog;
  2611. }
  2612. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  2613. }
  2614. /**
  2615. * 手工新增协助工序(写入 purchase_order)
  2616. *
  2617. * @param array<string, mixed> $params
  2618. * @return int scydgy_id
  2619. */
  2620. protected function saveManualPickOrder(array $params): int
  2621. {
  2622. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  2623. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  2624. $ccydhIn = trim((string)($params['CCYDH'] ?? ''));
  2625. $lockName = 'procuremen_manual_order_alloc';
  2626. if (!$this->acquireProcuremenNamedLock($lockName, 10)) {
  2627. throw new \RuntimeException('系统繁忙,请稍后重试');
  2628. }
  2629. try {
  2630. $ccydh = $ccydhIn !== '' ? $ccydhIn : $this->allocateManualOrderCcydh();
  2631. $now = date('Y-m-d H:i:s');
  2632. $sid = $this->allocateManualScydgyId();
  2633. $this->ensurePurchaseOrderNotifySalesmanColumn();
  2634. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  2635. // 选择供应商 / 通知业务员:支持多选,落库用顿号拼接
  2636. $supplierName = $this->joinRfqMultiSelectValues($params['cGzzxMc'] ?? ($params['pick_company_name'] ?? ''));
  2637. $notifySalesman = $this->joinRfqMultiSelectValues($params['notify_salesman'] ?? '');
  2638. $data = [
  2639. 'scydgy_id' => $sid,
  2640. 'CCYDH' => $ccydh,
  2641. 'CYJMC' => $cyjmc,
  2642. 'CGYMC' => $cgymc,
  2643. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  2644. 'CDW' => trim((string)($params['CDW'] ?? '')),
  2645. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  2646. 'CDF' => trim((string)($params['CDF'] ?? '')),
  2647. 'cGzzxMc' => $supplierName,
  2648. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  2649. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  2650. 'notify_salesman' => $notifySalesman,
  2651. 'rfq_salesman_notified' => 0,
  2652. 'rfq_salesman_notify_time' => null,
  2653. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  2654. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  2655. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  2656. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  2657. 'createtime' => $now,
  2658. 'dStamp' => $now,
  2659. 'dputrecord' => $now,
  2660. ];
  2661. Db::table('purchase_order')->insert($data);
  2662. $poId = (int)Db::getLastInsID();
  2663. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  2664. return $sid;
  2665. } finally {
  2666. $this->releaseProcuremenNamedLock($lockName);
  2667. }
  2668. }
  2669. protected function formatProcuremenRowLabel(array $row): string
  2670. {
  2671. return ProcuremenFormat::rowLabel($row);
  2672. }
  2673. /**
  2674. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  2675. */
  2676. protected function extractScydgyRowId(array $row): int
  2677. {
  2678. return ProcuremenFormat::extractScydgyRowId($row);
  2679. }
  2680. protected function isValidScydgyRowId(int $id): bool
  2681. {
  2682. return ProcuremenGuard::isValidScydgyId($id);
  2683. }
  2684. protected function isManualScydgyRowId(int $id): bool
  2685. {
  2686. return $id < 0;
  2687. }
  2688. /**
  2689. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  2690. *
  2691. * @param int[] $scydgyIds
  2692. * @return array<int, string[]>
  2693. */
  2694. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  2695. {
  2696. $out = [];
  2697. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2698. if ($scydgyIds === []) {
  2699. return $out;
  2700. }
  2701. try {
  2702. $rows = Db::table('purchase_order_detail')
  2703. ->where('scydgy_id', 'in', $scydgyIds)
  2704. ->field('scydgy_id,company_name')
  2705. ->order('company_name', 'asc')
  2706. ->select();
  2707. } catch (\Throwable $e) {
  2708. $rows = [];
  2709. }
  2710. if (!is_array($rows)) {
  2711. return $out;
  2712. }
  2713. foreach ($rows as $r) {
  2714. if (!is_array($r)) {
  2715. continue;
  2716. }
  2717. $sid = (int)($r['scydgy_id'] ?? 0);
  2718. $cn = trim((string)($r['company_name'] ?? ''));
  2719. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2720. continue;
  2721. }
  2722. if (!isset($out[$sid])) {
  2723. $out[$sid] = [];
  2724. }
  2725. if (!in_array($cn, $out[$sid], true)) {
  2726. $out[$sid][] = $cn;
  2727. }
  2728. }
  2729. return $out;
  2730. }
  2731. /**
  2732. * 列表展示通知供应商(完整列表,前端单行省略展开)
  2733. *
  2734. * @param string[] $names
  2735. */
  2736. protected function formatNotifySupplierDisplay(array $names): string
  2737. {
  2738. return ProcuremenFormat::notifySupplierDisplay($names);
  2739. }
  2740. /**
  2741. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  2742. *
  2743. * @param int[] $scydgyIds
  2744. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  2745. */
  2746. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  2747. {
  2748. $out = [];
  2749. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2750. if ($scydgyIds === []) {
  2751. return $out;
  2752. }
  2753. try {
  2754. $rows = Db::table('purchase_order_detail')
  2755. ->where('scydgy_id', 'in', $scydgyIds)
  2756. ->field('scydgy_id,company_name,amount')
  2757. ->select();
  2758. } catch (\Throwable $e) {
  2759. $rows = [];
  2760. }
  2761. if (!is_array($rows)) {
  2762. return $out;
  2763. }
  2764. foreach ($rows as $r) {
  2765. if (!is_array($r)) {
  2766. continue;
  2767. }
  2768. $sid = (int)($r['scydgy_id'] ?? 0);
  2769. $cn = trim((string)($r['company_name'] ?? ''));
  2770. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2771. continue;
  2772. }
  2773. if (!isset($out[$sid])) {
  2774. $out[$sid] = ['all' => [], 'quoted' => []];
  2775. }
  2776. $out[$sid]['all'][$cn] = true;
  2777. $am = trim((string)($r['amount'] ?? ''));
  2778. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2779. $out[$sid]['quoted'][$cn] = true;
  2780. }
  2781. }
  2782. return $out;
  2783. }
  2784. /**
  2785. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  2786. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  2787. */
  2788. protected function mergeQuotedSupplierBuckets(array $buckets): array
  2789. {
  2790. $merged = ['all' => [], 'quoted' => []];
  2791. foreach ($buckets as $b) {
  2792. if (!is_array($b)) {
  2793. continue;
  2794. }
  2795. foreach ($b['all'] ?? [] as $cn => $_) {
  2796. $merged['all'][$cn] = true;
  2797. }
  2798. foreach ($b['quoted'] ?? [] as $cn => $_) {
  2799. $merged['quoted'][$cn] = true;
  2800. }
  2801. }
  2802. return $merged;
  2803. }
  2804. /**
  2805. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  2806. */
  2807. protected function formatQuotedSupplierLines(array $bucket): string
  2808. {
  2809. return ProcuremenFormat::quotedSupplierLines($bucket);
  2810. }
  2811. /**
  2812. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  2813. */
  2814. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  2815. {
  2816. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2817. $this->view->engine->layout(false);
  2818. try {
  2819. $bodyHtml = $this->view->fetch($view);
  2820. $this->view->assign('dialogBody', $bodyHtml);
  2821. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  2822. return $this->view->fetch('procuremen/dialog_lite_shell');
  2823. } finally {
  2824. if ($restoreLayout) {
  2825. $this->view->engine->layout($restoreLayout);
  2826. }
  2827. }
  2828. }
  2829. /**
  2830. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  2831. */
  2832. protected function resolveBundleSysRq(array $bundle): string
  2833. {
  2834. foreach ($bundle['pos'] ?? [] as $po) {
  2835. if (!is_array($po)) {
  2836. continue;
  2837. }
  2838. $sr = trim((string)($po['sys_rq'] ?? ''));
  2839. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  2840. return $sr;
  2841. }
  2842. }
  2843. return '';
  2844. }
  2845. /**
  2846. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  2847. */
  2848. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  2849. {
  2850. $raw = trim((string)$sysRq);
  2851. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  2852. return true;
  2853. }
  2854. $ts = strtotime(str_replace('T', ' ', $raw));
  2855. if ($ts === false || $ts <= 0) {
  2856. return true;
  2857. }
  2858. return time() >= $ts;
  2859. }
  2860. /**
  2861. * 开标前校验:必须已过报价截止时间
  2862. *
  2863. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2864. */
  2865. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  2866. {
  2867. $sysRq = $this->resolveBundleSysRq($bundle);
  2868. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  2869. $this->error('未到招标截止日期');
  2870. }
  2871. }
  2872. /**
  2873. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  2874. *
  2875. * @param array<string, mixed> $d
  2876. * @param string $deliveryYmd
  2877. */
  2878. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  2879. {
  2880. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  2881. return max(0, (int)$d['lead_days']);
  2882. }
  2883. if ($deliveryYmd === '') {
  2884. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  2885. }
  2886. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  2887. return null;
  2888. }
  2889. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2890. $t2 = strtotime($m[1] . ' 00:00:00');
  2891. if ($t1 === false || $t2 === false) {
  2892. return null;
  2893. }
  2894. return max(0, (int)round(($t2 - $t1) / 86400));
  2895. }
  2896. /**
  2897. * @param int|null $days
  2898. */
  2899. protected function formatProcuremenLeadDaysText($days): string
  2900. {
  2901. return ProcuremenFormat::leadDaysText($days);
  2902. }
  2903. /**
  2904. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2905. *
  2906. * @param array<string, mixed> $line
  2907. */
  2908. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2909. {
  2910. $amountFilled = !empty($line['amount_filled']);
  2911. $deliveryFilled = !empty($line['delivery_filled']);
  2912. $leadFilled = !empty($line['lead_days_filled']);
  2913. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2914. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2915. $line['amount_show'] = '';
  2916. if (array_key_exists('amount_text', $line)) {
  2917. $line['amount_text'] = $line['unit_price_text'];
  2918. }
  2919. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2920. $line['delivery_show'] = $deliveryText;
  2921. if (array_key_exists('delivery_text', $line)) {
  2922. $line['delivery_text'] = $deliveryText;
  2923. }
  2924. $line['delivery_ymd'] = '';
  2925. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2926. $line['lead_days_show'] = $leadText;
  2927. $line['lead_days_text'] = $leadText;
  2928. $line['lead_days'] = '';
  2929. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2930. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2931. $line['subtotal_num'] = null;
  2932. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2933. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2934. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2935. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2936. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2937. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2938. $line['amount_filled'] = false;
  2939. $line['delivery_filled'] = false;
  2940. $line['lead_days_filled'] = false;
  2941. $line['is_quoted'] = false;
  2942. if (array_key_exists('quote_label', $line)) {
  2943. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2944. }
  2945. }
  2946. protected function ensurePurchaseOrderBidOpenTable(): void
  2947. {
  2948. static $ready = false;
  2949. if ($ready) {
  2950. return;
  2951. }
  2952. $cacheKey = 'procuremen_bid_open_table_ok_v2';
  2953. try {
  2954. if (Cache::get($cacheKey)) {
  2955. $ready = true;
  2956. return;
  2957. }
  2958. } catch (\Throwable $e) {
  2959. }
  2960. try {
  2961. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2962. $ready = true;
  2963. try {
  2964. Cache::set($cacheKey, 1, 86400);
  2965. } catch (\Throwable $e) {
  2966. }
  2967. } catch (\Throwable $e) {
  2968. Db::execute(
  2969. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2970. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2971. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2972. `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号(多订单同批开标)',
  2973. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2974. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2975. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2976. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2977. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2978. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2979. `createtime` datetime DEFAULT NULL,
  2980. PRIMARY KEY (`id`),
  2981. UNIQUE KEY `uk_ccydh` (`ccydh`),
  2982. KEY `idx_order_batch_no` (`order_batch_no`)
  2983. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2984. );
  2985. $ready = true;
  2986. try {
  2987. Cache::set($cacheKey, 1, 86400);
  2988. } catch (\Throwable $e2) {
  2989. }
  2990. }
  2991. // 旧表兼容:补批次号列(不影响已有按订单号的开标记录)
  2992. try {
  2993. $cols = Db::query("SHOW COLUMNS FROM `purchase_order_bid_open` LIKE 'order_batch_no'");
  2994. if (!is_array($cols) || $cols === []) {
  2995. Db::execute(
  2996. "ALTER TABLE `purchase_order_bid_open` ADD COLUMN `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号(多订单同批开标)' AFTER `ccydh`"
  2997. );
  2998. }
  2999. } catch (\Throwable $e) {
  3000. // ignore
  3001. }
  3002. try {
  3003. $idx = Db::query("SHOW INDEX FROM `purchase_order_bid_open` WHERE Key_name = 'idx_order_batch_no'");
  3004. if (!is_array($idx) || $idx === []) {
  3005. Db::execute('ALTER TABLE `purchase_order_bid_open` ADD INDEX `idx_order_batch_no` (`order_batch_no`)');
  3006. }
  3007. } catch (\Throwable $e) {
  3008. // ignore
  3009. }
  3010. }
  3011. /**
  3012. * 列表/合并行订单号可能为「A、B」拼接,拆成单个订单号
  3013. *
  3014. * @param mixed $raw
  3015. * @return array<int, string>
  3016. */
  3017. protected function expandProcuremenCcydhTokens($raw): array
  3018. {
  3019. $s = trim((string)$raw);
  3020. if ($s === '') {
  3021. return [];
  3022. }
  3023. $parts = preg_split('/[、;;,\n\r]+/u', $s);
  3024. if (!is_array($parts)) {
  3025. return [$s];
  3026. }
  3027. $out = [];
  3028. foreach ($parts as $p) {
  3029. $p = trim((string)$p);
  3030. if ($p !== '' && !in_array($p, $out, true)) {
  3031. $out[] = $p;
  3032. }
  3033. }
  3034. return $out;
  3035. }
  3036. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  3037. {
  3038. $ccydh = trim($ccydh);
  3039. if ($ccydh === '') {
  3040. return false;
  3041. }
  3042. $this->ensurePurchaseOrderBidOpenTable();
  3043. try {
  3044. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3045. return is_array($row);
  3046. } catch (\Throwable $e) {
  3047. return false;
  3048. }
  3049. }
  3050. protected function isProcuremenBidOpenVerifiedByBatchNo(string $batchNo): bool
  3051. {
  3052. $batchNo = trim($batchNo);
  3053. if ($batchNo === '') {
  3054. return false;
  3055. }
  3056. $this->ensurePurchaseOrderBidOpenTable();
  3057. try {
  3058. $row = Db::table('purchase_order_bid_open')
  3059. ->where('order_batch_no', $batchNo)
  3060. ->find();
  3061. return is_array($row);
  3062. } catch (\Throwable $e) {
  3063. return false;
  3064. }
  3065. }
  3066. /**
  3067. * 批量查询订单是否已开标验证(入参支持「A、B」拼接)
  3068. *
  3069. * @param array<int, string> $ccydhs
  3070. * @return array<string, bool> ccydh => true
  3071. */
  3072. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  3073. {
  3074. $set = [];
  3075. $list = [];
  3076. foreach ($ccydhs as $c) {
  3077. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  3078. $list[$one] = true;
  3079. }
  3080. }
  3081. if ($list === []) {
  3082. return $set;
  3083. }
  3084. $this->ensurePurchaseOrderBidOpenTable();
  3085. try {
  3086. $rows = Db::table('purchase_order_bid_open')
  3087. ->where('ccydh', 'in', array_keys($list))
  3088. ->field('ccydh')
  3089. ->select();
  3090. foreach ($rows as $row) {
  3091. if (!is_array($row)) {
  3092. continue;
  3093. }
  3094. $c = trim((string)($row['ccydh'] ?? ''));
  3095. if ($c !== '') {
  3096. $set[$c] = true;
  3097. }
  3098. }
  3099. } catch (\Throwable $e) {
  3100. return [];
  3101. }
  3102. return $set;
  3103. }
  3104. /**
  3105. * 批量查询批次是否已开标
  3106. *
  3107. * @param array<int, string> $batchNos
  3108. * @return array<string, bool>
  3109. */
  3110. protected function loadProcuremenBidOpenVerifiedBatchSet(array $batchNos): array
  3111. {
  3112. $set = [];
  3113. $list = [];
  3114. foreach ($batchNos as $b) {
  3115. $b = trim((string)$b);
  3116. if ($b !== '') {
  3117. $list[$b] = true;
  3118. }
  3119. }
  3120. if ($list === []) {
  3121. return $set;
  3122. }
  3123. $this->ensurePurchaseOrderBidOpenTable();
  3124. try {
  3125. $rows = Db::table('purchase_order_bid_open')
  3126. ->where('order_batch_no', 'in', array_keys($list))
  3127. ->field('order_batch_no')
  3128. ->select();
  3129. foreach ($rows as $row) {
  3130. if (!is_array($row)) {
  3131. continue;
  3132. }
  3133. $b = trim((string)($row['order_batch_no'] ?? ''));
  3134. if ($b !== '') {
  3135. $set[$b] = true;
  3136. }
  3137. }
  3138. } catch (\Throwable $e) {
  3139. return [];
  3140. }
  3141. return $set;
  3142. }
  3143. /**
  3144. * 批量查询订单是否已指定供应商(免开标;入参支持「A、B」拼接)
  3145. * 仅统计未软删除行(mod_rq 空)
  3146. *
  3147. * @param array<int, string> $ccydhs
  3148. * @return array<string, bool> ccydh => true
  3149. */
  3150. protected function loadProcuremenManualPickedCcydhSet(array $ccydhs): array
  3151. {
  3152. $set = [];
  3153. $list = [];
  3154. foreach ($ccydhs as $c) {
  3155. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  3156. $list[$one] = true;
  3157. }
  3158. }
  3159. if ($list === []) {
  3160. return $set;
  3161. }
  3162. $this->ensurePurchaseOrderManualPickColumns();
  3163. try {
  3164. $q = Db::table('purchase_order')
  3165. ->where('CCYDH', 'in', array_keys($list))
  3166. ->where('manual_pick', 1)
  3167. ->whereRaw("(mod_rq IS NULL OR mod_rq = '' OR mod_rq LIKE '0000-00-00%')")
  3168. ->field('CCYDH');
  3169. $rows = $q->select();
  3170. foreach ($rows as $row) {
  3171. if (!is_array($row)) {
  3172. continue;
  3173. }
  3174. $c = trim((string)($row['CCYDH'] ?? ''));
  3175. if ($c !== '') {
  3176. $set[$c] = true;
  3177. }
  3178. }
  3179. } catch (\Throwable $e) {
  3180. return [];
  3181. }
  3182. return $set;
  3183. }
  3184. /**
  3185. * 清除开标验证记录(按订单号 + 批次号)
  3186. *
  3187. * @param array<int, string> $ccydhs
  3188. * @param array<int, string> $batchNos
  3189. */
  3190. protected function clearProcuremenBidOpenRecords(array $ccydhs = [], array $batchNos = []): void
  3191. {
  3192. $ccydhList = [];
  3193. foreach ($ccydhs as $c) {
  3194. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  3195. $ccydhList[$one] = true;
  3196. }
  3197. }
  3198. $batchList = [];
  3199. foreach ($batchNos as $b) {
  3200. $b = trim((string)$b);
  3201. if ($b !== '') {
  3202. $batchList[$b] = true;
  3203. }
  3204. }
  3205. if ($ccydhList === [] && $batchList === []) {
  3206. return;
  3207. }
  3208. try {
  3209. $this->ensurePurchaseOrderBidOpenTable();
  3210. if ($ccydhList !== []) {
  3211. Db::table('purchase_order_bid_open')->where('ccydh', 'in', array_keys($ccydhList))->delete();
  3212. }
  3213. if ($batchList !== []) {
  3214. Db::table('purchase_order_bid_open')->where('order_batch_no', 'in', array_keys($batchList))->delete();
  3215. }
  3216. } catch (\Throwable $e) {
  3217. // ignore
  3218. }
  3219. }
  3220. /**
  3221. * 新下发/重新下发:同订单号+同工序下「其它有明确批次号」的未完结主单记 mod_rq 软删除。
  3222. * 不处理:本批保留行、无批次号旧数据、已完结单(避免误伤生产并行工序)。
  3223. *
  3224. * @param array<int, string> $ccydhs
  3225. * @param array<int, int|string> $keepScydgyIds 保留的工序 ID(本批)
  3226. * @param string $keepBatchNo 本批批次号(同批其它工序行也保留)
  3227. * @param array<int, string> $cgySet 本批工序名称集合(防止同订单不同工序被误删)
  3228. * @return array<int, true> 实际被软删的 scydgy_id 集合
  3229. */
  3230. protected function softDeleteOtherBatchPurchaseOrders(array $ccydhs, array $keepScydgyIds = [], string $keepBatchNo = '', array $cgySet = []): array
  3231. {
  3232. $ccydhList = [];
  3233. foreach ($ccydhs as $c) {
  3234. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  3235. $ccydhList[$one] = true;
  3236. }
  3237. }
  3238. $keepBatchNo = trim($keepBatchNo);
  3239. // 无本批批次号时不做软删,避免把同订单其它有效工序一并清掉
  3240. if ($ccydhList === [] || $keepBatchNo === '') {
  3241. return [];
  3242. }
  3243. $keepSid = [];
  3244. foreach ($keepScydgyIds as $sid) {
  3245. $sid = (int)$sid;
  3246. if ($this->isValidScydgyRowId($sid)) {
  3247. $keepSid[$sid] = true;
  3248. }
  3249. }
  3250. $now = date('Y-m-d H:i:s');
  3251. $bnEsc = str_replace(["\\", "'"], ["\\\\", "''"], $keepBatchNo);
  3252. try {
  3253. $q = Db::table('purchase_order')
  3254. ->where('CCYDH', 'in', array_keys($ccydhList))
  3255. ->whereRaw("(mod_rq IS NULL OR mod_rq = '' OR mod_rq LIKE '0000-00-00%')")
  3256. // 仅软删「其它非空批次」;空批次号旧数据留给展示层按批次隔离
  3257. ->whereRaw("TRIM(CAST(order_batch_no AS CHAR(64))) <> ''")
  3258. ->whereRaw("order_batch_no <> '{$bnEsc}'")
  3259. // 已完结不软删
  3260. ->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  3261. // 按工序名称隔离,防止同订单不同工序被误删
  3262. if ($cgySet !== []) {
  3263. $cgyEscList = [];
  3264. foreach ($cgySet as $cgy) {
  3265. $cgyEsc = str_replace(["\\", "'"], ["\\\\", "''"], trim((string)$cgy));
  3266. if ($cgyEsc !== '') {
  3267. $cgyEscList[] = "'" . $cgyEsc . "'";
  3268. }
  3269. }
  3270. if ($cgyEscList !== []) {
  3271. $q->whereRaw("CGYMC IN (" . implode(',', $cgyEscList) . ")");
  3272. }
  3273. }
  3274. if ($keepSid !== []) {
  3275. $q->where('scydgy_id', 'not in', array_keys($keepSid));
  3276. }
  3277. $q->update([
  3278. 'mod_rq' => $now,
  3279. 'manual_pick' => 0,
  3280. 'manual_pick_reason' => '',
  3281. ]);
  3282. // 返回本次实际被软删的 scydgy_id,供调用方废弃明细用
  3283. return Db::table('purchase_order')
  3284. ->where('CCYDH', 'in', array_keys($ccydhList))
  3285. ->whereRaw("(mod_rq IS NULL OR mod_rq = '' OR mod_rq LIKE '0000-00-00%')")
  3286. ->whereRaw("TRIM(CAST(order_batch_no AS CHAR(64))) <> ''")
  3287. ->whereRaw("order_batch_no <> '{$bnEsc}'")
  3288. ->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')')
  3289. ->where('mod_rq', $now)
  3290. ->column('scydgy_id');
  3291. } catch (\Throwable $e) {
  3292. Log::write('softDeleteOtherBatchPurchaseOrders: ' . $e->getMessage(), 'error');
  3293. return [];
  3294. }
  3295. }
  3296. /**
  3297. * 重新下发/新下发:清掉按订单号落库的供应商评分,避免旧批 0 分/旧排名串到新批
  3298. *
  3299. * @param array<int, string> $ccydhs
  3300. */
  3301. protected function clearProcuremenSupplierScoresForCcydhs(array $ccydhs): void
  3302. {
  3303. $list = [];
  3304. foreach ($ccydhs as $c) {
  3305. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  3306. $list[$one] = true;
  3307. }
  3308. }
  3309. if ($list === []) {
  3310. return;
  3311. }
  3312. try {
  3313. Db::table('supplier_service_score')->where('ccydh', 'in', array_keys($list))->delete();
  3314. } catch (\Throwable $e) {
  3315. Log::write('clearProcuremenSupplierScoresForCcydhs: ' . $e->getMessage(), 'error');
  3316. }
  3317. }
  3318. /**
  3319. * 列表行开标状态:有批次号时只认本批次开标/本行指定,避免同订单号旧批串读
  3320. *
  3321. * @param array<string, mixed> $rw
  3322. * @param array<string, bool> $bidOpenSet
  3323. * @param array<string, bool> $manualPickSet
  3324. * @param array<string, bool> $bidOpenBatchSet
  3325. * @return array{verified:bool,manual:bool,text:string}
  3326. */
  3327. protected function resolveProcuremenListBidOpenState(
  3328. array $rw,
  3329. array $bidOpenSet,
  3330. array $manualPickSet,
  3331. array $bidOpenBatchSet = []
  3332. ): array {
  3333. $batchNo = $this->resolveProcuremenOrderBatchNo($rw);
  3334. if ($batchNo === '' && !empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3335. foreach ($rw['_order_merge_rows'] as $mr) {
  3336. if (!is_array($mr)) {
  3337. continue;
  3338. }
  3339. $batchNo = $this->resolveProcuremenOrderBatchNo($mr);
  3340. if ($batchNo !== '') {
  3341. break;
  3342. }
  3343. }
  3344. }
  3345. $manual = ((int)($rw['manual_pick'] ?? 0) === 1);
  3346. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3347. foreach ($rw['_order_merge_rows'] as $mr) {
  3348. if (!is_array($mr)) {
  3349. continue;
  3350. }
  3351. // 合并行仅认同一批次(无批次号时退回同订单兼容)
  3352. if ($batchNo !== '') {
  3353. $mrBatch = $this->resolveProcuremenOrderBatchNo($mr);
  3354. if ($mrBatch !== '' && $mrBatch !== $batchNo) {
  3355. continue;
  3356. }
  3357. }
  3358. if ((int)($mr['manual_pick'] ?? 0) === 1) {
  3359. $manual = true;
  3360. }
  3361. }
  3362. }
  3363. // 收集本行/合并行订单号,供开标记录与自选集合兜底(自选=免开标,等同已开标可继续确认)
  3364. $ccydhTokens = $this->expandProcuremenCcydhTokens($rw['CCYDH'] ?? '');
  3365. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3366. foreach ($rw['_order_merge_rows'] as $mr) {
  3367. if (!is_array($mr)) {
  3368. continue;
  3369. }
  3370. if ($batchNo !== '') {
  3371. $mrBatch = $this->resolveProcuremenOrderBatchNo($mr);
  3372. if ($mrBatch !== '' && $mrBatch !== $batchNo) {
  3373. continue;
  3374. }
  3375. }
  3376. foreach ($this->expandProcuremenCcydhTokens($mr['CCYDH'] ?? '') as $one) {
  3377. if (!in_array($one, $ccydhTokens, true)) {
  3378. $ccydhTokens[] = $one;
  3379. }
  3380. }
  3381. }
  3382. }
  3383. if ($batchNo !== '') {
  3384. // 有正式批次号:开标只看本批
  3385. $verified = isset($bidOpenBatchSet[$batchNo]);
  3386. // 自选兜底:本行字段漏带时,仍可用有效主单上的自选标记(旧批已软删,不会串读)
  3387. if (!$manual) {
  3388. foreach ($ccydhTokens as $c) {
  3389. if (isset($manualPickSet[$c])) {
  3390. $manual = true;
  3391. break;
  3392. }
  3393. }
  3394. }
  3395. } else {
  3396. // 旧数据无批次号:兼容按订单号开标/指定
  3397. $verified = false;
  3398. foreach ($ccydhTokens as $c) {
  3399. if (isset($bidOpenSet[$c])) {
  3400. $verified = true;
  3401. }
  3402. if (isset($manualPickSet[$c])) {
  3403. $manual = true;
  3404. }
  3405. }
  3406. }
  3407. if ($verified) {
  3408. $text = '已开标';
  3409. } elseif ($manual) {
  3410. $text = '已指定供应商';
  3411. } else {
  3412. $text = '待开标';
  3413. }
  3414. return ['verified' => $verified, 'manual' => $manual, 'text' => $text];
  3415. }
  3416. /**
  3417. * 确认供应商列表:按开标状态筛选(已开标 / 已指定供应商 / 待开标)
  3418. *
  3419. * @param array<int, array<string, mixed>> $pool
  3420. * @return array<int, array<string, mixed>>
  3421. */
  3422. protected function filterProcuremenPoolByBidOpenStatus(array $pool, string $status): array
  3423. {
  3424. $status = trim($status);
  3425. if ($status === '' || !in_array($status, ['待开标', '已开标', '已指定供应商'], true)) {
  3426. return $pool;
  3427. }
  3428. $ccydhList = [];
  3429. $batchList = [];
  3430. foreach ($pool as $rw) {
  3431. if (!is_array($rw)) {
  3432. continue;
  3433. }
  3434. $c = trim((string)($rw['CCYDH'] ?? ''));
  3435. if ($c !== '') {
  3436. $ccydhList[] = $c;
  3437. }
  3438. $b = $this->resolveProcuremenOrderBatchNo($rw);
  3439. if ($b !== '') {
  3440. $batchList[] = $b;
  3441. }
  3442. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3443. foreach ($rw['_order_merge_rows'] as $mr) {
  3444. if (!is_array($mr)) {
  3445. continue;
  3446. }
  3447. $cm = trim((string)($mr['CCYDH'] ?? ''));
  3448. if ($cm !== '') {
  3449. $ccydhList[] = $cm;
  3450. }
  3451. $bm = $this->resolveProcuremenOrderBatchNo($mr);
  3452. if ($bm !== '') {
  3453. $batchList[] = $bm;
  3454. }
  3455. }
  3456. }
  3457. }
  3458. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  3459. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  3460. $bidOpenBatchSet = $this->loadProcuremenBidOpenVerifiedBatchSet($batchList);
  3461. $out = [];
  3462. foreach ($pool as $rw) {
  3463. if (!is_array($rw)) {
  3464. continue;
  3465. }
  3466. $state = $this->resolveProcuremenListBidOpenState($rw, $bidOpenSet, $manualPickSet, $bidOpenBatchSet);
  3467. if (($state['text'] ?? '') === $status) {
  3468. $out[] = $rw;
  3469. }
  3470. }
  3471. return $out;
  3472. }
  3473. /**
  3474. * 按订单状态筛选(待确认 / 已驳回 / 待审核 / 已审核)
  3475. *
  3476. * @param array<int, array<string, mixed>> $pool
  3477. * @return array<int, array<string, mixed>>
  3478. */
  3479. protected function filterProcuremenPoolByOrderStatus(array $pool, string $status): array
  3480. {
  3481. $status = trim($status);
  3482. if ($status === '' || !in_array($status, ['待确认', '已驳回', '待审核', '已审核'], true)) {
  3483. return $pool;
  3484. }
  3485. $out = [];
  3486. foreach ($pool as $rw) {
  3487. if (!is_array($rw)) {
  3488. continue;
  3489. }
  3490. $label = trim((string)($rw['order_status_text'] ?? ''));
  3491. if ($label === '') {
  3492. $label = ProcuremenStatus::orderStatusLabelForList($rw['wflow_status'] ?? '');
  3493. }
  3494. if ($label === $status) {
  3495. $out[] = $rw;
  3496. }
  3497. }
  3498. return $out;
  3499. }
  3500. /**
  3501. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  3502. *
  3503. * @param array<string, mixed> $group
  3504. */
  3505. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  3506. {
  3507. if ($quoteVisible) {
  3508. $group['remark_quote_pending'] = 0;
  3509. return;
  3510. }
  3511. $group['remark'] = '';
  3512. $group['remark_quote_pending'] = 0;
  3513. }
  3514. /**
  3515. * 下发订单备注 MBZ(印件规格),不是供应商填写
  3516. *
  3517. * @param array{pos?:array, merge_rows?:array} $bundle
  3518. */
  3519. protected function resolveBundleOrderMbz(array $bundle): string
  3520. {
  3521. foreach (['pos', 'merge_rows'] as $key) {
  3522. foreach ($bundle[$key] ?? [] as $row) {
  3523. if (!is_array($row)) {
  3524. continue;
  3525. }
  3526. $mbz = trim((string)($row['MBZ'] ?? $row['mbz'] ?? ''));
  3527. if ($mbz !== '') {
  3528. return $mbz;
  3529. }
  3530. }
  3531. }
  3532. return '';
  3533. }
  3534. /**
  3535. * 供应商自己填的备注;与订单 MBZ 相同视为未填(历史误把规格写入明细)
  3536. */
  3537. protected function resolveSupplierOwnRemark($detailRemark, $orderMbz = ''): string
  3538. {
  3539. $own = trim((string)$detailRemark);
  3540. $mbz = trim((string)$orderMbz);
  3541. if ($own === '' || ($mbz !== '' && $own === $mbz)) {
  3542. return '';
  3543. }
  3544. return $own;
  3545. }
  3546. /**
  3547. * 供应商备注展示:仅自己填写的;有工序行时始终占一行「投标备注」(空也显示标签)
  3548. *
  3549. * @param array<string, mixed> $group
  3550. */
  3551. protected function finalizeSupplierRemarkDisplay(array &$group, string $orderMbz, bool $quoteVisible): void
  3552. {
  3553. $group['remark'] = $this->resolveSupplierOwnRemark($group['remark'] ?? '', $orderMbz);
  3554. $this->maskSupplierRemarkBeforeBidOpen($group, $quoteVisible);
  3555. $lineCount = (int)($group['line_count'] ?? 0);
  3556. if ($lineCount <= 0) {
  3557. $lines = $group['lines'] ?? $group['pick_lines'] ?? [];
  3558. $lineCount = is_array($lines) ? count($lines) : 0;
  3559. }
  3560. // 与手机端一致:有供应商工序行就显示投标备注行,内容可为空
  3561. $group['has_remark'] = $lineCount > 0;
  3562. $extra = (!empty($group['has_remark']) ? 1 : 0) + (!empty($group['has_total']) ? 1 : 0);
  3563. $group['display_rowspan'] = $lineCount > 0 ? ($lineCount + $extra) : 0;
  3564. }
  3565. /**
  3566. * @param array{ccydh?:string,pos?:array,order_batch_no?:string} $bundle
  3567. */
  3568. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  3569. {
  3570. $batchNo = $this->resolveBundleOrderBatchNo($bundle);
  3571. // 有批次号:只认本批开标,避免同订单号历史开标串到新批
  3572. if ($batchNo !== '') {
  3573. return $this->isProcuremenBidOpenVerifiedByBatchNo($batchNo);
  3574. }
  3575. $list = [];
  3576. foreach ($bundle['pos'] ?? [] as $po) {
  3577. if (!is_array($po)) {
  3578. continue;
  3579. }
  3580. foreach ($this->expandProcuremenCcydhTokens($po['CCYDH'] ?? '') as $dh) {
  3581. $list[$dh] = true;
  3582. }
  3583. }
  3584. $primary = trim((string)($bundle['ccydh'] ?? ''));
  3585. foreach ($this->expandProcuremenCcydhTokens($primary) as $dh) {
  3586. $list[$dh] = true;
  3587. }
  3588. if ($list === []) {
  3589. return false;
  3590. }
  3591. // 旧数据无批次号:全部订单号都有开标记录才算已开标
  3592. foreach (array_keys($list) as $ccydh) {
  3593. if (!$this->isProcuremenBidOpenVerified($ccydh)) {
  3594. return false;
  3595. }
  3596. }
  3597. return true;
  3598. }
  3599. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  3600. {
  3601. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  3602. return true;
  3603. }
  3604. return $this->isProcuremenManualPickedForBundle($bundle);
  3605. }
  3606. /**
  3607. * 确保 purchase_order 自选供应商字段
  3608. */
  3609. protected function ensurePurchaseOrderManualPickColumns(): void
  3610. {
  3611. static $done = false;
  3612. if ($done) {
  3613. return;
  3614. }
  3615. $done = true;
  3616. $adds = [
  3617. 'manual_pick' => "ADD COLUMN `manual_pick` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=自选供应商(免开标)' AFTER `pick_company_name`",
  3618. 'manual_pick_reason' => "ADD COLUMN `manual_pick_reason` varchar(500) NOT NULL DEFAULT '' COMMENT '自选供应商选择说明' AFTER `manual_pick`",
  3619. ];
  3620. foreach ($adds as $col => $ddl) {
  3621. try {
  3622. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  3623. if (!is_array($cols) || $cols === []) {
  3624. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  3625. }
  3626. } catch (\Throwable $e) {
  3627. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  3628. }
  3629. }
  3630. }
  3631. /**
  3632. * 是否已自选供应商(免开标查看报价)——仅看本 bundle 行,不按订单号串旧批
  3633. *
  3634. * @param array{pos?:array} $bundle
  3635. */
  3636. protected function isProcuremenManualPickedForBundle(array $bundle): bool
  3637. {
  3638. $this->ensurePurchaseOrderManualPickColumns();
  3639. foreach ($bundle['pos'] ?? [] as $poRow) {
  3640. if (!is_array($poRow)) {
  3641. continue;
  3642. }
  3643. if ((int)($poRow['manual_pick'] ?? 0) === 1) {
  3644. return true;
  3645. }
  3646. }
  3647. return false;
  3648. }
  3649. /**
  3650. * @param array{pos?:array} $bundle
  3651. * @return array{company:string,reason:string}
  3652. */
  3653. protected function resolveProcuremenManualPickInfo(array $bundle): array
  3654. {
  3655. $this->ensurePurchaseOrderManualPickColumns();
  3656. foreach ($bundle['pos'] ?? [] as $poRow) {
  3657. if (!is_array($poRow)) {
  3658. continue;
  3659. }
  3660. if ((int)($poRow['manual_pick'] ?? 0) !== 1) {
  3661. continue;
  3662. }
  3663. $cn = trim((string)($poRow['pick_company_name'] ?? ''));
  3664. $reason = trim((string)($poRow['manual_pick_reason'] ?? ''));
  3665. return ['company' => $cn, 'reason' => $reason];
  3666. }
  3667. return ['company' => '', 'reason' => ''];
  3668. }
  3669. protected function loadBidOpenAdminUser(int $adminId): ?array
  3670. {
  3671. if ($adminId <= 0) {
  3672. return null;
  3673. }
  3674. try {
  3675. $row = Db::name('admin')->where('id', $adminId)->find();
  3676. } catch (\Throwable $e) {
  3677. return null;
  3678. }
  3679. if (!is_array($row)) {
  3680. return null;
  3681. }
  3682. $status = strtolower(trim((string)($row['status'] ?? '')));
  3683. if ($status !== '' && $status !== 'normal') {
  3684. return null;
  3685. }
  3686. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  3687. return null;
  3688. }
  3689. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  3690. if (!preg_match('/^1\d{10}$/', $phone)) {
  3691. return null;
  3692. }
  3693. $name = trim((string)($row['nickname'] ?? ''));
  3694. if ($name === '') {
  3695. $name = trim((string)($row['username'] ?? ''));
  3696. }
  3697. return [
  3698. 'id' => (int)$row['id'],
  3699. 'username' => trim((string)($row['username'] ?? '')),
  3700. 'nickname' => $name,
  3701. 'mobile' => $phone,
  3702. ];
  3703. }
  3704. /**
  3705. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  3706. */
  3707. protected function bidOpenVerifierAuthGroupRootId(): int
  3708. {
  3709. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  3710. return $id > 0 ? $id : 10;
  3711. }
  3712. /**
  3713. * @return int[]
  3714. */
  3715. protected function loadBidOpenVerifierAuthGroupIds(): array
  3716. {
  3717. static $memo = [];
  3718. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  3719. if (isset($memo[$rootId])) {
  3720. return $memo[$rootId];
  3721. }
  3722. try {
  3723. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  3724. } catch (\Throwable $e) {
  3725. $memo[$rootId] = [$rootId];
  3726. return $memo[$rootId];
  3727. }
  3728. if (!is_array($groups) || $groups === []) {
  3729. $memo[$rootId] = [$rootId];
  3730. return $memo[$rootId];
  3731. }
  3732. $groupList = [];
  3733. foreach ($groups as $g) {
  3734. if (is_array($g)) {
  3735. $groupList[] = $g;
  3736. }
  3737. }
  3738. if ($groupList === []) {
  3739. $memo[$rootId] = [$rootId];
  3740. return $memo[$rootId];
  3741. }
  3742. $tree = \fast\Tree::instance();
  3743. $tree->init($groupList);
  3744. $ids = $tree->getChildrenIds($rootId, true);
  3745. if (!is_array($ids) || $ids === []) {
  3746. $memo[$rootId] = [$rootId];
  3747. return $memo[$rootId];
  3748. }
  3749. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  3750. return $memo[$rootId];
  3751. }
  3752. protected function isBidOpenVerifierAdmin(int $adminId): bool
  3753. {
  3754. if ($adminId <= 0) {
  3755. return false;
  3756. }
  3757. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3758. if ($groupIds === []) {
  3759. return false;
  3760. }
  3761. try {
  3762. return (bool)Db::name('auth_group_access')
  3763. ->where('uid', $adminId)
  3764. ->where('group_id', 'in', $groupIds)
  3765. ->count();
  3766. } catch (\Throwable $e) {
  3767. return false;
  3768. }
  3769. }
  3770. /**
  3771. * @return array<int, array<string, mixed>>
  3772. */
  3773. protected function listBidOpenVerifierCandidates(): array
  3774. {
  3775. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3776. if ($groupIds === []) {
  3777. return [];
  3778. }
  3779. try {
  3780. $adminIds = Db::name('auth_group_access')
  3781. ->where('group_id', 'in', $groupIds)
  3782. ->column('uid');
  3783. } catch (\Throwable $e) {
  3784. $adminIds = [];
  3785. }
  3786. $adminIds = is_array($adminIds)
  3787. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  3788. : [];
  3789. if ($adminIds === []) {
  3790. return [];
  3791. }
  3792. try {
  3793. $rows = Db::name('admin')
  3794. ->where('status', 'normal')
  3795. ->where('id', 'in', $adminIds)
  3796. ->where('mobile', '<>', '')
  3797. ->order('id', 'asc')
  3798. ->select();
  3799. } catch (\Throwable $e) {
  3800. return [];
  3801. }
  3802. if (!is_array($rows)) {
  3803. return [];
  3804. }
  3805. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  3806. $out = [];
  3807. foreach ($rows as $row) {
  3808. if (!is_array($row)) {
  3809. continue;
  3810. }
  3811. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  3812. if ($one === null) {
  3813. continue;
  3814. }
  3815. $out[] = [
  3816. 'id' => $one['id'],
  3817. 'username' => $one['username'],
  3818. 'nickname' => $one['nickname'],
  3819. 'group_name' => $groupNameMap[$one['id']] ?? '',
  3820. 'mobile' => mask_phone($one['mobile']),
  3821. 'mobile_plain' => (string)$one['mobile'],
  3822. ];
  3823. }
  3824. return $out;
  3825. }
  3826. /**
  3827. * @param int[] $adminIds
  3828. * @return array<int, string>
  3829. */
  3830. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  3831. {
  3832. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  3833. if ($adminIds === []) {
  3834. return [];
  3835. }
  3836. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3837. try {
  3838. $rows = Db::name('auth_group_access')
  3839. ->alias('aga')
  3840. ->join('auth_group ag', 'aga.group_id = ag.id')
  3841. ->where('aga.uid', 'in', $adminIds)
  3842. ->where('aga.group_id', 'in', $groupIds)
  3843. ->field('aga.uid,ag.name')
  3844. ->order('aga.uid', 'asc')
  3845. ->order('aga.group_id', 'asc')
  3846. ->select();
  3847. } catch (\Throwable $e) {
  3848. return [];
  3849. }
  3850. if (!is_array($rows)) {
  3851. return [];
  3852. }
  3853. $out = [];
  3854. foreach ($rows as $row) {
  3855. if (!is_array($row)) {
  3856. continue;
  3857. }
  3858. $uid = (int)($row['uid'] ?? 0);
  3859. $name = trim((string)($row['name'] ?? ''));
  3860. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  3861. continue;
  3862. }
  3863. $out[$uid] = $name;
  3864. }
  3865. return $out;
  3866. }
  3867. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  3868. {
  3869. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  3870. }
  3871. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  3872. {
  3873. return 'procuremen_bidopen_wait_' . $adminId;
  3874. }
  3875. protected function renderBidOpenVerifySms(string $code): string
  3876. {
  3877. $tpl = '';
  3878. try {
  3879. $row = $this->loadNotifyTemplateRow('bid_open');
  3880. if (is_array($row)) {
  3881. $tpl = trim((string)($row['content'] ?? ''));
  3882. }
  3883. } catch (\Throwable $e) {
  3884. $tpl = '';
  3885. }
  3886. if ($tpl === '') {
  3887. $tpl = '【可集达】您的短信验证码是{code}';
  3888. }
  3889. return str_replace('{code}', $code, $tpl);
  3890. }
  3891. protected function sendBidOpenVerifySms(string $phone, string $code): void
  3892. {
  3893. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  3894. }
  3895. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  3896. {
  3897. $code = trim($code);
  3898. if (!preg_match('/^\d{6}$/', $code)) {
  3899. return false;
  3900. }
  3901. $mock = Config::get('mproc.mock_sms_code');
  3902. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3903. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3904. return true;
  3905. }
  3906. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3907. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3908. return false;
  3909. }
  3910. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3911. return true;
  3912. }
  3913. /**
  3914. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3915. */
  3916. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  3917. {
  3918. $ccydhList = [];
  3919. $batchNo = $this->resolveBundleOrderBatchNo($bundle);
  3920. foreach ($bundle['pos'] ?? [] as $poRow) {
  3921. if (!is_array($poRow)) {
  3922. continue;
  3923. }
  3924. foreach ($this->expandProcuremenCcydhTokens($poRow['CCYDH'] ?? '') as $dh) {
  3925. $ccydhList[$dh] = true;
  3926. }
  3927. if ($batchNo === '') {
  3928. $batchNo = $this->resolveProcuremenOrderBatchNo($poRow);
  3929. }
  3930. }
  3931. $primaryCcydh = trim((string)($bundle['ccydh'] ?? ''));
  3932. foreach ($this->expandProcuremenCcydhTokens($primaryCcydh) as $dh) {
  3933. $ccydhList[$dh] = true;
  3934. }
  3935. if ($ccydhList === []) {
  3936. throw new \InvalidArgumentException('订单号无效');
  3937. }
  3938. $this->ensurePurchaseOrderBidOpenTable();
  3939. list($operatorId, $operatorName) = $this->GetUseName();
  3940. $now = date('Y-m-d H:i:s');
  3941. $payloadBase = [
  3942. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  3943. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  3944. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  3945. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  3946. 'operator_id' => (int)$operatorId,
  3947. 'operator_name' => trim((string)$operatorName),
  3948. 'createtime' => $now,
  3949. 'order_batch_no' => $batchNo,
  3950. ];
  3951. foreach (array_keys($ccydhList) as $ccydh) {
  3952. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3953. $payload = $payloadBase;
  3954. $payload['ccydh'] = $ccydh;
  3955. if (is_array($exists)) {
  3956. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  3957. } else {
  3958. Db::table('purchase_order_bid_open')->insert($payload);
  3959. }
  3960. }
  3961. $name1 = $payloadBase['verifier1_name'] !== '' ? $payloadBase['verifier1_name'] : ('ID' . $payloadBase['verifier1_id']);
  3962. $name2 = $payloadBase['verifier2_name'] !== '' ? $payloadBase['verifier2_name'] : ('ID' . $payloadBase['verifier2_id']);
  3963. $labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
  3964. (int)$payloadBase['verifier1_id'],
  3965. (int)$payloadBase['verifier2_id'],
  3966. ]);
  3967. if (isset($labelMap[(int)$payloadBase['verifier1_id']]) && (int)$payloadBase['verifier1_id'] > 0) {
  3968. $name1 = $labelMap[(int)$payloadBase['verifier1_id']];
  3969. }
  3970. if (isset($labelMap[(int)$payloadBase['verifier2_id']]) && (int)$payloadBase['verifier2_id'] > 0) {
  3971. $name2 = $labelMap[(int)$payloadBase['verifier2_id']];
  3972. }
  3973. $logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
  3974. $seenSid = [];
  3975. foreach ($bundle['pos'] ?? [] as $poRow) {
  3976. if (!is_array($poRow)) {
  3977. continue;
  3978. }
  3979. $sid = (int)($poRow['scydgy_id'] ?? 0);
  3980. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  3981. continue;
  3982. }
  3983. $seenSid[$sid] = true;
  3984. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  3985. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  3986. }
  3987. if ($seenSid === []) {
  3988. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  3989. if ($this->isValidScydgyRowId($anchor)) {
  3990. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  3991. }
  3992. }
  3993. // 开标通过后:按订单号分别计算并写入供应商服务评分(避免多订单串分)
  3994. try {
  3995. $ym = date('Y-m', strtotime($now) ?: time());
  3996. $this->saveProcuremenSupplierScoresForBundle($bundle, $ym);
  3997. } catch (\Throwable $e) {
  3998. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  3999. }
  4000. }
  4001. /**
  4002. * 按 bundle 内各订单分别计分落库(单订单价格分);一批多单展示时再按数量×限价比例跨单加权
  4003. *
  4004. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  4005. */
  4006. protected function saveProcuremenSupplierScoresForBundle(array $bundle, ?string $ym = null): void
  4007. {
  4008. $batchNo = $this->resolveBundleOrderBatchNo($bundle);
  4009. $posByCcydh = [];
  4010. foreach ($bundle['pos'] ?? [] as $po) {
  4011. if (!is_array($po)) {
  4012. continue;
  4013. }
  4014. $dh = trim((string)($po['CCYDH'] ?? ''));
  4015. if ($dh === '') {
  4016. continue;
  4017. }
  4018. if (!isset($posByCcydh[$dh])) {
  4019. $posByCcydh[$dh] = [];
  4020. }
  4021. $posByCcydh[$dh][] = $po;
  4022. }
  4023. if ($posByCcydh === []) {
  4024. $fallback = trim((string)($bundle['ccydh'] ?? ''));
  4025. if ($fallback === '') {
  4026. return;
  4027. }
  4028. $groups = $this->loadAuditSupplierQuoteGroups($bundle);
  4029. ProcuremenSupplierScore::saveForOrder($fallback, $groups, $ym, $batchNo);
  4030. return;
  4031. }
  4032. $mergeAll = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  4033. foreach ($posByCcydh as $ccydh => $posList) {
  4034. $sidSet = [];
  4035. foreach ($posList as $po) {
  4036. $sid = (int)($po['scydgy_id'] ?? 0);
  4037. if ($this->isValidScydgyRowId($sid)) {
  4038. $sidSet[$sid] = true;
  4039. }
  4040. }
  4041. $mergeRows = [];
  4042. foreach ($mergeAll as $mr) {
  4043. if (!is_array($mr)) {
  4044. continue;
  4045. }
  4046. $gid = $this->extractScydgyRowId($mr);
  4047. if ($this->isValidScydgyRowId($gid) && isset($sidSet[$gid])) {
  4048. $mergeRows[] = $mr;
  4049. }
  4050. }
  4051. $subBundle = [
  4052. 'ccydh' => $ccydh,
  4053. 'order_batch_no' => $batchNo,
  4054. 'pos' => $posList,
  4055. 'merge_rows' => $mergeRows !== [] ? $mergeRows : $this->scydgyRowsForPurchaseOrders($posList),
  4056. ];
  4057. $groups = $this->loadAuditSupplierQuoteGroups($subBundle);
  4058. ProcuremenSupplierScore::saveForOrder($ccydh, $groups, $ym, $batchNo);
  4059. }
  4060. }
  4061. /**
  4062. * 报价行展示字段默认值(模板安全访问)
  4063. *
  4064. * @param array<string, mixed> $line
  4065. * @return array<string, mixed>
  4066. */
  4067. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  4068. {
  4069. if (!array_key_exists('amount_quote_pending', $line)) {
  4070. $line['amount_quote_pending'] = 0;
  4071. }
  4072. if (!array_key_exists('delivery_quote_pending', $line)) {
  4073. $line['delivery_quote_pending'] = 0;
  4074. }
  4075. if (!array_key_exists('quote_before_deadline', $line)) {
  4076. $line['quote_before_deadline'] = 0;
  4077. }
  4078. if (!array_key_exists('amount_filled', $line)) {
  4079. $line['amount_filled'] = 0;
  4080. }
  4081. if (!array_key_exists('delivery_filled', $line)) {
  4082. $line['delivery_filled'] = 0;
  4083. }
  4084. if (!array_key_exists('lead_days_filled', $line)) {
  4085. $line['lead_days_filled'] = 0;
  4086. }
  4087. if (!array_key_exists('lead_days_quote_pending', $line)) {
  4088. $line['lead_days_quote_pending'] = 0;
  4089. }
  4090. if (!array_key_exists('lead_days_show', $line)) {
  4091. $line['lead_days_show'] = '未填写';
  4092. }
  4093. if (!array_key_exists('lead_days_text', $line)) {
  4094. $line['lead_days_text'] = $line['lead_days_show'];
  4095. }
  4096. if (!array_key_exists('ccydh', $line)) {
  4097. $line['ccydh'] = '';
  4098. }
  4099. if (!array_key_exists('cgymc', $line)) {
  4100. $line['cgymc'] = '';
  4101. }
  4102. // 工序列展示文案:上行订单号、下行工序(无括号;兼容旧模板)
  4103. if (!array_key_exists('cgymc_display', $line) || trim((string)$line['cgymc_display']) === '') {
  4104. $dh = trim((string)$line['ccydh']);
  4105. $gy = trim((string)$line['cgymc']);
  4106. $line['cgymc_display'] = $dh !== '' ? ($dh . "\n" . $gy) : $gy;
  4107. }
  4108. return $line;
  4109. }
  4110. /**
  4111. * 供应商报价表「工序名称」列:订单号 + 工序名(不加 [])
  4112. *
  4113. * @return array{ccydh:string,cgymc:string,cgymc_display:string}
  4114. */
  4115. protected function buildSupplierProcessNameFields(string $ccydh, string $cgymc): array
  4116. {
  4117. $ccydh = trim($ccydh);
  4118. $cgymc = trim($cgymc);
  4119. if ($cgymc === '') {
  4120. $cgymc = '工序';
  4121. }
  4122. return [
  4123. 'ccydh' => $ccydh,
  4124. 'cgymc' => $cgymc,
  4125. 'cgymc_display' => $ccydh !== '' ? ($ccydh . "\n" . $cgymc) : $cgymc,
  4126. ];
  4127. }
  4128. /**
  4129. * 审核弹窗:按供应商汇总报价明细
  4130. *
  4131. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  4132. * @return array<int, array<string, mixed>>
  4133. */
  4134. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  4135. {
  4136. $sids = [];
  4137. foreach ($bundle['pos'] ?? [] as $po) {
  4138. if (!is_array($po)) {
  4139. continue;
  4140. }
  4141. $sid = (int)($po['scydgy_id'] ?? 0);
  4142. if ($this->isValidScydgyRowId($sid)) {
  4143. $sids[$sid] = true;
  4144. }
  4145. }
  4146. if ($sids === []) {
  4147. return [];
  4148. }
  4149. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  4150. $orderMbz = $this->resolveBundleOrderMbz($bundle);
  4151. $orderDeadlineMap = $this->buildBundleOrderDeliveryDeadlineMap($bundle);
  4152. $gymcMap = [];
  4153. $ccydhBySid = [];
  4154. $qtyBySid = [];
  4155. $ceilingBySid = [];
  4156. $extraSids = [];
  4157. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  4158. if (!is_array($mr)) {
  4159. continue;
  4160. }
  4161. $gid = $this->extractScydgyRowId($mr);
  4162. if ($this->isValidScydgyRowId($gid)) {
  4163. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  4164. $dh = trim((string)($mr['CCYDH'] ?? ''));
  4165. if ($dh !== '') {
  4166. $ccydhBySid[$gid] = $dh;
  4167. }
  4168. $qtyBySid[$gid] = $this->resolveProcuremenThisQuantity($mr);
  4169. $ceilingBySid[$gid] = $this->resolveProcuremenCeilingPrice($mr);
  4170. }
  4171. }
  4172. foreach ($bundle['pos'] ?? [] as $po) {
  4173. if (!is_array($po)) {
  4174. continue;
  4175. }
  4176. $gid = (int)($po['scydgy_id'] ?? 0);
  4177. if ($this->isValidScydgyRowId($gid)) {
  4178. $nm = trim((string)($po['CGYMC'] ?? ''));
  4179. if ($nm !== '') {
  4180. $gymcMap[$gid] = $nm;
  4181. }
  4182. $dh = trim((string)($po['CCYDH'] ?? ''));
  4183. if ($dh !== '' && empty($ccydhBySid[$gid])) {
  4184. $ccydhBySid[$gid] = $dh;
  4185. }
  4186. if (!isset($qtyBySid[$gid]) || trim((string)$qtyBySid[$gid]) === '') {
  4187. $qtyBySid[$gid] = $this->resolveProcuremenThisQuantity($po);
  4188. }
  4189. if (!isset($ceilingBySid[$gid]) || trim((string)$ceilingBySid[$gid]) === '') {
  4190. $ceilingBySid[$gid] = $this->resolveProcuremenCeilingPrice($po);
  4191. }
  4192. $extraSids[] = $gid;
  4193. }
  4194. }
  4195. // 与上方工序表一致:按订单号升序排供应商明细行
  4196. $orderedSids = $this->orderedScydgyIdsLikeProcessDisplay(
  4197. is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [],
  4198. $extraSids
  4199. );
  4200. try {
  4201. $detailsQuery = Db::table('purchase_order_detail')
  4202. ->where('scydgy_id', 'in', array_keys($sids));
  4203. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  4204. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  4205. } catch (\Throwable $e) {
  4206. try {
  4207. $detailsQuery = Db::table('purchase_order_detail')
  4208. ->where('scydgy_id', 'in', array_keys($sids));
  4209. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  4210. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  4211. } catch (\Throwable $e2) {
  4212. $details = [];
  4213. }
  4214. }
  4215. if (!is_array($details)) {
  4216. $details = [];
  4217. }
  4218. $byCompany = [];
  4219. foreach ($details as $d) {
  4220. if (!is_array($d)) {
  4221. continue;
  4222. }
  4223. $cn = trim((string)($d['company_name'] ?? ''));
  4224. if ($cn === '') {
  4225. continue;
  4226. }
  4227. if (!isset($byCompany[$cn])) {
  4228. $ph = trim((string)($d['phone'] ?? ''));
  4229. $username = trim((string)($d['username'] ?? ''));
  4230. if ($username === '') {
  4231. $username = $this->resolveCustomerContactName($ph, $cn);
  4232. }
  4233. $byCompany[$cn] = [
  4234. 'name' => $cn,
  4235. 'email' => trim((string)($d['email'] ?? '')),
  4236. 'phone' => $ph,
  4237. 'username' => $username,
  4238. 'remark' => '',
  4239. 'has_quote' => false,
  4240. 'lines_map' => [],
  4241. ];
  4242. }
  4243. if ($byCompany[$cn]['remark'] === '') {
  4244. $rm = '';
  4245. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  4246. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  4247. $rm = trim((string)$d[$rk]);
  4248. break;
  4249. }
  4250. }
  4251. if ($rm !== '') {
  4252. $byCompany[$cn]['remark'] = $rm;
  4253. }
  4254. }
  4255. $sid = (int)($d['scydgy_id'] ?? 0);
  4256. $am = trim((string)($d['amount'] ?? ''));
  4257. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  4258. $ccydhLine = trim((string)($ccydhBySid[$sid] ?? ''));
  4259. $processName = $this->buildSupplierProcessNameFields($ccydhLine, $gymc);
  4260. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  4261. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  4262. if ($deliveryShow === '' && $deliveryRaw !== '') {
  4263. $deliveryShow = $deliveryRaw;
  4264. }
  4265. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  4266. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  4267. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  4268. $subtotal = null;
  4269. if ($amountNum !== null) {
  4270. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  4271. }
  4272. $unitPriceText = $amountFilled
  4273. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  4274. : '未填写';
  4275. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  4276. $leadFilled = ($leadDays !== null);
  4277. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  4278. $lineRow = array_merge($processName, [
  4279. 'scydgy_id' => $sid,
  4280. 'This_quantity' => (string)($qtyBySid[$sid] ?? ''),
  4281. 'ceilingPrice' => (string)($ceilingBySid[$sid] ?? ''),
  4282. 'amount' => $am,
  4283. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  4284. 'amount_filled' => $amountFilled,
  4285. 'unit_price_text' => $unitPriceText,
  4286. 'delivery' => $deliveryRaw,
  4287. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  4288. 'delivery_filled' => $deliveryFilled,
  4289. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  4290. 'order_delivery_deadline' => $orderDeadlineMap[$ccydhLine] ?? '',
  4291. 'lead_days' => $leadFilled ? $leadDays : '',
  4292. 'lead_days_filled' => $leadFilled,
  4293. 'lead_days_show' => $leadText,
  4294. 'lead_days_text' => $leadText,
  4295. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  4296. 'subtotal_num' => $subtotal,
  4297. 'status_name' => trim((string)($d['status_name'] ?? '')),
  4298. 'is_quoted' => $amountFilled,
  4299. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  4300. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  4301. ]);
  4302. if (!$quoteVisible) {
  4303. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  4304. }
  4305. // 按工序 id 暂存,下面再按上方工序表顺序输出
  4306. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  4307. }
  4308. foreach ($byCompany as $cn => $g) {
  4309. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  4310. $lines = [];
  4311. $usedSids = [];
  4312. foreach ($orderedSids as $sid) {
  4313. if (!isset($linesMap[$sid])) {
  4314. continue;
  4315. }
  4316. $lines[] = $linesMap[$sid];
  4317. $usedSids[$sid] = true;
  4318. }
  4319. foreach ($linesMap as $sid => $ln) {
  4320. if (isset($usedSids[$sid])) {
  4321. continue;
  4322. }
  4323. $lines[] = $ln;
  4324. }
  4325. $total = count($lines);
  4326. $quoted = 0;
  4327. $groupTotal = 0.0;
  4328. $groupHasTotal = false;
  4329. if ($quoteVisible) {
  4330. foreach ($lines as $ln) {
  4331. $am = trim((string)($ln['amount'] ?? ''));
  4332. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  4333. $quoted++;
  4334. }
  4335. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  4336. $groupTotal += (float)$ln['subtotal_num'];
  4337. $groupHasTotal = true;
  4338. }
  4339. }
  4340. }
  4341. unset($byCompany[$cn]['lines_map']);
  4342. $byCompany[$cn]['lines'] = $lines;
  4343. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  4344. $byCompany[$cn]['line_count'] = $total;
  4345. $byCompany[$cn]['has_total'] = $total > 0;
  4346. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  4347. $this->finalizeSupplierRemarkDisplay($byCompany[$cn], $orderMbz, $quoteVisible);
  4348. }
  4349. $groups = array_values($byCompany);
  4350. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  4351. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  4352. }
  4353. /**
  4354. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  4355. *
  4356. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  4357. * @return array<int, array<string, mixed>>
  4358. */
  4359. protected function loadConfirmSupplierPickGroups(array $bundle): array
  4360. {
  4361. $sids = [];
  4362. $poIdMap = [];
  4363. foreach ($bundle['pos'] ?? [] as $po) {
  4364. if (!is_array($po)) {
  4365. continue;
  4366. }
  4367. $sid = (int)($po['scydgy_id'] ?? 0);
  4368. if ($this->isValidScydgyRowId($sid)) {
  4369. $sids[$sid] = true;
  4370. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  4371. }
  4372. }
  4373. if ($sids === []) {
  4374. return [];
  4375. }
  4376. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  4377. $orderMbz = $this->resolveBundleOrderMbz($bundle);
  4378. $orderDeadlineMap = $this->buildBundleOrderDeliveryDeadlineMap($bundle);
  4379. $gymcMap = [];
  4380. $ccydhBySid = [];
  4381. $qtyBySid = [];
  4382. $ceilingBySid = [];
  4383. $extraSids = [];
  4384. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  4385. if (!is_array($mr)) {
  4386. continue;
  4387. }
  4388. $gid = $this->extractScydgyRowId($mr);
  4389. if ($this->isValidScydgyRowId($gid)) {
  4390. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  4391. $dh = trim((string)($mr['CCYDH'] ?? ''));
  4392. if ($dh !== '') {
  4393. $ccydhBySid[$gid] = $dh;
  4394. }
  4395. $qtyBySid[$gid] = $this->resolveProcuremenThisQuantity($mr);
  4396. $ceilingBySid[$gid] = $this->resolveProcuremenCeilingPrice($mr);
  4397. }
  4398. }
  4399. foreach ($bundle['pos'] ?? [] as $po) {
  4400. if (!is_array($po)) {
  4401. continue;
  4402. }
  4403. $gid = (int)($po['scydgy_id'] ?? 0);
  4404. if ($this->isValidScydgyRowId($gid)) {
  4405. $nm = trim((string)($po['CGYMC'] ?? ''));
  4406. if ($nm !== '') {
  4407. $gymcMap[$gid] = $nm;
  4408. }
  4409. $dh = trim((string)($po['CCYDH'] ?? ''));
  4410. if ($dh !== '' && empty($ccydhBySid[$gid])) {
  4411. $ccydhBySid[$gid] = $dh;
  4412. }
  4413. if (!isset($qtyBySid[$gid]) || trim((string)$qtyBySid[$gid]) === '') {
  4414. $qtyBySid[$gid] = $this->resolveProcuremenThisQuantity($po);
  4415. }
  4416. if (!isset($ceilingBySid[$gid]) || trim((string)$ceilingBySid[$gid]) === '') {
  4417. $ceilingBySid[$gid] = $this->resolveProcuremenCeilingPrice($po);
  4418. }
  4419. $extraSids[] = $gid;
  4420. }
  4421. }
  4422. // 与上方工序表一致:按订单号升序排供应商明细行
  4423. $orderedSids = $this->orderedScydgyIdsLikeProcessDisplay(
  4424. is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [],
  4425. $extraSids
  4426. );
  4427. try {
  4428. $details = Db::table('purchase_order_detail')
  4429. ->where('scydgy_id', 'in', array_keys($sids))
  4430. ->order('company_name', 'asc')
  4431. ->order('id', 'asc')
  4432. ->select();
  4433. } catch (\Throwable $e) {
  4434. try {
  4435. $details = Db::table('purchase_order_detail')
  4436. ->where('scydgy_id', 'in', array_keys($sids))
  4437. ->order('company_name', 'asc')
  4438. ->order('ID', 'asc')
  4439. ->select();
  4440. } catch (\Throwable $e2) {
  4441. $details = [];
  4442. }
  4443. }
  4444. if (!is_array($details)) {
  4445. $details = [];
  4446. }
  4447. $byCompany = [];
  4448. foreach ($details as $d) {
  4449. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  4450. continue;
  4451. }
  4452. $cn = trim((string)($d['company_name'] ?? ''));
  4453. if ($cn === '') {
  4454. continue;
  4455. }
  4456. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  4457. $sid = (int)($d['scydgy_id'] ?? 0);
  4458. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  4459. continue;
  4460. }
  4461. if (!isset($byCompany[$cn])) {
  4462. $ph = trim((string)($d['phone'] ?? ''));
  4463. $username = trim((string)($d['username'] ?? ''));
  4464. if ($username === '') {
  4465. $username = $this->resolveCustomerContactName($ph, $cn);
  4466. }
  4467. $byCompany[$cn] = [
  4468. 'name' => $cn,
  4469. 'email' => trim((string)($d['email'] ?? '')),
  4470. 'phone' => $ph,
  4471. 'username' => $username,
  4472. 'remark' => '',
  4473. 'pick_lines' => [],
  4474. 'detail_picks' => [],
  4475. ];
  4476. }
  4477. if ($byCompany[$cn]['remark'] === '') {
  4478. $rm = '';
  4479. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  4480. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  4481. $rm = trim((string)$d[$rk]);
  4482. break;
  4483. }
  4484. }
  4485. if ($rm !== '') {
  4486. $byCompany[$cn]['remark'] = $rm;
  4487. }
  4488. }
  4489. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  4490. $ccydhLine = trim((string)($ccydhBySid[$sid] ?? ''));
  4491. $processName = $this->buildSupplierProcessNameFields($ccydhLine, $gymc);
  4492. $am = trim((string)($d['amount'] ?? ''));
  4493. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  4494. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  4495. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  4496. if ($deliveryShow === '' && $deliveryRaw !== '') {
  4497. $deliveryShow = $deliveryRaw;
  4498. }
  4499. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  4500. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  4501. $subtotal = null;
  4502. if ($amountNum !== null) {
  4503. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  4504. }
  4505. $unitPriceText = $amountFilled
  4506. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  4507. : '未填写';
  4508. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  4509. $leadFilled = ($leadDays !== null);
  4510. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  4511. $pickLine = array_merge($processName, [
  4512. 'scydgy_id' => $sid,
  4513. 'This_quantity' => (string)($qtyBySid[$sid] ?? ''),
  4514. 'ceilingPrice' => (string)($ceilingBySid[$sid] ?? ''),
  4515. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  4516. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  4517. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  4518. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  4519. 'order_delivery_deadline' => $orderDeadlineMap[$ccydhLine] ?? '',
  4520. 'amount_filled' => $amountFilled,
  4521. 'delivery_filled' => $deliveryFilled,
  4522. 'unit_price_text' => $unitPriceText,
  4523. 'lead_days' => $leadFilled ? $leadDays : '',
  4524. 'lead_days_filled' => $leadFilled,
  4525. 'lead_days_show' => $leadText,
  4526. 'lead_days_text' => $leadText,
  4527. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  4528. 'subtotal_num' => $subtotal,
  4529. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  4530. 'is_quoted' => $amountFilled,
  4531. ]);
  4532. if (!$quoteVisible) {
  4533. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  4534. }
  4535. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  4536. $byCompany[$cn]['detail_picks'][$sid] = [
  4537. 'scydgy_id' => $sid,
  4538. 'detail_id' => $detailId,
  4539. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  4540. 'cgymc' => $processName['cgymc'],
  4541. 'ccydh' => $processName['ccydh'],
  4542. ];
  4543. }
  4544. $out = [];
  4545. foreach ($byCompany as $g) {
  4546. $pickLinesMap = $g['pick_lines'] ?? [];
  4547. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  4548. continue;
  4549. }
  4550. $pickLines = [];
  4551. $usedLineSids = [];
  4552. foreach ($orderedSids as $sid) {
  4553. if (!isset($pickLinesMap[$sid])) {
  4554. continue;
  4555. }
  4556. $pickLines[] = $pickLinesMap[$sid];
  4557. $usedLineSids[$sid] = true;
  4558. }
  4559. foreach ($pickLinesMap as $sid => $ln) {
  4560. if (isset($usedLineSids[$sid])) {
  4561. continue;
  4562. }
  4563. $pickLines[] = $ln;
  4564. }
  4565. $groupTotal = 0.0;
  4566. $groupHasTotal = false;
  4567. if ($quoteVisible) {
  4568. foreach ($pickLines as $ln) {
  4569. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  4570. $groupTotal += (float)$ln['subtotal_num'];
  4571. $groupHasTotal = true;
  4572. }
  4573. }
  4574. }
  4575. $lineCount = count($pickLines);
  4576. $g['pick_lines'] = $pickLines;
  4577. $g['line_count'] = $lineCount;
  4578. $g['has_total'] = $lineCount > 0;
  4579. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  4580. $this->finalizeSupplierRemarkDisplay($g, $orderMbz, $quoteVisible);
  4581. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  4582. $detailPicks = [];
  4583. $usedPickSids = [];
  4584. foreach ($orderedSids as $sid) {
  4585. if (!isset($detailPicksMap[$sid])) {
  4586. continue;
  4587. }
  4588. $detailPicks[] = $detailPicksMap[$sid];
  4589. $usedPickSids[$sid] = true;
  4590. }
  4591. foreach ($detailPicksMap as $sid => $dp) {
  4592. if (isset($usedPickSids[$sid])) {
  4593. continue;
  4594. }
  4595. $detailPicks[] = $dp;
  4596. }
  4597. $g['detail_picks'] = $detailPicks;
  4598. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  4599. unset($g['detail_picks']);
  4600. $out[] = $g;
  4601. }
  4602. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  4603. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  4604. }
  4605. /**
  4606. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  4607. * @return array<int, int[]> scydgy_id => detail_id[]
  4608. */
  4609. protected function mapDetailIdsByScydgyId(array $details): array
  4610. {
  4611. $out = [];
  4612. foreach ($details as $d) {
  4613. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  4614. continue;
  4615. }
  4616. $sid = (int)($d['scydgy_id'] ?? 0);
  4617. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  4618. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  4619. continue;
  4620. }
  4621. if (!isset($out[$sid])) {
  4622. $out[$sid] = [];
  4623. }
  4624. $out[$sid][] = $pk;
  4625. }
  4626. foreach ($out as $sid => $ids) {
  4627. $out[$sid] = array_values(array_unique($ids));
  4628. }
  4629. return $out;
  4630. }
  4631. /**
  4632. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  4633. *
  4634. * @param array<string, mixed> $dbRow
  4635. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  4636. */
  4637. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  4638. {
  4639. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  4640. $r = [
  4641. 'ID' => $sid,
  4642. 'scydgy_id' => $sid,
  4643. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  4644. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  4645. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  4646. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  4647. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  4648. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  4649. 'CDW' => $dbRow['CDW'] ?? '',
  4650. 'czlyq' => $dbRow['czlyq'] ?? '',
  4651. 'NGZL' => $dbRow['NGZL'] ?? '',
  4652. 'CDF' => $dbRow['CDF'] ?? '',
  4653. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  4654. 'MBZ' => $dbRow['MBZ'] ?? '',
  4655. 'bwjg' => $dbRow['bwjg'] ?? '',
  4656. 'iStatus' => $dbRow['iStatus'] ?? '',
  4657. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  4658. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  4659. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  4660. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  4661. 'dStamp' => $dbRow['dStamp'] ?? '',
  4662. 'pick_time' => $dbRow['pick_time'] ?? '',
  4663. 'order_batch_no' => $this->resolveProcuremenOrderBatchNo($dbRow),
  4664. ];
  4665. $r['This_quantity'] = $this->resolveProcuremenThisQuantity($r);
  4666. $r['ceilingPrice'] = $this->resolveProcuremenCeilingPrice($r);
  4667. if ($sid > 0 && isset($dStampMap[$sid])) {
  4668. $t = trim((string)$dStampMap[$sid]);
  4669. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  4670. $r['dStamp'] = $dStampMap[$sid];
  4671. }
  4672. }
  4673. $dsOut = trim((string)($r['dStamp'] ?? ''));
  4674. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  4675. $ct = $dbRow['createtime'];
  4676. if (is_numeric($ct) && (int)$ct > 946684800) {
  4677. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  4678. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  4679. $r['dStamp'] = trim($ct);
  4680. }
  4681. }
  4682. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  4683. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  4684. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  4685. $fallback = trim((string)($r['dStamp'] ?? ''));
  4686. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  4687. $r['dputrecord'] = $fallback;
  4688. }
  4689. }
  4690. if (array_key_exists('id', $dbRow)) {
  4691. $r['purchase_order_id'] = (int)$dbRow['id'];
  4692. }
  4693. if ($sid < 0) {
  4694. $r['_is_manual'] = 1;
  4695. }
  4696. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  4697. $pickOut = trim((string)($r['pick_time'] ?? ''));
  4698. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  4699. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  4700. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  4701. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  4702. $r['pick_time'] = $pickFallback;
  4703. break;
  4704. }
  4705. }
  4706. }
  4707. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  4708. if ($pickNm !== '') {
  4709. $r['pick_company_name'] = $pickNm;
  4710. $r['picked_supplier_name'] = $pickNm;
  4711. }
  4712. // 列表开标状态依赖此字段:有批次号时只认本行/合并行,必须从库带出
  4713. $r['manual_pick'] = ((int)($dbRow['manual_pick'] ?? 0) === 1) ? 1 : 0;
  4714. $r['wflow_status'] = trim((string)($dbRow['wflow_status'] ?? ''));
  4715. $r['order_status_text'] = ProcuremenStatus::orderStatusLabelForList($r['wflow_status']);
  4716. if (array_key_exists('status', $dbRow)) {
  4717. $r['status'] = $dbRow['status'];
  4718. }
  4719. return $r;
  4720. }
  4721. /**
  4722. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  4723. *
  4724. * @return array<int, array<string, mixed>>
  4725. */
  4726. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  4727. {
  4728. $pool = [];
  4729. if (!is_array($dbRows) || $dbRows === []) {
  4730. return $pool;
  4731. }
  4732. $dStampMap = [];
  4733. $sidList = [];
  4734. foreach ($dbRows as $tmpRow) {
  4735. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  4736. $sid = (int)$tmpRow['scydgy_id'];
  4737. if ($sid > 0) {
  4738. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  4739. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  4740. $sidList[$sid] = true;
  4741. }
  4742. }
  4743. }
  4744. }
  4745. if ($sidList !== []) {
  4746. try {
  4747. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  4748. } catch (\Throwable $e) {
  4749. $dStampMap = [];
  4750. }
  4751. }
  4752. foreach ($dbRows as $dbRow) {
  4753. if (!is_array($dbRow)) {
  4754. continue;
  4755. }
  4756. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  4757. }
  4758. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  4759. $needCcydh = [];
  4760. foreach ($pool as $row) {
  4761. if (!is_array($row)) {
  4762. continue;
  4763. }
  4764. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  4765. continue;
  4766. }
  4767. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  4768. if ($ccydh !== '') {
  4769. $needCcydh[$ccydh] = true;
  4770. }
  4771. }
  4772. if ($needCcydh !== []) {
  4773. $czMap = [];
  4774. try {
  4775. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  4776. } catch (\Throwable $e) {
  4777. $czMap = [];
  4778. }
  4779. if (is_array($czMap) && $czMap !== []) {
  4780. foreach ($pool as &$row) {
  4781. if (!is_array($row)) {
  4782. continue;
  4783. }
  4784. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  4785. continue;
  4786. }
  4787. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  4788. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  4789. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  4790. }
  4791. }
  4792. unset($row);
  4793. }
  4794. }
  4795. return $pool;
  4796. }
  4797. /**
  4798. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  4799. *
  4800. * @param int[] $scydgyIds
  4801. * @return array<int, array<string, mixed>>
  4802. */
  4803. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  4804. {
  4805. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4806. if ($scydgyIds === []) {
  4807. return [];
  4808. }
  4809. try {
  4810. $list = Db::table('purchase_order_detail')
  4811. ->where('scydgy_id', 'in', $scydgyIds)
  4812. ->field('scydgy_id,company_name,amount,delivery')
  4813. ->select();
  4814. } catch (\Throwable $e) {
  4815. $list = [];
  4816. }
  4817. return is_array($list) ? $list : [];
  4818. }
  4819. /**
  4820. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  4821. *
  4822. * @param int[] $scydgyIds
  4823. * @param array<int, array<string, mixed>> $allRows
  4824. * @return array{cnt:int, amt:int, deliv:int}
  4825. */
  4826. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  4827. {
  4828. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4829. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4830. if ($scydgyIds === [] || $allRows === []) {
  4831. return $out;
  4832. }
  4833. $idSet = array_flip($scydgyIds);
  4834. $all = [];
  4835. $withAmt = [];
  4836. $withDeliv = [];
  4837. foreach ($allRows as $r) {
  4838. if (!is_array($r)) {
  4839. continue;
  4840. }
  4841. $sid = (int)($r['scydgy_id'] ?? 0);
  4842. if (!isset($idSet[$sid])) {
  4843. continue;
  4844. }
  4845. $cn = trim((string)($r['company_name'] ?? ''));
  4846. if ($cn === '') {
  4847. continue;
  4848. }
  4849. $all[$cn] = true;
  4850. $am = $r['amount'] ?? null;
  4851. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  4852. $withAmt[$cn] = true;
  4853. }
  4854. $dv = $r['delivery'] ?? null;
  4855. if ($dv !== null && trim((string)$dv) !== '') {
  4856. $withDeliv[$cn] = true;
  4857. }
  4858. }
  4859. return [
  4860. 'cnt' => count($all),
  4861. 'amt' => count($withAmt),
  4862. 'deliv' => count($withDeliv),
  4863. ];
  4864. }
  4865. /**
  4866. * 本次数量:优先 This_quantity,空则回退工作量 NGZL(与下发/确认/审批弹窗一致)
  4867. *
  4868. * @param array<string, mixed> $row
  4869. */
  4870. protected function resolveProcuremenThisQuantity(array $row): string
  4871. {
  4872. $q = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  4873. if ($q !== '') {
  4874. return $q;
  4875. }
  4876. $ngzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  4877. if (!is_scalar($ngzl)) {
  4878. return '';
  4879. }
  4880. $s = trim((string)$ngzl);
  4881. if ($s === '') {
  4882. return '';
  4883. }
  4884. if (is_numeric($s) && (float)$s === 0.0) {
  4885. return '';
  4886. }
  4887. return $s;
  4888. }
  4889. /**
  4890. * @param array<string, mixed> $row
  4891. */
  4892. protected function resolveProcuremenCeilingPrice(array $row): string
  4893. {
  4894. return trim((string)($row['ceilingPrice'] ?? $row['ceiling_price'] ?? ''));
  4895. }
  4896. /**
  4897. * 多工序数量/限价拼接:跳过空值,避免出现「、10」「304、」
  4898. *
  4899. * @param array<int, mixed> $parts
  4900. */
  4901. protected function joinProcuremenNonEmpty(array $parts, string $sep = '、'): string
  4902. {
  4903. $out = [];
  4904. foreach ($parts as $p) {
  4905. $s = trim((string)$p);
  4906. if ($s !== '') {
  4907. $out[] = $s;
  4908. }
  4909. }
  4910. return $out === [] ? '' : implode($sep, $out);
  4911. }
  4912. /**
  4913. * 确认/审批列表:合并行按各工序同步本次数量、最高限价(顿号间隔)
  4914. *
  4915. * @param array<int, array<string, mixed>> $rows
  4916. */
  4917. protected function syncCollapsedOrderQtyPriceForList(array &$rows): void
  4918. {
  4919. if ($rows === []) {
  4920. return;
  4921. }
  4922. $idList = [];
  4923. foreach ($rows as $rw) {
  4924. if (!is_array($rw)) {
  4925. continue;
  4926. }
  4927. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4928. foreach ($rw['_order_merge_rows'] as $mr) {
  4929. if (!is_array($mr)) {
  4930. continue;
  4931. }
  4932. $mid = (int)($mr['ID'] ?? 0);
  4933. if ($this->isValidScydgyRowId($mid)) {
  4934. $idList[$mid] = true;
  4935. }
  4936. }
  4937. }
  4938. $id = (int)($rw['ID'] ?? 0);
  4939. if ($this->isValidScydgyRowId($id)) {
  4940. $idList[$id] = true;
  4941. }
  4942. }
  4943. if ($idList === []) {
  4944. return;
  4945. }
  4946. try {
  4947. $list = Db::table('purchase_order')
  4948. ->where('scydgy_id', 'in', array_keys($idList))
  4949. ->field('scydgy_id,This_quantity,ceilingPrice,NGZL,pick_company_name')
  4950. ->select();
  4951. } catch (\Throwable $e) {
  4952. return;
  4953. }
  4954. if (!is_array($list)) {
  4955. return;
  4956. }
  4957. $byId = [];
  4958. foreach ($list as $dbRow) {
  4959. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4960. continue;
  4961. }
  4962. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4963. }
  4964. foreach ($rows as &$rw) {
  4965. if (!is_array($rw)) {
  4966. continue;
  4967. }
  4968. $mergeRows = [];
  4969. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4970. $mergeRows = $rw['_order_merge_rows'];
  4971. } else {
  4972. $mergeRows = [$rw];
  4973. }
  4974. $qtyList = [];
  4975. $priceList = [];
  4976. $picked = '';
  4977. foreach ($mergeRows as $mr) {
  4978. if (!is_array($mr)) {
  4979. continue;
  4980. }
  4981. $sid = (int)($mr['ID'] ?? 0);
  4982. $db = ($sid !== 0 && isset($byId[$sid])) ? $byId[$sid] : null;
  4983. $src = $mr;
  4984. if (is_array($db)) {
  4985. $qDb = trim((string)($db['This_quantity'] ?? $db['this_quantity'] ?? ''));
  4986. $pDb = trim((string)($db['ceilingPrice'] ?? $db['ceiling_price'] ?? ''));
  4987. $ngzlDb = $db['NGZL'] ?? $db['ngzl'] ?? null;
  4988. if ($qDb !== '') {
  4989. $src['This_quantity'] = $qDb;
  4990. }
  4991. if ($pDb !== '') {
  4992. $src['ceilingPrice'] = $pDb;
  4993. }
  4994. if ($ngzlDb !== null && trim((string)$ngzlDb) !== '') {
  4995. $src['NGZL'] = $ngzlDb;
  4996. }
  4997. if ($picked === '') {
  4998. $picked = trim((string)($db['pick_company_name'] ?? ''));
  4999. }
  5000. }
  5001. if ($picked === '') {
  5002. $picked = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  5003. }
  5004. $qtyList[] = $this->resolveProcuremenThisQuantity($src);
  5005. $priceList[] = $this->resolveProcuremenCeilingPrice($src);
  5006. }
  5007. $rw['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  5008. $rw['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  5009. if ($picked !== '') {
  5010. $rw['pick_company_name'] = $picked;
  5011. $rw['picked_supplier_name'] = $picked;
  5012. }
  5013. }
  5014. unset($rw);
  5015. }
  5016. /**
  5017. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  5018. *
  5019. * @param int[] $scydgyIds
  5020. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  5021. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  5022. */
  5023. protected function OrderDetailSummary(array $scydgyIds)
  5024. {
  5025. $out = [];
  5026. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  5027. if ($scydgyIds === []) {
  5028. return $out;
  5029. }
  5030. $list = [];
  5031. try {
  5032. $list = Db::table('purchase_order_detail')
  5033. ->where('scydgy_id', 'in', $scydgyIds)
  5034. ->field('id,scydgy_id,amount,delivery')
  5035. ->select();
  5036. } catch (\Throwable $e) {
  5037. $list = [];
  5038. }
  5039. if (!is_array($list)) {
  5040. return $out;
  5041. }
  5042. foreach ($list as $r) {
  5043. if (!is_array($r)) {
  5044. continue;
  5045. }
  5046. $ids = (int)($r['scydgy_id'] ?? 0);
  5047. if (!$this->isValidScydgyRowId($ids)) {
  5048. continue;
  5049. }
  5050. if (!isset($out[$ids])) {
  5051. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  5052. }
  5053. $out[$ids]['cnt']++;
  5054. $am = $r['amount'] ?? null;
  5055. if ($am !== null && $am !== '') {
  5056. if (!(is_string($am) && trim($am) === '')) {
  5057. $out[$ids]['amt']++;
  5058. }
  5059. }
  5060. $dv = $r['delivery'] ?? null;
  5061. if ($dv !== null && trim((string)$dv) !== '') {
  5062. $out[$ids]['deliv']++;
  5063. }
  5064. }
  5065. return $out;
  5066. }
  5067. /**
  5068. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  5069. *
  5070. * @return array
  5071. */
  5072. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  5073. {
  5074. $strContains = function ($haystack, $needle) {
  5075. if ($needle === '') {
  5076. return false;
  5077. }
  5078. $haystack = (string)$haystack;
  5079. if (function_exists('mb_stripos')) {
  5080. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  5081. }
  5082. return stripos($haystack, $needle) !== false;
  5083. };
  5084. $stripAlias = function ($f) {
  5085. return preg_replace('/^[ab]\./i', '', (string)$f);
  5086. };
  5087. $searchColNames = [];
  5088. foreach (explode(',', $this->searchFields) as $colRaw) {
  5089. $c = $stripAlias(trim($colRaw));
  5090. if ($c !== '') {
  5091. $searchColNames[] = $c;
  5092. }
  5093. }
  5094. // 等值条件先行(表头下拉),减少后续日期解析量
  5095. $eqFilters = [];
  5096. $otherFilters = [];
  5097. foreach ($filterArr as $fk => $fv) {
  5098. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  5099. continue;
  5100. }
  5101. if (is_array($fv)) {
  5102. continue;
  5103. }
  5104. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  5105. continue;
  5106. }
  5107. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  5108. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  5109. $field = $stripAlias($fk);
  5110. if ($sym === '=' || $sym === '') {
  5111. $eqFilters[$field] = trim((string)$fv);
  5112. } else {
  5113. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  5114. }
  5115. }
  5116. $ymTarget = '';
  5117. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  5118. $ymTarget = $ymM[1];
  5119. }
  5120. $filtered = [];
  5121. foreach ($pool as $r) {
  5122. if (!is_array($r)) {
  5123. continue;
  5124. }
  5125. foreach ($eqFilters as $field => $fv) {
  5126. if (trim((string)($r[$field] ?? '')) !== $fv) {
  5127. continue 2;
  5128. }
  5129. }
  5130. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  5131. // 初选池不应含手工单;若混入则直接剔除
  5132. if ($isManual) {
  5133. continue;
  5134. }
  5135. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  5136. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  5137. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  5138. continue;
  5139. }
  5140. if ($applyMonthRange) {
  5141. $mo = (int)$m[2];
  5142. if ($mo < 1 || $mo > 12) {
  5143. continue;
  5144. }
  5145. if ($ymTarget !== '') {
  5146. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  5147. if ($ymRow !== $ymTarget) {
  5148. continue;
  5149. }
  5150. } else {
  5151. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  5152. $rowMonthStart = $ymRow . '-01 00:00:00';
  5153. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  5154. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  5155. continue;
  5156. }
  5157. }
  5158. }
  5159. if ($search !== '') {
  5160. $hitSearch = false;
  5161. foreach ($searchColNames as $c) {
  5162. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  5163. if ($cell !== '' && $strContains($cell, $search)) {
  5164. $hitSearch = true;
  5165. break;
  5166. }
  5167. }
  5168. if (!$hitSearch) {
  5169. continue;
  5170. }
  5171. }
  5172. foreach ($otherFilters as $item) {
  5173. $fv = $item['fv'];
  5174. $sym = $item['sym'];
  5175. $field = $item['field'];
  5176. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  5177. $cellStr = trim((string)$cell);
  5178. switch ($sym) {
  5179. case '<>':
  5180. if ((string)$cell === (string)$fv) {
  5181. continue 3;
  5182. }
  5183. break;
  5184. case 'LIKE':
  5185. case 'NOT LIKE':
  5186. $needle = trim((string)$fv);
  5187. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  5188. if ($sym === 'LIKE' && !$hit) {
  5189. continue 3;
  5190. }
  5191. if ($sym === 'NOT LIKE' && $hit) {
  5192. continue 3;
  5193. }
  5194. break;
  5195. case 'BETWEEN':
  5196. case 'RANGE':
  5197. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  5198. if (count($parts) < 2) {
  5199. $parts = is_string($fv) ? explode(',', $fv) : [];
  5200. }
  5201. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  5202. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  5203. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  5204. continue 3;
  5205. }
  5206. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  5207. continue 3;
  5208. }
  5209. break;
  5210. case '>':
  5211. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  5212. continue 3;
  5213. }
  5214. break;
  5215. case '>=':
  5216. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  5217. continue 3;
  5218. }
  5219. break;
  5220. case '<':
  5221. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  5222. continue 3;
  5223. }
  5224. break;
  5225. case '<=':
  5226. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  5227. continue 3;
  5228. }
  5229. break;
  5230. default:
  5231. if ((string)$cell !== (string)$fv) {
  5232. continue 3;
  5233. }
  5234. break;
  5235. }
  5236. }
  5237. $filtered[] = $r;
  5238. }
  5239. return $filtered;
  5240. }
  5241. /**
  5242. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  5243. */
  5244. public function snapshotToProcure()
  5245. {
  5246. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5247. $this->error(__('Invalid parameters'));
  5248. }
  5249. $row = json_decode($this->request->post('row_json', ''), true);
  5250. if (!is_array($row)) {
  5251. $this->error(__('Invalid parameters'));
  5252. }
  5253. try {
  5254. $ids = $this->extractScydgyRowId($row);
  5255. if (!$this->isValidScydgyRowId($ids)) {
  5256. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  5257. }
  5258. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5259. $data = $this->normalizePurchaseOrderWritePayload([
  5260. 'scydgy_id' => $ids,
  5261. 'CCYDH' => $row['CCYDH'] ?? null,
  5262. 'CYJMC' => $row['CYJMC'] ?? null,
  5263. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  5264. 'CDXMC' => $row['CDXMC'] ?? null,
  5265. 'CGYBH' => $row['CGYBH'] ?? null,
  5266. 'CGYMC' => $row['CGYMC'] ?? null,
  5267. 'CDW' => $row['CDW'] ?? null,
  5268. 'czlyq' => $row['czlyq'] ?? null,
  5269. 'NGZL' => $row['NGZL'] ?? null,
  5270. 'CDF' => $row['CDF'] ?? null,
  5271. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  5272. 'MBZ' => $row['MBZ'] ?? null,
  5273. 'bwjg' => $row['bwjg'] ?? null,
  5274. 'iStatus' => $row['iStatus'] ?? null,
  5275. 'dStamp' => $row['dStamp'] ?? null,
  5276. 'dputrecord' => $row['dputrecord'] ?? null,
  5277. 'cywyxm' => $row['cywyxm'] ?? null,
  5278. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  5279. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  5280. ], $row);
  5281. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  5282. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  5283. $mbzSnap = trim((string)($data['MBZ'] ?? ''));
  5284. if (!$exists && $qtySnap === '' && $priceSnap === '' && $mbzSnap === '') {
  5285. $this->success('操作成功');
  5286. return;
  5287. }
  5288. if ($exists) {
  5289. $upd = $data;
  5290. unset($upd['scydgy_id'], $upd['status']);
  5291. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  5292. } else {
  5293. // 新增:不写 status(空/走库默认);仅写创建时间
  5294. $data['createtime'] = date('Y-m-d H:i:s');
  5295. Db::table('purchase_order')->insert($data);
  5296. }
  5297. } catch (\Throwable $e) {
  5298. $this->error($e->getMessage());
  5299. }
  5300. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  5301. $this->success('操作成功');
  5302. }
  5303. /**
  5304. * 未发列表
  5305. * 「完结」或「仅保存本次数量/最高限价/备注」:有则改、无则插
  5306. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  5307. */
  5308. public function completeDirectly()
  5309. {
  5310. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5311. $this->error(__('参数错误'));
  5312. }
  5313. if (!$this->procuremenCanComplete()) {
  5314. $this->error(__('You have no permission'));
  5315. }
  5316. $row = json_decode($this->request->post('row_json', ''), true);
  5317. if (!is_array($row)) {
  5318. $this->error(__('Invalid parameters'));
  5319. }
  5320. $finishRaw = $this->request->post('finish', '1');
  5321. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  5322. $poIdLog = null;
  5323. try {
  5324. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  5325. $ids = $this->extractScydgyRowId($row);
  5326. if (!$this->isValidScydgyRowId($ids)) {
  5327. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  5328. }
  5329. if ($asComplete) {
  5330. $this->assertPickRowCanComplete($ids, $row);
  5331. }
  5332. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5333. $data = $this->normalizePurchaseOrderWritePayload([
  5334. 'scydgy_id' => $ids,
  5335. 'CCYDH' => $row['CCYDH'] ?? null,
  5336. 'CYJMC' => $row['CYJMC'] ?? null,
  5337. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  5338. 'CDXMC' => $row['CDXMC'] ?? null,
  5339. 'CGYBH' => $row['CGYBH'] ?? null,
  5340. 'CGYMC' => $row['CGYMC'] ?? null,
  5341. 'CDW' => $row['CDW'] ?? null,
  5342. 'czlyq' => $row['czlyq'] ?? null,
  5343. 'NGZL' => $row['NGZL'] ?? null,
  5344. 'CDF' => $row['CDF'] ?? null,
  5345. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  5346. 'MBZ' => $row['MBZ'] ?? null,
  5347. 'bwjg' => $row['bwjg'] ?? null,
  5348. 'iStatus' => $row['iStatus'] ?? null,
  5349. 'dStamp' => $row['dStamp'] ?? null,
  5350. 'dputrecord' => $row['dputrecord'] ?? null,
  5351. 'cywyxm' => $row['cywyxm'] ?? null,
  5352. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  5353. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  5354. ], $row);
  5355. if ($asComplete) {
  5356. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  5357. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  5358. }
  5359. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  5360. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  5361. $mbzCd = trim((string)($data['MBZ'] ?? ''));
  5362. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '' && $mbzCd === '') {
  5363. $this->success('操作成功');
  5364. return;
  5365. }
  5366. if ($exists) {
  5367. $upd = $data;
  5368. unset($upd['scydgy_id']);
  5369. if (!$asComplete) {
  5370. unset($upd['status']);
  5371. }
  5372. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  5373. } else {
  5374. // 新增:不写 status;完结时 $data 已含 status=1
  5375. $data['createtime'] = date('Y-m-d H:i:s');
  5376. Db::table('purchase_order')->insert($data);
  5377. }
  5378. } catch (\Throwable $e) {
  5379. $this->error($e->getMessage());
  5380. }
  5381. try {
  5382. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5383. if (is_array($rpo)) {
  5384. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  5385. $poIdLog = $tid > 0 ? $tid : null;
  5386. }
  5387. } catch (\Throwable $e) {
  5388. $poIdLog = null;
  5389. }
  5390. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  5391. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  5392. if ($asComplete) {
  5393. $this->addOrderLog(
  5394. $ids,
  5395. 'mark_complete',
  5396. '点击「完结」,已标记为已完结',
  5397. $poIdLog
  5398. );
  5399. try {
  5400. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  5401. if ($pdfPublicPath === '') {
  5402. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  5403. }
  5404. } catch (\Throwable $e) {
  5405. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  5406. }
  5407. } else {
  5408. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  5409. $mbz = isset($data['MBZ']) ? trim((string)$data['MBZ']) : '';
  5410. $parts = [];
  5411. if ($q !== '') {
  5412. $parts[] = ($gymc !== '' ? ($gymc . '本次数量') : '本次数量') . '「' . $q . '」';
  5413. } elseif ($gymc !== '') {
  5414. // 仅改限价/备注时仍带工序名便于辨认
  5415. $parts[] = $gymc;
  5416. }
  5417. if ($p !== '') {
  5418. $parts[] = '最高限价「' . $p . '」';
  5419. }
  5420. if ($mbz !== '') {
  5421. $parts[] = '招标备注「' . $mbz . '」';
  5422. }
  5423. $detail = $parts !== [] ? implode(',', $parts) : '(未改数量/限价/招标备注)';
  5424. $this->addOrderLog(
  5425. $ids,
  5426. 'save_qty_price',
  5427. '保存本次数量、最高限价、招标备注:' . $detail,
  5428. $poIdLog
  5429. );
  5430. }
  5431. $this->pickHiddenScydgySetCache = null;
  5432. $this->success("操作成功");
  5433. }
  5434. /**
  5435. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价、备注(若表中有对应列)
  5436. *
  5437. * @param array<int, array> $rows 引用传递当前页行
  5438. */
  5439. protected function mergePurchaseOrder(array &$rows)
  5440. {
  5441. if ($rows === []) {
  5442. return;
  5443. }
  5444. $ids = [];
  5445. foreach ($rows as $rw) {
  5446. if (!is_array($rw)) {
  5447. continue;
  5448. }
  5449. $id = (int)($rw['ID'] ?? 0);
  5450. // 含手工新增负数 scydgy_id,避免限价/数量不同步
  5451. if ($this->isValidScydgyRowId($id)) {
  5452. $ids[$id] = true;
  5453. }
  5454. }
  5455. $idList = array_keys($ids);
  5456. if ($idList === []) {
  5457. return;
  5458. }
  5459. try {
  5460. $list = Db::table('purchase_order')
  5461. ->where('scydgy_id', 'in', $idList)
  5462. ->field('scydgy_id,This_quantity,ceilingPrice,MBZ')
  5463. ->select();
  5464. } catch (\Throwable $e) {
  5465. return;
  5466. }
  5467. if (!is_array($list)) {
  5468. return;
  5469. }
  5470. $byId = [];
  5471. foreach ($list as $dbRow) {
  5472. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  5473. continue;
  5474. }
  5475. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  5476. }
  5477. foreach ($rows as &$rw) {
  5478. if (!is_array($rw)) {
  5479. continue;
  5480. }
  5481. $sid = (int)($rw['ID'] ?? 0);
  5482. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  5483. continue;
  5484. }
  5485. $db = $byId[$sid];
  5486. // 有 purchase_order 记录时同步数量/限价/备注(含清空后的空串,避免刷新后又冒出来)
  5487. if (array_key_exists('This_quantity', $db)) {
  5488. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  5489. }
  5490. if (array_key_exists('ceilingPrice', $db)) {
  5491. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  5492. } elseif (array_key_exists('ceiling_price', $db)) {
  5493. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  5494. }
  5495. if (array_key_exists('MBZ', $db)) {
  5496. $poMbz = $db['MBZ'] === null ? '' : trim((string)$db['MBZ']);
  5497. if ($poMbz !== '') {
  5498. $rw['MBZ'] = $poMbz;
  5499. }
  5500. }
  5501. }
  5502. unset($rw);
  5503. }
  5504. /**
  5505. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  5506. */
  5507. public function purchaseConfirmPick()
  5508. {
  5509. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5510. $this->error(__('Invalid parameters'));
  5511. }
  5512. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  5513. $this->error(__('You have no permission'));
  5514. }
  5515. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  5516. if ($batchRaw !== '') {
  5517. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  5518. return;
  5519. }
  5520. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5521. $sid = (int)$scydgyId;
  5522. if (!$this->isValidScydgyRowId($sid)) {
  5523. $this->error('参数无效');
  5524. }
  5525. $parseIdList = function ($raw) {
  5526. if (is_array($raw)) {
  5527. $arr = $raw;
  5528. } else {
  5529. $decoded = json_decode((string)$raw, true);
  5530. $arr = is_array($decoded) ? $decoded : [];
  5531. }
  5532. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  5533. };
  5534. $selectedRaw = $this->request->post('selected_ids', null);
  5535. if ($selectedRaw === null || $selectedRaw === '') {
  5536. $legacy = (int)$this->request->post('selected_id', 0);
  5537. $selectedIds = $legacy > 0 ? [$legacy] : [];
  5538. } else {
  5539. $selectedIds = $parseIdList($selectedRaw);
  5540. }
  5541. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  5542. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  5543. try {
  5544. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  5545. } catch (\InvalidArgumentException $e) {
  5546. $this->error($e->getMessage());
  5547. } catch (\Throwable $e) {
  5548. $this->error($e->getMessage());
  5549. }
  5550. $this->pickHiddenScydgySetCache = null;
  5551. $this->success('操作成功', '', $result);
  5552. }
  5553. /**
  5554. * 整单采购确认(多道工序一次提交)
  5555. */
  5556. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  5557. {
  5558. $decoded = json_decode($batchRaw, true);
  5559. if (!is_array($decoded) || $decoded === []) {
  5560. $this->error('提交数据无效');
  5561. }
  5562. $picks = [];
  5563. foreach ($decoded as $item) {
  5564. if (!is_array($item)) {
  5565. continue;
  5566. }
  5567. $sid = (int)($item['scydgy_id'] ?? 0);
  5568. if (!$this->isValidScydgyRowId($sid)) {
  5569. continue;
  5570. }
  5571. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  5572. if (!is_array($sel)) {
  5573. $sel = [(int)$sel];
  5574. }
  5575. $unsel = $item['unselected_ids'] ?? [];
  5576. if (!is_array($unsel)) {
  5577. $unsel = json_decode((string)$unsel, true);
  5578. $unsel = is_array($unsel) ? $unsel : [];
  5579. }
  5580. $picks[] = [
  5581. 'scydgy_id' => $sid,
  5582. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  5583. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  5584. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  5585. ];
  5586. }
  5587. if ($picks === []) {
  5588. $this->error('提交数据无效');
  5589. }
  5590. Db::startTrans();
  5591. $results = [];
  5592. try {
  5593. foreach ($picks as $pick) {
  5594. $results[] = $this->runPurchaseConfirmPick(
  5595. (int)$pick['scydgy_id'],
  5596. $pick['selected_ids'],
  5597. $pick['unselected_ids'],
  5598. (int)$pick['purchase_order_id'],
  5599. false,
  5600. false
  5601. );
  5602. }
  5603. Db::commit();
  5604. } catch (\Throwable $e) {
  5605. Db::rollback();
  5606. $msg = $e->getMessage();
  5607. $this->error($msg !== '' ? $msg : '提交失败');
  5608. }
  5609. try {
  5610. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  5611. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  5612. } catch (\Throwable $e) {
  5613. Log::write('采购确认通知批量发送异常: ' . $e->getMessage(), 'error');
  5614. }
  5615. $this->pickHiddenScydgySetCache = null;
  5616. $this->success('操作成功', '', ['batch' => $results]);
  5617. }
  5618. /**
  5619. * @return array<string, mixed>
  5620. */
  5621. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  5622. {
  5623. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  5624. ProcuremenGuard::assertWflowPendingApproval($poRow);
  5625. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  5626. $scydgyId = (string)$sid;
  5627. if ($selectedIds === []) {
  5628. throw new \InvalidArgumentException('请至少勾选一条明细');
  5629. }
  5630. $inter = array_intersect($selectedIds, $unselectedIds);
  5631. if ($inter !== []) {
  5632. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  5633. }
  5634. $allIds = $this->purchaseOrderDetail($sid);
  5635. if ($allIds === []) {
  5636. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  5637. }
  5638. foreach ($selectedIds as $id) {
  5639. if (!in_array($id, $allIds, true)) {
  5640. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  5641. }
  5642. }
  5643. foreach ($unselectedIds as $id) {
  5644. if (!in_array($id, $allIds, true)) {
  5645. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  5646. }
  5647. }
  5648. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  5649. sort($union, SORT_NUMERIC);
  5650. $expect = $allIds;
  5651. sort($expect, SORT_NUMERIC);
  5652. if ($union !== $expect) {
  5653. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  5654. }
  5655. if ($manageTransaction) {
  5656. Db::startTrans();
  5657. }
  5658. try {
  5659. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  5660. $aff = 0;
  5661. try {
  5662. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  5663. } catch (\Throwable $e) {
  5664. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  5665. }
  5666. if ($aff < 1) {
  5667. throw new \Exception('更新选中状态失败');
  5668. }
  5669. $poPayload = [
  5670. // 审核通过后进入「待入库评分」;合格/不合格后才置已完结
  5671. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5672. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  5673. ];
  5674. if ($purchaseOrderId > 0) {
  5675. $poAff = (int)Db::table('purchase_order')
  5676. ->where('id', $purchaseOrderId)
  5677. ->where('scydgy_id', $sid)
  5678. ->update($poPayload);
  5679. if ($poAff < 1) {
  5680. throw new \Exception('主表订单不存在或与工序行不匹配');
  5681. }
  5682. } else {
  5683. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  5684. if ($poAff < 1) {
  5685. throw new \Exception('未找到');
  5686. }
  5687. }
  5688. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  5689. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  5690. if ($manageTransaction) {
  5691. Db::commit();
  5692. }
  5693. } catch (\Throwable $e) {
  5694. if ($manageTransaction) {
  5695. Db::rollback();
  5696. }
  5697. throw $e;
  5698. }
  5699. $poIdFinal = $purchaseOrderId;
  5700. if ($poIdFinal <= 0) {
  5701. try {
  5702. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  5703. if (is_array($rpo)) {
  5704. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  5705. }
  5706. } catch (\Throwable $e) {
  5707. $poIdFinal = 0;
  5708. }
  5709. }
  5710. $pickNames = [];
  5711. foreach ($selectedIds as $pid) {
  5712. $dr = $this->purchaseOrderDetai($sid, $pid);
  5713. $nm = trim((string)($dr['company_name'] ?? ''));
  5714. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  5715. }
  5716. $this->addOrderLog(
  5717. $sid,
  5718. 'purchase_confirm',
  5719. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  5720. $poIdFinal > 0 ? $poIdFinal : null
  5721. );
  5722. if ($sendNotifications) {
  5723. try {
  5724. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  5725. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  5726. 'scydgy_id' => $sid,
  5727. 'selected_ids' => $selectedIds,
  5728. 'unselected_ids' => $unselectedIds,
  5729. 'purchase_order_id' => $purchaseOrderId,
  5730. ]]);
  5731. } catch (\Throwable $e) {
  5732. Log::write('采购确认通知发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  5733. }
  5734. }
  5735. Log::write(sprintf(
  5736. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  5737. $scydgyId,
  5738. $purchaseOrderId,
  5739. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  5740. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  5741. ), 'notice');
  5742. $pdfPublicPath = '';
  5743. try {
  5744. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  5745. } catch (\Throwable $e) {
  5746. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  5747. }
  5748. return [
  5749. 'scydgy_id' => $scydgyId,
  5750. 'purchase_order_id' => $purchaseOrderId,
  5751. 'selected_ids' => $selectedIds,
  5752. 'unselected_ids' => $unselectedIds,
  5753. 'purchase_confirm_pdf' => $pdfPublicPath,
  5754. ];
  5755. }
  5756. /**
  5757. * 审批通过短信:按本次涉及的工序汇总 process_lines
  5758. *
  5759. * @param int[]|string[] $scydgyIds
  5760. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  5761. */
  5762. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  5763. {
  5764. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  5765. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  5766. if ($scydgyIds === []) {
  5767. return $empty;
  5768. }
  5769. $pos = [];
  5770. try {
  5771. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  5772. } catch (\Throwable $e) {
  5773. $rows = [];
  5774. }
  5775. if (is_array($rows)) {
  5776. foreach ($rows as $po) {
  5777. if (is_array($po)) {
  5778. $pos[] = $po;
  5779. }
  5780. }
  5781. }
  5782. if ($pos === []) {
  5783. return $empty;
  5784. }
  5785. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  5786. return [
  5787. 'ccydh' => $ccydh,
  5788. 'pos' => $pos,
  5789. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  5790. ];
  5791. }
  5792. /**
  5793. * 审批通过/未通过:短信 + 邮件(同一供应商只发一条;邮件含平台链接)
  5794. *
  5795. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  5796. * @param array<int, array<string, mixed>> $picks
  5797. */
  5798. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  5799. {
  5800. if ($picks === []) {
  5801. return;
  5802. }
  5803. $this->ensureConfirmResultEmailTemplates();
  5804. $fallbackDetailId = 0;
  5805. $winners = [];
  5806. $losers = [];
  5807. foreach ($picks as $pick) {
  5808. if (!is_array($pick)) {
  5809. continue;
  5810. }
  5811. $sid = (int)($pick['scydgy_id'] ?? 0);
  5812. if (!$this->isValidScydgyRowId($sid)) {
  5813. continue;
  5814. }
  5815. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  5816. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  5817. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  5818. $fallbackDetailId = (int)$selectedIds[0];
  5819. }
  5820. foreach ($selectedIds as $pid) {
  5821. $dr = $this->purchaseOrderDetai($sid, $pid);
  5822. if (!is_array($dr)) {
  5823. continue;
  5824. }
  5825. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  5826. }
  5827. foreach ($unselectedIds as $pid) {
  5828. $dr = $this->purchaseOrderDetai($sid, $pid);
  5829. if (!is_array($dr)) {
  5830. continue;
  5831. }
  5832. $key = $this->notifySupplierDedupeKey($dr);
  5833. if (!isset($winners[$key])) {
  5834. $losers[$key] = $dr;
  5835. }
  5836. }
  5837. }
  5838. if ($winners === [] && $losers === []) {
  5839. return;
  5840. }
  5841. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  5842. $poIdLog = 0;
  5843. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5844. if (isset($pos[0]) && is_array($pos[0])) {
  5845. $poIdLog = (int)($pos[0]['id'] ?? 0);
  5846. }
  5847. $mergeRowsLog = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  5848. $emailLogCcydh = $this->collectCcydhListForEmailLog($mergeRowsLog, $pos);
  5849. $emailLogBatchNo = $this->resolveBundleOrderBatchNo($bundle);
  5850. $sendSmsSafe = function ($phone, $content) {
  5851. $phone = trim((string)$phone);
  5852. if ($phone === '') {
  5853. return;
  5854. }
  5855. try {
  5856. $this->smsbao($phone, $content);
  5857. } catch (\Throwable $e) {
  5858. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  5859. }
  5860. };
  5861. $sendConfirmEmailSafe = function (array $dr, string $emailScene) use ($confirmNotifyVars, $poIdLog, $emailLogCcydh, $emailLogBatchNo) {
  5862. $cname = trim((string)($dr['company_name'] ?? ''));
  5863. $ph = trim((string)($dr['phone'] ?? ''));
  5864. $toEmail = trim((string)($dr['email'] ?? ''));
  5865. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5866. Log::write('采购确认邮件跳过:无有效邮箱 company=' . $cname, 'error');
  5867. return;
  5868. }
  5869. $detailId = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5870. if ($detailId <= 0) {
  5871. $detailId = (int)($confirmNotifyVars['_fallback_detail_id'] ?? 0);
  5872. }
  5873. try {
  5874. $platformUrl = $this->buildMprocMobileOrderUrl($detailId);
  5875. } catch (\Throwable $e) {
  5876. Log::write('采购确认邮件链接失败: ' . $e->getMessage(), 'error');
  5877. $platformUrl = '';
  5878. }
  5879. $vars = array_merge($confirmNotifyVars, [
  5880. 'company_name' => $cname,
  5881. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5882. 'phone' => $ph,
  5883. 'email' => $toEmail,
  5884. 'platform_url' => $platformUrl,
  5885. ]);
  5886. unset($vars['_fallback_detail_id']);
  5887. try {
  5888. $mailPlain = $this->renderNotifyTemplate($emailScene, $vars);
  5889. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  5890. $mailSubject = $this->resolveProcuremenEmailSubject($emailScene);
  5891. $mailConfig = $this->loadMailerConfig();
  5892. $this->issueSendSupplierEmail([
  5893. 'company_name' => $cname,
  5894. 'email' => $toEmail,
  5895. 'mail_plain' => $mailPlain,
  5896. 'mail_body' => $mailBody,
  5897. 'notify_vars' => $vars,
  5898. 'sms_content' => '',
  5899. 'detail_links' => $platformUrl !== '' ? [['url' => $platformUrl, 'cgymc' => '']] : [],
  5900. 'email_log_scene' => (strpos((string)$emailScene, 'confirm_ok') !== false) ? 'confirm_ok' : 'confirm_fail',
  5901. 'email_log_scydgy_id' => (int)($dr['scydgy_id'] ?? 0),
  5902. 'email_log_purchase_order_id' => $poIdLog,
  5903. 'email_log_ccydh' => $emailLogCcydh !== '' ? $emailLogCcydh : trim((string)($vars['ccydh'] ?? '')),
  5904. 'email_log_order_batch_no' => $emailLogBatchNo,
  5905. ], $mailConfig, $mailSubject);
  5906. } catch (\Throwable $e) {
  5907. Log::write('采购确认邮件失败 company=' . $cname . ' email=' . $toEmail . ' ' . $e->getMessage(), 'error');
  5908. }
  5909. };
  5910. $confirmNotifyVars['_fallback_detail_id'] = $fallbackDetailId;
  5911. foreach ($winners as $dr) {
  5912. $cname = trim((string)($dr['company_name'] ?? ''));
  5913. $ph = trim((string)($dr['phone'] ?? ''));
  5914. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  5915. 'company_name' => $cname,
  5916. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5917. 'phone' => $ph,
  5918. ]));
  5919. $sendSmsSafe($ph, $sms);
  5920. $sendConfirmEmailSafe($dr, 'confirm_ok_email');
  5921. }
  5922. foreach ($losers as $dr) {
  5923. $cname = trim((string)($dr['company_name'] ?? ''));
  5924. $ph = trim((string)($dr['phone'] ?? ''));
  5925. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  5926. 'company_name' => $cname,
  5927. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5928. 'phone' => $ph,
  5929. ]));
  5930. $sendSmsSafe($ph, $sms);
  5931. $sendConfirmEmailSafe($dr, 'confirm_fail_email');
  5932. }
  5933. }
  5934. /**
  5935. * 短信去重键:优先手机号,否则公司名
  5936. */
  5937. protected function notifySupplierDedupeKey(array $detailRow): string
  5938. {
  5939. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  5940. if ($ph !== '') {
  5941. return 'p:' . $ph;
  5942. }
  5943. $cn = trim((string)($detailRow['company_name'] ?? ''));
  5944. return 'c:' . $cn;
  5945. }
  5946. /**
  5947. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  5948. *
  5949. * @param int[] $detailIds
  5950. */
  5951. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  5952. {
  5953. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  5954. if ($detailIds === []) {
  5955. return;
  5956. }
  5957. $payload = ['status_name' => $statusName];
  5958. try {
  5959. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  5960. } catch (\Throwable $e) {
  5961. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  5962. }
  5963. }
  5964. /**
  5965. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  5966. */
  5967. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  5968. {
  5969. try {
  5970. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  5971. } catch (\Throwable $e) {
  5972. return;
  5973. }
  5974. if (!is_array($rows)) {
  5975. return;
  5976. }
  5977. foreach ($rows as $dr) {
  5978. if (!is_array($dr)) {
  5979. continue;
  5980. }
  5981. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5982. if ($id <= 0) {
  5983. continue;
  5984. }
  5985. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  5986. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  5987. try {
  5988. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  5989. } catch (\Throwable $e) {
  5990. }
  5991. }
  5992. }
  5993. /**
  5994. * @param array<string, mixed> $detailRow
  5995. */
  5996. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  5997. {
  5998. $am = $detailRow['amount'] ?? null;
  5999. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  6000. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  6001. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  6002. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  6003. }
  6004. /**
  6005. * @return int[]
  6006. */
  6007. protected function purchaseOrderDetail(int $scydgyId): array
  6008. {
  6009. if (!$this->isValidScydgyRowId($scydgyId)) {
  6010. return [];
  6011. }
  6012. try {
  6013. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  6014. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  6015. $list = $listQuery->select();
  6016. } catch (\Throwable $e) {
  6017. return [];
  6018. }
  6019. if (!is_array($list)) {
  6020. return [];
  6021. }
  6022. $ids = [];
  6023. foreach ($list as $r) {
  6024. if (!is_array($r)) {
  6025. continue;
  6026. }
  6027. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  6028. if ($pk > 0) {
  6029. $ids[] = $pk;
  6030. }
  6031. }
  6032. return array_values(array_unique($ids));
  6033. }
  6034. /**
  6035. * 获取当前登录用户信息 [id, 展示名]
  6036. * admin_name 一律记「名称」(昵称),无昵称再回退账号
  6037. */
  6038. protected function GetUseName(): array
  6039. {
  6040. $id = 0;
  6041. $name = '';
  6042. try {
  6043. if ($this->auth && $this->auth->isLogin()) {
  6044. $u = $this->auth->getUserInfo();
  6045. if (is_array($u)) {
  6046. $id = (int)($u['id'] ?? 0);
  6047. $name = trim((string)($u['nickname'] ?? ''));
  6048. // 会话昵称缺失或等于登录账号时,再查库取正式昵称
  6049. $sessionUser = trim((string)($u['username'] ?? ''));
  6050. if ($id > 0 && ($name === '' || ($sessionUser !== '' && strcasecmp($name, $sessionUser) === 0))) {
  6051. try {
  6052. $row = Db::name('admin')->where('id', $id)->field('nickname,username')->find();
  6053. if (is_array($row)) {
  6054. $nick = trim((string)($row['nickname'] ?? ''));
  6055. if ($nick !== '') {
  6056. $name = $nick;
  6057. } elseif ($name === '') {
  6058. $name = trim((string)($row['username'] ?? ''));
  6059. }
  6060. }
  6061. } catch (\Throwable $e) {
  6062. }
  6063. }
  6064. if ($name === '') {
  6065. $name = $sessionUser;
  6066. }
  6067. }
  6068. }
  6069. } catch (\Throwable $e) {
  6070. }
  6071. if ($name === '') {
  6072. $name = '未知用户';
  6073. }
  6074. return [$id, $name];
  6075. }
  6076. /**
  6077. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  6078. */
  6079. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  6080. {
  6081. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  6082. }
  6083. /**
  6084. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  6085. *
  6086. * @param array<int, array<string, mixed>> $rows
  6087. */
  6088. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  6089. {
  6090. $sidList = [];
  6091. foreach ($rows as $rw) {
  6092. if (!is_array($rw)) {
  6093. continue;
  6094. }
  6095. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  6096. foreach ($rw['_order_merge_rows'] as $mr) {
  6097. $mid = (int)($mr['ID'] ?? 0);
  6098. if ($this->isValidScydgyRowId($mid)) {
  6099. $sidList[$mid] = true;
  6100. }
  6101. }
  6102. }
  6103. $id = (int)($rw['ID'] ?? 0);
  6104. if ($this->isValidScydgyRowId($id)) {
  6105. $sidList[$id] = true;
  6106. }
  6107. }
  6108. $sids = array_keys($sidList);
  6109. $issueBySid = [];
  6110. $confirmBySid = [];
  6111. $approveBySid = [];
  6112. if ($sids !== []) {
  6113. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  6114. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  6115. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  6116. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  6117. try {
  6118. $logs = Db::table('purchase_order_oper_log')
  6119. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  6120. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  6121. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  6122. ->order('id', 'asc')
  6123. ->select();
  6124. } catch (\Throwable $e) {
  6125. $logs = [];
  6126. }
  6127. if (is_array($logs)) {
  6128. $issueSet = array_fill_keys($issueActs, true);
  6129. $confirmSet = array_fill_keys($confirmActs, true);
  6130. $approveSet = array_fill_keys($approveActs, true);
  6131. foreach ($logs as $lg) {
  6132. if (!is_array($lg)) {
  6133. continue;
  6134. }
  6135. $lg = ProcuremenOperLog::normalizeRow($lg);
  6136. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  6137. if ($sid === 0) {
  6138. continue;
  6139. }
  6140. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  6141. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  6142. if ($t === '') {
  6143. continue;
  6144. }
  6145. if (isset($issueSet[$action])) {
  6146. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  6147. $issueBySid[$sid] = $t;
  6148. }
  6149. }
  6150. if (isset($confirmSet[$action])) {
  6151. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  6152. $confirmBySid[$sid] = $t;
  6153. }
  6154. }
  6155. if (isset($approveSet[$action])) {
  6156. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  6157. $approveBySid[$sid] = $t;
  6158. }
  6159. }
  6160. }
  6161. }
  6162. }
  6163. foreach ($rows as &$rw) {
  6164. if (!is_array($rw)) {
  6165. continue;
  6166. }
  6167. $mergeSids = [];
  6168. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  6169. foreach ($rw['_order_merge_rows'] as $mr) {
  6170. $mid = (int)($mr['ID'] ?? 0);
  6171. if ($this->isValidScydgyRowId($mid)) {
  6172. $mergeSids[] = $mid;
  6173. }
  6174. }
  6175. }
  6176. $rid = (int)($rw['ID'] ?? 0);
  6177. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  6178. $mergeSids[] = $rid;
  6179. }
  6180. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  6181. $issue = $pick;
  6182. $confirm = '';
  6183. $approve = '';
  6184. foreach ($mergeSids as $sid) {
  6185. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  6186. $issue = $issueBySid[$sid];
  6187. }
  6188. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  6189. $confirm = $confirmBySid[$sid];
  6190. }
  6191. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  6192. $approve = $approveBySid[$sid];
  6193. }
  6194. }
  6195. if ($issue === '' && $pick !== '') {
  6196. $issue = $pick;
  6197. }
  6198. $rw['issue_time'] = $issue;
  6199. $rw['confirm_time'] = $confirm;
  6200. $rw['approve_time'] = $approve;
  6201. }
  6202. unset($rw);
  6203. }
  6204. /**
  6205. * 按主键取一条
  6206. */
  6207. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  6208. {
  6209. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  6210. return [];
  6211. }
  6212. try {
  6213. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  6214. if (is_array($one)) {
  6215. return $one;
  6216. }
  6217. } catch (\Throwable $e) {
  6218. }
  6219. try {
  6220. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  6221. if (is_array($one)) {
  6222. return $one;
  6223. }
  6224. } catch (\Throwable $e) {
  6225. }
  6226. return [];
  6227. }
  6228. /**
  6229. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  6230. */
  6231. protected function formatProcuremenDetailTime($v): string
  6232. {
  6233. return ProcuremenFormat::detailTime($v);
  6234. }
  6235. /**
  6236. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  6237. */
  6238. protected function formatDeliveryYmd($v): string
  6239. {
  6240. return ProcuremenFormat::deliveryYmd($v);
  6241. }
  6242. /**
  6243. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  6244. */
  6245. protected function detailRowSupplierOperated(array $r): bool
  6246. {
  6247. $am = $r['amount'] ?? null;
  6248. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  6249. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  6250. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  6251. return $okAmt || $okDel;
  6252. }
  6253. /**
  6254. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  6255. */
  6256. protected function resolveDetailSupplierOperTime(array $r): string
  6257. {
  6258. if (!$this->detailRowSupplierOperated($r)) {
  6259. return '';
  6260. }
  6261. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  6262. if ($t !== '') {
  6263. return $t;
  6264. }
  6265. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  6266. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  6267. continue;
  6268. }
  6269. $t = $this->formatProcuremenDetailTime($r[$col]);
  6270. if ($t !== '') {
  6271. return $t;
  6272. }
  6273. }
  6274. return '';
  6275. }
  6276. /**
  6277. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  6278. */
  6279. protected function detailRowSupplierAccepted(array $r): bool
  6280. {
  6281. $am = $r['amount'] ?? null;
  6282. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  6283. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  6284. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  6285. return $okAmt && $okDel;
  6286. }
  6287. /**
  6288. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  6289. */
  6290. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  6291. {
  6292. if ($detailCount > 0) {
  6293. return true;
  6294. }
  6295. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  6296. return true;
  6297. }
  6298. $pickTime = trim((string)($main['pick_time'] ?? ''));
  6299. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  6300. return true;
  6301. }
  6302. return false;
  6303. }
  6304. /**
  6305. * 下发时间:优先 pick_time,其次首条下发明细时间
  6306. */
  6307. protected function resolveProcuremenIssueTime(array $main, array $details): string
  6308. {
  6309. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  6310. if ($issueTime !== '') {
  6311. return $issueTime;
  6312. }
  6313. foreach ($details as $dr) {
  6314. if (!is_array($dr)) {
  6315. continue;
  6316. }
  6317. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  6318. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  6319. $issueTime = $t;
  6320. }
  6321. }
  6322. if ($issueTime !== '') {
  6323. return $issueTime;
  6324. }
  6325. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  6326. }
  6327. /**
  6328. * 直接点「完结」时间:优先操作记录 mark_complete
  6329. */
  6330. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  6331. {
  6332. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  6333. }
  6334. /**
  6335. * 操作记录时间(取指定 action 最近一条)
  6336. *
  6337. * @param string|array<int, string> $actions
  6338. */
  6339. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  6340. {
  6341. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  6342. }
  6343. /**
  6344. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  6345. *
  6346. * @param array $main purchase_order 一行
  6347. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  6348. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  6349. */
  6350. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  6351. {
  6352. $issueCnt = count($details);
  6353. $acceptCnt = 0;
  6354. $pickedName = '';
  6355. $pickedTime = '';
  6356. foreach ($details as $dr) {
  6357. if (!is_array($dr)) {
  6358. continue;
  6359. }
  6360. if ($this->detailRowSupplierAccepted($dr)) {
  6361. $acceptCnt++;
  6362. }
  6363. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  6364. if ($pickedName === '') {
  6365. $pickedName = trim((string)($dr['company_name'] ?? ''));
  6366. }
  6367. if ($pickedTime === '') {
  6368. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  6369. if ($pickedTime === '') {
  6370. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  6371. }
  6372. }
  6373. }
  6374. }
  6375. $hasMain = $main !== [];
  6376. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  6377. if ($poTime === '') {
  6378. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  6379. }
  6380. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  6381. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  6382. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  6383. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  6384. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  6385. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  6386. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  6387. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  6388. $inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
  6389. $inboundResult = '';
  6390. if ($scydgyId > 0) {
  6391. try {
  6392. $inRow = Db::table('purchase_order_inbound_score')
  6393. ->where('scydgy_id', $scydgyId)
  6394. ->field('result,updatetime,createtime')
  6395. ->find();
  6396. } catch (\Throwable $e) {
  6397. $inRow = null;
  6398. }
  6399. if (is_array($inRow) && $inRow !== []) {
  6400. $inboundResult = trim((string)($inRow['result'] ?? ''));
  6401. if ($inboundScoreTime === '') {
  6402. $inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
  6403. }
  6404. }
  6405. }
  6406. $inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
  6407. $supplierTime = '';
  6408. if ($acceptCnt > 0) {
  6409. foreach ($details as $dr) {
  6410. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  6411. continue;
  6412. }
  6413. $t = $this->resolveDetailSupplierOperTime($dr);
  6414. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  6415. $supplierTime = $t;
  6416. }
  6417. }
  6418. }
  6419. $directComplete = ($mainCompleted && !$issued);
  6420. $doneTime = '';
  6421. if ($mainCompleted) {
  6422. if ($directComplete) {
  6423. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  6424. }
  6425. if ($doneTime === '' && $inboundScoreTime !== '') {
  6426. $doneTime = $inboundScoreTime;
  6427. }
  6428. if ($doneTime === '') {
  6429. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  6430. }
  6431. if ($doneTime === '') {
  6432. foreach ($details as $dr) {
  6433. if (!is_array($dr)) {
  6434. continue;
  6435. }
  6436. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  6437. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  6438. $doneTime = $t;
  6439. }
  6440. }
  6441. }
  6442. if ($doneTime === '') {
  6443. $doneTime = $poTime;
  6444. }
  6445. // 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
  6446. if ($doneTime === '' && $confirmApproveTime !== '') {
  6447. $doneTime = $confirmApproveTime;
  6448. }
  6449. }
  6450. if ($directComplete) {
  6451. // 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
  6452. $step1Done = $hasMain;
  6453. $step2Done = false;
  6454. $step3Done = false;
  6455. $step4Done = false;
  6456. $step5Done = false;
  6457. $stepInboundDone = $inboundScored;
  6458. $step6Done = $mainCompleted && $inboundScored;
  6459. } else {
  6460. $step1Done = $issued;
  6461. $step2Done = $issued;
  6462. $step3Done = $acceptCnt > 0;
  6463. $step4Done = $wflowPendingApproval;
  6464. if (!$step4Done) {
  6465. foreach ($details as $dr) {
  6466. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  6467. $step4Done = true;
  6468. break;
  6469. }
  6470. }
  6471. }
  6472. $step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
  6473. $stepInboundDone = $inboundScored;
  6474. // 未确认合格/不合格时,「已完结」保持未点亮(灰色)
  6475. $step6Done = $mainCompleted && $inboundScored;
  6476. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  6477. if ($mainCompleted && $issued) {
  6478. $step3Done = true;
  6479. $step4Done = true;
  6480. $step5Done = true;
  6481. // 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
  6482. if ($supplierTime === '') {
  6483. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6484. if ($fillT !== '') {
  6485. $supplierTime = $fillT;
  6486. }
  6487. }
  6488. if ($pickedTime === '') {
  6489. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6490. if ($fillT !== '') {
  6491. $pickedTime = $fillT;
  6492. }
  6493. }
  6494. if ($auditSelectTime === '') {
  6495. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6496. if ($fillT !== '') {
  6497. $auditSelectTime = $fillT;
  6498. }
  6499. }
  6500. if ($confirmApproveTime === '') {
  6501. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6502. if ($fillT !== '') {
  6503. $confirmApproveTime = $fillT;
  6504. }
  6505. }
  6506. }
  6507. }
  6508. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  6509. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  6510. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  6511. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  6512. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  6513. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  6514. $inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
  6515. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  6516. $deadlineLines = [];
  6517. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  6518. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  6519. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  6520. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  6521. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  6522. }
  6523. }
  6524. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  6525. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  6526. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  6527. if ($deliveryDisp === '') {
  6528. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  6529. }
  6530. if ($deliveryDisp !== '') {
  6531. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  6532. }
  6533. }
  6534. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  6535. $deadlineText = implode("\n", $deadlineLines);
  6536. $prefixOperTime = static function (string $t): string {
  6537. $t = trim($t);
  6538. if ($t === '' || $t === '—') {
  6539. return $t;
  6540. }
  6541. if (strpos($t, '操作时间') === 0) {
  6542. return $t;
  6543. }
  6544. return '操作时间:' . $t;
  6545. };
  6546. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  6547. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  6548. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
  6549. $stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  6550. $step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  6551. $steps = [
  6552. [
  6553. 'title' => '未发',
  6554. 'subtitle' => '',
  6555. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  6556. 'done' => $step1Done,
  6557. ],
  6558. [
  6559. 'title' => '下发',
  6560. 'subtitle' => $deadlineText,
  6561. 'time' => $prefixOperTime($step2Time),
  6562. 'done' => $step2Done,
  6563. ],
  6564. [
  6565. 'title' => '供应商接单',
  6566. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  6567. 'time' => '',
  6568. 'done' => $step3Done,
  6569. ],
  6570. [
  6571. 'title' => '待确认',
  6572. 'subtitle' => $step4Done
  6573. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  6574. : ($issued ? '待选供应商' : ''),
  6575. 'time' => $prefixOperTime($step4Time),
  6576. 'done' => $step4Done,
  6577. ],
  6578. [
  6579. 'title' => '待审批',
  6580. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  6581. 'time' => $prefixOperTime($step5Time),
  6582. 'done' => $step5Done,
  6583. ],
  6584. [
  6585. 'title' => '是否合格',
  6586. 'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
  6587. 'time' => $prefixOperTime($stepInboundTime),
  6588. 'done' => $stepInboundDone,
  6589. ],
  6590. [
  6591. 'title' => '已完结',
  6592. 'subtitle' => '',
  6593. 'time' => $prefixOperTime($step6Time),
  6594. 'done' => $step6Done,
  6595. ],
  6596. ];
  6597. $currentIdx = count($steps) - 1;
  6598. if ($directComplete) {
  6599. // 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
  6600. if (!$step6Done) {
  6601. foreach ($steps as $i => $s) {
  6602. if (($s['title'] ?? '') === '是否合格') {
  6603. $currentIdx = $i;
  6604. break;
  6605. }
  6606. }
  6607. }
  6608. } else {
  6609. foreach ($steps as $i => $s) {
  6610. if (!$s['done']) {
  6611. $currentIdx = $i;
  6612. break;
  6613. }
  6614. }
  6615. }
  6616. $nSteps = count($steps);
  6617. foreach ($steps as $idx => &$s) {
  6618. $s['current'] = ($idx === $currentIdx);
  6619. if ($idx === 0) {
  6620. $s['pdf_left_bg'] = '';
  6621. } else {
  6622. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  6623. }
  6624. if ($idx >= $nSteps - 1) {
  6625. $s['pdf_right_bg'] = '';
  6626. } else {
  6627. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  6628. }
  6629. }
  6630. unset($s);
  6631. $labelMap = [
  6632. 'CCYDH' => '订单号',
  6633. 'CYJMC' => '印件名称',
  6634. 'CCLBMMC' => '承揽部门',
  6635. 'CGYMC' => '工序名称',
  6636. 'CDW' => '单位',
  6637. 'czlyq' => '类型',
  6638. 'NGZL' => '工作量',
  6639. 'CDF' => '单价',
  6640. 'cGzzxMc' => '工作中心',
  6641. 'MBZ' => '招标备注',
  6642. 'This_quantity' => '本次数量',
  6643. 'ceilingPrice' => '最高限价',
  6644. ];
  6645. $orderSummary = [];
  6646. foreach ($labelMap as $key => $lab) {
  6647. if (!array_key_exists($key, $main)) {
  6648. continue;
  6649. }
  6650. $val = $main[$key];
  6651. if ($val === null) {
  6652. $val = '';
  6653. } elseif (!is_scalar($val)) {
  6654. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  6655. } else {
  6656. $val = (string)$val;
  6657. }
  6658. $orderSummary[] = ['label' => $lab, 'value' => $val];
  6659. }
  6660. $orderSummary[] = [
  6661. 'label' => '是否合格',
  6662. 'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
  6663. ];
  6664. $orderSummaryGrid = [];
  6665. $n = count($orderSummary);
  6666. for ($i = 0; $i < $n; $i += 2) {
  6667. $left = $orderSummary[$i];
  6668. $hasRight = ($i + 1) < $n;
  6669. $orderSummaryGrid[] = [
  6670. 'l1' => $left['label'],
  6671. 'v1' => $left['value'],
  6672. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  6673. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  6674. ];
  6675. }
  6676. return [
  6677. 'steps' => $steps,
  6678. 'orderSummary' => $orderSummary,
  6679. 'orderSummaryGrid' => $orderSummaryGrid,
  6680. 'inbound_result' => $inboundResult,
  6681. 'inbound_score_time'=> $inboundScoreTime,
  6682. 'detailRows' => $details,
  6683. ];
  6684. }
  6685. /**
  6686. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  6687. *
  6688. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  6689. */
  6690. protected function prepareProcuremenDetailsView(string $ids): array
  6691. {
  6692. $main = [];
  6693. try {
  6694. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  6695. $main = is_array($one) ? $one : [];
  6696. } catch (\Throwable $e) {
  6697. $main = [];
  6698. }
  6699. $details = [];
  6700. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  6701. if ($mergeRows === []) {
  6702. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  6703. if ($mergeRows === [] && $main !== []) {
  6704. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  6705. }
  6706. }
  6707. $detailSidList = [];
  6708. $anchorSid = (int)$ids;
  6709. if ($anchorSid !== 0) {
  6710. $detailSidList[$anchorSid] = true;
  6711. }
  6712. foreach ($mergeRows as $mr) {
  6713. if (!is_array($mr)) {
  6714. continue;
  6715. }
  6716. $sid = $this->extractScydgyRowId($mr);
  6717. if ($sid !== 0) {
  6718. $detailSidList[$sid] = true;
  6719. }
  6720. }
  6721. try {
  6722. if ($detailSidList !== []) {
  6723. $details = Db::table('purchase_order_detail')
  6724. ->where('scydgy_id', 'in', array_keys($detailSidList))
  6725. ->order('id', 'asc')
  6726. ->select();
  6727. }
  6728. } catch (\Throwable $e) {
  6729. $details = [];
  6730. }
  6731. if (!is_array($details)) {
  6732. $details = [];
  6733. }
  6734. foreach ($details as &$r) {
  6735. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  6736. $r['id'] = $r['ID'];
  6737. }
  6738. if (isset($r['createtime'])) {
  6739. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  6740. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  6741. } else {
  6742. $r['createtime_text'] = (string)$r['createtime'];
  6743. }
  6744. } else {
  6745. $r['createtime_text'] = '';
  6746. }
  6747. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  6748. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  6749. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  6750. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  6751. if (is_array($r)) {
  6752. $r = $this->maskSupplierContactFields($r);
  6753. }
  6754. }
  6755. unset($r);
  6756. $activeDetails = [];
  6757. foreach ($details as $r) {
  6758. if (is_array($r) && empty($r['is_void'])) {
  6759. $activeDetails[] = $r;
  6760. }
  6761. }
  6762. $operLogs = [];
  6763. try {
  6764. $operSidList = array_keys($detailSidList);
  6765. if ($operSidList === [] && (int)$ids !== 0) {
  6766. $operSidList = [(int)$ids];
  6767. }
  6768. if ($operSidList !== []) {
  6769. $operLogs = Db::table('purchase_order_oper_log')
  6770. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  6771. ->order('id', 'asc')
  6772. ->select();
  6773. }
  6774. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  6775. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  6776. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  6777. if ($poId > 0) {
  6778. $operLogs = Db::table('purchase_order_oper_log')
  6779. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  6780. ->order('id', 'asc')
  6781. ->select();
  6782. }
  6783. }
  6784. } catch (\Throwable $e) {
  6785. $operLogs = [];
  6786. }
  6787. if (!is_array($operLogs)) {
  6788. $operLogs = [];
  6789. }
  6790. $operLogsRaw = $operLogs;
  6791. $processNameBySid = [];
  6792. foreach ($mergeRows as $mr) {
  6793. if (!is_array($mr)) {
  6794. continue;
  6795. }
  6796. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  6797. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  6798. if ($psid !== 0 && $gymc !== '') {
  6799. $processNameBySid[$psid] = $gymc;
  6800. }
  6801. }
  6802. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  6803. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
  6804. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  6805. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  6806. if ($ccydh === '') {
  6807. foreach ($details as $r) {
  6808. if (!is_array($r)) {
  6809. continue;
  6810. }
  6811. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  6812. if ($ccydh !== '') {
  6813. break;
  6814. }
  6815. }
  6816. }
  6817. $this->view->assign('ccydh', $ccydh);
  6818. $this->view->assign('steps', $bundle['steps']);
  6819. $this->view->assign('orderSummary', $bundle['orderSummary']);
  6820. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  6821. $this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
  6822. $this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
  6823. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  6824. $this->view->assign('processCount', count($mergeRows));
  6825. $orderBatchNo = $this->resolveProcuremenOrderBatchNo($main);
  6826. if ($orderBatchNo === '' && $detailSidList !== []) {
  6827. try {
  6828. $poBn = Db::table('purchase_order')
  6829. ->where('scydgy_id', 'in', array_keys($detailSidList))
  6830. ->whereRaw("TRIM(IFNULL(`order_batch_no`,'')) <> ''")
  6831. ->order('id', 'desc')
  6832. ->find();
  6833. if (is_array($poBn)) {
  6834. $orderBatchNo = $this->resolveProcuremenOrderBatchNo($poBn);
  6835. }
  6836. } catch (\Throwable $e) {
  6837. $orderBatchNo = '';
  6838. }
  6839. }
  6840. $this->view->assign('orderBatchNo', $orderBatchNo);
  6841. $this->view->assign('detailRows', $details);
  6842. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  6843. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  6844. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  6845. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  6846. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  6847. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  6848. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  6849. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  6850. $this->view->assign('operLogs', $operLogs);
  6851. $sg = $quoteView['supplier_groups'] ?? [];
  6852. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
  6853. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  6854. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
  6855. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
  6856. return [
  6857. 'ok' => $main !== [] || $details !== [],
  6858. 'ccydh' => $ccydh,
  6859. 'steps' => $bundle['steps'],
  6860. ];
  6861. }
  6862. /**
  6863. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  6864. */
  6865. public function details()
  6866. {
  6867. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6868. if (is_array($ids)) {
  6869. $ids = isset($ids[0]) ? $ids[0] : '';
  6870. }
  6871. $ids = trim((string)$ids);
  6872. if ($ids === '') {
  6873. $this->error(__('Invalid parameters'));
  6874. }
  6875. $this->assertManualOrderDetailsViewable((int)$ids);
  6876. // 已完结:打开详情时按最新进度/操作记录重存存证 PDF(含质量/交货评分)
  6877. $sid = (int)$ids;
  6878. if ($this->isValidScydgyRowId($sid)) {
  6879. try {
  6880. $poCheck = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  6881. if (is_array($poCheck) && ProcuremenStatus::isPoCompleted($poCheck['status'] ?? '')) {
  6882. $this->refreshCompletedOrderArchivePdf($sid, true);
  6883. }
  6884. } catch (\Throwable $e) {
  6885. Log::write('详情页刷新完结存证PDF失败 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'notice');
  6886. }
  6887. }
  6888. $this->prepareProcuremenDetailsView($ids);
  6889. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  6890. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  6891. $this->view->engine->layout(false);
  6892. try {
  6893. return $this->view->fetch('procuremen/details_dialog_shell');
  6894. } finally {
  6895. if ($restoreLayout) {
  6896. $this->view->engine->layout($restoreLayout);
  6897. }
  6898. }
  6899. }
  6900. /**
  6901. * 已完结订单重生成存证 PDF(与详情页一致,含质量/交货评分与「已完结」节点)
  6902. *
  6903. * @param bool $requireCompleted true 时仅已完结才重生成;false 强制按当前详情重存
  6904. * @return string 本地 web 路径或 OSS URL,失败为空串
  6905. */
  6906. protected function refreshCompletedOrderArchivePdf(int $scydgyId, bool $requireCompleted = true): string
  6907. {
  6908. if (!$this->isValidScydgyRowId($scydgyId)) {
  6909. return '';
  6910. }
  6911. try {
  6912. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6913. } catch (\Throwable $e) {
  6914. $po = null;
  6915. }
  6916. if (!is_array($po) || $po === []) {
  6917. return '';
  6918. }
  6919. if ($requireCompleted && !ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6920. return trim((string)($po['pdf_url'] ?? ''));
  6921. }
  6922. $poId = (int)($po['id'] ?? 0);
  6923. return $this->savePurchaseConfirmDetailPdf($scydgyId, $poId);
  6924. }
  6925. /**
  6926. * CLI / 手机端评分完结后调用:无后台登录态重生成存证 PDF
  6927. */
  6928. public static function regenerateArchivePdfWithoutAuth(int $scydgyId, bool $requireCompleted = true): string
  6929. {
  6930. if ((int)$scydgyId === 0) {
  6931. return '';
  6932. }
  6933. try {
  6934. $ctl = new class extends Procuremen {
  6935. public function _initialize()
  6936. {
  6937. $this->request = \think\Request::instance();
  6938. $tpl = \think\Config::get('template');
  6939. if (!is_array($tpl)) {
  6940. $tpl = [];
  6941. }
  6942. // CLI / 跨模块调用时无 admin 视图目录
  6943. $tpl['view_path'] = APP_PATH . 'admin' . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR;
  6944. $this->view = new \think\View($tpl, \think\Config::get('view_replace_str'));
  6945. $this->model = new \app\admin\model\Procuremen();
  6946. try {
  6947. ProcuremenSchema::ensureAll();
  6948. } catch (\Throwable $e) {
  6949. }
  6950. }
  6951. public function runRegen(int $sid, bool $requireCompleted): string
  6952. {
  6953. return $this->refreshCompletedOrderArchivePdf($sid, $requireCompleted);
  6954. }
  6955. };
  6956. return $ctl->runRegen($scydgyId, $requireCompleted);
  6957. } catch (\Throwable $e) {
  6958. Log::write('regenerateArchivePdfWithoutAuth 失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'error');
  6959. return '';
  6960. }
  6961. }
  6962. /**
  6963. * 解析合并下发工序行(可跨订单,且均未协助)
  6964. *
  6965. * @return array<int, array<string, mixed>>
  6966. */
  6967. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  6968. {
  6969. $primary = json_decode($rowJson, true);
  6970. if (!is_array($primary)) {
  6971. $this->error(__('Invalid parameters'));
  6972. }
  6973. $merge = json_decode($mergeRowsJson, true);
  6974. if (!is_array($merge) || $merge === []) {
  6975. $merge = [$primary];
  6976. }
  6977. $seen = [];
  6978. $out = [];
  6979. foreach ($merge as $r) {
  6980. if (!is_array($r)) {
  6981. continue;
  6982. }
  6983. $id = $this->extractScydgyRowId($r);
  6984. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  6985. continue;
  6986. }
  6987. $seen[$id] = true;
  6988. $out[] = $r;
  6989. }
  6990. if ($out === []) {
  6991. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  6992. }
  6993. // 允许多订单同批下发:不再校验订单号一致
  6994. $ids = [];
  6995. foreach ($out as $r) {
  6996. $id = $this->extractScydgyRowId($r);
  6997. if ($this->isValidScydgyRowId($id)) {
  6998. $ids[$id] = true;
  6999. }
  7000. }
  7001. $poBySid = [];
  7002. $detCntBySid = [];
  7003. if ($ids !== []) {
  7004. $idList = array_keys($ids);
  7005. try {
  7006. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  7007. if (is_array($poList)) {
  7008. foreach ($poList as $po) {
  7009. if (!is_array($po)) {
  7010. continue;
  7011. }
  7012. $sid = (int)($po['scydgy_id'] ?? 0);
  7013. if ($this->isValidScydgyRowId($sid)) {
  7014. $poBySid[$sid] = $po;
  7015. }
  7016. }
  7017. }
  7018. } catch (\Throwable $e) {
  7019. }
  7020. try {
  7021. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  7022. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  7023. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  7024. if (is_array($detRows)) {
  7025. foreach ($detRows as $dr) {
  7026. if (!is_array($dr)) {
  7027. continue;
  7028. }
  7029. $sid = (int)($dr['scydgy_id'] ?? 0);
  7030. if ($this->isValidScydgyRowId($sid)) {
  7031. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  7032. }
  7033. }
  7034. }
  7035. } catch (\Throwable $e) {
  7036. }
  7037. }
  7038. foreach ($out as $r) {
  7039. $id = $this->extractScydgyRowId($r);
  7040. if (!$this->isValidScydgyRowId($id)) {
  7041. continue;
  7042. }
  7043. $po = $poBySid[$id] ?? null;
  7044. if (!is_array($po)) {
  7045. continue;
  7046. }
  7047. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  7048. $gymc = trim((string)($r['CGYMC'] ?? ''));
  7049. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  7050. }
  7051. $detCnt = (int)($detCntBySid[$id] ?? 0);
  7052. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  7053. $gymc = trim((string)($r['CGYMC'] ?? ''));
  7054. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  7055. }
  7056. }
  7057. return $out;
  7058. }
  7059. /**
  7060. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  7061. */
  7062. protected function maskSupplierContactFields(array $item): array
  7063. {
  7064. if (array_key_exists('email', $item)) {
  7065. $item['email'] = mask_email((string)$item['email']);
  7066. }
  7067. if (array_key_exists('phone', $item)) {
  7068. $item['phone'] = mask_phone((string)$item['phone']);
  7069. }
  7070. return $item;
  7071. }
  7072. /**
  7073. * @param array<int, array<string, mixed>> $list
  7074. * @return array<int, array<string, mixed>>
  7075. */
  7076. protected function maskSupplierContactList(array $list): array
  7077. {
  7078. $out = [];
  7079. foreach ($list as $item) {
  7080. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  7081. }
  7082. return $out;
  7083. }
  7084. /**
  7085. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  7086. *
  7087. * @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
  7088. * @return array<string, string>|null
  7089. */
  7090. protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
  7091. {
  7092. if (!is_array($row)) {
  7093. return null;
  7094. }
  7095. $norm = [];
  7096. foreach ($row as $k => $v) {
  7097. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  7098. }
  7099. $row = $norm;
  7100. $st = $row['status'] ?? '';
  7101. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  7102. return null;
  7103. }
  7104. $companyName = '';
  7105. foreach (['company_name', 'name'] as $nk) {
  7106. if (!empty($row[$nk])) {
  7107. $companyName = trim((string)$row[$nk]);
  7108. break;
  7109. }
  7110. }
  7111. if ($companyName === '') {
  7112. return null;
  7113. }
  7114. $username = '';
  7115. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  7116. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  7117. $username = trim((string)$row[$uk]);
  7118. break;
  7119. }
  7120. }
  7121. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  7122. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  7123. if ($phone === '' && isset($row['account'])) {
  7124. $phone = trim((string)$row['account']);
  7125. }
  7126. if ($phone === '' && isset($row['mobile'])) {
  7127. $phone = trim((string)$row['mobile']);
  7128. }
  7129. if ($requireContactChannels && $email === '' && $phone === '') {
  7130. return null;
  7131. }
  7132. $category = '';
  7133. foreach (['company_type', 'category', 'type_name'] as $ck) {
  7134. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  7135. $category = trim((string)$row[$ck]);
  7136. break;
  7137. }
  7138. }
  7139. return [
  7140. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  7141. 'name' => $companyName,
  7142. 'company_name' => $companyName,
  7143. 'username' => $username,
  7144. 'email' => $email,
  7145. 'phone' => $phone,
  7146. 'category' => $category,
  7147. 'company_type' => $category,
  7148. 'can_select' => ($email !== '' && $phone !== '') ? 1 : 0,
  7149. ];
  7150. }
  7151. /**
  7152. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  7153. */
  7154. protected function resolveCustomerContactById(string $id): ?array
  7155. {
  7156. $id = trim($id);
  7157. if ($id === '' || !ctype_digit($id)) {
  7158. return null;
  7159. }
  7160. try {
  7161. $row = Db::table('customer')->where('id', (int)$id)->find();
  7162. } catch (\Throwable $e) {
  7163. return null;
  7164. }
  7165. return $this->buildCustomerContactPayloadFromRow($row);
  7166. }
  7167. /**
  7168. * 按供应商名称解析联系信息(兼容旧提交数据)
  7169. *
  7170. * @param bool $requireContactChannels true 时须有邮箱或手机
  7171. */
  7172. protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
  7173. {
  7174. $name = trim($name);
  7175. if ($name === '') {
  7176. return null;
  7177. }
  7178. try {
  7179. // customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
  7180. $row = Db::table('customer')
  7181. ->where('company_name', $name)
  7182. ->order('id', 'desc')
  7183. ->find();
  7184. } catch (\Throwable $e) {
  7185. return null;
  7186. }
  7187. return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
  7188. }
  7189. /**
  7190. * 规范化下发/确认时勾选的供应商
  7191. *
  7192. * @param array<int, mixed> $companies
  7193. * @return array<int, array<string, string>>
  7194. */
  7195. protected function normalizePickCompanies(array $companies): array
  7196. {
  7197. $out = [];
  7198. foreach ($companies as $c) {
  7199. if (!is_array($c)) {
  7200. continue;
  7201. }
  7202. $resolved = null;
  7203. $cid = trim((string)($c['id'] ?? ''));
  7204. if ($cid !== '') {
  7205. $resolved = $this->resolveCustomerContactById($cid);
  7206. }
  7207. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  7208. if ($resolved === null && $name !== '') {
  7209. $resolved = $this->resolveCustomerContactByCompanyName($name);
  7210. }
  7211. if ($resolved === null) {
  7212. continue;
  7213. }
  7214. $email = trim((string)($resolved['email'] ?? ''));
  7215. $phone = trim((string)($resolved['phone'] ?? ''));
  7216. // 下发须同时有邮箱和手机号(与初选弹窗可选规则一致)
  7217. if ($email === '' || $phone === '') {
  7218. continue;
  7219. }
  7220. $out[] = $resolved;
  7221. }
  7222. return $out;
  7223. }
  7224. /**
  7225. * 同一次下发批次的时间(优先 pick_time,空则 createtime)
  7226. */
  7227. protected function procuremenIssueBatchTime(array $row): string
  7228. {
  7229. $t = $this->procuremenRowListSortTime($row, 'pick_time');
  7230. if ($t !== '') {
  7231. return $t;
  7232. }
  7233. $t = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  7234. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  7235. return $t;
  7236. }
  7237. return '';
  7238. }
  7239. /**
  7240. * 读取下发批次号(兼容旧字段 issue_batch_no)
  7241. *
  7242. * @param array<string, mixed> $row
  7243. */
  7244. protected function resolveProcuremenOrderBatchNo(array $row): string
  7245. {
  7246. foreach (['order_batch_no', 'issue_batch_no'] as $k) {
  7247. $v = trim((string)($row[$k] ?? ''));
  7248. if ($v !== '') {
  7249. return $v;
  7250. }
  7251. }
  7252. return '';
  7253. }
  7254. /**
  7255. * 从订单 bundle 取下发批次号
  7256. *
  7257. * @param array{order_batch_no?:mixed,pos?:array} $bundle
  7258. */
  7259. protected function resolveBundleOrderBatchNo(array $bundle): string
  7260. {
  7261. $direct = trim((string)($bundle['order_batch_no'] ?? ''));
  7262. if ($direct !== '') {
  7263. return $direct;
  7264. }
  7265. foreach ($bundle['pos'] ?? [] as $po) {
  7266. if (!is_array($po)) {
  7267. continue;
  7268. }
  7269. $bn = $this->resolveProcuremenOrderBatchNo($po);
  7270. if ($bn !== '') {
  7271. return $bn;
  7272. }
  7273. }
  7274. return '';
  7275. }
  7276. /**
  7277. * @param int[] $sidList
  7278. * @return array<int, string> scydgy_id => MBZ
  7279. */
  7280. protected function loadScydgyMbzByIds(array $sidList): array
  7281. {
  7282. $ids = [];
  7283. foreach ($sidList as $sid) {
  7284. $sid = (int)$sid;
  7285. if ($this->isValidScydgyRowId($sid)) {
  7286. $ids[$sid] = true;
  7287. }
  7288. }
  7289. if ($ids === []) {
  7290. return [];
  7291. }
  7292. try {
  7293. $map = Db::table('scydgy')->where('ID', 'in', array_keys($ids))->column('MBZ', 'ID');
  7294. } catch (\Throwable $e) {
  7295. return [];
  7296. }
  7297. return is_array($map) ? $map : [];
  7298. }
  7299. /**
  7300. * purchase_order / 列表行 MBZ 为空时,回退 ERP 工序表 scydgy.MBZ
  7301. *
  7302. * @param array<int, array<string, mixed>> $rows
  7303. */
  7304. protected function enrichProcuremenRowsMbz(array &$rows): void
  7305. {
  7306. if ($rows === []) {
  7307. return;
  7308. }
  7309. $need = [];
  7310. foreach ($rows as $r) {
  7311. if (!is_array($r)) {
  7312. continue;
  7313. }
  7314. if (trim((string)($r['MBZ'] ?? $r['mbz'] ?? '')) !== '') {
  7315. continue;
  7316. }
  7317. $sid = $this->extractScydgyRowId($r);
  7318. if ($this->isValidScydgyRowId($sid)) {
  7319. $need[$sid] = true;
  7320. }
  7321. }
  7322. if ($need === []) {
  7323. return;
  7324. }
  7325. $mbzMap = $this->loadScydgyMbzByIds(array_keys($need));
  7326. if ($mbzMap === []) {
  7327. return;
  7328. }
  7329. foreach ($rows as &$r) {
  7330. if (!is_array($r)) {
  7331. continue;
  7332. }
  7333. if (trim((string)($r['MBZ'] ?? $r['mbz'] ?? '')) !== '') {
  7334. continue;
  7335. }
  7336. $sid = $this->extractScydgyRowId($r);
  7337. if (!$this->isValidScydgyRowId($sid) || !isset($mbzMap[$sid])) {
  7338. continue;
  7339. }
  7340. $mbz = trim((string)$mbzMap[$sid]);
  7341. if ($mbz !== '') {
  7342. $r['MBZ'] = $mbz;
  7343. }
  7344. }
  7345. unset($r);
  7346. }
  7347. /**
  7348. * 列表/弹窗合并键:优先正式批次号 order_batch_no;
  7349. * 旧数据无批次号时回退为「同一订单号 + 同一次下发时间」。
  7350. */
  7351. protected function procuremenIssueBatchGroupKey(array $row): string
  7352. {
  7353. $batchNo = $this->resolveProcuremenOrderBatchNo($row);
  7354. if ($batchNo !== '') {
  7355. return 'bn:' . $batchNo;
  7356. }
  7357. $dh = trim((string)($row['CCYDH'] ?? ''));
  7358. $sid = (int)($row['scydgy_id'] ?? $row['ID'] ?? $row['id'] ?? 0);
  7359. if ($dh === '') {
  7360. return '_id_' . $sid;
  7361. }
  7362. $batch = $this->procuremenIssueBatchTime($row);
  7363. return $batch !== '' ? ($dh . '|' . $batch) : ($dh . '|sid:' . $sid);
  7364. }
  7365. /**
  7366. * 是否同一次下发(同批次号,或旧数据同订单号且下发时间一致)
  7367. */
  7368. protected function isSameProcuremenIssueBatch(array $anchor, array $po): bool
  7369. {
  7370. return $this->procuremenIssueBatchGroupKey($anchor) === $this->procuremenIssueBatchGroupKey($po);
  7371. }
  7372. /**
  7373. * @param array<int, mixed> $pos
  7374. * @return array<int, array<string, mixed>>
  7375. */
  7376. protected function filterPurchaseOrdersSameIssueBatch(array $pos, array $anchor): array
  7377. {
  7378. $out = [];
  7379. foreach ($pos as $po) {
  7380. if (is_array($po) && $this->isSameProcuremenIssueBatch($anchor, $po)) {
  7381. $out[] = $po;
  7382. }
  7383. }
  7384. return $out !== [] ? $out : [$anchor];
  7385. }
  7386. /**
  7387. * 确认供应商列表:同一订单号且同一次下发才合并为一行
  7388. *
  7389. * @param array<int, array<string, mixed>> $pool
  7390. * @return array<int, array<string, mixed>>
  7391. */
  7392. protected function collapseProcuremenPoolByOrder(array $pool): array
  7393. {
  7394. if ($pool === []) {
  7395. return [];
  7396. }
  7397. $groups = [];
  7398. foreach ($pool as $row) {
  7399. if (!is_array($row)) {
  7400. continue;
  7401. }
  7402. $key = $this->procuremenIssueBatchGroupKey($row);
  7403. if (!isset($groups[$key])) {
  7404. $groups[$key] = [];
  7405. }
  7406. $groups[$key][] = $row;
  7407. }
  7408. $out = [];
  7409. foreach ($groups as $ccydh => $rows) {
  7410. if ($rows === []) {
  7411. continue;
  7412. }
  7413. // 与确认/审批弹窗「本单工序」一致:按订单号 → 印件名称 → 工序名称 → 工序ID
  7414. usort($rows, function ($a, $b) {
  7415. $oa = trim((string)($a['CCYDH'] ?? ''));
  7416. $ob = trim((string)($b['CCYDH'] ?? ''));
  7417. if ($oa !== $ob) {
  7418. return strcmp($oa, $ob);
  7419. }
  7420. $na = trim((string)($a['CYJMC'] ?? ''));
  7421. $nb = trim((string)($b['CYJMC'] ?? ''));
  7422. if ($na !== $nb) {
  7423. return strcmp($na, $nb);
  7424. }
  7425. $ga = trim((string)($a['CGYMC'] ?? ''));
  7426. $gb = trim((string)($b['CGYMC'] ?? ''));
  7427. if ($ga !== $gb) {
  7428. return strcmp($ga, $gb);
  7429. }
  7430. $ida = (int)($a['ID'] ?? $a['scydgy_id'] ?? 0);
  7431. $idb = (int)($b['ID'] ?? $b['scydgy_id'] ?? 0);
  7432. return $ida <=> $idb;
  7433. });
  7434. $head = $rows[0];
  7435. $gymcList = [];
  7436. foreach ($rows as $r) {
  7437. $g = trim((string)($r['CGYMC'] ?? ''));
  7438. if ($g !== '' && !in_array($g, $gymcList, true)) {
  7439. $gymcList[] = $g;
  7440. }
  7441. }
  7442. $merged = $head;
  7443. $orderDhList = [];
  7444. $nameList = [];
  7445. foreach ($rows as $r) {
  7446. if (!is_array($r)) {
  7447. continue;
  7448. }
  7449. $odh = trim((string)($r['CCYDH'] ?? ''));
  7450. if ($odh !== '' && !in_array($odh, $orderDhList, true)) {
  7451. $orderDhList[] = $odh;
  7452. }
  7453. $onm = trim((string)($r['CYJMC'] ?? ''));
  7454. if ($onm !== '' && !in_array($onm, $nameList, true)) {
  7455. $nameList[] = $onm;
  7456. }
  7457. }
  7458. $orderDh = $orderDhList !== [] ? implode('、', $orderDhList) : trim((string)($head['CCYDH'] ?? ''));
  7459. $merged['CCYDH'] = $orderDh;
  7460. $merged['order_key'] = $orderDh;
  7461. if ($nameList !== []) {
  7462. $merged['CYJMC'] = implode('、', $nameList);
  7463. }
  7464. $merged['order_batch_no'] = $this->resolveProcuremenOrderBatchNo($head);
  7465. $merged['process_count'] = count($rows);
  7466. $merged['_order_merge_rows'] = $rows;
  7467. $qtyList = [];
  7468. $priceList = [];
  7469. foreach ($rows as $r) {
  7470. if (!is_array($r)) {
  7471. continue;
  7472. }
  7473. $qtyList[] = $this->resolveProcuremenThisQuantity($r);
  7474. $priceList[] = $this->resolveProcuremenCeilingPrice($r);
  7475. }
  7476. if (count($rows) > 1) {
  7477. $merged['CGYMC'] = implode('、', $gymcList);
  7478. // 多工序:数量/限价按有值项顿号间隔(空值不占位)
  7479. $merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  7480. $merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  7481. } else {
  7482. $merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
  7483. $merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
  7484. }
  7485. // 已选供应商:取合并行中首个非空 pick_company_name
  7486. $pickedName = '';
  7487. $manualPick = ((int)($head['manual_pick'] ?? 0) === 1) ? 1 : 0;
  7488. foreach ($rows as $r) {
  7489. if (!is_array($r)) {
  7490. continue;
  7491. }
  7492. if ((int)($r['manual_pick'] ?? 0) === 1) {
  7493. $manualPick = 1;
  7494. }
  7495. $pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
  7496. if ($pn !== '' && $pickedName === '') {
  7497. $pickedName = $pn;
  7498. }
  7499. }
  7500. $merged['manual_pick'] = $manualPick;
  7501. if ($pickedName !== '') {
  7502. $merged['pick_company_name'] = $pickedName;
  7503. $merged['picked_supplier_name'] = $pickedName;
  7504. }
  7505. $mergedPickTime = '';
  7506. foreach ($rows as $r) {
  7507. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  7508. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  7509. $mergedPickTime = $t;
  7510. }
  7511. }
  7512. if ($mergedPickTime !== '') {
  7513. $merged['pick_time'] = $mergedPickTime;
  7514. }
  7515. $out[] = $merged;
  7516. }
  7517. usort($out, function ($a, $b) {
  7518. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  7519. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  7520. if ($ta === $tb) {
  7521. $ida = (int)($a['purchase_order_id'] ?? 0);
  7522. $idb = (int)($b['purchase_order_id'] ?? 0);
  7523. if ($ida !== $idb) {
  7524. return $idb <=> $ida;
  7525. }
  7526. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  7527. }
  7528. if ($ta === '') {
  7529. return 1;
  7530. }
  7531. if ($tb === '') {
  7532. return -1;
  7533. }
  7534. return strcmp($tb, $ta);
  7535. });
  7536. return $out;
  7537. }
  7538. /**
  7539. * 待确认供应商:同一次下发批次的工序(优先 order_batch_no;旧数据回退同订单+同下发时间)
  7540. *
  7541. * @return array{ccydh:string, order_batch_no?:string, pos:array<int,array>, merge_rows:array<int,array>}
  7542. */
  7543. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  7544. {
  7545. $scydgyId = trim($scydgyId);
  7546. $empty = ['ccydh' => '', 'order_batch_no' => '', 'pos' => [], 'merge_rows' => []];
  7547. if ($scydgyId === '') {
  7548. return $empty;
  7549. }
  7550. try {
  7551. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7552. } catch (\Throwable $e) {
  7553. $anchor = null;
  7554. }
  7555. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  7556. return $empty;
  7557. }
  7558. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7559. $batchNo = $this->resolveProcuremenOrderBatchNo($anchor);
  7560. try {
  7561. if ($batchNo !== '') {
  7562. $pos = Db::table('purchase_order')
  7563. ->where('order_batch_no', $batchNo)
  7564. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())
  7565. ->order('scydgy_id', 'asc')
  7566. ->select();
  7567. } elseif ($ccydh !== '') {
  7568. $pos = Db::table('purchase_order')
  7569. ->where('CCYDH', $ccydh)
  7570. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())
  7571. ->order('scydgy_id', 'asc')
  7572. ->select();
  7573. } else {
  7574. $pos = [$anchor];
  7575. }
  7576. } catch (\Throwable $e) {
  7577. $pos = [$anchor];
  7578. }
  7579. if (!is_array($pos) || $pos === []) {
  7580. $pos = [$anchor];
  7581. }
  7582. $pos = $this->filterPurchaseOrdersSameIssueBatch($pos, $anchor);
  7583. return [
  7584. 'ccydh' => $ccydh,
  7585. 'order_batch_no' => $batchNo,
  7586. 'pos' => $pos,
  7587. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  7588. ];
  7589. }
  7590. /**
  7591. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  7592. */
  7593. protected function purchaseOrderRowInConfirmStage(array $po): bool
  7594. {
  7595. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  7596. return false;
  7597. }
  7598. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  7599. return false;
  7600. }
  7601. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  7602. return true;
  7603. }
  7604. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  7605. $sid = (int)($po['scydgy_id'] ?? 0);
  7606. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  7607. }
  7608. return false;
  7609. }
  7610. /**
  7611. * 采购确认:同一次下发批次的待审批工序(优先 order_batch_no)
  7612. *
  7613. * @return array{ccydh:string, order_batch_no?:string, pos:array<int,array>, merge_rows:array<int,array>}
  7614. */
  7615. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  7616. {
  7617. $scydgyId = trim($scydgyId);
  7618. $empty = ['ccydh' => '', 'order_batch_no' => '', 'pos' => [], 'merge_rows' => []];
  7619. if ($scydgyId === '') {
  7620. return $empty;
  7621. }
  7622. try {
  7623. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7624. } catch (\Throwable $e) {
  7625. $anchor = null;
  7626. }
  7627. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  7628. return $empty;
  7629. }
  7630. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7631. $batchNo = $this->resolveProcuremenOrderBatchNo($anchor);
  7632. try {
  7633. if ($batchNo !== '') {
  7634. $posQuery = Db::table('purchase_order')->where('order_batch_no', $batchNo);
  7635. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  7636. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  7637. } elseif ($ccydh !== '') {
  7638. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  7639. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  7640. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  7641. } else {
  7642. $pos = [$anchor];
  7643. }
  7644. } catch (\Throwable $e) {
  7645. $pos = [$anchor];
  7646. }
  7647. if (!is_array($pos) || $pos === []) {
  7648. $pos = [$anchor];
  7649. }
  7650. $pos = array_values(array_filter($pos, function ($po) {
  7651. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  7652. }));
  7653. if ($pos === []) {
  7654. $pos = [$anchor];
  7655. }
  7656. $pos = $this->filterPurchaseOrdersSameIssueBatch($pos, $anchor);
  7657. return [
  7658. 'ccydh' => $ccydh,
  7659. 'order_batch_no' => $batchNo,
  7660. 'pos' => $pos,
  7661. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  7662. ];
  7663. }
  7664. /**
  7665. * @param array<int, array<string, mixed>> $purchaseOrders
  7666. * @return array<int, array<string, mixed>>
  7667. */
  7668. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  7669. {
  7670. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  7671. $byId = [];
  7672. foreach ($pool as $r) {
  7673. if (!is_array($r)) {
  7674. continue;
  7675. }
  7676. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  7677. if ($this->isValidScydgyRowId($sid)) {
  7678. $byId[$sid] = $r;
  7679. }
  7680. }
  7681. $out = [];
  7682. foreach ($purchaseOrders as $po) {
  7683. if (!is_array($po)) {
  7684. continue;
  7685. }
  7686. $sid = (int)($po['scydgy_id'] ?? 0);
  7687. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  7688. $out[] = $byId[$sid];
  7689. }
  7690. }
  7691. $this->enrichProcuremenRowsMbz($out);
  7692. return $out;
  7693. }
  7694. /**
  7695. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  7696. *
  7697. * @return array<int, array<string, mixed>>
  7698. */
  7699. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  7700. {
  7701. $scydgyId = trim($scydgyId);
  7702. if ($scydgyId === '') {
  7703. return [];
  7704. }
  7705. try {
  7706. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7707. } catch (\Throwable $e) {
  7708. $anchor = null;
  7709. }
  7710. if (!is_array($anchor)) {
  7711. return [];
  7712. }
  7713. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  7714. return [];
  7715. }
  7716. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7717. $batchNo = $this->resolveProcuremenOrderBatchNo($anchor);
  7718. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  7719. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  7720. try {
  7721. $q = Db::table('purchase_order');
  7722. if ($batchNo !== '') {
  7723. $q->where('order_batch_no', $batchNo);
  7724. } elseif ($ccydh !== '' && $isValidPick) {
  7725. $q->where('CCYDH', $ccydh)->where('pick_time', $pickTime);
  7726. } else {
  7727. $q->where('scydgy_id', $scydgyId);
  7728. }
  7729. $pos = $q->order('scydgy_id', 'asc')->select();
  7730. } catch (\Throwable $e) {
  7731. $pos = [$anchor];
  7732. }
  7733. if (!is_array($pos) || $pos === []) {
  7734. $pos = [$anchor];
  7735. }
  7736. $pos = array_values(array_filter($pos, function ($po) {
  7737. if (!is_array($po)) {
  7738. return false;
  7739. }
  7740. $mr = $po['mod_rq'] ?? null;
  7741. if ($mr === null || $mr === '') {
  7742. return true;
  7743. }
  7744. $mrs = trim((string)$mr);
  7745. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  7746. }));
  7747. if ($pos === []) {
  7748. $pos = [$anchor];
  7749. }
  7750. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  7751. if ($rows === []) {
  7752. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  7753. }
  7754. return $rows;
  7755. }
  7756. /**
  7757. * 工序/报价明细统一排序:订单号升序 → 印件名称 → 工序名称 → 工序行ID
  7758. * (与审核弹窗上方工序表一致)
  7759. *
  7760. * @param array<int, array<string, mixed>> $mergeRows
  7761. * @return array<int, array<string, mixed>>
  7762. */
  7763. protected function sortProcuremenMergeRowsByCcydh(array $mergeRows): array
  7764. {
  7765. $list = [];
  7766. foreach ($mergeRows as $r) {
  7767. if (is_array($r)) {
  7768. $list[] = $r;
  7769. }
  7770. }
  7771. usort($list, function ($a, $b) {
  7772. $oa = trim((string)($a['CCYDH'] ?? ''));
  7773. $ob = trim((string)($b['CCYDH'] ?? ''));
  7774. if ($oa !== $ob) {
  7775. return strcmp($oa, $ob);
  7776. }
  7777. $na = trim((string)($a['CYJMC'] ?? ''));
  7778. $nb = trim((string)($b['CYJMC'] ?? ''));
  7779. if ($na !== $nb) {
  7780. return strcmp($na, $nb);
  7781. }
  7782. $ga = trim((string)($a['CGYMC'] ?? ''));
  7783. $gb = trim((string)($b['CGYMC'] ?? ''));
  7784. if ($ga !== $gb) {
  7785. return strcmp($ga, $gb);
  7786. }
  7787. $ida = $this->extractScydgyRowId($a);
  7788. $idb = $this->extractScydgyRowId($b);
  7789. return $ida <=> $idb;
  7790. });
  7791. return $list;
  7792. }
  7793. /**
  7794. * 按工序表同序得到 scydgy_id 列表(供应商报价明细行顺序用)
  7795. *
  7796. * @param array<int, array<string, mixed>> $mergeRows
  7797. * @param int[] $extraSids 合并行未覆盖时追加
  7798. * @return int[]
  7799. */
  7800. protected function orderedScydgyIdsLikeProcessDisplay(array $mergeRows, array $extraSids = []): array
  7801. {
  7802. $out = [];
  7803. $seen = [];
  7804. foreach ($this->sortProcuremenMergeRowsByCcydh($mergeRows) as $r) {
  7805. $sid = $this->extractScydgyRowId($r);
  7806. if (!$this->isValidScydgyRowId($sid) || isset($seen[$sid])) {
  7807. continue;
  7808. }
  7809. $seen[$sid] = true;
  7810. $out[] = $sid;
  7811. }
  7812. foreach ($extraSids as $sid) {
  7813. $sid = (int)$sid;
  7814. if (!$this->isValidScydgyRowId($sid) || isset($seen[$sid])) {
  7815. continue;
  7816. }
  7817. $seen[$sid] = true;
  7818. $out[] = $sid;
  7819. }
  7820. return $out;
  7821. }
  7822. /**
  7823. * 审核弹窗工序表展示行(与下发弹窗列一致;按订单号排序,同订单合并订单号/印件名称单元格)
  7824. *
  7825. * @param array<int, array<string, mixed>> $mergeRows
  7826. * @return array<int, array<string, mixed>>
  7827. */
  7828. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  7829. {
  7830. $list = $this->sortProcuremenMergeRowsByCcydh($mergeRows);
  7831. $n = count($list);
  7832. // 连续同订单号+印件名称:合并单元格 rowspan
  7833. $groupSpan = array_fill(0, $n, 1);
  7834. $groupStart = array_fill(0, $n, true);
  7835. $i = 0;
  7836. while ($i < $n) {
  7837. $key = trim((string)($list[$i]['CCYDH'] ?? '')) . "\0" . trim((string)($list[$i]['CYJMC'] ?? ''));
  7838. $j = $i + 1;
  7839. while ($j < $n) {
  7840. $key2 = trim((string)($list[$j]['CCYDH'] ?? '')) . "\0" . trim((string)($list[$j]['CYJMC'] ?? ''));
  7841. if ($key === '' || $key2 !== $key) {
  7842. break;
  7843. }
  7844. $j++;
  7845. }
  7846. $span = $j - $i;
  7847. $groupSpan[$i] = $span;
  7848. for ($k = $i + 1; $k < $j; $k++) {
  7849. $groupStart[$k] = false;
  7850. $groupSpan[$k] = 1;
  7851. }
  7852. $i = $j;
  7853. }
  7854. $out = [];
  7855. foreach ($list as $idx => $r) {
  7856. $qty = $this->resolveProcuremenThisQuantity($r);
  7857. $price = $this->resolveProcuremenCeilingPrice($r);
  7858. $sid = $this->extractScydgyRowId($r);
  7859. $out[] = [
  7860. 'seq' => $idx + 1,
  7861. 'scydgy_id' => $sid,
  7862. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  7863. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  7864. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  7865. 'CDW' => trim((string)($r['CDW'] ?? '')),
  7866. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  7867. 'NGZL' => $r['NGZL'] ?? '',
  7868. 'This_quantity' => $qty,
  7869. 'ceilingPrice' => $price,
  7870. 'CDF' => trim((string)($r['CDF'] ?? '')),
  7871. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  7872. 'show_order_cells' => !empty($groupStart[$idx]),
  7873. 'order_rowspan' => (int)($groupSpan[$idx] ?? 1),
  7874. ];
  7875. }
  7876. return $out;
  7877. }
  7878. /**
  7879. * 解析金额/数量(去千分位等非数字字符)
  7880. */
  7881. protected function parseProcuremenMoneyNumber($value): ?float
  7882. {
  7883. return ProcuremenFormat::moneyNumber($value);
  7884. }
  7885. protected function formatProcuremenMoneyDisplay(?float $amount): string
  7886. {
  7887. return ProcuremenFormat::moneyDisplay($amount);
  7888. }
  7889. /**
  7890. * 列表/详情展示:工作量为 0 时显示空
  7891. */
  7892. protected function formatProcuremenWorkloadDisplay($value): string
  7893. {
  7894. return ProcuremenFormat::workloadDisplay($value);
  7895. }
  7896. /**
  7897. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  7898. */
  7899. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  7900. {
  7901. foreach ($details as $d) {
  7902. if (!is_array($d)) {
  7903. continue;
  7904. }
  7905. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  7906. $cn = trim((string)($d['company_name'] ?? ''));
  7907. if ($cn !== '') {
  7908. return $cn;
  7909. }
  7910. }
  7911. }
  7912. return trim((string)($main['pick_company_name'] ?? ''));
  7913. }
  7914. /**
  7915. * 详情报价小计:单价 × 本工序本次数量
  7916. */
  7917. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  7918. {
  7919. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  7920. if ($unit === null) {
  7921. return null;
  7922. }
  7923. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  7924. if ($qty === null || $qty <= 0) {
  7925. return null;
  7926. }
  7927. return $unit * $qty;
  7928. }
  7929. /**
  7930. * 详情页:工序小计 + 供应商分组报价与总计
  7931. *
  7932. * @param array<int, array<string, mixed>> $mergeRows
  7933. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  7934. * @return array{
  7935. * process_rows: array,
  7936. * supplier_groups: array,
  7937. * order_total_text: string,
  7938. * order_total_has: bool,
  7939. * selected_company: string
  7940. * }
  7941. */
  7942. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  7943. {
  7944. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  7945. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  7946. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
  7947. || ((int)($main['manual_pick'] ?? 0) === 1);
  7948. $orderMbz = trim((string)($main['MBZ'] ?? $main['mbz'] ?? ''));
  7949. if ($orderMbz === '') {
  7950. $orderMbz = $this->resolveBundleOrderMbz(['pos' => [$main], 'merge_rows' => $mergeRows]);
  7951. }
  7952. $qtyBySid = [];
  7953. $ceilingBySid = [];
  7954. $gymcBySid = [];
  7955. $ccydhBySid = [];
  7956. foreach ($mergeRows as $mr) {
  7957. if (!is_array($mr)) {
  7958. continue;
  7959. }
  7960. $sid = $this->extractScydgyRowId($mr);
  7961. if (!$this->isValidScydgyRowId($sid)) {
  7962. continue;
  7963. }
  7964. $qtyBySid[$sid] = $this->resolveProcuremenThisQuantity($mr);
  7965. $ceilingBySid[$sid] = $this->resolveProcuremenCeilingPrice($mr);
  7966. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  7967. $dh = trim((string)($mr['CCYDH'] ?? ''));
  7968. if ($dh !== '') {
  7969. $ccydhBySid[$sid] = $dh;
  7970. }
  7971. }
  7972. // 与上方工序表一致:按订单号升序
  7973. $orderedSids = $this->orderedScydgyIdsLikeProcessDisplay($mergeRows);
  7974. $mainCcydh = trim((string)($main['CCYDH'] ?? $ccydh));
  7975. if ($mainCcydh !== '') {
  7976. foreach ($orderedSids as $sid) {
  7977. if (empty($ccydhBySid[$sid])) {
  7978. $ccydhBySid[$sid] = $mainCcydh;
  7979. }
  7980. }
  7981. }
  7982. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  7983. $detailByCompanySid = [];
  7984. foreach ($details as $d) {
  7985. if (!is_array($d)) {
  7986. continue;
  7987. }
  7988. $cn = trim((string)($d['company_name'] ?? ''));
  7989. $sid = (int)($d['scydgy_id'] ?? 0);
  7990. if ($cn === '' || $sid === 0) {
  7991. continue;
  7992. }
  7993. if (!isset($detailByCompanySid[$cn])) {
  7994. $detailByCompanySid[$cn] = [];
  7995. }
  7996. $detailByCompanySid[$cn][$sid] = $d;
  7997. }
  7998. $supplierGroups = [];
  7999. foreach ($detailByCompanySid as $cn => $bySid) {
  8000. $lines = [];
  8001. $groupTotal = 0.0;
  8002. $groupHas = false;
  8003. $groupVoid = true;
  8004. $usedSids = [];
  8005. $appendLine = function (int $sid, array $d) use (
  8006. &$lines,
  8007. &$groupTotal,
  8008. &$groupHas,
  8009. &$groupVoid,
  8010. $qtyBySid,
  8011. $ceilingBySid,
  8012. $gymcBySid,
  8013. $ccydhBySid,
  8014. $quoteVisible
  8015. ) {
  8016. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  8017. if (!$isVoid) {
  8018. $groupVoid = false;
  8019. }
  8020. $qtyStr = $qtyBySid[$sid] ?? '';
  8021. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  8022. $am = trim((string)($d['amount'] ?? ''));
  8023. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  8024. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  8025. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  8026. $sub = null;
  8027. if (!$isVoid && $amountNum !== null) {
  8028. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  8029. }
  8030. $ct = $this->resolveDetailSupplierOperTime($d);
  8031. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  8032. $leadFilled = ($leadDays !== null);
  8033. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  8034. $processName = $this->buildSupplierProcessNameFields(
  8035. (string)($ccydhBySid[$sid] ?? ''),
  8036. (string)($gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')))
  8037. );
  8038. $line = array_merge($processName, [
  8039. 'scydgy_id' => $sid,
  8040. 'This_quantity' => (string)$qtyStr,
  8041. 'ceilingPrice' => (string)($ceilingBySid[$sid] ?? ''),
  8042. 'amount' => $am,
  8043. 'unit_price_text' => $amountFilled
  8044. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  8045. : '未填写',
  8046. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  8047. 'delivery_ymd' => $deliveryYmd,
  8048. 'amount_filled' => $amountFilled,
  8049. 'delivery_filled' => $deliveryFilled,
  8050. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  8051. 'lead_days' => $leadFilled ? $leadDays : '',
  8052. 'lead_days_filled'=> $leadFilled,
  8053. 'lead_days_show' => $leadText,
  8054. 'lead_days_text' => $leadText,
  8055. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  8056. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  8057. 'is_void' => $isVoid,
  8058. 'oper_time_text' => $ct,
  8059. ]);
  8060. if (!$quoteVisible && !$isVoid) {
  8061. $this->maskSupplierQuoteLineBeforeDeadline($line);
  8062. } elseif ($sub !== null) {
  8063. $groupTotal += $sub;
  8064. $groupHas = true;
  8065. }
  8066. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  8067. };
  8068. foreach ($orderedSids as $sid) {
  8069. if (!isset($bySid[$sid])) {
  8070. continue;
  8071. }
  8072. $usedSids[$sid] = true;
  8073. $appendLine($sid, $bySid[$sid]);
  8074. }
  8075. foreach ($bySid as $sid => $d) {
  8076. if (isset($usedSids[$sid])) {
  8077. continue;
  8078. }
  8079. $appendLine((int)$sid, $d);
  8080. }
  8081. $firstDetail = null;
  8082. foreach ($bySid as $d) {
  8083. if (is_array($d)) {
  8084. $firstDetail = $d;
  8085. break;
  8086. }
  8087. }
  8088. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  8089. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  8090. if ($username === '' && $ph !== '') {
  8091. $username = $this->resolveCustomerContactName($ph, $cn);
  8092. }
  8093. $remark = '';
  8094. foreach ($bySid as $d) {
  8095. if (!is_array($d)) {
  8096. continue;
  8097. }
  8098. $rm = '';
  8099. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  8100. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  8101. $rm = trim((string)$d[$rk]);
  8102. break;
  8103. }
  8104. }
  8105. if ($rm !== '') {
  8106. $remark = $rm;
  8107. break;
  8108. }
  8109. }
  8110. $lineCount = count($lines);
  8111. $supplierGroup = [
  8112. 'company_name' => $cn,
  8113. 'username' => $username,
  8114. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  8115. 'phone' => $ph,
  8116. 'remark' => $remark,
  8117. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  8118. 'is_void' => $groupVoid,
  8119. 'lines' => $lines,
  8120. 'line_count' => $lineCount,
  8121. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  8122. 'has_total' => $lineCount > 0,
  8123. ];
  8124. $this->finalizeSupplierRemarkDisplay($supplierGroup, $orderMbz, $quoteVisible);
  8125. $supplierGroups[] = $supplierGroup;
  8126. }
  8127. usort($supplierGroups, function ($a, $b) {
  8128. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  8129. return ($a['is_void'] ?? false) ? 1 : -1;
  8130. }
  8131. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  8132. return ($a['is_selected'] ?? false) ? -1 : 1;
  8133. }
  8134. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  8135. });
  8136. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  8137. return [
  8138. 'process_rows' => $processRows,
  8139. 'supplier_groups' => $supplierGroups,
  8140. 'order_total_text' => '',
  8141. 'order_total_has' => false,
  8142. 'selected_company' => $selectedCompany,
  8143. ];
  8144. }
  8145. /**
  8146. * 短信用工序明细。
  8147. * 单订单:仅工序行(订单号/印件名称由模版 {ccydh}{cyjmc} 排版);
  8148. * 多订单同批:每个订单各自输出「订单号 + 印件名称 + 工序列表」,组间空行。
  8149. */
  8150. protected function buildProcessLinesPlain(array $mergeRows): string
  8151. {
  8152. $groups = [];
  8153. foreach ($mergeRows as $r) {
  8154. if (!is_array($r)) {
  8155. continue;
  8156. }
  8157. $dh = trim((string)($r['CCYDH'] ?? ''));
  8158. $key = $dh !== '' ? $dh : ('__sid_' . (int)($r['ID'] ?? $r['id'] ?? $r['scydgy_id'] ?? 0));
  8159. if (!isset($groups[$key])) {
  8160. $groups[$key] = [
  8161. 'ccydh' => $dh,
  8162. 'cyjmc' => trim((string)($r['CYJMC'] ?? '')),
  8163. 'rows' => [],
  8164. ];
  8165. } elseif ($groups[$key]['cyjmc'] === '') {
  8166. $groups[$key]['cyjmc'] = trim((string)($r['CYJMC'] ?? ''));
  8167. }
  8168. $groups[$key]['rows'][] = $r;
  8169. }
  8170. if ($groups === []) {
  8171. return '';
  8172. }
  8173. $multiOrder = count($groups) > 1;
  8174. $blocks = [];
  8175. foreach ($groups as $g) {
  8176. $lines = [];
  8177. if ($multiOrder) {
  8178. if ($g['ccydh'] !== '') {
  8179. $lines[] = '订单号:' . $g['ccydh'];
  8180. }
  8181. if ($g['cyjmc'] !== '') {
  8182. $lines[] = '印件名称:' . $g['cyjmc'];
  8183. }
  8184. }
  8185. foreach ($g['rows'] as $r) {
  8186. if (!is_array($r)) {
  8187. continue;
  8188. }
  8189. $gymc = trim((string)($r['CGYMC'] ?? ''));
  8190. if ($gymc === '') {
  8191. $gymc = '—';
  8192. }
  8193. $dw = trim((string)($r['CDW'] ?? ''));
  8194. // 下发通知展示「本次数量」(优先 This_quantity,空则回退 NGZL),与确认/审批弹窗一致
  8195. $qty = $this->resolveProcuremenThisQuantity($r);
  8196. $parts = ['工序名称:' . $gymc];
  8197. if ($dw !== '') {
  8198. $parts[] = '单位:' . $dw;
  8199. }
  8200. if ($qty !== '') {
  8201. $parts[] = '本次数量:' . $qty;
  8202. }
  8203. $lines[] = implode(' ', $parts);
  8204. }
  8205. if ($lines !== []) {
  8206. $blocks[] = implode("\n", $lines);
  8207. }
  8208. }
  8209. return implode("\n\n", $blocks);
  8210. }
  8211. /** 中文友好显示宽度(全角约 2,半角 1) */
  8212. protected function mbDisplayWidth(string $s): int
  8213. {
  8214. if ($s === '') {
  8215. return 0;
  8216. }
  8217. if (function_exists('mb_strwidth')) {
  8218. return (int)mb_strwidth($s, 'UTF-8');
  8219. }
  8220. if (function_exists('mb_strlen')) {
  8221. return (int)mb_strlen($s, 'UTF-8');
  8222. }
  8223. return strlen($s);
  8224. }
  8225. /** 按显示宽度右侧补空格,便于短信/邮件工序行对齐 */
  8226. protected function mbPadRight(string $s, int $width): string
  8227. {
  8228. $cur = $this->mbDisplayWidth($s);
  8229. if ($cur >= $width) {
  8230. return $s;
  8231. }
  8232. return $s . str_repeat(' ', $width - $cur);
  8233. }
  8234. /**
  8235. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  8236. *
  8237. * @return array<string, string>
  8238. */
  8239. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  8240. {
  8241. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  8242. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  8243. }
  8244. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  8245. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  8246. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  8247. $cyjmc = '';
  8248. foreach ($mergeRows as $mr) {
  8249. if (!is_array($mr)) {
  8250. continue;
  8251. }
  8252. if ($ccydh === '') {
  8253. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  8254. }
  8255. if ($cyjmc === '') {
  8256. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  8257. }
  8258. }
  8259. if ($pos !== []) {
  8260. $firstPo = $pos[0];
  8261. if (is_array($firstPo)) {
  8262. if ($ccydh === '') {
  8263. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  8264. }
  8265. if ($cyjmc === '') {
  8266. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  8267. }
  8268. }
  8269. }
  8270. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  8271. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  8272. if (is_array($any)) {
  8273. if ($ccydh === '') {
  8274. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  8275. }
  8276. if ($cyjmc === '') {
  8277. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  8278. }
  8279. }
  8280. }
  8281. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  8282. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  8283. $cgymc = '';
  8284. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  8285. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  8286. }
  8287. return [
  8288. 'ccydh' => $ccydh,
  8289. 'cyjmc' => $cyjmc,
  8290. 'cgymc' => $cgymc,
  8291. 'process_lines' => $processLines,
  8292. 'process_lines_html' => '',
  8293. ];
  8294. }
  8295. /**
  8296. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  8297. * 多订单时 processPlain 已含各订单头,不再重复拼订单号/印件名称。
  8298. */
  8299. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  8300. {
  8301. $processPlain = trim($processPlain);
  8302. if ($processPlain !== '' && preg_match('/^订单号:/u', $processPlain)) {
  8303. return $processPlain;
  8304. }
  8305. $lines = [];
  8306. if ($ccydh !== '') {
  8307. $lines[] = '订单号:' . $ccydh;
  8308. }
  8309. if ($cyjmc !== '') {
  8310. $lines[] = '印件名称:' . $cyjmc;
  8311. }
  8312. if ($processPlain !== '') {
  8313. $lines[] = $processPlain;
  8314. }
  8315. return implode("\n", $lines);
  8316. }
  8317. /**
  8318. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  8319. *
  8320. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  8321. */
  8322. protected function buildPlatformLinksPlain(array $detailLinks): string
  8323. {
  8324. $lines = [];
  8325. $i = 1;
  8326. foreach ($detailLinks as $lk) {
  8327. if (!is_array($lk)) {
  8328. continue;
  8329. }
  8330. $url = trim((string)($lk['url'] ?? ''));
  8331. if ($url === '') {
  8332. continue;
  8333. }
  8334. $label = trim((string)($lk['cgymc'] ?? ''));
  8335. if ($label === '') {
  8336. $label = '工序' . $i;
  8337. }
  8338. $lines[] = $label . ':' . $url;
  8339. $i++;
  8340. }
  8341. return implode("\n", $lines);
  8342. }
  8343. /**
  8344. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  8345. *
  8346. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  8347. */
  8348. protected function buildPlatformLinksHtml(array $detailLinks): string
  8349. {
  8350. $parts = [];
  8351. $i = 1;
  8352. foreach ($detailLinks as $lk) {
  8353. if (!is_array($lk)) {
  8354. continue;
  8355. }
  8356. $url = trim((string)($lk['url'] ?? ''));
  8357. if ($url === '') {
  8358. continue;
  8359. }
  8360. $label = trim((string)($lk['cgymc'] ?? ''));
  8361. if ($label === '') {
  8362. $label = '工序' . $i;
  8363. }
  8364. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  8365. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  8366. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  8367. $i++;
  8368. }
  8369. return implode("<br>\n", $parts);
  8370. }
  8371. /**
  8372. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  8373. *
  8374. * @return array<string, mixed>
  8375. */
  8376. protected function loadMailerConfig(): array
  8377. {
  8378. try {
  8379. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  8380. } catch (\Throwable $e) {
  8381. $cfg = [];
  8382. }
  8383. return is_array($cfg) ? $cfg : [];
  8384. }
  8385. protected function loadNotifyTemplateRow(string $scene): ?array
  8386. {
  8387. if (in_array($scene, ['confirm_ok_email', 'confirm_fail_email'], true)) {
  8388. $this->ensureConfirmResultEmailTemplates();
  8389. }
  8390. if (in_array($scene, ['review_email', 'review_sms'], true)) {
  8391. $this->ensureReviewEmailTemplate();
  8392. $this->ensureReviewSmsTemplate();
  8393. }
  8394. try {
  8395. $row = Db::table('purchase_sms_template')
  8396. ->where('scene', $scene)
  8397. ->where(function ($q) {
  8398. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  8399. })
  8400. ->order('id', 'asc')
  8401. ->find();
  8402. } catch (\Throwable $e) {
  8403. return null;
  8404. }
  8405. if (!is_array($row) || $row === []) {
  8406. return null;
  8407. }
  8408. return [
  8409. 'title' => trim((string)($row['title'] ?? '')),
  8410. 'content' => trim((string)($row['content'] ?? '')),
  8411. ];
  8412. }
  8413. /**
  8414. * 邮件用工序明细 HTML。
  8415. * 多订单同批时按订单分组;单订单保持原表格/单行样式。
  8416. */
  8417. protected function buildProcessLinesHtml(array $mergeRows): string
  8418. {
  8419. $groups = [];
  8420. foreach ($mergeRows as $r) {
  8421. if (!is_array($r)) {
  8422. continue;
  8423. }
  8424. $dh = trim((string)($r['CCYDH'] ?? ''));
  8425. $key = $dh !== '' ? $dh : ('__sid_' . (int)($r['ID'] ?? $r['id'] ?? $r['scydgy_id'] ?? 0));
  8426. if (!isset($groups[$key])) {
  8427. $groups[$key] = [
  8428. 'ccydh' => $dh,
  8429. 'cyjmc' => trim((string)($r['CYJMC'] ?? '')),
  8430. 'rows' => [],
  8431. ];
  8432. } elseif ($groups[$key]['cyjmc'] === '') {
  8433. $groups[$key]['cyjmc'] = trim((string)($r['CYJMC'] ?? ''));
  8434. }
  8435. $groups[$key]['rows'][] = $r;
  8436. }
  8437. if ($groups === []) {
  8438. return '';
  8439. }
  8440. $multiOrder = count($groups) > 1;
  8441. $flatRows = [];
  8442. foreach ($groups as $g) {
  8443. foreach ($g['rows'] as $r) {
  8444. $flatRows[] = $r;
  8445. }
  8446. }
  8447. if (!$multiOrder && count($flatRows) <= 1) {
  8448. $r = $flatRows[0] ?? [];
  8449. if (!is_array($r)) {
  8450. return '';
  8451. }
  8452. $gymc = trim((string)($r['CGYMC'] ?? ''));
  8453. $dw = trim((string)($r['CDW'] ?? ''));
  8454. $qty = $this->resolveProcuremenThisQuantity($r);
  8455. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  8456. if ($dw !== '') {
  8457. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  8458. }
  8459. if ($qty !== '') {
  8460. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  8461. }
  8462. return $html;
  8463. }
  8464. $blocks = [];
  8465. foreach ($groups as $g) {
  8466. $head = '';
  8467. if ($multiOrder) {
  8468. if ($g['ccydh'] !== '') {
  8469. $head .= '<div style="margin:10px 0 4px;font-weight:700;">订单号:'
  8470. . htmlspecialchars($g['ccydh'], ENT_QUOTES, 'UTF-8') . '</div>';
  8471. }
  8472. if ($g['cyjmc'] !== '') {
  8473. $head .= '<div style="margin:0 0 6px;color:#333;">印件名称:'
  8474. . htmlspecialchars($g['cyjmc'], ENT_QUOTES, 'UTF-8') . '</div>';
  8475. }
  8476. }
  8477. $rows = '';
  8478. $i = 1;
  8479. foreach ($g['rows'] as $r) {
  8480. if (!is_array($r)) {
  8481. continue;
  8482. }
  8483. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  8484. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  8485. $qty = htmlspecialchars($this->resolveProcuremenThisQuantity($r), ENT_QUOTES, 'UTF-8');
  8486. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  8487. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  8488. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  8489. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  8490. $i++;
  8491. }
  8492. if ($rows === '') {
  8493. continue;
  8494. }
  8495. $table = '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:4px 0 12px;font-size:14px;width:100%;max-width:560px;">'
  8496. . '<thead><tr style="background:#f5f5f5;">'
  8497. . '<th style="padding:6px 8px;border:1px solid #ddd;width:48px;">序号</th>'
  8498. . '<th style="padding:6px 8px;border:1px solid #ddd;text-align:left;">工序名称</th>'
  8499. . '<th style="padding:6px 8px;border:1px solid #ddd;width:64px;">单位</th>'
  8500. . '<th style="padding:6px 8px;border:1px solid #ddd;width:88px;">本次数量</th>'
  8501. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  8502. $blocks[] = $head . $table;
  8503. }
  8504. return implode('', $blocks);
  8505. }
  8506. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  8507. {
  8508. $sysRq = trim($sysRq);
  8509. if ($sysRq === '') {
  8510. if ($required) {
  8511. $this->error('请选择招标截止日期');
  8512. }
  8513. return '';
  8514. }
  8515. $ts = strtotime($sysRq);
  8516. if ($ts === false || $ts <= 0) {
  8517. $this->error('招标截止日期格式无效');
  8518. }
  8519. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  8520. if (!$allowPast) {
  8521. $ymd = date('Y-m-d', $ts);
  8522. if ($ymd < date('Y-m-d')) {
  8523. $this->error('招标截止日期不能早于今天');
  8524. }
  8525. if ($ts <= time()) {
  8526. $this->error('招标截止时间不能早于当前时间');
  8527. }
  8528. }
  8529. return date('Y-m-d H:i:s', $ts);
  8530. }
  8531. /**
  8532. * 确保 purchase_order.czlyq(类型)存在
  8533. */
  8534. protected function ensurePurchaseOrderCzlyqColumn(): void
  8535. {
  8536. static $done = false;
  8537. if ($done) {
  8538. return;
  8539. }
  8540. $done = true;
  8541. try {
  8542. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  8543. if (empty($cols)) {
  8544. Db::execute(
  8545. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  8546. );
  8547. }
  8548. } catch (\Throwable $e) {
  8549. // ignore
  8550. }
  8551. }
  8552. /**
  8553. * 确保 purchase_order.delivery_deadline 存在
  8554. */
  8555. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  8556. {
  8557. static $done = false;
  8558. if ($done) {
  8559. return;
  8560. }
  8561. $done = true;
  8562. try {
  8563. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  8564. if (empty($cols)) {
  8565. Db::execute(
  8566. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  8567. );
  8568. }
  8569. } catch (\Throwable $e) {
  8570. // ignore
  8571. }
  8572. }
  8573. /**
  8574. * 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
  8575. */
  8576. protected function ensurePurchaseOrderScoreRuleIdColumn(): void
  8577. {
  8578. static $done = false;
  8579. if ($done) {
  8580. return;
  8581. }
  8582. $done = true;
  8583. // 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
  8584. $adds = [
  8585. 'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
  8586. 'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
  8587. 'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
  8588. 'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
  8589. 'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
  8590. ];
  8591. $changed = false;
  8592. foreach ($adds as $col => $ddl) {
  8593. try {
  8594. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  8595. if (!is_array($cols) || $cols === []) {
  8596. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  8597. $changed = true;
  8598. }
  8599. } catch (\Throwable $e) {
  8600. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  8601. }
  8602. }
  8603. if ($changed) {
  8604. $this->clearPurchaseOrderTableFieldsCache();
  8605. }
  8606. }
  8607. /**
  8608. * 确保 purchase_order.order_batch_no(下发批次号)存在
  8609. */
  8610. protected function ensurePurchaseOrderOrderBatchNoColumn(): void
  8611. {
  8612. static $done = false;
  8613. if ($done) {
  8614. return;
  8615. }
  8616. $done = true;
  8617. try {
  8618. $hasNew = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'order_batch_no'");
  8619. if (is_array($hasNew) && $hasNew !== []) {
  8620. return;
  8621. }
  8622. $hasOld = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'issue_batch_no'");
  8623. if (is_array($hasOld) && $hasOld !== []) {
  8624. Db::execute(
  8625. "ALTER TABLE `purchase_order` CHANGE COLUMN `issue_batch_no` `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号(如XH202608240001)'"
  8626. );
  8627. try {
  8628. Db::execute('ALTER TABLE `purchase_order` DROP INDEX `idx_issue_batch_no`');
  8629. } catch (\Throwable $eDrop) {
  8630. }
  8631. try {
  8632. Db::execute('ALTER TABLE `purchase_order` ADD INDEX `idx_order_batch_no` (`order_batch_no`)');
  8633. } catch (\Throwable $eIdx) {
  8634. }
  8635. } else {
  8636. Db::execute(
  8637. "ALTER TABLE `purchase_order` ADD COLUMN `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号(如XH202608240001)'"
  8638. );
  8639. try {
  8640. Db::execute('ALTER TABLE `purchase_order` ADD INDEX `idx_order_batch_no` (`order_batch_no`)');
  8641. } catch (\Throwable $eIdx) {
  8642. }
  8643. }
  8644. $this->clearPurchaseOrderTableFieldsCache();
  8645. } catch (\Throwable $e) {
  8646. Log::write('purchase_order.order_batch_no: ' . $e->getMessage(), 'error');
  8647. }
  8648. }
  8649. /** @deprecated 兼容旧调用 */
  8650. protected function ensurePurchaseOrderIssueBatchNoColumn(): void
  8651. {
  8652. $this->ensurePurchaseOrderOrderBatchNoColumn();
  8653. }
  8654. /**
  8655. * 批次号日流水表:取号时立刻落库递增,避免并发下发撞号
  8656. */
  8657. protected function ensurePurchaseIssueBatchSeqTable(): void
  8658. {
  8659. static $done = false;
  8660. if ($done) {
  8661. return;
  8662. }
  8663. $done = true;
  8664. try {
  8665. Db::execute(
  8666. "CREATE TABLE IF NOT EXISTS `purchase_issue_batch_seq` (
  8667. `ymd` char(8) NOT NULL COMMENT '日期Ymd',
  8668. `last_no` int unsigned NOT NULL DEFAULT 0 COMMENT '当日已分配最大流水',
  8669. `updatetime` datetime DEFAULT NULL,
  8670. PRIMARY KEY (`ymd`)
  8671. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助下发批次号日流水'"
  8672. );
  8673. } catch (\Throwable $e) {
  8674. Log::write('purchase_issue_batch_seq: ' . $e->getMessage(), 'error');
  8675. }
  8676. }
  8677. /**
  8678. * 生成下发批次号:XH + Ymd + 当日4位流水(如 XH202608240001)
  8679. * 必须拿到日锁后先递增流水表再返回,避免两笔下发同时取到同一号。
  8680. *
  8681. * @throws \RuntimeException
  8682. */
  8683. protected function allocateProcuremenIssueBatchNo(): string
  8684. {
  8685. $this->ensurePurchaseOrderOrderBatchNoColumn();
  8686. $this->ensurePurchaseIssueBatchSeqTable();
  8687. $ymd = date('Ymd');
  8688. $prefix = 'XH' . $ymd;
  8689. $lockName = 'procuremen_issue_batch_' . $ymd;
  8690. if (!$this->acquireProcuremenNamedLock($lockName, 15)) {
  8691. throw new \RuntimeException('批次号生成繁忙,请稍后重试');
  8692. }
  8693. try {
  8694. $last = 0;
  8695. $hasSeqRow = false;
  8696. try {
  8697. $row = Db::table('purchase_issue_batch_seq')->where('ymd', $ymd)->find();
  8698. if (is_array($row) && $row !== []) {
  8699. $hasSeqRow = true;
  8700. $last = (int)($row['last_no'] ?? 0);
  8701. }
  8702. } catch (\Throwable $e) {
  8703. $last = 0;
  8704. }
  8705. // 兼容:流水表为空时,用已有 purchase_order.order_batch_no 最大值对齐
  8706. try {
  8707. $maxPo = Db::table('purchase_order')
  8708. ->where('order_batch_no', 'like', $prefix . '%')
  8709. ->order('order_batch_no', 'desc')
  8710. ->value('order_batch_no');
  8711. if (is_string($maxPo) && preg_match('/^XH\d{8}(\d{4})$/', $maxPo, $m)) {
  8712. $last = max($last, (int)$m[1]);
  8713. }
  8714. } catch (\Throwable $e) {
  8715. }
  8716. $seq = $last + 1;
  8717. if ($seq < 1) {
  8718. $seq = 1;
  8719. }
  8720. if ($seq > 9999) {
  8721. throw new \RuntimeException('当日批次号已用尽,请联系管理员');
  8722. }
  8723. $now = date('Y-m-d H:i:s');
  8724. try {
  8725. if ($hasSeqRow) {
  8726. Db::table('purchase_issue_batch_seq')->where('ymd', $ymd)->update([
  8727. 'last_no' => $seq,
  8728. 'updatetime' => $now,
  8729. ]);
  8730. } else {
  8731. try {
  8732. Db::table('purchase_issue_batch_seq')->insert([
  8733. 'ymd' => $ymd,
  8734. 'last_no' => $seq,
  8735. 'updatetime' => $now,
  8736. ]);
  8737. } catch (\Throwable $eIns) {
  8738. Db::table('purchase_issue_batch_seq')->where('ymd', $ymd)->update([
  8739. 'last_no' => $seq,
  8740. 'updatetime' => $now,
  8741. ]);
  8742. }
  8743. }
  8744. } catch (\Throwable $e) {
  8745. throw new \RuntimeException('批次号写入失败,请重试');
  8746. }
  8747. return $prefix . str_pad((string)$seq, 4, '0', STR_PAD_LEFT);
  8748. } finally {
  8749. $this->releaseProcuremenNamedLock($lockName);
  8750. }
  8751. }
  8752. /**
  8753. * ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
  8754. */
  8755. protected function clearPurchaseOrderTableFieldsCache(): void
  8756. {
  8757. try {
  8758. $db = (string)Config::get('database.database');
  8759. $key = $db . '.purchase_order';
  8760. $ref = new \ReflectionProperty(\think\db\Query::class, 'info');
  8761. $ref->setAccessible(true);
  8762. $info = $ref->getValue();
  8763. if (is_array($info) && isset($info[$key])) {
  8764. unset($info[$key]);
  8765. $ref->setValue(null, $info);
  8766. }
  8767. } catch (\Throwable $e) {
  8768. }
  8769. try {
  8770. $db = (string)Config::get('database.database');
  8771. $schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
  8772. if (is_file($schemaFile)) {
  8773. @unlink($schemaFile);
  8774. }
  8775. } catch (\Throwable $e) {
  8776. }
  8777. }
  8778. /**
  8779. * @return array<string, bool>
  8780. */
  8781. protected function loadPurchaseOrderColumnSet(): array
  8782. {
  8783. static $set = null;
  8784. if (is_array($set)) {
  8785. return $set;
  8786. }
  8787. $set = [];
  8788. try {
  8789. $cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
  8790. } catch (\Throwable $e) {
  8791. return $set;
  8792. }
  8793. if (!is_array($cols)) {
  8794. return $set;
  8795. }
  8796. foreach ($cols as $c) {
  8797. if (!is_array($c)) {
  8798. continue;
  8799. }
  8800. $f = (string)($c['Field'] ?? $c['field'] ?? '');
  8801. if ($f !== '') {
  8802. $set[$f] = true;
  8803. }
  8804. }
  8805. return $set;
  8806. }
  8807. /**
  8808. * 解析交货截止日期(仅年月日)
  8809. */
  8810. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  8811. {
  8812. $raw = trim($raw);
  8813. if ($raw === '') {
  8814. if ($required) {
  8815. $this->error('请选择交货截止日期');
  8816. }
  8817. return '';
  8818. }
  8819. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  8820. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  8821. } else {
  8822. $ts = strtotime(str_replace('/', '-', $raw));
  8823. if ($ts === false || $ts <= 0) {
  8824. $this->error('交货截止日期格式无效');
  8825. }
  8826. $ymd = date('Y-m-d', $ts);
  8827. }
  8828. if ($ymd < date('Y-m-d')) {
  8829. $this->error('交货截止日期不能早于今天');
  8830. }
  8831. return $ymd;
  8832. }
  8833. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  8834. {
  8835. return ProcuremenFormat::deliveryDeadlineForInput($value);
  8836. }
  8837. /**
  8838. * @param array{pos?:array} $bundle
  8839. * @return array<string, string> CCYDH => Y-m-d
  8840. */
  8841. protected function buildBundleOrderDeliveryDeadlineMap(array $bundle): array
  8842. {
  8843. $map = [];
  8844. foreach ($bundle['pos'] ?? [] as $po) {
  8845. if (!is_array($po)) {
  8846. continue;
  8847. }
  8848. $dh = trim((string)($po['CCYDH'] ?? ''));
  8849. if ($dh === '' || isset($map[$dh])) {
  8850. continue;
  8851. }
  8852. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  8853. if ($d !== '') {
  8854. $map[$dh] = $d;
  8855. }
  8856. }
  8857. return $map;
  8858. }
  8859. /**
  8860. * @param array{pos?:array} $bundle
  8861. */
  8862. protected function resolveBundleDeliveryDeadline(array $bundle): string
  8863. {
  8864. $map = $this->buildBundleOrderDeliveryDeadlineMap($bundle);
  8865. if ($map !== []) {
  8866. $firstDeadline = reset($map);
  8867. return (string)$firstDeadline;
  8868. }
  8869. return '';
  8870. }
  8871. protected function formatProcuremenSysRqForInput($sysRq): string
  8872. {
  8873. return ProcuremenFormat::sysRqForInput($sysRq);
  8874. }
  8875. protected function formatProcuremenSysRqForDisplay($sysRq): string
  8876. {
  8877. return ProcuremenFormat::sysRqForDisplay($sysRq);
  8878. }
  8879. /**
  8880. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  8881. *
  8882. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  8883. * @return array{ccydh?:string,pos:array,merge_rows:array}
  8884. */
  8885. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  8886. {
  8887. return $bundle;
  8888. }
  8889. /**
  8890. * 写入/更新 purchase_order(单道工序行)
  8891. *
  8892. * @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
  8893. */
  8894. protected function upsertPurchaseOrderFromRow(
  8895. array $row,
  8896. string $sysRqDb,
  8897. $wflowStatus = null,
  8898. ?string $pickTime = null,
  8899. ?array $exists = null,
  8900. ?string $deliveryDeadline = null,
  8901. $scoreRuleId = null,
  8902. ?string $issueBatchNo = null
  8903. ): void {
  8904. $ids = $this->extractScydgyRowId($row);
  8905. if (!$this->isValidScydgyRowId($ids)) {
  8906. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  8907. }
  8908. if ($exists === null) {
  8909. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  8910. }
  8911. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  8912. $this->ensurePurchaseOrderScoreRuleIdColumn();
  8913. $this->ensurePurchaseOrderOrderBatchNoColumn();
  8914. $this->ensurePurchaseOrderCzlyqColumn();
  8915. $data = $this->normalizePurchaseOrderWritePayload([
  8916. 'scydgy_id' => $ids,
  8917. 'CCYDH' => $row['CCYDH'] ?? null,
  8918. 'CYJMC' => $row['CYJMC'] ?? null,
  8919. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  8920. 'CDXMC' => $row['CDXMC'] ?? null,
  8921. 'CGYBH' => $row['CGYBH'] ?? null,
  8922. 'CGYMC' => $row['CGYMC'] ?? null,
  8923. 'CDW' => $row['CDW'] ?? null,
  8924. 'czlyq' => $row['czlyq'] ?? null,
  8925. 'NGZL' => $row['NGZL'] ?? null,
  8926. 'CDF' => $row['CDF'] ?? null,
  8927. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  8928. 'MBZ' => trim((string)($row['MBZ'] ?? $row['mbz'] ?? '')),
  8929. 'bwjg' => $row['bwjg'] ?? null,
  8930. 'iStatus' => $row['iStatus'] ?? null,
  8931. 'dStamp' => $row['dStamp'] ?? null,
  8932. 'dputrecord' => $row['dputrecord'] ?? null,
  8933. 'cywyxm' => $row['cywyxm'] ?? null,
  8934. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  8935. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  8936. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  8937. 'sys_rq' => $sysRqDb,
  8938. ], $row);
  8939. // 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
  8940. $qtyUp = trim((string)($data['This_quantity'] ?? ''));
  8941. if ($qtyUp === '') {
  8942. $qtyFallback = $this->resolveProcuremenThisQuantity([
  8943. 'This_quantity' => '',
  8944. 'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
  8945. ]);
  8946. if ($qtyFallback !== '') {
  8947. $data['This_quantity'] = $qtyFallback;
  8948. }
  8949. }
  8950. if ($deliveryDeadline !== null) {
  8951. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  8952. }
  8953. // 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
  8954. $scoreRule = null;
  8955. if (is_array($scoreRuleId)) {
  8956. $scoreRule = $scoreRuleId;
  8957. $scoreRuleId = (int)($scoreRule['id'] ?? 0);
  8958. } else {
  8959. $scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
  8960. }
  8961. if ($scoreRuleId !== null && $scoreRuleId > 0) {
  8962. $poCols = $this->loadPurchaseOrderColumnSet();
  8963. if (!empty($poCols['score_rule_id'])) {
  8964. $data['score_rule_id'] = $scoreRuleId;
  8965. if (is_array($scoreRule)) {
  8966. if (!empty($poCols['score_rule_name'])) {
  8967. $data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
  8968. }
  8969. if (!empty($poCols['score_quality_weight'])) {
  8970. $data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
  8971. }
  8972. if (!empty($poCols['score_price_weight'])) {
  8973. $data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
  8974. }
  8975. if (!empty($poCols['score_lead_weight'])) {
  8976. $data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
  8977. }
  8978. }
  8979. }
  8980. }
  8981. if ($wflowStatus !== null && $wflowStatus !== '') {
  8982. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  8983. }
  8984. if ($pickTime !== null && $pickTime !== '') {
  8985. $data['pick_time'] = $pickTime;
  8986. $data['pick_company_name'] = '';
  8987. // 新下发批次:清空「指定供应商」,避免沿用上轮免开标状态导致提前可见报价
  8988. $this->ensurePurchaseOrderManualPickColumns();
  8989. $data['manual_pick'] = 0;
  8990. $data['manual_pick_reason'] = '';
  8991. // 同订单重新下发后需重新开标(按订单号 + 批次号);并软删同订单其它旧批
  8992. $dh = trim((string)($data['CCYDH'] ?? $row['CCYDH'] ?? ''));
  8993. $bn = trim((string)($issueBatchNo ?? ''));
  8994. if ($bn === '') {
  8995. $bn = $this->resolveProcuremenOrderBatchNo(array_merge(is_array($exists) ? $exists : [], $data, $row));
  8996. }
  8997. $this->clearProcuremenBidOpenRecords($dh !== '' ? [$dh] : [], $bn !== '' ? [$bn] : []);
  8998. if ($dh !== '') {
  8999. // 新下发只清开标/评分;软删其它批仅在「重新下发」入口做,避免正常补发工序误伤并行单
  9000. $this->clearProcuremenSupplierScoresForCcydhs([$dh]);
  9001. }
  9002. }
  9003. if ($issueBatchNo !== null) {
  9004. $batchNo = trim($issueBatchNo);
  9005. $poCols = $this->loadPurchaseOrderColumnSet();
  9006. if (!empty($poCols['order_batch_no'])) {
  9007. $data['order_batch_no'] = $batchNo;
  9008. }
  9009. }
  9010. if ($exists) {
  9011. $upd = $data;
  9012. unset($upd['scydgy_id']);
  9013. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  9014. } else {
  9015. $data['createtime'] = date('Y-m-d H:i:s');
  9016. Db::table('purchase_order')->insert($data);
  9017. }
  9018. }
  9019. /**
  9020. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  9021. *
  9022. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  9023. */
  9024. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
  9025. {
  9026. $toDb = function ($value) {
  9027. if ($value === null) {
  9028. return null;
  9029. }
  9030. if (is_scalar($value)) {
  9031. return $value;
  9032. }
  9033. return json_encode($value, JSON_UNESCAPED_UNICODE);
  9034. };
  9035. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  9036. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  9037. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  9038. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  9039. if ($username === '') {
  9040. $username = $this->resolveCustomerContactName($phone, $companyName);
  9041. }
  9042. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  9043. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  9044. }
  9045. if ($requirePhone && $phone === '') {
  9046. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  9047. }
  9048. $detailLinks = [];
  9049. foreach ($mergeRows as $row) {
  9050. if (!is_array($row)) {
  9051. continue;
  9052. }
  9053. $sid = $this->extractScydgyRowId($row);
  9054. $detailId = 0;
  9055. if ($skipExisting) {
  9056. try {
  9057. $existsQuery = Db::table('purchase_order_detail')
  9058. ->where('scydgy_id', $sid)
  9059. ->where('company_name', $companyName);
  9060. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  9061. $exists = $existsQuery->find();
  9062. } catch (\Throwable $e) {
  9063. $exists = null;
  9064. }
  9065. if (is_array($exists)) {
  9066. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  9067. }
  9068. }
  9069. if ($detailId <= 0) {
  9070. $one = [
  9071. 'scydgy_id' => $toDb($sid),
  9072. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  9073. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  9074. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  9075. 'username' => $username !== '' ? $username : null,
  9076. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  9077. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  9078. 'createtime' => date('Y-m-d H:i:s'),
  9079. 'status' => ProcuremenStatus::POD_UNPICKED,
  9080. 'status_name' => '未提交',
  9081. ];
  9082. // 新下发/重新下发均不继承历史报价,供应商需对本批次重新填报
  9083. Db::table('purchase_order_detail')->insert($one);
  9084. $detailId = (int)Db::getLastInsID();
  9085. }
  9086. $mprocUrl = '';
  9087. if ($buildMobileLinks && $detailId > 0) {
  9088. // 手工询价 → 待报价;协助下发 → 未提交
  9089. $listTab = ($sid < 0) ? 'rfq' : 'draft';
  9090. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId, $listTab);
  9091. }
  9092. $detailLinks[] = [
  9093. 'detail_id' => $detailId,
  9094. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  9095. 'url' => $mprocUrl,
  9096. ];
  9097. }
  9098. $this->invalidatePickHiddenScydgyCache();
  9099. return $detailLinks;
  9100. }
  9101. /**
  9102. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  9103. * @return array<string, mixed>
  9104. */
  9105. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks, string $emailTplScene = 'review_email'): array
  9106. {
  9107. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  9108. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  9109. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  9110. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  9111. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  9112. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  9113. $isMerge = !empty($ctx['is_merge']);
  9114. $contactName = trim((string)($c['username'] ?? ''));
  9115. if ($contactName === '') {
  9116. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  9117. }
  9118. $notifyVars = [
  9119. 'company_name' => $companyName,
  9120. 'contact_name' => $contactName,
  9121. 'phone' => $phone,
  9122. 'email' => $toEmail,
  9123. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  9124. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  9125. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  9126. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  9127. 'deadline' => (string)($ctx['deadline'] ?? ''),
  9128. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  9129. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  9130. 'order_type' => (string)($ctx['order_type'] ?? ''),
  9131. 'score_weights' => (string)($ctx['score_weights'] ?? ''),
  9132. 'platform_url' => $platformUrl,
  9133. 'platform_links' => $platformLinksPlain,
  9134. 'platform_links_html' => $platformLinksHtml,
  9135. ];
  9136. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  9137. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  9138. $mailPlain = $this->renderNotifyTemplate($emailTplScene, $notifyVars);
  9139. if (!empty($ctx['multi_order'])) {
  9140. $smsContent = $this->stripEmptyOrderHeaderLines($smsContent);
  9141. $mailPlain = $this->stripEmptyOrderHeaderLines($mailPlain);
  9142. }
  9143. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  9144. // 邮件:用表格替换纯文本工序块,列对齐更整齐
  9145. $processHtml = trim((string)($ctx['process_html'] ?? ''));
  9146. $processPlain = trim((string)($ctx['process_plain'] ?? ''));
  9147. if ($processHtml !== '' && $processPlain !== '') {
  9148. $plainBlockHtml = $this->plainTextToHtmlEmailBody($processPlain);
  9149. if ($plainBlockHtml !== '' && strpos($mailBody, $plainBlockHtml) !== false) {
  9150. $mailBody = str_replace($plainBlockHtml, $processHtml, $mailBody);
  9151. }
  9152. }
  9153. return [
  9154. 'company_name' => $companyName,
  9155. 'phone' => $phone,
  9156. 'email' => $toEmail,
  9157. 'sms_content' => $smsContent,
  9158. 'mail_plain' => $mailPlain,
  9159. 'mail_body' => $mailBody,
  9160. 'notify_vars' => $notifyVars,
  9161. 'detail_links' => $detailLinks,
  9162. ];
  9163. }
  9164. /**
  9165. * 多订单下发时模版里「订单号:{ccydh}」可能变成空行,去掉以免重复
  9166. */
  9167. protected function stripEmptyOrderHeaderLines(string $text): string
  9168. {
  9169. $text = str_replace(["\r\n", "\r"], "\n", $text);
  9170. $text = preg_replace('/^订单号:\s*\n/mu', '', $text);
  9171. $text = preg_replace('/^印件名称:\s*\n/mu', '', $text);
  9172. $text = preg_replace("/\n{3,}/", "\n\n", (string)$text);
  9173. return (string)$text;
  9174. }
  9175. /**
  9176. * @param array<string, mixed> $chosen
  9177. * @param array<int, array<string, mixed>> $mergeRows
  9178. * @param array{ccydh:string, pos:array} $bundle
  9179. */
  9180. /**
  9181. * 先把成功 JSON 回给浏览器,再继续后台任务(发短信/邮件)。
  9182. * 避免多家供应商通知串行导致页面一直转圈、网关超时被当成系统失败。
  9183. *
  9184. * @param array<string, mixed>|string|null $data
  9185. */
  9186. protected function respondSuccessThenContinue(string $msg, $data = null): void
  9187. {
  9188. $result = [
  9189. 'code' => 1,
  9190. 'msg' => $msg,
  9191. 'data' => $data,
  9192. 'url' => '',
  9193. 'wait' => 3,
  9194. ];
  9195. $json = json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  9196. if ($json === false) {
  9197. $json = '{"code":1,"msg":"操作成功","data":null,"url":"","wait":3}';
  9198. }
  9199. while (ob_get_level() > 0) {
  9200. @ob_end_clean();
  9201. }
  9202. if (!headers_sent()) {
  9203. header('Content-Type: application/json; charset=utf-8');
  9204. header('Cache-Control: no-store, no-cache, must-revalidate');
  9205. header('Connection: close');
  9206. header('Content-Length: ' . strlen($json));
  9207. }
  9208. echo $json;
  9209. if (session_status() === PHP_SESSION_ACTIVE) {
  9210. @session_write_close();
  9211. }
  9212. if (function_exists('fastcgi_finish_request')) {
  9213. @fastcgi_finish_request();
  9214. } else {
  9215. @flush();
  9216. }
  9217. @ignore_user_abort(true);
  9218. @set_time_limit(300);
  9219. @ini_set('max_execution_time', '300');
  9220. }
  9221. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue', string $emailTplScene = 'review_email'): void
  9222. {
  9223. if (!$sendSms && !$sendEmail) {
  9224. return;
  9225. }
  9226. $companyName = trim((string)($chosen['name'] ?? ''));
  9227. $phone = trim((string)($chosen['phone'] ?? ''));
  9228. $toEmail = trim((string)($chosen['email'] ?? ''));
  9229. if ($companyName === '') {
  9230. throw new \Exception('供应商名称无效');
  9231. }
  9232. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  9233. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  9234. }
  9235. if ($sendSms && $phone === '') {
  9236. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  9237. }
  9238. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  9239. $linkListTab = (strpos($emailTplScene, 'rfq_') === 0) ? 'rfq' : 'draft';
  9240. $sids = [];
  9241. foreach ($mergeRows as $mr) {
  9242. if (!is_array($mr)) {
  9243. continue;
  9244. }
  9245. $sid = $this->extractScydgyRowId($mr);
  9246. if ($this->isValidScydgyRowId($sid)) {
  9247. $sids[$sid] = true;
  9248. }
  9249. }
  9250. if ($sids === []) {
  9251. throw new \Exception('未找到工序行,无法发送通知');
  9252. }
  9253. $sysRqNotify = '';
  9254. $pos = $bundle['pos'] ?? [];
  9255. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  9256. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  9257. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  9258. $ts = strtotime($sr);
  9259. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  9260. }
  9261. }
  9262. try {
  9263. $detailsQuery = Db::table('purchase_order_detail')
  9264. ->where('scydgy_id', 'in', array_keys($sids))
  9265. ->where('company_name', $companyName);
  9266. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  9267. $details = $detailsQuery->order('id', 'asc')->select();
  9268. } catch (\Throwable $e) {
  9269. $details = [];
  9270. }
  9271. if (!is_array($details) || $details === []) {
  9272. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  9273. try {
  9274. $detailsQuery = Db::table('purchase_order_detail')
  9275. ->where('scydgy_id', 'in', array_keys($sids))
  9276. ->where('company_name', $companyName);
  9277. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  9278. $details = $detailsQuery->order('id', 'asc')->select();
  9279. } catch (\Throwable $e) {
  9280. $details = [];
  9281. }
  9282. }
  9283. if (!is_array($details) || $details === []) {
  9284. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  9285. }
  9286. $detailLinks = [];
  9287. foreach ($details as $d) {
  9288. if (!is_array($d)) {
  9289. continue;
  9290. }
  9291. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  9292. if ($detailId <= 0) {
  9293. continue;
  9294. }
  9295. $sid = (int)($d['scydgy_id'] ?? 0);
  9296. $gymc = '';
  9297. foreach ($mergeRows as $mr) {
  9298. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  9299. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  9300. break;
  9301. }
  9302. }
  9303. $detailLinks[] = [
  9304. 'detail_id' => $detailId,
  9305. 'cgymc' => $gymc,
  9306. // 询价邮件 → 待报价;下发报价 → 未提交
  9307. 'url' => $this->buildMprocMobileOrderUrl(
  9308. $detailId,
  9309. ($linkListTab === 'rfq' || $sid < 0) ? 'rfq' : 'draft'
  9310. ),
  9311. ];
  9312. }
  9313. if ($detailLinks === []) {
  9314. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  9315. }
  9316. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  9317. $orderTypeCtx = $this->resolveIssueNotifyOrderTypeFromBundle($bundle);
  9318. $ctx['order_type'] = (string)($orderTypeCtx['order_type'] ?? '');
  9319. $ctx['score_weights'] = (string)($orderTypeCtx['score_weights'] ?? '');
  9320. $this->ensureReviewEmailTemplate();
  9321. $this->ensureReviewSmsTemplate();
  9322. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks, $emailTplScene);
  9323. $notifyBundle['email_log_scene'] = $emailLogScene;
  9324. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  9325. $poIdLog = 0;
  9326. $pos = $bundle['pos'] ?? [];
  9327. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  9328. $poIdLog = (int)($pos[0]['id'] ?? 0);
  9329. }
  9330. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  9331. // 日志单独记订单号/批次号:多订单下发时模版变量 ccydh 会刻意留空,不能沿用到日志
  9332. $notifyBundle['email_log_ccydh'] = $this->collectCcydhListForEmailLog($mergeRows, $pos);
  9333. $notifyBundle['email_log_order_batch_no'] = $this->resolveBundleOrderBatchNo($bundle);
  9334. if ($sendEmail) {
  9335. $mailTplRow = $this->loadNotifyTemplateRow($emailTplScene);
  9336. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  9337. throw new \Exception($this->notifyTemplateMissingMessage($emailTplScene));
  9338. }
  9339. $mailSubject = $this->resolveProcuremenEmailSubject($emailTplScene);
  9340. $mailConfig = $this->loadMailerConfig();
  9341. if (!$this->isProcuremenNotifyDryRun()) {
  9342. if (empty($mailConfig['host'])) {
  9343. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9344. }
  9345. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9346. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9347. }
  9348. }
  9349. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  9350. }
  9351. if ($sendSms) {
  9352. $this->issueSendSupplierSms($notifyBundle);
  9353. }
  9354. }
  9355. /**
  9356. * @param array<int, array<string, mixed>> $quoteGroups
  9357. * @return array<int, array<string, mixed>>
  9358. */
  9359. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  9360. {
  9361. $names = [];
  9362. if (is_string($companiesJson) && $companiesJson !== '') {
  9363. $decoded = json_decode($companiesJson, true);
  9364. if (is_array($decoded)) {
  9365. foreach ($decoded as $nm) {
  9366. $nm = trim((string)$nm);
  9367. if ($nm !== '') {
  9368. $names[] = $nm;
  9369. }
  9370. }
  9371. }
  9372. }
  9373. $names = array_values(array_unique($names));
  9374. if ($names === [] && $selectedCompany !== '') {
  9375. $names = [$selectedCompany];
  9376. }
  9377. if ($names === []) {
  9378. return $quoteGroups;
  9379. }
  9380. $targets = [];
  9381. foreach ($quoteGroups as $g) {
  9382. if (!is_array($g)) {
  9383. continue;
  9384. }
  9385. $cn = trim((string)($g['name'] ?? ''));
  9386. if ($cn !== '' && in_array($cn, $names, true)) {
  9387. $targets[] = $g;
  9388. }
  9389. }
  9390. return $targets;
  9391. }
  9392. /**
  9393. * @return array{pos:array, merge_rows:array, bundle:array}
  9394. */
  9395. protected function loadAuditResendBundle(string $scydgyId): array
  9396. {
  9397. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  9398. $pos = $bundle['pos'];
  9399. $mergeRows = $bundle['merge_rows'];
  9400. if ($pos === [] || $mergeRows === []) {
  9401. $this->error('该订单不在待确认供应商状态');
  9402. }
  9403. $sysRqDb = '';
  9404. if (isset($pos[0]) && is_array($pos[0])) {
  9405. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  9406. }
  9407. foreach ($pos as $i => $poRow) {
  9408. if (is_array($pos[$i]) && $sysRqDb !== '') {
  9409. $pos[$i]['sys_rq'] = $sysRqDb;
  9410. }
  9411. }
  9412. $bundle['pos'] = $pos;
  9413. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  9414. }
  9415. /**
  9416. * @param array<int, array<string, mixed>> $targets
  9417. */
  9418. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  9419. {
  9420. if ($targets === []) {
  9421. $this->error('未找到可通知的供应商');
  9422. }
  9423. $notifyErrors = [];
  9424. try {
  9425. $this->notifyDryRunPreview = [];
  9426. foreach ($targets as $g) {
  9427. if (!is_array($g)) {
  9428. continue;
  9429. }
  9430. $cname = trim((string)($g['name'] ?? ''));
  9431. if ($cname === '') {
  9432. continue;
  9433. }
  9434. $chosen = [
  9435. 'name' => $cname,
  9436. 'company_name' => $cname,
  9437. 'email' => trim((string)($g['email'] ?? '')),
  9438. 'phone' => trim((string)($g['phone'] ?? '')),
  9439. 'username' => trim((string)($g['username'] ?? '')),
  9440. ];
  9441. try {
  9442. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  9443. } catch (\Throwable $e) {
  9444. $notifyErrors[] = $cname . ':' . $e->getMessage();
  9445. }
  9446. }
  9447. } catch (\Throwable $e) {
  9448. Log::write('procuremen auditResend notify fatal: ' . $e->getMessage(), 'error');
  9449. $this->success('重发未全部完成,请核对联系方式后稍后再试', '', [
  9450. 'notify_failed' => 1,
  9451. ]);
  9452. }
  9453. if ($notifyErrors !== []) {
  9454. Log::write('procuremen auditResend partial fail: ' . implode(';', $notifyErrors), 'error');
  9455. $ok = max(0, count($targets) - count($notifyErrors));
  9456. $this->success(
  9457. '已向 ' . $ok . ' 家发送成功;',
  9458. '',
  9459. [
  9460. 'notify_failed' => 1,
  9461. 'notify_fail_detail' => $notifyErrors,
  9462. ]
  9463. );
  9464. }
  9465. if ($this->isProcuremenNotifyDryRun()) {
  9466. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  9467. 'notify_dry_run' => true,
  9468. 'notify_preview' => $this->notifyDryRunPreview,
  9469. ]);
  9470. }
  9471. $nameLabels = [];
  9472. foreach ($targets as $g) {
  9473. if (!is_array($g)) {
  9474. continue;
  9475. }
  9476. $n = trim((string)($g['name'] ?? ''));
  9477. if ($n !== '') {
  9478. $nameLabels[] = $n;
  9479. }
  9480. }
  9481. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  9482. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  9483. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  9484. $seenLogSid = [];
  9485. foreach ($bundle['pos'] ?? [] as $poRow) {
  9486. if (!is_array($poRow)) {
  9487. continue;
  9488. }
  9489. $sid = (int)($poRow['scydgy_id'] ?? 0);
  9490. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  9491. continue;
  9492. }
  9493. $seenLogSid[$sid] = true;
  9494. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  9495. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  9496. }
  9497. if ($seenLogSid === []) {
  9498. foreach ($mergeRows as $mr) {
  9499. if (!is_array($mr)) {
  9500. continue;
  9501. }
  9502. $sid = $this->extractScydgyRowId($mr);
  9503. if ($this->isValidScydgyRowId($sid)) {
  9504. $this->addOrderLog($sid, $logAction, $logMsg, null);
  9505. break;
  9506. }
  9507. }
  9508. }
  9509. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  9510. }
  9511. /**
  9512. * 协助下发 — 发送短信(一家供应商)
  9513. *
  9514. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  9515. */
  9516. protected function issueSendSupplierSms(array $bundle): void
  9517. {
  9518. $companyName = (string)($bundle['company_name'] ?? '');
  9519. $phone = (string)($bundle['phone'] ?? '');
  9520. $smsContent = (string)($bundle['sms_content'] ?? '');
  9521. $this->logIssueNotifyDebug('短信', [
  9522. 'company' => $companyName,
  9523. 'phone' => $phone,
  9524. 'sms_content' => $smsContent,
  9525. ]);
  9526. if ($this->isProcuremenNotifyDryRun()) {
  9527. $this->recordNotifyDryRunPreview([
  9528. 'scene' => 'issue_sms',
  9529. 'company_name' => $companyName,
  9530. 'phone' => $phone,
  9531. 'sms_content' => $smsContent,
  9532. ]);
  9533. return;
  9534. }
  9535. $this->smsbao($phone, $smsContent);
  9536. }
  9537. /**
  9538. * 协助下发 — 发送邮件(一家供应商)
  9539. *
  9540. * @param array<string, mixed> $bundle
  9541. * @param array<string, mixed> $mailConfig
  9542. */
  9543. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  9544. {
  9545. $companyName = (string)($bundle['company_name'] ?? '');
  9546. $toEmail = (string)($bundle['email'] ?? '');
  9547. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  9548. $mailBody = (string)($bundle['mail_body'] ?? '');
  9549. $this->logIssueNotifyDebug('邮件', [
  9550. 'company' => $companyName,
  9551. 'email' => $toEmail,
  9552. 'cc_email' => $this->resolveMprocNotifyCcEmails($toEmail),
  9553. 'mail_subject' => $mailSubject,
  9554. 'mail_body' => $mailPlain,
  9555. ]);
  9556. if ($this->isProcuremenNotifyDryRun()) {
  9557. $this->recordNotifyDryRunPreview([
  9558. 'scene' => 'issue_email',
  9559. 'company_name' => $companyName,
  9560. 'email' => $toEmail,
  9561. 'cc_email' => $this->resolveMprocNotifyCcEmails($toEmail),
  9562. 'mail_subject' => $mailSubject,
  9563. 'mail_body' => $mailPlain,
  9564. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  9565. 'notify_vars' => $bundle['notify_vars'] ?? [],
  9566. 'detail_links' => $bundle['detail_links'] ?? [],
  9567. ]);
  9568. return;
  9569. }
  9570. $mail = new PHPMailer(true);
  9571. $mail->isSMTP();
  9572. $mail->Host = $mailConfig['host'];
  9573. $mail->SMTPAuth = true;
  9574. $mail->Username = $mailConfig['addr'];
  9575. $mail->Password = $mailConfig['pass'];
  9576. $mail->SMTPSecure = $mailConfig['security'];
  9577. $mail->Port = $mailConfig['port'];
  9578. $mail->CharSet = $mailConfig['charset'];
  9579. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  9580. $mail->addAddress($toEmail, $companyName);
  9581. $ccList = $this->resolveMprocNotifyCcEmails($toEmail);
  9582. foreach ($ccList as $cc) {
  9583. $mail->addCC($cc);
  9584. }
  9585. $mail->isHTML(true);
  9586. $mail->Subject = $mailSubject;
  9587. $mail->Body = $mailBody;
  9588. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  9589. $sendOk = true;
  9590. $failReason = '';
  9591. $logCcydh = trim((string)($bundle['email_log_ccydh'] ?? ''));
  9592. if ($logCcydh === '') {
  9593. $logCcydh = trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? '')));
  9594. }
  9595. $logBatchNo = trim((string)($bundle['email_log_order_batch_no'] ?? ($bundle['order_batch_no'] ?? '')));
  9596. $logCommon = [
  9597. 'from_email' => $fromEmail,
  9598. 'to_email' => $toEmail,
  9599. 'send_time' => date('Y-m-d H:i:s'),
  9600. 'scene' => (string)($bundle['email_log_scene'] ?? '初选下发'),
  9601. 'order_batch_no' => $logBatchNo,
  9602. 'ccydh' => $logCcydh,
  9603. 'company_name' => $companyName,
  9604. 'mail_subject' => $mailSubject,
  9605. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  9606. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  9607. ];
  9608. try {
  9609. $mail->send();
  9610. } catch (\Throwable $e) {
  9611. $sendOk = false;
  9612. $failReason = $e->getMessage();
  9613. $this->persistEmailSendLog(array_merge($logCommon, [
  9614. 'status' => 0,
  9615. 'fail_reason' => $failReason,
  9616. ]));
  9617. throw $e;
  9618. }
  9619. $this->persistEmailSendLog(array_merge($logCommon, [
  9620. 'status' => 1,
  9621. 'fail_reason' => '',
  9622. ]));
  9623. }
  9624. /**
  9625. * 协助通知抄送:读取 mproc.cc_email(逗号分隔),排除与主收件人相同的地址
  9626. *
  9627. * @return array<int, string>
  9628. */
  9629. protected function resolveMprocNotifyCcEmails(string $toEmail = ''): array
  9630. {
  9631. $raw = trim((string)config('mproc.cc_email'));
  9632. if ($raw === '') {
  9633. return [];
  9634. }
  9635. $toNorm = strtolower(trim($toEmail));
  9636. $out = [];
  9637. $seen = [];
  9638. foreach (preg_split('/[,;,;\s]+/', $raw) ?: [] as $piece) {
  9639. $email = strtolower(trim((string)$piece));
  9640. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9641. continue;
  9642. }
  9643. if ($toNorm !== '' && $email === $toNorm) {
  9644. continue;
  9645. }
  9646. if (isset($seen[$email])) {
  9647. continue;
  9648. }
  9649. $seen[$email] = true;
  9650. $out[] = $email;
  9651. }
  9652. return $out;
  9653. }
  9654. /**
  9655. * 下发通知:解析订单类型名称与评分比例文案
  9656. *
  9657. * @param array<string, mixed> $bundle
  9658. * @return array{order_type:string,score_weights:string}
  9659. */
  9660. protected function resolveIssueNotifyOrderTypeFromBundle(array $bundle): array
  9661. {
  9662. $orderType = '';
  9663. $scoreWeights = '';
  9664. $rule = null;
  9665. Log::write('procuremen resolveOrderType bundle: ' . json_encode([
  9666. 'score_rule' => isset($bundle['score_rule']) ? $bundle['score_rule'] : 'NOT_SET',
  9667. 'pos0_score_rule_id' => isset($bundle['pos'][0]['score_rule_id']) ? $bundle['pos'][0]['score_rule_id'] : 'NOT_SET',
  9668. ], JSON_UNESCAPED_UNICODE), 'notice');
  9669. if (!empty($bundle['score_rule']) && is_array($bundle['score_rule'])) {
  9670. $rule = $bundle['score_rule'];
  9671. }
  9672. $pos = $bundle['pos'] ?? [];
  9673. $po0 = (is_array($pos) && isset($pos[0]) && is_array($pos[0])) ? $pos[0] : null;
  9674. if ($rule === null && is_array($po0)) {
  9675. $ruleId = (int)($po0['score_rule_id'] ?? 0);
  9676. if ($ruleId > 0) {
  9677. try {
  9678. $rule = ProcuremenSupplierScore::getRuleById($ruleId);
  9679. Log::write('procuremen resolveOrderType via pos ruleId=' . $ruleId . ' result: ' . json_encode($rule, JSON_UNESCAPED_UNICODE), 'notice');
  9680. } catch (\Throwable $e) {
  9681. $rule = null;
  9682. Log::write('procuremen resolveOrderType getRuleById exception: ' . $e->getMessage(), 'error');
  9683. }
  9684. }
  9685. if (!is_array($rule) || (int)($rule['id'] ?? 0) <= 0) {
  9686. $qw = (int)($po0['score_quality_weight'] ?? 0);
  9687. $pw = (int)($po0['score_price_weight'] ?? 0);
  9688. $lw = (int)($po0['score_lead_weight'] ?? 0);
  9689. if ($qw > 0 || $pw > 0 || $lw > 0) {
  9690. $rule = [
  9691. 'name' => trim((string)($po0['score_rule_name'] ?? '')),
  9692. 'quality_weight' => $qw,
  9693. 'price_weight' => $pw,
  9694. 'lead_weight' => $lw,
  9695. ];
  9696. }
  9697. }
  9698. }
  9699. if (is_array($rule)) {
  9700. $orderType = trim((string)($rule['name'] ?? ''));
  9701. $scoreWeights = $this->formatScoreRuleWeightsText($rule);
  9702. }
  9703. if ($orderType === '' && is_array($po0)) {
  9704. $orderType = trim((string)($po0['score_rule_name'] ?? ''));
  9705. }
  9706. Log::write('procuremen resolveOrderType result: orderType=' . $orderType . ', scoreWeights=' . $scoreWeights, 'notice');
  9707. return [
  9708. 'order_type' => $orderType,
  9709. 'score_weights' => $scoreWeights,
  9710. ];
  9711. }
  9712. /**
  9713. * 评分比例文案:质量30%、价格50%、交货20%
  9714. *
  9715. * @param array{quality_weight?:mixed,price_weight?:mixed,lead_weight?:mixed} $rule
  9716. */
  9717. protected function formatScoreRuleWeightsText(array $rule): string
  9718. {
  9719. return ProcuremenFormat::scoreRuleWeightsText($rule);
  9720. }
  9721. /**
  9722. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  9723. *
  9724. * @param array<int, array<string, mixed>> $mergeRows
  9725. * @return array<string, mixed>
  9726. */
  9727. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  9728. {
  9729. $head = $mergeRows[0] ?? [];
  9730. $isMerge = count($mergeRows) > 1;
  9731. $orderSet = [];
  9732. foreach ($mergeRows as $r) {
  9733. if (!is_array($r)) {
  9734. continue;
  9735. }
  9736. $dh = trim((string)($r['CCYDH'] ?? ''));
  9737. if ($dh !== '') {
  9738. $orderSet[$dh] = true;
  9739. }
  9740. }
  9741. $multiOrder = count($orderSet) > 1;
  9742. // 多订单:明细块自带各订单头,避免模版里 {ccydh}/{cyjmc} 只显示第一单
  9743. $ccydh = $multiOrder ? '' : (isset($head['CCYDH']) ? (string)$head['CCYDH'] : '');
  9744. $cyjmc = $multiOrder ? '' : (isset($head['CYJMC']) ? (string)$head['CYJMC'] : '');
  9745. return [
  9746. 'ccydh' => $ccydh,
  9747. 'cyjmc' => $cyjmc,
  9748. 'cgymc_single' => $multiOrder ? '' : trim((string)($head['CGYMC'] ?? '')),
  9749. 'is_merge' => $isMerge,
  9750. 'multi_order' => $multiOrder,
  9751. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  9752. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  9753. 'deadline' => $sysRqNotify,
  9754. 'order_type' => '',
  9755. 'score_weights' => '',
  9756. ];
  9757. }
  9758. /**
  9759. * 邮件发送日志用的订单号列表(多单逗号分隔;与模版变量是否留空无关)
  9760. *
  9761. * @param array<int, array<string, mixed>> $mergeRows
  9762. * @param array<int, array<string, mixed>> $pos
  9763. */
  9764. protected function collectCcydhListForEmailLog(array $mergeRows, array $pos = []): string
  9765. {
  9766. $set = [];
  9767. foreach ($mergeRows as $r) {
  9768. if (!is_array($r)) {
  9769. continue;
  9770. }
  9771. foreach (['CCYDH', 'ccydh'] as $k) {
  9772. $dh = trim((string)($r[$k] ?? ''));
  9773. if ($dh !== '') {
  9774. $set[$dh] = true;
  9775. break;
  9776. }
  9777. }
  9778. }
  9779. if ($set === []) {
  9780. foreach ($pos as $po) {
  9781. if (!is_array($po)) {
  9782. continue;
  9783. }
  9784. foreach (['CCYDH', 'ccydh'] as $k) {
  9785. $dh = trim((string)($po[$k] ?? ''));
  9786. if ($dh !== '') {
  9787. $set[$dh] = true;
  9788. break;
  9789. }
  9790. }
  9791. }
  9792. }
  9793. return implode(',', array_keys($set));
  9794. }
  9795. /**
  9796. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  9797. *
  9798. * @param array<string, mixed> $data
  9799. */
  9800. protected function logIssueNotifyDebug(string $type, array $data): void
  9801. {
  9802. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  9803. return;
  9804. }
  9805. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  9806. }
  9807. protected function ensurePurchaseEmailSendLogTableOnce(): void
  9808. {
  9809. try {
  9810. Db::query('SELECT `id`,`order_batch_no`,`ccydh` FROM `purchase_email_send_log` LIMIT 1');
  9811. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  9812. return;
  9813. } catch (\Throwable $e) {
  9814. }
  9815. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  9816. if (is_file($sqlFile)) {
  9817. $sql = file_get_contents($sqlFile);
  9818. if (is_string($sql) && $sql !== '') {
  9819. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  9820. $stmt = trim($stmt);
  9821. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  9822. continue;
  9823. }
  9824. try {
  9825. Db::execute($stmt);
  9826. } catch (\Throwable $ignore) {
  9827. }
  9828. }
  9829. }
  9830. }
  9831. try {
  9832. $cols = Db::query("SHOW COLUMNS FROM `purchase_email_send_log` LIKE 'order_batch_no'");
  9833. if (!is_array($cols) || $cols === []) {
  9834. Db::execute(
  9835. "ALTER TABLE `purchase_email_send_log` ADD COLUMN `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号' AFTER `scene`"
  9836. );
  9837. }
  9838. } catch (\Throwable $ignore) {
  9839. }
  9840. try {
  9841. $cols = Db::query("SHOW COLUMNS FROM `purchase_email_send_log` LIKE 'ccydh'");
  9842. if (is_array($cols) && $cols !== []) {
  9843. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  9844. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 500) {
  9845. Db::execute(
  9846. "ALTER TABLE `purchase_email_send_log` MODIFY COLUMN `ccydh` varchar(500) NOT NULL DEFAULT '' COMMENT '订单号(多单逗号分隔)'"
  9847. );
  9848. }
  9849. }
  9850. } catch (\Throwable $ignore) {
  9851. }
  9852. try {
  9853. $idx = Db::query("SHOW INDEX FROM `purchase_email_send_log` WHERE Key_name = 'idx_order_batch_no'");
  9854. if (!is_array($idx) || $idx === []) {
  9855. Db::execute('ALTER TABLE `purchase_email_send_log` ADD INDEX `idx_order_batch_no` (`order_batch_no`)');
  9856. }
  9857. } catch (\Throwable $ignore) {
  9858. }
  9859. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  9860. }
  9861. /**
  9862. * @param array<string, mixed> $row
  9863. */
  9864. protected function persistEmailSendLog(array $row): void
  9865. {
  9866. try {
  9867. $this->ensurePurchaseEmailSendLogTableOnce();
  9868. } catch (\Throwable $e) {
  9869. return;
  9870. }
  9871. list($adminId, $adminName) = $this->GetUseName();
  9872. $cut = function ($s, $max) {
  9873. $s = (string)$s;
  9874. if (function_exists('mb_substr')) {
  9875. return mb_substr($s, 0, $max, 'UTF-8');
  9876. }
  9877. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  9878. };
  9879. $data = [
  9880. 'from_email' => $cut($row['from_email'] ?? '', 128),
  9881. 'to_email' => $cut($row['to_email'] ?? '', 128),
  9882. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  9883. 'scene' => $cut($this->normalizeEmailLogSceneForStore((string)($row['scene'] ?? '')), 64),
  9884. 'order_batch_no' => $cut($row['order_batch_no'] ?? '', 32),
  9885. 'ccydh' => $cut($row['ccydh'] ?? '', 500),
  9886. 'company_name' => $cut($row['company_name'] ?? '', 128),
  9887. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  9888. 'status' => !empty($row['status']) ? 1 : 0,
  9889. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  9890. 'admin_id' => (int)$adminId,
  9891. 'admin_name' => $cut($adminName, 64),
  9892. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  9893. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  9894. 'createtime' => date('Y-m-d H:i:s'),
  9895. ];
  9896. try {
  9897. Db::table('purchase_email_send_log')->insert($data);
  9898. } catch (\Throwable $e) {
  9899. // 兼容尚未自动补列的旧库:去掉批次号再试一次
  9900. if (stripos($e->getMessage(), 'order_batch_no') !== false) {
  9901. try {
  9902. unset($data['order_batch_no']);
  9903. Db::table('purchase_email_send_log')->insert($data);
  9904. return;
  9905. } catch (\Throwable $e2) {
  9906. Log::write('persistEmailSendLog: ' . $e2->getMessage(), 'error');
  9907. return;
  9908. }
  9909. }
  9910. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  9911. }
  9912. }
  9913. /**
  9914. * 邮件日志场景:库内统一存中文;兼容历史英文码
  9915. *
  9916. * @return array<string, string>
  9917. */
  9918. protected function emailLogSceneLabelMap(): array
  9919. {
  9920. return ProcuremenFormat::emailLogSceneLabelMap();
  9921. }
  9922. /** 写入邮件日志前:英文场景码转中文;已是中文则原样 */
  9923. protected function normalizeEmailLogSceneForStore(string $scene): string
  9924. {
  9925. return ProcuremenFormat::normalizeEmailLogSceneForStore($scene);
  9926. }
  9927. protected function formatEmailLogSceneText(string $scene): string
  9928. {
  9929. return ProcuremenFormat::emailLogSceneText($scene);
  9930. }
  9931. /**
  9932. * 邮件发送日志列表
  9933. */
  9934. public function emailLog()
  9935. {
  9936. $this->relationSearch = false;
  9937. $this->searchFields = 'from_email,to_email,ccydh,order_batch_no,company_name,admin_name,mail_subject';
  9938. $this->request->filter(['strip_tags', 'trim']);
  9939. $bakModel = $this->model;
  9940. $this->model = new \app\admin\model\Purchaseemailsendlog;
  9941. if ($this->request->isAjax()) {
  9942. $this->ensurePurchaseEmailSendLogTableOnce();
  9943. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  9944. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  9945. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  9946. $list = $this->model
  9947. ->where($where)
  9948. ->order($sortField, $orderDir)
  9949. ->paginate($limit);
  9950. $rows = [];
  9951. $needEnrichPoIds = [];
  9952. foreach ($list->items() as $item) {
  9953. $row = is_array($item) ? $item : $item->toArray();
  9954. $scene = trim((string)($row['scene'] ?? ''));
  9955. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  9956. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  9957. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  9958. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  9959. $row['order_batch_no'] = trim((string)($row['order_batch_no'] ?? ''));
  9960. $row['ccydh'] = trim((string)($row['ccydh'] ?? ''));
  9961. $poId = (int)($row['purchase_order_id'] ?? 0);
  9962. if ($poId > 0 && ($row['ccydh'] === '' || $row['order_batch_no'] === '')) {
  9963. $needEnrichPoIds[$poId] = true;
  9964. }
  9965. $rows[] = $row;
  9966. }
  9967. if ($needEnrichPoIds !== []) {
  9968. $poMap = $this->loadEmailLogEnrichPoMap(array_keys($needEnrichPoIds));
  9969. foreach ($rows as &$row) {
  9970. $poId = (int)($row['purchase_order_id'] ?? 0);
  9971. if ($poId <= 0 || !isset($poMap[$poId])) {
  9972. continue;
  9973. }
  9974. $info = $poMap[$poId];
  9975. if ($row['order_batch_no'] === '' && $info['order_batch_no'] !== '') {
  9976. $row['order_batch_no'] = $info['order_batch_no'];
  9977. }
  9978. if ($row['ccydh'] === '') {
  9979. if ($info['order_batch_no'] !== '' && isset($info['batch_ccydhs']) && $info['batch_ccydhs'] !== '') {
  9980. $row['ccydh'] = $info['batch_ccydhs'];
  9981. } elseif ($info['ccydh'] !== '') {
  9982. $row['ccydh'] = $info['ccydh'];
  9983. }
  9984. }
  9985. }
  9986. unset($row);
  9987. }
  9988. $this->model = $bakModel;
  9989. return json(['total' => $list->total(), 'rows' => $rows]);
  9990. }
  9991. $this->model = $bakModel;
  9992. return $this->view->fetch('procuremen/emaillog');
  9993. }
  9994. /**
  9995. * 历史邮件日志缺订单号/批次号时,按 purchase_order_id 回填展示
  9996. *
  9997. * @param array<int, int> $poIds
  9998. * @return array<int, array{ccydh:string,order_batch_no:string,batch_ccydhs:string}>
  9999. */
  10000. protected function loadEmailLogEnrichPoMap(array $poIds): array
  10001. {
  10002. $out = [];
  10003. $poIds = array_values(array_unique(array_filter(array_map('intval', $poIds))));
  10004. if ($poIds === []) {
  10005. return $out;
  10006. }
  10007. try {
  10008. $pos = Db::table('purchase_order')->where('id', 'in', $poIds)->field('id,CCYDH,order_batch_no')->select();
  10009. } catch (\Throwable $e) {
  10010. try {
  10011. $pos = Db::table('purchase_order')->where('id', 'in', $poIds)->field('id,CCYDH')->select();
  10012. } catch (\Throwable $e2) {
  10013. return $out;
  10014. }
  10015. }
  10016. $batchSet = [];
  10017. foreach ($pos as $po) {
  10018. if (!is_array($po)) {
  10019. continue;
  10020. }
  10021. $id = (int)($po['id'] ?? 0);
  10022. if ($id <= 0) {
  10023. continue;
  10024. }
  10025. $bn = $this->resolveProcuremenOrderBatchNo($po);
  10026. $out[$id] = [
  10027. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  10028. 'order_batch_no' => $bn,
  10029. 'batch_ccydhs' => '',
  10030. ];
  10031. if ($bn !== '') {
  10032. $batchSet[$bn] = true;
  10033. }
  10034. }
  10035. if ($batchSet === []) {
  10036. return $out;
  10037. }
  10038. try {
  10039. $batchRows = Db::table('purchase_order')
  10040. ->where('order_batch_no', 'in', array_keys($batchSet))
  10041. ->field('CCYDH,order_batch_no')
  10042. ->select();
  10043. } catch (\Throwable $e) {
  10044. return $out;
  10045. }
  10046. $byBatch = [];
  10047. foreach ($batchRows as $br) {
  10048. if (!is_array($br)) {
  10049. continue;
  10050. }
  10051. $bn = trim((string)($br['order_batch_no'] ?? ''));
  10052. $dh = trim((string)($br['CCYDH'] ?? ''));
  10053. if ($bn === '' || $dh === '') {
  10054. continue;
  10055. }
  10056. $byBatch[$bn][$dh] = true;
  10057. }
  10058. foreach ($out as $id => $info) {
  10059. $bn = $info['order_batch_no'];
  10060. if ($bn !== '' && isset($byBatch[$bn])) {
  10061. $out[$id]['batch_ccydhs'] = implode(',', array_keys($byBatch[$bn]));
  10062. }
  10063. }
  10064. return $out;
  10065. }
  10066. /**
  10067. * 协助下发弹窗(选多家供应商并通知)
  10068. */
  10069. public function pickReview()
  10070. {
  10071. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  10072. $this->error(__('You have no permission'));
  10073. }
  10074. if ($this->request->isPost()) {
  10075. $this->error('请使用弹窗内「确认下发」提交');
  10076. }
  10077. $this->view->assign('pickMode', 1);
  10078. $this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
  10079. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  10080. }
  10081. /**
  10082. * 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
  10083. */
  10084. protected function ensurePurchaseOrderNotifySalesmanColumn(): void
  10085. {
  10086. static $done = false;
  10087. if ($done) {
  10088. return;
  10089. }
  10090. $done = true;
  10091. try {
  10092. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'notify_salesman'");
  10093. if (empty($cols)) {
  10094. Db::execute(
  10095. "ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
  10096. );
  10097. } else {
  10098. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  10099. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
  10100. Db::execute(
  10101. "ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
  10102. );
  10103. }
  10104. }
  10105. } catch (\Throwable $e) {
  10106. // ignore
  10107. }
  10108. }
  10109. /**
  10110. * 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
  10111. */
  10112. protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
  10113. {
  10114. static $done = false;
  10115. if ($done) {
  10116. return;
  10117. }
  10118. $done = true;
  10119. try {
  10120. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
  10121. if (empty($cols)) {
  10122. Db::execute(
  10123. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
  10124. );
  10125. }
  10126. } catch (\Throwable $e) {
  10127. // ignore
  10128. }
  10129. try {
  10130. $cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
  10131. if (empty($cols2)) {
  10132. Db::execute(
  10133. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
  10134. );
  10135. }
  10136. } catch (\Throwable $e) {
  10137. // ignore
  10138. }
  10139. }
  10140. /**
  10141. * 确保「采购确认通过/未通过」邮箱模版存在。
  10142. * title=说明;remark=邮箱通知;邮件主题由 resolveProcuremenEmailSubject 固定,不用 title。
  10143. */
  10144. protected function ensureConfirmResultEmailTemplates(): void
  10145. {
  10146. static $done = false;
  10147. if ($done) {
  10148. return;
  10149. }
  10150. $done = true;
  10151. $now = date('Y-m-d H:i:s');
  10152. $seeds = [
  10153. 'confirm_ok_email' => [
  10154. 'title' => '确认已通过通知',
  10155. 'content' => "您好,{company_name}:\n\n您参与的订单采购确认结果:已通过 已中标。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  10156. 'remark' => '邮箱通知',
  10157. ],
  10158. 'confirm_fail_email' => [
  10159. 'title' => '确认未通过通知',
  10160. 'content' => "您好,{company_name}:\n\n您参与的订单采购确认结果:未通过 未中标。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  10161. 'remark' => '邮箱通知',
  10162. ],
  10163. ];
  10164. try {
  10165. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  10166. } catch (\Throwable $e) {
  10167. return;
  10168. }
  10169. $colNames = [];
  10170. foreach ($cols as $c) {
  10171. if (!is_array($c)) {
  10172. continue;
  10173. }
  10174. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  10175. if ($n !== '') {
  10176. $colNames[$n] = true;
  10177. }
  10178. }
  10179. foreach ($seeds as $scene => $seed) {
  10180. try {
  10181. $row = Db::table('purchase_sms_template')->where('scene', $scene)->find();
  10182. } catch (\Throwable $e) {
  10183. continue;
  10184. }
  10185. if (is_array($row) && $row !== []) {
  10186. continue;
  10187. }
  10188. $data = [
  10189. 'scene' => $scene,
  10190. 'title' => $seed['title'],
  10191. 'content' => $seed['content'],
  10192. 'remark' => $seed['remark'],
  10193. 'status' => 1,
  10194. ];
  10195. if (isset($colNames['updatetime'])) {
  10196. $data['updatetime'] = $now;
  10197. }
  10198. if (isset($colNames['createtime'])) {
  10199. $data['createtime'] = $now;
  10200. }
  10201. try {
  10202. Db::table('purchase_sms_template')->insert($data);
  10203. } catch (\Throwable $e) {
  10204. // ignore
  10205. }
  10206. }
  10207. }
  10208. /**
  10209. * 确保「协助下发-邮箱」模版存在(含 {order_type};可在短信模版配置中修改)
  10210. */
  10211. protected function ensureReviewEmailTemplate(): void
  10212. {
  10213. static $done = false;
  10214. if ($done) {
  10215. return;
  10216. }
  10217. $done = true;
  10218. $content = "您好,{company_name}:\n\n"
  10219. . "您有新的协助加工订单,请登录平台查看并报价。\n\n"
  10220. . "需求编号:{ccydh}\n"
  10221. . "印件名称:{cyjmc}\n"
  10222. . "业务分类:{category}\n"
  10223. . "订单类型:{order_type}\n"
  10224. . "{process_lines}\n\n"
  10225. . "请在 {deadline} 前完成报价。\n\n"
  10226. . "平台链接:{platform_url}\n";
  10227. try {
  10228. $row = Db::table('purchase_sms_template')
  10229. ->where('scene', 'review_email')
  10230. ->find();
  10231. } catch (\Throwable $e) {
  10232. return;
  10233. }
  10234. $now = date('Y-m-d H:i:s');
  10235. if (is_array($row) && $row !== []) {
  10236. return;
  10237. }
  10238. try {
  10239. $data = [
  10240. 'scene' => 'review_email',
  10241. 'title' => '协助加工订单通知',
  10242. 'content' => $content,
  10243. 'remark' => '协助下发-邮箱;可在短信模版配置中修改',
  10244. 'status' => 1,
  10245. ];
  10246. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  10247. $colNames = [];
  10248. foreach ($cols as $c) {
  10249. if (!is_array($c)) {
  10250. continue;
  10251. }
  10252. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  10253. if ($n !== '') {
  10254. $colNames[$n] = true;
  10255. }
  10256. }
  10257. if (isset($colNames['updatetime'])) {
  10258. $data['updatetime'] = $now;
  10259. }
  10260. if (isset($colNames['createtime'])) {
  10261. $data['createtime'] = $now;
  10262. }
  10263. Db::table('purchase_sms_template')->insert($data);
  10264. } catch (\Throwable $e) {
  10265. // ignore
  10266. }
  10267. }
  10268. /**
  10269. * 确保「协助下发-短信」模版存在(含 {order_type};可在短信模版配置中修改)
  10270. */
  10271. protected function ensureReviewSmsTemplate(): void
  10272. {
  10273. static $done = false;
  10274. if ($done) {
  10275. return;
  10276. }
  10277. $done = true;
  10278. $content = "您好,{company_name}:\n\n"
  10279. . "您有新的协助加工订单,请登录平台查看并报价。\n\n"
  10280. . "需求编号:{ccydh}\n"
  10281. . "印件名称:{cyjmc}\n"
  10282. . "订单类型:{order_type}\n"
  10283. . "{process_lines}\n\n"
  10284. . "请在 {deadline} 前完成报价。\n\n"
  10285. . "平台链接:{platform_url}\n";
  10286. try {
  10287. $row = Db::table('purchase_sms_template')
  10288. ->where('scene', 'review_sms')
  10289. ->find();
  10290. } catch (\Throwable $e) {
  10291. return;
  10292. }
  10293. $now = date('Y-m-d H:i:s');
  10294. if (is_array($row) && $row !== []) {
  10295. return;
  10296. }
  10297. try {
  10298. $data = [
  10299. 'scene' => 'review_sms',
  10300. 'title' => '协助加工订单通知',
  10301. 'content' => $content,
  10302. 'remark' => '协助下发-短信;可在短信模版配置中修改',
  10303. 'status' => 1,
  10304. ];
  10305. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  10306. $colNames = [];
  10307. foreach ($cols as $c) {
  10308. if (!is_array($c)) {
  10309. continue;
  10310. }
  10311. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  10312. if ($n !== '') {
  10313. $colNames[$n] = true;
  10314. }
  10315. }
  10316. if (isset($colNames['updatetime'])) {
  10317. $data['updatetime'] = $now;
  10318. }
  10319. if (isset($colNames['createtime'])) {
  10320. $data['createtime'] = $now;
  10321. }
  10322. Db::table('purchase_sms_template')->insert($data);
  10323. } catch (\Throwable $e) {
  10324. // ignore
  10325. }
  10326. }
  10327. /**
  10328. * 确保「供应商询价通知」邮箱模版存在(查询询价-询价/发邮件;可在短信模版配置中修改)
  10329. */
  10330. protected function ensureRfqSupplierEmailTemplate(): void
  10331. {
  10332. static $done = false;
  10333. if ($done) {
  10334. return;
  10335. }
  10336. $done = true;
  10337. $content = "您好,{company_name}:\n\n"
  10338. . "您有新的协助采购询价需求,请登录平台查看并处理。\n\n"
  10339. . "需求编号:{ccydh}\n"
  10340. . "印件名称:{cyjmc}\n"
  10341. . "{process_lines}\n\n"
  10342. . "请在 {deadline} 前完成回复。\n\n"
  10343. . "平台链接:{platform_url}\n";
  10344. try {
  10345. $row = Db::table('purchase_sms_template')
  10346. ->where('scene', 'rfq_supplier_email')
  10347. ->find();
  10348. } catch (\Throwable $e) {
  10349. return;
  10350. }
  10351. $now = date('Y-m-d H:i:s');
  10352. if (is_array($row) && $row !== []) {
  10353. return;
  10354. }
  10355. try {
  10356. $data = [
  10357. 'scene' => 'rfq_supplier_email',
  10358. 'title' => '供应商询价通知',
  10359. 'content' => $content,
  10360. 'remark' => '查询询价-询价/发邮件通知供应商;模版名称作邮件主题',
  10361. 'status' => 1,
  10362. ];
  10363. try {
  10364. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  10365. } catch (\Throwable $e) {
  10366. $cols = [];
  10367. }
  10368. $colNames = [];
  10369. foreach ($cols as $c) {
  10370. if (!is_array($c)) {
  10371. continue;
  10372. }
  10373. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  10374. if ($n !== '') {
  10375. $colNames[$n] = true;
  10376. }
  10377. }
  10378. if (isset($colNames['updatetime'])) {
  10379. $data['updatetime'] = $now;
  10380. }
  10381. if (isset($colNames['createtime'])) {
  10382. $data['createtime'] = $now;
  10383. }
  10384. Db::table('purchase_sms_template')->insert($data);
  10385. } catch (\Throwable $e) {
  10386. // ignore
  10387. }
  10388. }
  10389. /**
  10390. * 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
  10391. */
  10392. protected function ensureRfqSalesmanEmailTemplate(): void
  10393. {
  10394. static $done = false;
  10395. if ($done) {
  10396. return;
  10397. }
  10398. $done = true;
  10399. $content = "您好,{contact_name}:\n\n"
  10400. . "有新的协助采购询价需求,请知悉。\n"
  10401. . "印件名称:{cyjmc}\n"
  10402. . "工序名称:{cgymc}\n"
  10403. . "本次数量:{this_quantity}\n"
  10404. . "供应商报价:\n{supplier_quotes}\n"
  10405. . "平台链接:{platform_url}\n"
  10406. . "需求发起人:{cywyxm}\n";
  10407. try {
  10408. $row = Db::table('purchase_sms_template')
  10409. ->where('scene', 'rfq_salesman_email')
  10410. ->find();
  10411. } catch (\Throwable $e) {
  10412. return;
  10413. }
  10414. $now = date('Y-m-d H:i:s');
  10415. if (is_array($row) && $row !== []) {
  10416. $old = (string)($row['content'] ?? '');
  10417. // 无报价表格 / 无平台链接 / 链接不在「需求发起人」上方时,同步默认文案
  10418. $urlPos = strpos($old, '{platform_url}');
  10419. $cywyPos = strpos($old, '需求发起人');
  10420. $linkNotAboveStarter = ($urlPos === false)
  10421. || ($cywyPos !== false && $urlPos > $cywyPos);
  10422. $needMigrate = (strpos($old, '{supplier_quotes}') === false)
  10423. || (strpos($old, '供应商:{supplier_name}') !== false)
  10424. || $linkNotAboveStarter;
  10425. if ($needMigrate) {
  10426. $data = ['content' => $content];
  10427. if (trim((string)($row['title'] ?? '')) === '' || trim((string)($row['title'] ?? '')) === '询价通知') {
  10428. $data['title'] = '业务员询价通知';
  10429. }
  10430. try {
  10431. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
  10432. if (!empty($cols)) {
  10433. $data['updatetime'] = $now;
  10434. }
  10435. } catch (\Throwable $e) {
  10436. }
  10437. try {
  10438. Db::table('purchase_sms_template')
  10439. ->where('id', (int)($row['id'] ?? 0))
  10440. ->update($data);
  10441. } catch (\Throwable $e) {
  10442. }
  10443. }
  10444. return;
  10445. }
  10446. try {
  10447. $data = [
  10448. 'scene' => 'rfq_salesman_email',
  10449. 'title' => '业务员询价通知',
  10450. 'content' => $content,
  10451. 'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
  10452. 'status' => 1,
  10453. ];
  10454. try {
  10455. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  10456. } catch (\Throwable $e) {
  10457. $cols = [];
  10458. }
  10459. $colNames = [];
  10460. foreach ($cols as $c) {
  10461. if (!is_array($c)) {
  10462. continue;
  10463. }
  10464. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  10465. if ($n !== '') {
  10466. $colNames[$n] = true;
  10467. }
  10468. }
  10469. if (isset($colNames['updatetime'])) {
  10470. $data['updatetime'] = $now;
  10471. }
  10472. if (isset($colNames['createtime'])) {
  10473. $data['createtime'] = $now;
  10474. }
  10475. Db::table('purchase_sms_template')->insert($data);
  10476. } catch (\Throwable $e) {
  10477. // ignore
  10478. }
  10479. }
  10480. /**
  10481. * 通知业务员邮件:供应商报价明细行(仅名称+单价)
  10482. *
  10483. * @return array<int, array{name:string,amount:string}>
  10484. */
  10485. protected function loadRfqSalesmanSupplierQuoteRows(int $sid, string $supplierRaw = ''): array
  10486. {
  10487. $list = [];
  10488. $seen = [];
  10489. try {
  10490. $rows = Db::table('purchase_order_detail')
  10491. ->where('scydgy_id', $sid)
  10492. ->field('company_name,amount')
  10493. ->order('id', 'asc')
  10494. ->select();
  10495. if (is_array($rows)) {
  10496. foreach ($rows as $r) {
  10497. if (!is_array($r)) {
  10498. continue;
  10499. }
  10500. $cn = trim((string)($r['company_name'] ?? ''));
  10501. if ($cn === '' || isset($seen[$cn])) {
  10502. continue;
  10503. }
  10504. $seen[$cn] = true;
  10505. $amount = trim((string)($r['amount'] ?? ''));
  10506. $list[] = [
  10507. 'name' => $cn,
  10508. 'amount' => $amount !== '' ? $amount : '未报价',
  10509. ];
  10510. }
  10511. }
  10512. } catch (\Throwable $e) {
  10513. }
  10514. if ($list === [] && $supplierRaw !== '') {
  10515. foreach ($this->splitRfqSalesmanNames($supplierRaw) as $cn) {
  10516. if ($cn === '' || isset($seen[$cn])) {
  10517. continue;
  10518. }
  10519. $seen[$cn] = true;
  10520. $list[] = [
  10521. 'name' => $cn,
  10522. 'amount' => '未报价',
  10523. ];
  10524. }
  10525. }
  10526. return $list;
  10527. }
  10528. /**
  10529. * 通知业务员邮件:供应商报价 HTML 表格(名称+单价,不含时间)
  10530. */
  10531. protected function buildRfqSalesmanSupplierQuotesHtml(int $sid, string $supplierRaw = ''): string
  10532. {
  10533. $rows = $this->loadRfqSalesmanSupplierQuoteRows($sid, $supplierRaw);
  10534. if ($rows === []) {
  10535. return '<p style="margin:8px 0;color:#888;">暂无报价</p>';
  10536. }
  10537. $html = '<table cellpadding="0" cellspacing="0" border="1" '
  10538. . 'style="border-collapse:collapse;border-color:#ddd;width:100%;max-width:560px;font-size:14px;margin:8px 0;">'
  10539. . '<thead><tr style="background:#f5f5f5;">'
  10540. . '<th style="padding:8px 10px;text-align:center;width:56px;">序号</th>'
  10541. . '<th style="padding:8px 10px;text-align:left;">供应商名称</th>'
  10542. . '<th style="padding:8px 10px;text-align:center;width:100px;">单价</th>'
  10543. . '</tr></thead><tbody>';
  10544. foreach ($rows as $i => $row) {
  10545. $html .= '<tr>'
  10546. . '<td style="padding:8px 10px;text-align:center;">' . ($i + 1) . '</td>'
  10547. . '<td style="padding:8px 10px;">' . htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8') . '</td>'
  10548. . '<td style="padding:8px 10px;text-align:center;">' . htmlspecialchars($row['amount'], ENT_QUOTES, 'UTF-8') . '</td>'
  10549. . '</tr>';
  10550. }
  10551. $html .= '</tbody></table>';
  10552. return $html;
  10553. }
  10554. /**
  10555. * 询价多选字段:数组或字符串统一为顿号拼接
  10556. *
  10557. * @param mixed $raw
  10558. */
  10559. protected function joinRfqMultiSelectValues($raw): string
  10560. {
  10561. $parts = [];
  10562. if (is_array($raw)) {
  10563. foreach ($raw as $item) {
  10564. if (is_array($item)) {
  10565. continue;
  10566. }
  10567. $v = trim((string)$item);
  10568. if ($v !== '') {
  10569. $parts[] = $v;
  10570. }
  10571. }
  10572. } else {
  10573. $s = trim((string)$raw);
  10574. if ($s !== '') {
  10575. foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
  10576. $v = trim((string)$piece);
  10577. if ($v !== '') {
  10578. $parts[] = $v;
  10579. }
  10580. }
  10581. }
  10582. }
  10583. $parts = array_values(array_unique($parts));
  10584. return implode('、', $parts);
  10585. }
  10586. /**
  10587. * 新增询价:可选供应商名称(仅落库记录,不发通知)
  10588. *
  10589. * @return string[]
  10590. */
  10591. protected function loadRfqSupplierNameOptions(): array
  10592. {
  10593. $out = [];
  10594. try {
  10595. $rows = Db::table('customer')
  10596. ->where(function ($q) {
  10597. $q->where('status', 1)
  10598. ->whereOr('status', '1')
  10599. ->whereOr('status', '')
  10600. ->whereNull('status');
  10601. })
  10602. ->order('id', 'desc')
  10603. ->column('company_name');
  10604. } catch (\Throwable $e) {
  10605. return [];
  10606. }
  10607. if (!is_array($rows)) {
  10608. return [];
  10609. }
  10610. foreach ($rows as $name) {
  10611. $name = trim((string)$name);
  10612. if ($name === '' || isset($out[$name])) {
  10613. continue;
  10614. }
  10615. $out[$name] = $name;
  10616. }
  10617. return array_values($out);
  10618. }
  10619. /**
  10620. * 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
  10621. */
  10622. protected function rfqNotifySalesmanAuthGroupId(): int
  10623. {
  10624. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  10625. if ($id > 0) {
  10626. return $id;
  10627. }
  10628. try {
  10629. $found = Db::name('auth_group')
  10630. ->where('name', '业务员')
  10631. ->where('status', 'normal')
  10632. ->order('id', 'asc')
  10633. ->value('id');
  10634. $id = (int)$found;
  10635. } catch (\Throwable $e) {
  10636. $id = 0;
  10637. }
  10638. return $id > 0 ? $id : 12;
  10639. }
  10640. /**
  10641. * 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
  10642. *
  10643. * @return string[]
  10644. */
  10645. protected function loadRfqSalesmanNameOptions(): array
  10646. {
  10647. $out = [];
  10648. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  10649. $name = trim((string)($row['name'] ?? ''));
  10650. if ($name !== '') {
  10651. $out[] = $name;
  10652. }
  10653. }
  10654. return $out;
  10655. }
  10656. /**
  10657. * 业务员角色组下管理员:姓名、邮箱、手机
  10658. *
  10659. * @return array<int, array{name:string,email:string,mobile:string}>
  10660. */
  10661. protected function loadRfqSalesmanContactOptions(): array
  10662. {
  10663. $out = [];
  10664. $seen = [];
  10665. $groupId = $this->rfqNotifySalesmanAuthGroupId();
  10666. if ($groupId <= 0) {
  10667. return [];
  10668. }
  10669. try {
  10670. $adminIds = Db::name('auth_group_access')
  10671. ->where('group_id', $groupId)
  10672. ->column('uid');
  10673. } catch (\Throwable $e) {
  10674. return [];
  10675. }
  10676. $adminIds = is_array($adminIds)
  10677. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  10678. : [];
  10679. if ($adminIds === []) {
  10680. return [];
  10681. }
  10682. try {
  10683. $rows = Db::name('admin')
  10684. ->where('status', 'normal')
  10685. ->where('id', 'in', $adminIds)
  10686. ->order('id', 'asc')
  10687. ->field('id,nickname,username,email,mobile')
  10688. ->select();
  10689. } catch (\Throwable $e) {
  10690. return [];
  10691. }
  10692. if (!is_array($rows)) {
  10693. return [];
  10694. }
  10695. foreach ($rows as $row) {
  10696. if (!is_array($row)) {
  10697. continue;
  10698. }
  10699. $name = trim((string)($row['nickname'] ?? ''));
  10700. if ($name === '') {
  10701. $name = trim((string)($row['username'] ?? ''));
  10702. }
  10703. if ($name === '' || isset($seen[$name])) {
  10704. continue;
  10705. }
  10706. $seen[$name] = true;
  10707. $out[] = [
  10708. 'name' => $name,
  10709. 'email' => trim((string)($row['email'] ?? '')),
  10710. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  10711. ];
  10712. }
  10713. return $out;
  10714. }
  10715. /**
  10716. * 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
  10717. *
  10718. * @return string[]
  10719. */
  10720. protected function loadRfqDeptNameOptions(): array
  10721. {
  10722. $out = [];
  10723. // ERP 承揽部门(主来源)
  10724. try {
  10725. $vals = Db::table('mcyd')
  10726. ->where('CCLBMMC', '<>', '')
  10727. ->whereNotNull('CCLBMMC')
  10728. ->distinct(true)
  10729. ->limit(300)
  10730. ->column('CCLBMMC');
  10731. } catch (\Throwable $e) {
  10732. $vals = [];
  10733. }
  10734. if (is_array($vals)) {
  10735. foreach ($vals as $v) {
  10736. $v = trim((string)$v);
  10737. if ($v === '' || isset($out[$v])) {
  10738. continue;
  10739. }
  10740. $out[$v] = $v;
  10741. }
  10742. }
  10743. // 手工询价历史部门补全
  10744. try {
  10745. $poVals = Db::table('purchase_order')
  10746. ->where('CCLBMMC', '<>', '')
  10747. ->whereNotNull('CCLBMMC')
  10748. ->distinct(true)
  10749. ->limit(200)
  10750. ->column('CCLBMMC');
  10751. } catch (\Throwable $e) {
  10752. $poVals = [];
  10753. }
  10754. if (is_array($poVals)) {
  10755. foreach ($poVals as $v) {
  10756. $v = trim((string)$v);
  10757. if ($v === '' || isset($out[$v])) {
  10758. continue;
  10759. }
  10760. $out[$v] = $v;
  10761. }
  10762. }
  10763. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  10764. if (!isset($out[$preset])) {
  10765. $out[$preset] = $preset;
  10766. }
  10767. }
  10768. $list = array_values($out);
  10769. // 常用部门靠前
  10770. usort($list, static function ($a, $b) {
  10771. $weight = [
  10772. '营销中心' => 1,
  10773. '业务部' => 2,
  10774. '市场部' => 3,
  10775. '外贸部' => 4,
  10776. '新华技术业务部' => 5,
  10777. ];
  10778. $wa = $weight[$a] ?? 100;
  10779. $wb = $weight[$b] ?? 100;
  10780. if ($wa !== $wb) {
  10781. return $wa <=> $wb;
  10782. }
  10783. return strcmp((string)$a, (string)$b);
  10784. });
  10785. return $list;
  10786. }
  10787. /**
  10788. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  10789. */
  10790. public function add()
  10791. {
  10792. if ($this->request->isPost()) {
  10793. $params = $this->request->post('row/a');
  10794. if (!is_array($params)) {
  10795. $this->error(__('Parameter %s can not be empty', ''));
  10796. }
  10797. [, $adminName] = $this->GetUseName();
  10798. $params['cywyxm'] = $adminName;
  10799. try {
  10800. $sid = $this->saveManualPickOrder($params);
  10801. } catch (\InvalidArgumentException $e) {
  10802. $this->error($e->getMessage());
  10803. } catch (\Throwable $e) {
  10804. $this->error($e->getMessage());
  10805. }
  10806. $this->success('新增成功', '', [
  10807. 'scydgy_id' => $sid,
  10808. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  10809. ]);
  10810. }
  10811. $this->ensurePurchaseOrderNotifySalesmanColumn();
  10812. [, $adminName] = $this->GetUseName();
  10813. $this->view->assign('adminNickname', $adminName);
  10814. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  10815. $this->view->assign('defaultCclbmmc', '营销中心');
  10816. $this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
  10817. $this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
  10818. $this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
  10819. return $this->view->fetch();
  10820. }
  10821. /**
  10822. * 业务员新增进度查询(手工询价;有查询权限看全部,含手机端新增且未通知业务员的)
  10823. */
  10824. public function rfqlist()
  10825. {
  10826. $this->relationSearch = false;
  10827. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ,order_batch_no';
  10828. $this->request->filter(['strip_tags', 'trim']);
  10829. $this->ensurePurchaseOrderNotifySalesmanColumn();
  10830. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  10831. $this->ensureRfqSalesmanEmailTemplate();
  10832. $this->ensureRfqSupplierEmailTemplate();
  10833. if ($this->request->isAjax()) {
  10834. try {
  10835. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  10836. $limit = max(10, min(500, (int)$limit));
  10837. $filterYm = trim((string)$this->request->param('filter_ym', ''));
  10838. if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
  10839. $filterYm = date('Y-m');
  10840. }
  10841. $applyFilters = function ($query) use ($where, $filterYm) {
  10842. $query->where('scydgy_id', '<', 0);
  10843. $this->applyPurchaseOrderNotDeletedWhere($query);
  10844. // 查询询价:有菜单权限即可看全部手工单(含手机端新增、尚未通知业务员的)
  10845. $this->applyRfqListMonthFilter($query, $filterYm);
  10846. if (!empty($where)) {
  10847. // 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
  10848. $safeWhere = [];
  10849. $skipFields = [
  10850. 'supplier_name' => true,
  10851. 'progress_text' => true,
  10852. 'createtime_text' => true,
  10853. 'notify_time_text' => true,
  10854. 'can_notify_salesman' => true,
  10855. 'has_issued' => true,
  10856. 'has_quoted' => true,
  10857. ];
  10858. foreach ((array)$where as $cond) {
  10859. if (!is_array($cond) || !isset($cond[0])) {
  10860. continue;
  10861. }
  10862. $field = (string)$cond[0];
  10863. $fieldBase = (string)preg_replace('/\|.*$/', '', $field);
  10864. $fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
  10865. if (isset($skipFields[$fieldBase])) {
  10866. continue;
  10867. }
  10868. if ($fieldBase === 'supplier_name') {
  10869. continue;
  10870. }
  10871. $safeWhere[] = $cond;
  10872. }
  10873. if ($safeWhere !== []) {
  10874. $query->where($safeWhere);
  10875. }
  10876. }
  10877. };
  10878. $countQuery = Db::table('purchase_order');
  10879. $applyFilters($countQuery);
  10880. $total = (int)$countQuery->count();
  10881. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  10882. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  10883. $listQuery = Db::table('purchase_order');
  10884. $applyFilters($listQuery);
  10885. $rows = $listQuery
  10886. ->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')
  10887. ->order($sortField, $orderDir)
  10888. ->limit($offset, $limit)
  10889. ->select();
  10890. if (!is_array($rows)) {
  10891. $rows = [];
  10892. }
  10893. $sidList = [];
  10894. foreach ($rows as $r) {
  10895. if (!is_array($r)) {
  10896. continue;
  10897. }
  10898. $sid = (int)($r['scydgy_id'] ?? 0);
  10899. if ($sid < 0) {
  10900. $sidList[$sid] = true;
  10901. }
  10902. }
  10903. $issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
  10904. $quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
  10905. $out = [];
  10906. foreach ($rows as $r) {
  10907. if (!is_array($r)) {
  10908. continue;
  10909. }
  10910. $sid = (int)($r['scydgy_id'] ?? 0);
  10911. if ($sid >= 0) {
  10912. continue;
  10913. }
  10914. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  10915. if ($createdText === '') {
  10916. $createdText = trim((string)($r['dStamp'] ?? ''));
  10917. }
  10918. $notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
  10919. $supplier = trim((string)($r['cGzzxMc'] ?? ''));
  10920. if ($supplier === '') {
  10921. $supplier = trim((string)($r['pick_company_name'] ?? ''));
  10922. }
  10923. $hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
  10924. || isset($issuedSidSet[$sid]);
  10925. $hasQuoted = isset($quotedSidSet[$sid]);
  10926. $salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
  10927. $canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
  10928. $out[] = [
  10929. 'id' => (int)($r['id'] ?? 0),
  10930. 'scydgy_id' => $sid,
  10931. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  10932. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  10933. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  10934. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  10935. 'CDW' => trim((string)($r['CDW'] ?? '')),
  10936. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  10937. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  10938. 'CDF' => trim((string)($r['CDF'] ?? '')),
  10939. 'supplier_name' => $supplier,
  10940. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  10941. 'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
  10942. 'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
  10943. 'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
  10944. 'notify_time_text' => $notifyTimeText,
  10945. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  10946. 'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
  10947. 'has_issued' => $hasIssued ? 1 : 0,
  10948. 'has_quoted' => $hasQuoted ? 1 : 0,
  10949. 'can_notify_salesman' => $canNotifySalesman,
  10950. 'createtime' => $r['createtime'] ?? null,
  10951. 'createtime_text' => $createdText,
  10952. ];
  10953. }
  10954. return json(['total' => $total, 'rows' => $out]);
  10955. } catch (\Throwable $e) {
  10956. Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
  10957. return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
  10958. }
  10959. }
  10960. $sidebar = $this->loadRfqSidebarYearMonths();
  10961. $defaultYm = $this->resolveRfqListDefaultYm($sidebar);
  10962. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  10963. [, $adminName] = $this->GetUseName();
  10964. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  10965. $this->view->assign('adminNickname', $adminName);
  10966. $this->view->assign('defaultYm', $defaultYm);
  10967. $this->view->assign('sidebarYearMonths', $sidebar);
  10968. return $this->view->fetch('procuremen/rfqlist');
  10969. }
  10970. /**
  10971. * 列表默认月份:当月有数据用当月,否则取最近有数据的月份
  10972. *
  10973. * @param array<int, array{year:string, months:array}> $sidebar
  10974. */
  10975. protected function resolveRfqListDefaultYm(array $sidebar): string
  10976. {
  10977. $current = date('Y-m');
  10978. $yms = $this->flattenProcuremenSidebarYms($sidebar);
  10979. if (in_array($current, $yms, true)) {
  10980. return $current;
  10981. }
  10982. if ($yms !== []) {
  10983. rsort($yms, SORT_STRING);
  10984. return (string)$yms[0];
  10985. }
  10986. return $current;
  10987. }
  10988. /**
  10989. * 手工询价列表左侧月份(按 createtime / dStamp)
  10990. *
  10991. * @return array<int, array{year:string, months:array}>
  10992. */
  10993. protected function loadRfqSidebarYearMonths(): array
  10994. {
  10995. $ymSet = [];
  10996. try {
  10997. $q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
  10998. $this->applyPurchaseOrderNotDeletedWhere($q);
  10999. $rows = $q->field('createtime,dStamp')->limit(5000)->select();
  11000. } catch (\Throwable $e) {
  11001. $rows = [];
  11002. }
  11003. if (!is_array($rows)) {
  11004. $rows = [];
  11005. }
  11006. foreach ($rows as $r) {
  11007. if (!is_array($r)) {
  11008. continue;
  11009. }
  11010. $t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  11011. if ($t === '') {
  11012. $t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
  11013. }
  11014. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  11015. $ymSet[$m[1] . '-' . $m[2]] = true;
  11016. }
  11017. }
  11018. return $this->buildYearMonthSidebar(array_keys($ymSet));
  11019. }
  11020. /**
  11021. * 手工询价可见范围(用于详情/操作校验):
  11022. * 超管、具备「查询询价」权限、需求发起人、通知业务员 → 可见
  11023. * 列表页本身不再按发起人/通知过滤,避免手机端新增后后台看不到。
  11024. */
  11025. protected function applyManualRfqViewerWhere($query): void
  11026. {
  11027. if ($this->auth->isSuperAdmin() || $this->hasProcuremenPerm(['rfqlist'])) {
  11028. return;
  11029. }
  11030. [, $adminName] = $this->GetUseName();
  11031. $adminName = trim((string)$adminName);
  11032. if ($adminName === '') {
  11033. $query->whereRaw('1 = 0');
  11034. return;
  11035. }
  11036. // 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
  11037. $query->where(function ($q) use ($adminName) {
  11038. $q->where('cywyxm', $adminName)
  11039. ->whereOr('notify_salesman', $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. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  11045. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  11046. });
  11047. }
  11048. /**
  11049. * 当前用户是否可查看/操作该手工询价单
  11050. */
  11051. protected function canViewManualRfqOrder(array $po): bool
  11052. {
  11053. if ($this->auth->isSuperAdmin()) {
  11054. return true;
  11055. }
  11056. // 有查询询价权限则可操作全部手工询价(询价/查看报价/通知业务员等)
  11057. if ($this->hasProcuremenPerm(['rfqlist'])) {
  11058. return true;
  11059. }
  11060. [, $adminName] = $this->GetUseName();
  11061. $adminName = trim((string)$adminName);
  11062. if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
  11063. return true;
  11064. }
  11065. if ($adminName !== '') {
  11066. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  11067. if ($n === $adminName) {
  11068. return true;
  11069. }
  11070. }
  11071. }
  11072. return false;
  11073. }
  11074. /**
  11075. * 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
  11076. */
  11077. protected function applyRfqListMonthFilter($query, string $ym): void
  11078. {
  11079. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  11080. $ym = date('Y-m');
  11081. }
  11082. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  11083. // 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
  11084. $query->whereRaw(
  11085. "("
  11086. . "CASE "
  11087. . "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  11088. . "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
  11089. . "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
  11090. . "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  11091. . "THEN TRIM(CAST(createtime AS CHAR(32))) "
  11092. . "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
  11093. . "END"
  11094. . ") LIKE '{$ymEsc}-%'"
  11095. );
  11096. }
  11097. /**
  11098. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  11099. */
  11100. public function rfqlistDetails()
  11101. {
  11102. return $this->details();
  11103. }
  11104. /**
  11105. * 查询询价 — 弹窗:可选通知业务员名单(勾选后确认通知)
  11106. */
  11107. public function rfqnotifysalesmen()
  11108. {
  11109. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman'])) {
  11110. $this->error(__('You have no permission'));
  11111. }
  11112. $this->ensurePurchaseOrderNotifySalesmanColumn();
  11113. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  11114. $sid = (int)$this->request->param('scydgy_id', 0);
  11115. if ($sid >= 0) {
  11116. $this->error('仅支持手工新增询价单');
  11117. }
  11118. $po = $this->loadManualRfqOrderForNotify($sid);
  11119. $selectedMap = [];
  11120. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  11121. $selectedMap[$n] = true;
  11122. }
  11123. $list = [];
  11124. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  11125. $name = trim((string)($row['name'] ?? ''));
  11126. if ($name === '') {
  11127. continue;
  11128. }
  11129. $email = trim((string)($row['email'] ?? ''));
  11130. $mobile = trim((string)($row['mobile'] ?? ''));
  11131. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  11132. $list[] = [
  11133. 'name' => $name,
  11134. 'email' => $email,
  11135. 'mobile' => $mobile,
  11136. 'can_select' => $hasEmail ? 1 : 0,
  11137. 'checked' => (!empty($selectedMap[$name]) && $hasEmail) ? 1 : 0,
  11138. ];
  11139. }
  11140. $canNotify = $this->canRfqNotifySalesman($po);
  11141. $this->success('', null, [
  11142. 'scydgy_id' => $sid,
  11143. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  11144. 'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
  11145. 'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
  11146. 'can_notify_salesman' => $canNotify ? 1 : 0,
  11147. 'list' => $list,
  11148. ]);
  11149. }
  11150. /**
  11151. * 查询询价 — 补加通知业务员可选名单
  11152. */
  11153. public function rfqsalesmanoptions()
  11154. {
  11155. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen'])) {
  11156. $this->error(__('You have no permission'));
  11157. }
  11158. $out = [];
  11159. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  11160. $email = trim((string)($row['email'] ?? ''));
  11161. $mobile = trim((string)($row['mobile'] ?? ''));
  11162. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  11163. $out[] = [
  11164. 'name' => (string)($row['name'] ?? ''),
  11165. 'email' => $email,
  11166. 'mobile' => $mobile,
  11167. 'can_select' => $hasEmail ? 1 : 0,
  11168. ];
  11169. }
  11170. $this->success('', null, ['list' => $out]);
  11171. }
  11172. /**
  11173. * 查询询价 — 补加通知业务员(合并更新 notify_salesman)
  11174. */
  11175. public function rfqappendsalesmen()
  11176. {
  11177. if (!$this->request->isPost()) {
  11178. $this->error(__('Invalid parameters'));
  11179. }
  11180. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen'])) {
  11181. $this->error(__('You have no permission'));
  11182. }
  11183. $this->ensurePurchaseOrderNotifySalesmanColumn();
  11184. $sid = (int)$this->request->post('scydgy_id', 0);
  11185. if ($sid >= 0) {
  11186. $this->error('仅支持手工新增询价单');
  11187. }
  11188. $po = $this->loadManualRfqOrderForNotify($sid);
  11189. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  11190. $this->error('订单已完结,无法添加业务员');
  11191. }
  11192. $raw = $this->request->post('salesmen/a', []);
  11193. if (!is_array($raw) || $raw === []) {
  11194. $salesmenJson = $this->request->post('salesmen_json', '');
  11195. if (is_string($salesmenJson) && $salesmenJson !== '') {
  11196. $decoded = json_decode($salesmenJson, true);
  11197. $raw = is_array($decoded) ? $decoded : [];
  11198. }
  11199. }
  11200. $addNames = [];
  11201. foreach ((array)$raw as $item) {
  11202. if (is_array($item)) {
  11203. $n = trim((string)($item['name'] ?? ''));
  11204. } else {
  11205. $n = trim((string)$item);
  11206. }
  11207. if ($n !== '') {
  11208. $addNames[] = $n;
  11209. }
  11210. }
  11211. $addNames = array_values(array_unique($addNames));
  11212. if ($addNames === []) {
  11213. $this->error('请选择要添加的业务员');
  11214. }
  11215. $allowedOptions = $this->loadRfqSalesmanContactOptions();
  11216. $allowedMap = [];
  11217. foreach ($allowedOptions as $opt) {
  11218. $n = trim((string)($opt['name'] ?? ''));
  11219. if ($n === '') {
  11220. continue;
  11221. }
  11222. $email = trim((string)($opt['email'] ?? ''));
  11223. $allowedMap[$n] = ($email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL));
  11224. }
  11225. foreach ($addNames as $n) {
  11226. if (!array_key_exists($n, $allowedMap)) {
  11227. $this->error('业务员不在可选名单中:' . $n);
  11228. }
  11229. if (!$allowedMap[$n]) {
  11230. $this->error('业务员未填写有效邮箱,无法添加:' . $n);
  11231. }
  11232. }
  11233. $existingRaw = trim((string)($po['notify_salesman'] ?? ''));
  11234. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  11235. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  11236. try {
  11237. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['notify_salesman' => $mergedStr]);
  11238. } catch (\Throwable $e) {
  11239. $this->error('保存失败:' . $e->getMessage());
  11240. }
  11241. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11242. $this->addOrderLog($sid, 'rfq_append_salesman', '添加通知业务员:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  11243. $this->success('已添加业务员', null, [
  11244. 'scydgy_id' => $sid,
  11245. 'notify_salesman' => $mergedStr,
  11246. 'added_count' => count($addNames),
  11247. ]);
  11248. }
  11249. /**
  11250. * 查询询价 — 勾选业务员后邮箱通知(salesmen_json)
  11251. */
  11252. public function rfqnotifysalesman()
  11253. {
  11254. if (!$this->request->isPost()) {
  11255. $this->error(__('Invalid parameters'));
  11256. }
  11257. if (!$this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen'])) {
  11258. $this->error(__('You have no permission'));
  11259. }
  11260. $this->ensurePurchaseOrderNotifySalesmanColumn();
  11261. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  11262. $sid = (int)$this->request->post('scydgy_id', 0);
  11263. if ($sid >= 0) {
  11264. $this->error('仅支持手工新增询价单');
  11265. }
  11266. $po = $this->loadManualRfqOrderForNotify($sid);
  11267. $this->assertRfqCanNotifySalesman($po);
  11268. $raw = $this->request->post('salesmen/a', []);
  11269. if (!is_array($raw) || $raw === []) {
  11270. $salesmenJson = $this->request->post('salesmen_json', '');
  11271. if (is_string($salesmenJson) && $salesmenJson !== '') {
  11272. $decoded = json_decode($salesmenJson, true);
  11273. $raw = is_array($decoded) ? $decoded : [];
  11274. }
  11275. }
  11276. // 兼容旧参数:notify_all / 单人 name
  11277. if ((!is_array($raw) || $raw === []) && (int)$this->request->post('notify_all', 0) === 1) {
  11278. $raw = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  11279. }
  11280. if ((!is_array($raw) || $raw === [])) {
  11281. $oneName = trim((string)$this->request->post('name', ''));
  11282. if ($oneName !== '') {
  11283. $raw = [$oneName];
  11284. }
  11285. }
  11286. $selectedNames = [];
  11287. foreach ((array)$raw as $item) {
  11288. if (is_array($item)) {
  11289. $n = trim((string)($item['name'] ?? ''));
  11290. } else {
  11291. $n = trim((string)$item);
  11292. }
  11293. if ($n !== '') {
  11294. $selectedNames[] = $n;
  11295. }
  11296. }
  11297. $selectedNames = array_values(array_unique($selectedNames));
  11298. if ($selectedNames === []) {
  11299. $this->error('请选择要通知的业务员');
  11300. }
  11301. $optionMap = [];
  11302. foreach ($this->loadRfqSalesmanContactOptions() as $opt) {
  11303. $n = trim((string)($opt['name'] ?? ''));
  11304. if ($n === '') {
  11305. continue;
  11306. }
  11307. $optionMap[$n] = $opt;
  11308. }
  11309. $targets = [];
  11310. foreach ($selectedNames as $n) {
  11311. if (!isset($optionMap[$n])) {
  11312. $this->error('业务员不在可选名单中:' . $n);
  11313. }
  11314. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  11315. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  11316. $this->error('业务员未填写有效邮箱,无法通知:' . $n);
  11317. }
  11318. $resolved = $this->resolveRfqSalesmanContactRows([$n]);
  11319. $targets[] = $resolved[0] ?? [
  11320. 'admin_id' => 0,
  11321. 'name' => $n,
  11322. 'email' => $email,
  11323. ];
  11324. }
  11325. $mergedStr = $this->joinRfqMultiSelectValues($selectedNames);
  11326. try {
  11327. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11328. 'notify_salesman' => $mergedStr,
  11329. ]);
  11330. } catch (\Throwable $e) {
  11331. $this->error('保存通知业务员失败:' . $e->getMessage());
  11332. }
  11333. $po['notify_salesman'] = $mergedStr;
  11334. $mailConfig = $this->loadMailerConfig();
  11335. if (empty($mailConfig['host'])) {
  11336. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  11337. }
  11338. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  11339. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  11340. }
  11341. $this->ensureRfqSalesmanEmailTemplate();
  11342. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  11343. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  11344. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  11345. $cdw = trim((string)($po['CDW'] ?? ''));
  11346. $qty = trim((string)$this->resolveProcuremenThisQuantity($po));
  11347. $ceiling = trim((string)$this->resolveProcuremenCeilingPrice($po));
  11348. $mbz = trim((string)($po['MBZ'] ?? ''));
  11349. $cywyxm = trim((string)($po['cywyxm'] ?? ''));
  11350. $supplier = trim((string)($po['cGzzxMc'] ?? ''));
  11351. if ($supplier === '') {
  11352. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  11353. }
  11354. $supplierQuotesHtml = $this->buildRfqSalesmanSupplierQuotesHtml($sid, $supplier);
  11355. try {
  11356. $platformUrl = $this->buildMprocMobileRfqAddUrl($sid, 'pending');
  11357. } catch (\Throwable $e) {
  11358. $platformUrl = '';
  11359. }
  11360. try {
  11361. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
  11362. } catch (\Throwable $e) {
  11363. $this->error($e->getMessage());
  11364. }
  11365. $okNames = [];
  11366. $failMsgs = [];
  11367. foreach ($targets as $contact) {
  11368. $toEmail = trim((string)($contact['email'] ?? ''));
  11369. $toName = trim((string)($contact['name'] ?? ''));
  11370. $notifyVars = [
  11371. 'contact_name' => $toName,
  11372. 'salesman_name' => $toName,
  11373. 'company_name' => $toName,
  11374. 'email' => $toEmail,
  11375. 'ccydh' => $ccydh,
  11376. 'cyjmc' => $cyjmc,
  11377. 'cgymc' => $cgymc,
  11378. 'cdw' => $cdw,
  11379. 'this_quantity' => $qty,
  11380. 'ceilingPrice' => $ceiling,
  11381. 'MBZ' => $mbz,
  11382. 'supplier_name' => $supplier,
  11383. // 占位符,转 HTML 后再替换成表格,避免被 htmlspecialchars 转义
  11384. 'supplier_quotes' => '__RFQ_SUPPLIER_QUOTES_TABLE__',
  11385. 'cywyxm' => $cywyxm,
  11386. 'platform_url' => $platformUrl,
  11387. ];
  11388. try {
  11389. $mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
  11390. $mailSubject = $mailSubjectTpl;
  11391. foreach ($notifyVars as $k => $v) {
  11392. if ($k === 'supplier_quotes') {
  11393. continue;
  11394. }
  11395. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  11396. }
  11397. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  11398. $mailSubject = trim((string)$mailSubject);
  11399. if ($mailSubject === '') {
  11400. $mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  11401. }
  11402. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  11403. $mailBody = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', $supplierQuotesHtml, $mailBody);
  11404. $mailPlainForLog = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', strip_tags(str_replace(['</tr>', '</p>'], "\n", $supplierQuotesHtml)), $mailPlain);
  11405. $bundle = [
  11406. 'company_name' => $toName,
  11407. 'email' => $toEmail,
  11408. 'mail_plain' => $mailPlainForLog,
  11409. 'mail_body' => $mailBody,
  11410. 'ccydh' => $ccydh,
  11411. 'email_log_scene' => 'rfq_salesman',
  11412. 'email_log_scydgy_id' => $sid,
  11413. 'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
  11414. 'email_log_ccydh' => $ccydh,
  11415. 'email_log_order_batch_no' => $this->resolveProcuremenOrderBatchNo(is_array($po) ? $po : []),
  11416. 'notify_vars' => $notifyVars,
  11417. ];
  11418. $this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
  11419. $okNames[] = $toName . '(' . $toEmail . ')';
  11420. } catch (\Throwable $e) {
  11421. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  11422. }
  11423. }
  11424. if ($okNames === []) {
  11425. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  11426. }
  11427. $now = date('Y-m-d H:i:s');
  11428. try {
  11429. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11430. 'rfq_salesman_notified' => 1,
  11431. 'rfq_salesman_notify_time' => $now,
  11432. ]);
  11433. } catch (\Throwable $e) {
  11434. // ignore
  11435. }
  11436. $this->addOrderLog(
  11437. $sid,
  11438. 'rfq_notify_salesman',
  11439. '邮箱通知业务员:' . implode('、', $okNames),
  11440. (int)($po['id'] ?? 0)
  11441. );
  11442. $msg = '已通知 ' . count($okNames) . ' 人';
  11443. if ($failMsgs !== []) {
  11444. $msg .= ';部分失败:' . implode(';', $failMsgs);
  11445. }
  11446. $this->success($msg, null, [
  11447. 'scydgy_id' => $sid,
  11448. 'notify_salesman' => $mergedStr,
  11449. 'rfq_salesman_notified' => 1,
  11450. 'rfq_salesman_notify_time' => $now,
  11451. 'notify_time_text' => $now,
  11452. 'ok_count' => count($okNames),
  11453. 'fail_count' => count($failMsgs),
  11454. ]);
  11455. }
  11456. /**
  11457. * 生产部角色组 id(mproc.mobile_delivery_group_id,缺省按组名「生产部/生产员」查找)
  11458. */
  11459. protected function deliveryNotifyAuthGroupId(): int
  11460. {
  11461. static $mprocCfgLoaded = false;
  11462. if (!$mprocCfgLoaded) {
  11463. $mprocCfgLoaded = true;
  11464. if (is_file(APP_PATH . 'extra/mproc.php')) {
  11465. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  11466. }
  11467. }
  11468. $id = (int)Config::get('mproc.mobile_delivery_group_id');
  11469. if ($id > 0) {
  11470. return $id;
  11471. }
  11472. try {
  11473. foreach (['生产部', '生产员'] as $name) {
  11474. $gid = (int)Db::name('auth_group')->where('name', $name)->value('id');
  11475. if ($gid > 0) {
  11476. return $gid;
  11477. }
  11478. }
  11479. } catch (\Throwable $e) {
  11480. }
  11481. return 0;
  11482. }
  11483. /**
  11484. * 生产部人员:姓名、邮箱、手机
  11485. *
  11486. * @return array<int, array{name:string,email:string,mobile:string,admin_id:int}>
  11487. */
  11488. protected function loadDeliveryStaffContactOptions(): array
  11489. {
  11490. $out = [];
  11491. $seen = [];
  11492. $groupId = $this->deliveryNotifyAuthGroupId();
  11493. if ($groupId <= 0) {
  11494. return [];
  11495. }
  11496. try {
  11497. $adminIds = Db::name('auth_group_access')
  11498. ->where('group_id', $groupId)
  11499. ->column('uid');
  11500. } catch (\Throwable $e) {
  11501. return [];
  11502. }
  11503. $adminIds = is_array($adminIds)
  11504. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  11505. : [];
  11506. if ($adminIds === []) {
  11507. return [];
  11508. }
  11509. try {
  11510. $rows = Db::name('admin')
  11511. ->where('status', 'normal')
  11512. ->where('id', 'in', $adminIds)
  11513. ->order('id', 'asc')
  11514. ->field('id,nickname,username,email,mobile')
  11515. ->select();
  11516. } catch (\Throwable $e) {
  11517. return [];
  11518. }
  11519. if (!is_array($rows)) {
  11520. return [];
  11521. }
  11522. foreach ($rows as $row) {
  11523. if (!is_array($row)) {
  11524. continue;
  11525. }
  11526. $name = trim((string)($row['nickname'] ?? ''));
  11527. if ($name === '') {
  11528. $name = trim((string)($row['username'] ?? ''));
  11529. }
  11530. if ($name === '' || isset($seen[$name])) {
  11531. continue;
  11532. }
  11533. $seen[$name] = true;
  11534. $out[] = [
  11535. 'admin_id' => (int)($row['id'] ?? 0),
  11536. 'name' => $name,
  11537. 'email' => trim((string)($row['email'] ?? '')),
  11538. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  11539. ];
  11540. }
  11541. return $out;
  11542. }
  11543. /**
  11544. * 交货情况页直达链接(邮件用,单参数避免邮箱客户端拆坏)
  11545. */
  11546. protected function buildMprocMobileDeliveryscoreUrl(string $ccydh): string
  11547. {
  11548. static $mprocCfgLoaded = false;
  11549. if (!$mprocCfgLoaded) {
  11550. $mprocCfgLoaded = true;
  11551. if (is_file(APP_PATH . 'extra/mproc.php')) {
  11552. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  11553. }
  11554. }
  11555. $base = $this->resolveMprocMobilePublicBaseUrl();
  11556. if ($base === '') {
  11557. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  11558. }
  11559. $path = '/index.php/index/index/deliveryscore';
  11560. $ccydh = trim($ccydh);
  11561. if ($ccydh === '') {
  11562. return $base . $path;
  11563. }
  11564. return $base . $path . '?ccydh=' . rawurlencode($ccydh);
  11565. }
  11566. /**
  11567. * 按订单号取已审核外发单(合并工序字段)
  11568. *
  11569. * @return array<string, mixed>|null
  11570. */
  11571. protected function loadApprovedOrderForDeliveryNotify(string $ccydh, int $sid = 0): ?array
  11572. {
  11573. $ccydh = trim($ccydh);
  11574. if ($ccydh === '' && $sid > 0) {
  11575. try {
  11576. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
  11577. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  11578. } catch (\Throwable $e) {
  11579. $ccydh = '';
  11580. }
  11581. }
  11582. if ($ccydh === '') {
  11583. return null;
  11584. }
  11585. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  11586. $approvedIn = implode(',', array_map(static function ($v) {
  11587. return "'" . str_replace("'", "''", (string)$v) . "'";
  11588. }, $approvedVals));
  11589. try {
  11590. $rows = Db::table('purchase_order')
  11591. ->where('CCYDH', $ccydh)
  11592. ->where('scydgy_id', '>', 0)
  11593. ->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%\')')
  11594. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  11595. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  11596. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,CDW,This_quantity,NGZL,pick_company_name,delivery_deadline,MBZ,cywyxm,wflow_status,status')
  11597. ->order('id', 'asc')
  11598. ->select();
  11599. } catch (\Throwable $e) {
  11600. $rows = [];
  11601. }
  11602. if (!is_array($rows) || $rows === []) {
  11603. return null;
  11604. }
  11605. $gymc = [];
  11606. $qty = [];
  11607. $first = null;
  11608. foreach ($rows as $r) {
  11609. if (!is_array($r)) {
  11610. continue;
  11611. }
  11612. if ($first === null) {
  11613. $first = $r;
  11614. }
  11615. $g = trim((string)($r['CGYMC'] ?? ''));
  11616. if ($g !== '' && !in_array($g, $gymc, true)) {
  11617. $gymc[] = $g;
  11618. }
  11619. $q = trim((string)$this->resolveProcuremenThisQuantity($r));
  11620. if ($q !== '' && !in_array($q, $qty, true)) {
  11621. $qty[] = $q;
  11622. }
  11623. }
  11624. if (!is_array($first)) {
  11625. return null;
  11626. }
  11627. $first['CGYMC'] = $gymc !== [] ? implode('、', $gymc) : '';
  11628. $first['This_quantity'] = $qty !== [] ? implode('、', $qty) : '';
  11629. $first['delivery_deadline'] = $this->mprocFormatYmdForNotify($first['delivery_deadline'] ?? '');
  11630. return $first;
  11631. }
  11632. protected function mprocFormatYmdForNotify($raw): string
  11633. {
  11634. return ProcuremenFormat::mprocYmdForNotify($raw);
  11635. }
  11636. /**
  11637. * 确保「交货情况通知生产部-邮箱」模版存在
  11638. */
  11639. protected function ensureDeliveryNotifyEmailTemplate(): void
  11640. {
  11641. static $done = false;
  11642. if ($done) {
  11643. return;
  11644. }
  11645. $done = true;
  11646. $content = "您好,{contact_name}:\n\n"
  11647. . "有订单已中标外发,需要您在手机端确认交货情况(填写库位、交货情况、交货日期等)。\n\n"
  11648. . "订单号:{ccydh}\n"
  11649. . "印件名称:{cyjmc}\n"
  11650. . "工序名称:{cgymc}\n"
  11651. . "订单数量:{this_quantity}\n"
  11652. . "中标供应商:{supplier_name}\n"
  11653. . "交货截止日期:{delivery_deadline}\n\n"
  11654. . "请点击下方链接登录后,找到该订单进行填写:\n"
  11655. . "{platform_url}\n";
  11656. try {
  11657. $row = Db::table('purchase_sms_template')
  11658. ->where('scene', 'delivery_notify_email')
  11659. ->find();
  11660. } catch (\Throwable $e) {
  11661. return;
  11662. }
  11663. $now = date('Y-m-d H:i:s');
  11664. if (is_array($row) && $row !== []) {
  11665. return;
  11666. }
  11667. try {
  11668. $data = [
  11669. 'scene' => 'delivery_notify_email',
  11670. 'title' => '交货情况确认通知 - {ccydh}',
  11671. 'content' => $content,
  11672. 'remark' => '审批通过后通知生产部填写交货情况;模版名称作邮件主题,支持变量',
  11673. 'status' => 1,
  11674. ];
  11675. try {
  11676. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  11677. } catch (\Throwable $e) {
  11678. $cols = [];
  11679. }
  11680. $colNames = [];
  11681. foreach ($cols as $c) {
  11682. if (!is_array($c)) {
  11683. continue;
  11684. }
  11685. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  11686. if ($n !== '') {
  11687. $colNames[$n] = true;
  11688. }
  11689. }
  11690. if (isset($colNames['updatetime'])) {
  11691. $data['updatetime'] = $now;
  11692. }
  11693. if (isset($colNames['createtime'])) {
  11694. $data['createtime'] = $now;
  11695. }
  11696. Db::table('purchase_sms_template')->insert($data);
  11697. } catch (\Throwable $e) {
  11698. // ignore
  11699. }
  11700. }
  11701. /**
  11702. * 通知生产部 — 可选人员名单
  11703. */
  11704. public function deliverynotifymen()
  11705. {
  11706. if (!$this->hasProcuremenPerm(['deliverynotifymen', 'deliverynotify', 'outward_detail', 'outwarddetail', 'purchaseconfirmpick', 'details'])) {
  11707. $this->error(__('You have no permission'));
  11708. }
  11709. $this->ensureDeliveryNotifyEmailTemplate();
  11710. $sid = (int)$this->request->request('scydgy_id', 0);
  11711. $ccydh = trim((string)$this->request->request('ccydh', ''));
  11712. $po = $this->loadApprovedOrderForDeliveryNotify($ccydh, $sid);
  11713. if ($po === null) {
  11714. $this->error('未找到已审核且已中标的订单,无法通知生产部');
  11715. }
  11716. $list = [];
  11717. foreach ($this->loadDeliveryStaffContactOptions() as $opt) {
  11718. $email = trim((string)($opt['email'] ?? ''));
  11719. $list[] = [
  11720. 'name' => (string)($opt['name'] ?? ''),
  11721. 'email' => $email,
  11722. 'mobile' => (string)($opt['mobile'] ?? ''),
  11723. 'can_select' => ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) ? 1 : 0,
  11724. 'checked' => 0,
  11725. ];
  11726. }
  11727. $this->success('', null, [
  11728. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  11729. 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
  11730. 'cgymc' => trim((string)($po['CGYMC'] ?? '')),
  11731. 'this_quantity' => trim((string)($po['This_quantity'] ?? '')),
  11732. 'supplier_name' => trim((string)($po['pick_company_name'] ?? '')),
  11733. 'delivery_deadline' => trim((string)($po['delivery_deadline'] ?? '')),
  11734. 'list' => $list,
  11735. ]);
  11736. }
  11737. /**
  11738. * 通知生产部 — 勾选后发邮件(staff_json / names)
  11739. */
  11740. public function deliverynotify()
  11741. {
  11742. if (!$this->request->isPost()) {
  11743. $this->error(__('Invalid parameters'));
  11744. }
  11745. if (!$this->hasProcuremenPerm(['deliverynotify', 'deliverynotifymen', 'outward_detail', 'outwarddetail', 'purchaseconfirmpick', 'details'])) {
  11746. $this->error(__('You have no permission'));
  11747. }
  11748. $this->ensureDeliveryNotifyEmailTemplate();
  11749. $sid = (int)$this->request->post('scydgy_id', 0);
  11750. $ccydh = trim((string)$this->request->post('ccydh', ''));
  11751. $po = $this->loadApprovedOrderForDeliveryNotify($ccydh, $sid);
  11752. if ($po === null) {
  11753. $this->error('未找到已审核且已中标的订单,无法通知生产部');
  11754. }
  11755. $ccydh = trim((string)($po['CCYDH'] ?? $ccydh));
  11756. $raw = $this->request->post('staff/a', []);
  11757. if (!is_array($raw) || $raw === []) {
  11758. $staffJson = $this->request->post('staff_json', '');
  11759. if (is_string($staffJson) && $staffJson !== '') {
  11760. $decoded = json_decode($staffJson, true);
  11761. $raw = is_array($decoded) ? $decoded : [];
  11762. }
  11763. }
  11764. $selectedNames = [];
  11765. foreach ((array)$raw as $item) {
  11766. if (is_array($item)) {
  11767. $n = trim((string)($item['name'] ?? ''));
  11768. } else {
  11769. $n = trim((string)$item);
  11770. }
  11771. if ($n !== '') {
  11772. $selectedNames[] = $n;
  11773. }
  11774. }
  11775. $selectedNames = array_values(array_unique($selectedNames));
  11776. if ($selectedNames === []) {
  11777. $this->error('请选择要通知的生产部人员');
  11778. }
  11779. $optionMap = [];
  11780. foreach ($this->loadDeliveryStaffContactOptions() as $opt) {
  11781. $n = trim((string)($opt['name'] ?? ''));
  11782. if ($n === '') {
  11783. continue;
  11784. }
  11785. $optionMap[$n] = $opt;
  11786. }
  11787. $targets = [];
  11788. foreach ($selectedNames as $n) {
  11789. if (!isset($optionMap[$n])) {
  11790. $this->error('人员不在生产部可选名单中:' . $n);
  11791. }
  11792. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  11793. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  11794. $this->error('未填写有效邮箱,无法通知:' . $n);
  11795. }
  11796. $targets[] = $optionMap[$n];
  11797. }
  11798. $mailConfig = $this->loadMailerConfig();
  11799. if (empty($mailConfig['host'])) {
  11800. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  11801. }
  11802. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  11803. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  11804. }
  11805. try {
  11806. $platformUrl = $this->buildMprocMobileDeliveryscoreUrl($ccydh);
  11807. } catch (\Throwable $e) {
  11808. $this->error($e->getMessage());
  11809. }
  11810. try {
  11811. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('delivery_notify_email');
  11812. } catch (\Throwable $e) {
  11813. $this->error($e->getMessage());
  11814. }
  11815. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  11816. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  11817. $qty = trim((string)($po['This_quantity'] ?? ''));
  11818. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  11819. $deadline = trim((string)($po['delivery_deadline'] ?? ''));
  11820. $firstSid = (int)($po['scydgy_id'] ?? 0);
  11821. $firstPoId = (int)($po['id'] ?? 0);
  11822. $okNames = [];
  11823. $failMsgs = [];
  11824. foreach ($targets as $contact) {
  11825. $toEmail = trim((string)($contact['email'] ?? ''));
  11826. $toName = trim((string)($contact['name'] ?? ''));
  11827. $notifyVars = [
  11828. 'contact_name' => $toName,
  11829. 'company_name' => $toName,
  11830. 'email' => $toEmail,
  11831. 'ccydh' => $ccydh,
  11832. 'cyjmc' => $cyjmc,
  11833. 'cgymc' => $cgymc,
  11834. 'this_quantity' => $qty,
  11835. 'supplier_name' => $supplier,
  11836. 'delivery_deadline' => $deadline,
  11837. 'platform_url' => $platformUrl,
  11838. ];
  11839. try {
  11840. $mailPlain = $this->renderNotifyTemplate('delivery_notify_email', $notifyVars);
  11841. $mailSubject = $mailSubjectTpl;
  11842. foreach ($notifyVars as $k => $v) {
  11843. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  11844. }
  11845. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  11846. $mailSubject = trim((string)$mailSubject);
  11847. if ($mailSubject === '') {
  11848. $mailSubject = '交货情况确认通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  11849. }
  11850. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  11851. $this->issueSendSupplierEmail([
  11852. 'company_name' => $toName,
  11853. 'email' => $toEmail,
  11854. 'mail_plain' => $mailPlain,
  11855. 'mail_body' => $mailBody,
  11856. 'ccydh' => $ccydh,
  11857. 'email_log_scene' => 'delivery_notify',
  11858. 'email_log_scydgy_id' => $firstSid,
  11859. 'email_log_purchase_order_id' => $firstPoId,
  11860. 'email_log_ccydh' => $ccydh,
  11861. 'email_log_order_batch_no' => $this->resolveProcuremenOrderBatchNo(is_array($po) ? $po : []),
  11862. 'notify_vars' => $notifyVars,
  11863. ], $mailConfig, $mailSubject);
  11864. $okNames[] = $toName . '(' . $toEmail . ')';
  11865. } catch (\Throwable $e) {
  11866. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  11867. }
  11868. }
  11869. if ($okNames === []) {
  11870. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  11871. }
  11872. if ($firstSid > 0) {
  11873. $this->addOrderLog(
  11874. $firstSid,
  11875. 'delivery_notify',
  11876. '邮箱通知生产部:' . implode('、', $okNames),
  11877. $firstPoId > 0 ? $firstPoId : null
  11878. );
  11879. }
  11880. $msg = '已通知 ' . count($okNames) . ' 人';
  11881. if ($failMsgs !== []) {
  11882. $msg .= ';部分失败:' . implode(';', $failMsgs);
  11883. }
  11884. $this->success($msg, null, [
  11885. 'ccydh' => $ccydh,
  11886. 'ok_count' => count($okNames),
  11887. 'fail_count'=> count($failMsgs),
  11888. 'platform_url' => $platformUrl,
  11889. ]);
  11890. }
  11891. /**
  11892. * 查询询价 — 下发前:返回将通知的供应商表格数据
  11893. */
  11894. public function rfqissuesuppliers()
  11895. {
  11896. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers'])) {
  11897. $this->error(__('You have no permission'));
  11898. }
  11899. $sid = (int)$this->request->param('scydgy_id', 0);
  11900. if ($sid >= 0) {
  11901. $this->error('仅支持手工新增询价单');
  11902. }
  11903. $po = $this->loadManualRfqOrderForNotify($sid);
  11904. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  11905. if ($supplierRaw === '') {
  11906. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  11907. }
  11908. $names = $this->splitRfqSalesmanNames($supplierRaw);
  11909. // 已成功发过询价邮件的供应商(含历史 pick_issue 场景)
  11910. $notifiedMap = [];
  11911. try {
  11912. $this->ensurePurchaseEmailSendLogTableOnce();
  11913. $logRows = Db::table('purchase_email_send_log')
  11914. ->where('scydgy_id', $sid)
  11915. ->where('status', 1)
  11916. ->where('scene', 'in', [
  11917. 'rfq_supplier', 'pick_issue',
  11918. '供应商询价通知', '初选下发',
  11919. ])
  11920. ->field('company_name')
  11921. ->select();
  11922. if (is_array($logRows)) {
  11923. foreach ($logRows as $lr) {
  11924. if (!is_array($lr)) {
  11925. continue;
  11926. }
  11927. $cn = trim((string)($lr['company_name'] ?? ''));
  11928. if ($cn !== '') {
  11929. $notifiedMap[$cn] = true;
  11930. }
  11931. }
  11932. }
  11933. } catch (\Throwable $e) {
  11934. }
  11935. // 兼容:明细已生成(曾下发)也视为已通知
  11936. try {
  11937. $detRows = Db::table('purchase_order_detail')
  11938. ->where('scydgy_id', $sid)
  11939. ->field('company_name')
  11940. ->select();
  11941. if (is_array($detRows)) {
  11942. foreach ($detRows as $dr) {
  11943. if (!is_array($dr)) {
  11944. continue;
  11945. }
  11946. $cn = trim((string)($dr['company_name'] ?? ''));
  11947. if ($cn !== '') {
  11948. $notifiedMap[$cn] = true;
  11949. }
  11950. }
  11951. }
  11952. } catch (\Throwable $e) {
  11953. }
  11954. $list = [];
  11955. foreach ($names as $name) {
  11956. // 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
  11957. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  11958. $email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
  11959. $phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
  11960. $username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
  11961. $okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
  11962. $notified = !empty($notifiedMap[$name]) ? 1 : 0;
  11963. $list[] = [
  11964. 'name' => $name,
  11965. 'username' => $username,
  11966. 'email' => $email,
  11967. 'phone' => $phone,
  11968. 'can_notify' => $okEmail ? 1 : 0,
  11969. 'found' => is_array($contact) ? 1 : 0,
  11970. 'notified' => $notified,
  11971. 'notify_status_text' => $notified ? '已通知' : '未通知',
  11972. ];
  11973. }
  11974. $this->success('', null, [
  11975. 'scydgy_id' => $sid,
  11976. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  11977. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  11978. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  11979. 'CDW' => trim((string)($po['CDW'] ?? '')),
  11980. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  11981. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  11982. 'CDF' => trim((string)($po['CDF'] ?? '')),
  11983. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  11984. 'list' => $list,
  11985. ]);
  11986. }
  11987. /**
  11988. * 查询询价 — 补加供应商可选名单
  11989. */
  11990. public function rfqsupplieroptions()
  11991. {
  11992. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
  11993. $this->error(__('You have no permission'));
  11994. }
  11995. $names = array_values($this->loadRfqSupplierNameOptions());
  11996. $out = [];
  11997. foreach ($names as $name) {
  11998. $out[] = ['name' => $name];
  11999. }
  12000. $this->success('', null, ['list' => $out]);
  12001. }
  12002. /**
  12003. * 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
  12004. */
  12005. public function rfqappendsuppliers()
  12006. {
  12007. if (!$this->request->isPost()) {
  12008. $this->error(__('Invalid parameters'));
  12009. }
  12010. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers'])) {
  12011. $this->error(__('You have no permission'));
  12012. }
  12013. $sid = (int)$this->request->post('scydgy_id', 0);
  12014. if ($sid >= 0) {
  12015. $this->error('仅支持手工新增询价单');
  12016. }
  12017. $po = $this->loadManualRfqOrderForNotify($sid);
  12018. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  12019. $this->error('订单已完结,无法补加供应商');
  12020. }
  12021. $raw = $this->request->post('suppliers/a', []);
  12022. if (!is_array($raw) || $raw === []) {
  12023. $suppliersJson = $this->request->post('suppliers_json', '');
  12024. if (is_string($suppliersJson) && $suppliersJson !== '') {
  12025. $decoded = json_decode($suppliersJson, true);
  12026. $raw = is_array($decoded) ? $decoded : [];
  12027. }
  12028. }
  12029. $addNames = [];
  12030. foreach ((array)$raw as $item) {
  12031. if (is_array($item)) {
  12032. $n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
  12033. } else {
  12034. $n = trim((string)$item);
  12035. }
  12036. if ($n !== '') {
  12037. $addNames[] = $n;
  12038. }
  12039. }
  12040. $addNames = array_values(array_unique($addNames));
  12041. if ($addNames === []) {
  12042. $this->error('请选择要补加的供应商');
  12043. }
  12044. $existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
  12045. if ($existingRaw === '') {
  12046. $existingRaw = trim((string)($po['pick_company_name'] ?? ''));
  12047. }
  12048. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  12049. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  12050. try {
  12051. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
  12052. } catch (\Throwable $e) {
  12053. $this->error('保存失败:' . $e->getMessage());
  12054. }
  12055. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  12056. $this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  12057. $this->success('已补加供应商', null, [
  12058. 'scydgy_id' => $sid,
  12059. 'cGzzxMc' => $mergedStr,
  12060. 'added_count' => count($addNames),
  12061. ]);
  12062. }
  12063. /**
  12064. * 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
  12065. */
  12066. public function rfqissue()
  12067. {
  12068. if (!$this->request->isPost()) {
  12069. $this->error(__('Invalid parameters'));
  12070. }
  12071. if (!$this->hasProcuremenPerm(['rfqissue'])) {
  12072. $this->error(__('You have no permission'));
  12073. }
  12074. $this->ensureRfqSupplierEmailTemplate();
  12075. $sid = (int)$this->request->post('scydgy_id', 0);
  12076. if ($sid >= 0) {
  12077. $this->error('仅支持手工新增询价单');
  12078. }
  12079. $po = $this->loadManualRfqOrderForNotify($sid);
  12080. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  12081. $this->error('订单已完结,无法下发');
  12082. }
  12083. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  12084. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  12085. $this->error('订单已进入后续流程,无法再下发');
  12086. }
  12087. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  12088. if ($supplierRaw === '') {
  12089. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  12090. }
  12091. $supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
  12092. if ($supplierNames === []) {
  12093. $this->error('请先在新增询价时选择供应商');
  12094. }
  12095. $companies = [];
  12096. $missing = [];
  12097. $noEmail = [];
  12098. foreach ($supplierNames as $name) {
  12099. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  12100. if ($contact === null) {
  12101. $missing[] = $name;
  12102. continue;
  12103. }
  12104. $em = trim((string)($contact['email'] ?? ''));
  12105. if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
  12106. $noEmail[] = $name;
  12107. continue;
  12108. }
  12109. $companies[] = $contact;
  12110. }
  12111. if ($missing !== []) {
  12112. $this->error('未找到供应商档案:' . implode('、', $missing));
  12113. }
  12114. if ($noEmail !== []) {
  12115. $this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
  12116. }
  12117. if ($companies === []) {
  12118. $this->error('没有可通知的供应商');
  12119. }
  12120. $mailConfig = $this->loadMailerConfig();
  12121. if (empty($mailConfig['host'])) {
  12122. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  12123. }
  12124. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  12125. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  12126. }
  12127. $mergeRow = $po;
  12128. $mergeRow['ID'] = $sid;
  12129. $mergeRow['id'] = $sid;
  12130. $mergeRows = [$mergeRow];
  12131. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  12132. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  12133. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  12134. }
  12135. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  12136. $issueTime = date('Y-m-d H:i:s');
  12137. $nameLabels = [];
  12138. foreach ($companies as $c) {
  12139. $nameLabels[] = trim((string)($c['name'] ?? ''));
  12140. }
  12141. $logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
  12142. Db::startTrans();
  12143. try {
  12144. $this->upsertPurchaseOrderFromRow(
  12145. $mergeRow,
  12146. $sysRqDb,
  12147. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  12148. $issueTime,
  12149. $po,
  12150. null,
  12151. $scoreRule
  12152. );
  12153. foreach ($companies as $c) {
  12154. $this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
  12155. }
  12156. Db::commit();
  12157. } catch (\Throwable $e) {
  12158. Db::rollback();
  12159. $this->error($e->getMessage());
  12160. }
  12161. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  12162. if ($poId <= 0) {
  12163. try {
  12164. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  12165. } catch (\Throwable $e) {
  12166. $poId = 0;
  12167. }
  12168. }
  12169. $this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
  12170. $posNotify = [];
  12171. try {
  12172. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  12173. if (is_array($fresh)) {
  12174. $fresh['sys_rq'] = $sysRqDb;
  12175. $posNotify = [$fresh];
  12176. }
  12177. } catch (\Throwable $e) {
  12178. $posNotify = [$po];
  12179. $posNotify[0]['sys_rq'] = $sysRqDb;
  12180. }
  12181. $notifyBundle = [
  12182. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  12183. 'pos' => $posNotify,
  12184. 'merge_rows' => $mergeRows,
  12185. ];
  12186. $notifyErrors = [];
  12187. foreach ($companies as $c) {
  12188. $cname = trim((string)($c['name'] ?? ''));
  12189. try {
  12190. // 询价下发:仅邮箱通知供应商
  12191. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  12192. } catch (\Throwable $e) {
  12193. $notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
  12194. }
  12195. }
  12196. if ($notifyErrors !== []) {
  12197. Log::write('procuremen rfq issue notify fail sid=' . $sid . ': ' . implode(';', $notifyErrors), 'error');
  12198. $this->success('询价下发成功。部分供应商邮件未送达,可稍后重发。', null, [
  12199. 'scydgy_id' => $sid,
  12200. 'progress_text' => '待报价',
  12201. 'supplier_count' => count($companies),
  12202. 'notify_failed' => 1,
  12203. 'notify_fail_detail' => $notifyErrors,
  12204. ]);
  12205. }
  12206. $this->success('已询价并邮件通知供应商', null, [
  12207. 'scydgy_id' => $sid,
  12208. 'progress_text' => '待报价',
  12209. 'supplier_count' => count($companies),
  12210. 'notify_failed' => 0,
  12211. ]);
  12212. }
  12213. /**
  12214. * 查询询价 — 弹窗内向单个供应商发送询价邮件
  12215. */
  12216. public function rfqissuesendmail()
  12217. {
  12218. if (!$this->request->isPost()) {
  12219. $this->error(__('Invalid parameters'));
  12220. }
  12221. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail'])) {
  12222. $this->error(__('You have no permission'));
  12223. }
  12224. $this->ensureRfqSupplierEmailTemplate();
  12225. $sid = (int)$this->request->post('scydgy_id', 0);
  12226. $companyName = trim((string)$this->request->post('company_name', ''));
  12227. if ($sid >= 0) {
  12228. $this->error('仅支持手工新增询价单');
  12229. }
  12230. if ($companyName === '') {
  12231. $this->error('请选择供应商');
  12232. }
  12233. $po = $this->loadManualRfqOrderForNotify($sid);
  12234. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  12235. $this->error('订单已完结,无法发送');
  12236. }
  12237. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  12238. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  12239. $this->error('订单已进入后续流程,无法再发送');
  12240. }
  12241. $contact = $this->resolveCustomerContactByCompanyName($companyName, false);
  12242. if ($contact === null) {
  12243. $this->error('未找到供应商档案:' . $companyName);
  12244. }
  12245. $email = trim((string)($contact['email'] ?? ''));
  12246. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  12247. $this->error('该供应商未填写有效邮箱');
  12248. }
  12249. $mailConfig = $this->loadMailerConfig();
  12250. if (empty($mailConfig['host'])) {
  12251. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  12252. }
  12253. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  12254. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  12255. }
  12256. $mergeRow = $po;
  12257. $mergeRow['ID'] = $sid;
  12258. $mergeRow['id'] = $sid;
  12259. $mergeRows = [$mergeRow];
  12260. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  12261. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  12262. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  12263. }
  12264. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  12265. $issueTime = date('Y-m-d H:i:s');
  12266. Db::startTrans();
  12267. try {
  12268. $this->upsertPurchaseOrderFromRow(
  12269. $mergeRow,
  12270. $sysRqDb,
  12271. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  12272. $issueTime,
  12273. $po,
  12274. null,
  12275. $scoreRule
  12276. );
  12277. $this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
  12278. Db::commit();
  12279. } catch (\Throwable $e) {
  12280. Db::rollback();
  12281. $this->error($e->getMessage());
  12282. }
  12283. $posNotify = [];
  12284. try {
  12285. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  12286. if (is_array($fresh)) {
  12287. $fresh['sys_rq'] = $sysRqDb;
  12288. $posNotify = [$fresh];
  12289. }
  12290. } catch (\Throwable $e) {
  12291. $posNotify = [$po];
  12292. $posNotify[0]['sys_rq'] = $sysRqDb;
  12293. }
  12294. $notifyBundle = [
  12295. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  12296. 'pos' => $posNotify,
  12297. 'merge_rows' => $mergeRows,
  12298. ];
  12299. $mailFail = '';
  12300. try {
  12301. $this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  12302. } catch (\Throwable $e) {
  12303. $mailFail = $e->getMessage();
  12304. Log::write('procuremen rfqissuesendmail fail sid=' . $sid . ' company=' . $companyName . ': ' . $mailFail, 'error');
  12305. }
  12306. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  12307. if ($poId <= 0) {
  12308. try {
  12309. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  12310. } catch (\Throwable $e) {
  12311. $poId = 0;
  12312. }
  12313. }
  12314. $this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
  12315. if ($mailFail !== '') {
  12316. $this->success('询价已保存。邮件未送达「' . $companyName . '」:' . $mailFail . '。可稍后重发。', null, [
  12317. 'scydgy_id' => $sid,
  12318. 'notify_failed' => 1,
  12319. ]);
  12320. }
  12321. $this->success('已向「' . $companyName . '」发送询价邮件', null, [
  12322. 'scydgy_id' => $sid,
  12323. 'company_name' => $companyName,
  12324. ]);
  12325. }
  12326. /**
  12327. * 查询询价 — 查看各供应商报价(单价)
  12328. */
  12329. public function rfqquotes()
  12330. {
  12331. if (!$this->hasProcuremenPerm(['rfqquotes', 'rfqissue'])) {
  12332. $this->error(__('You have no permission'));
  12333. }
  12334. $sid = (int)$this->request->param('scydgy_id', 0);
  12335. if ($sid >= 0) {
  12336. $this->error('仅支持手工新增询价单');
  12337. }
  12338. $po = $this->loadManualRfqOrderForNotify($sid);
  12339. $rows = [];
  12340. try {
  12341. // 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
  12342. $q = Db::table('purchase_order_detail')
  12343. ->where('scydgy_id', $sid)
  12344. ->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
  12345. ->order('id', 'asc');
  12346. $this->applyActivePurchaseOrderDetailWhere($q);
  12347. $rows = $q->select();
  12348. } catch (\Throwable $e) {
  12349. try {
  12350. $q = Db::table('purchase_order_detail')
  12351. ->where('scydgy_id', $sid)
  12352. ->order('id', 'asc');
  12353. $this->applyActivePurchaseOrderDetailWhere($q);
  12354. $rows = $q->select();
  12355. } catch (\Throwable $e2) {
  12356. $rows = [];
  12357. }
  12358. }
  12359. if (!is_array($rows)) {
  12360. $rows = [];
  12361. }
  12362. $list = [];
  12363. foreach ($rows as $row) {
  12364. if (!is_array($row)) {
  12365. continue;
  12366. }
  12367. $amount = trim((string)($row['amount'] ?? ''));
  12368. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  12369. // 未报价不显示时间(createtime 是下发时间,不是报价时间)
  12370. $oper = '';
  12371. if ($isQuoted) {
  12372. $oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
  12373. if ($oper === '') {
  12374. $oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  12375. }
  12376. }
  12377. $list[] = [
  12378. 'id' => (int)($row['id'] ?? 0),
  12379. 'company_name' => trim((string)($row['company_name'] ?? '')),
  12380. 'amount' => $amount,
  12381. 'amount_text' => $isQuoted ? $amount : '',
  12382. 'is_quoted' => $isQuoted,
  12383. 'quote_label' => $isQuoted ? '已报价' : '未报价',
  12384. 'status_name' => trim((string)($row['status_name'] ?? '')),
  12385. 'oper_time' => $oper,
  12386. ];
  12387. }
  12388. $this->success('', null, [
  12389. 'scydgy_id' => $sid,
  12390. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  12391. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  12392. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  12393. 'CDW' => trim((string)($po['CDW'] ?? '')),
  12394. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  12395. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  12396. 'CDF' => trim((string)($po['CDF'] ?? '')),
  12397. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  12398. 'list' => $list,
  12399. ]);
  12400. }
  12401. /**
  12402. * 手工询价是否已下发(有下发明细或已进入待确认及之后)
  12403. */
  12404. protected function isRfqOrderIssued(array $po): bool
  12405. {
  12406. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  12407. return true;
  12408. }
  12409. $sid = (int)($po['scydgy_id'] ?? 0);
  12410. if ($sid >= 0) {
  12411. return false;
  12412. }
  12413. try {
  12414. $q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  12415. $this->applyActivePurchaseOrderDetailWhere($q);
  12416. return (int)$q->count() > 0;
  12417. } catch (\Throwable $e) {
  12418. return false;
  12419. }
  12420. }
  12421. /**
  12422. * 批量:已有下发明细的手工询价 scydgy_id
  12423. *
  12424. * @param int[] $scydgyIds
  12425. * @return array<int, bool>
  12426. */
  12427. protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
  12428. {
  12429. $set = [];
  12430. $ids = [];
  12431. foreach ($scydgyIds as $sid) {
  12432. $sid = (int)$sid;
  12433. if ($sid < 0) {
  12434. $ids[$sid] = true;
  12435. }
  12436. }
  12437. if ($ids === []) {
  12438. return $set;
  12439. }
  12440. try {
  12441. $q = Db::table('purchase_order_detail')
  12442. ->where('scydgy_id', 'in', array_keys($ids))
  12443. ->field('scydgy_id');
  12444. $this->applyActivePurchaseOrderDetailWhere($q);
  12445. $rows = $q->select();
  12446. } catch (\Throwable $e) {
  12447. return $set;
  12448. }
  12449. if (!is_array($rows)) {
  12450. return $set;
  12451. }
  12452. foreach ($rows as $row) {
  12453. if (!is_array($row)) {
  12454. continue;
  12455. }
  12456. $sid = (int)($row['scydgy_id'] ?? 0);
  12457. if ($sid < 0) {
  12458. $set[$sid] = true;
  12459. }
  12460. }
  12461. return $set;
  12462. }
  12463. /**
  12464. * 批量:已填单价(已报价)的手工询价 scydgy_id
  12465. *
  12466. * @param int[] $scydgyIds
  12467. * @return array<int, bool>
  12468. */
  12469. protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
  12470. {
  12471. $set = [];
  12472. $ids = [];
  12473. foreach ($scydgyIds as $sid) {
  12474. $sid = (int)$sid;
  12475. if ($sid < 0) {
  12476. $ids[$sid] = true;
  12477. }
  12478. }
  12479. if ($ids === []) {
  12480. return $set;
  12481. }
  12482. try {
  12483. $q = Db::table('purchase_order_detail')
  12484. ->where('scydgy_id', 'in', array_keys($ids))
  12485. ->field('scydgy_id,amount');
  12486. $this->applyActivePurchaseOrderDetailWhere($q);
  12487. $rows = $q->select();
  12488. } catch (\Throwable $e) {
  12489. return $set;
  12490. }
  12491. if (!is_array($rows)) {
  12492. return $set;
  12493. }
  12494. foreach ($rows as $row) {
  12495. if (!is_array($row)) {
  12496. continue;
  12497. }
  12498. $amount = trim((string)($row['amount'] ?? ''));
  12499. if ($amount === '' || $amount === '0' || $amount === '0.00') {
  12500. continue;
  12501. }
  12502. $sid = (int)($row['scydgy_id'] ?? 0);
  12503. if ($sid < 0) {
  12504. $set[$sid] = true;
  12505. }
  12506. }
  12507. return $set;
  12508. }
  12509. /**
  12510. * 已下发且至少一家供应商已报价,才允许通知业务员
  12511. */
  12512. protected function canRfqNotifySalesman(array $po): bool
  12513. {
  12514. if (!$this->isRfqOrderIssued($po)) {
  12515. return false;
  12516. }
  12517. $sid = (int)($po['scydgy_id'] ?? 0);
  12518. if ($sid >= 0) {
  12519. return false;
  12520. }
  12521. $quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
  12522. return isset($quoted[$sid]);
  12523. }
  12524. protected function assertRfqCanNotifySalesman(array $po): void
  12525. {
  12526. if (!$this->isRfqOrderIssued($po)) {
  12527. $this->error('请先询价并等待供应商报价后再通知业务员');
  12528. }
  12529. if (!$this->canRfqNotifySalesman($po)) {
  12530. $this->error('供应商尚未报价,暂不能通知业务员');
  12531. }
  12532. }
  12533. /**
  12534. * 加载手工询价单(含可见性校验)
  12535. *
  12536. * @return array<string, mixed>
  12537. */
  12538. protected function loadManualRfqOrderForNotify(int $scydgyId): array
  12539. {
  12540. try {
  12541. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  12542. } catch (\Throwable $e) {
  12543. $po = null;
  12544. }
  12545. if (!is_array($po)) {
  12546. $this->error('订单不存在');
  12547. }
  12548. $modRq = trim((string)($po['mod_rq'] ?? ''));
  12549. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  12550. $this->error('订单不存在');
  12551. }
  12552. if ($this->auth->isSuperAdmin()) {
  12553. return $po;
  12554. }
  12555. if ($this->canViewManualRfqOrder($po)) {
  12556. return $po;
  12557. }
  12558. $this->error('无权操作该订单');
  12559. }
  12560. /**
  12561. * @return string[]
  12562. */
  12563. protected function splitRfqSalesmanNames(string $raw): array
  12564. {
  12565. $parts = [];
  12566. $raw = trim($raw);
  12567. if ($raw === '') {
  12568. return [];
  12569. }
  12570. foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
  12571. $v = trim((string)$piece);
  12572. if ($v !== '' && !in_array($v, $parts, true)) {
  12573. $parts[] = $v;
  12574. }
  12575. }
  12576. return $parts;
  12577. }
  12578. /**
  12579. * 按姓名匹配 fa_admin 邮箱
  12580. *
  12581. * @param string[] $names
  12582. * @return array<int, array{admin_id:int,name:string,email:string}>
  12583. */
  12584. protected function resolveRfqSalesmanContactRows(array $names): array
  12585. {
  12586. $out = [];
  12587. foreach ($names as $name) {
  12588. $name = trim((string)$name);
  12589. if ($name === '') {
  12590. continue;
  12591. }
  12592. $adminId = 0;
  12593. $email = '';
  12594. try {
  12595. $row = Db::name('admin')
  12596. ->where(function ($q) use ($name) {
  12597. $q->where('nickname', $name)->whereOr('username', $name);
  12598. })
  12599. ->where('status', 'normal')
  12600. ->order('id', 'asc')
  12601. ->field('id,nickname,username,email')
  12602. ->find();
  12603. } catch (\Throwable $e) {
  12604. $row = null;
  12605. }
  12606. if (is_array($row)) {
  12607. $adminId = (int)($row['id'] ?? 0);
  12608. $email = trim((string)($row['email'] ?? ''));
  12609. $disp = trim((string)($row['nickname'] ?? ''));
  12610. if ($disp === '') {
  12611. $disp = trim((string)($row['username'] ?? ''));
  12612. }
  12613. if ($disp !== '') {
  12614. $name = $disp;
  12615. }
  12616. }
  12617. $out[] = [
  12618. 'admin_id' => $adminId,
  12619. 'name' => $name,
  12620. 'email' => $email,
  12621. ];
  12622. }
  12623. return $out;
  12624. }
  12625. /**
  12626. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  12627. */
  12628. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  12629. {
  12630. if ($scydgyId >= 0) {
  12631. return;
  12632. }
  12633. try {
  12634. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  12635. } catch (\Throwable $e) {
  12636. $po = null;
  12637. }
  12638. if (!is_array($po)) {
  12639. $this->error('订单不存在');
  12640. }
  12641. $modRq = trim((string)($po['mod_rq'] ?? ''));
  12642. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  12643. $this->error('订单不存在');
  12644. }
  12645. if ($this->auth->isSuperAdmin()) {
  12646. return;
  12647. }
  12648. [, $adminName] = $this->GetUseName();
  12649. $cywy = trim((string)($po['cywyxm'] ?? ''));
  12650. if ($cywy !== '' && $cywy === $adminName) {
  12651. return;
  12652. }
  12653. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  12654. try {
  12655. if ($this->auth->check($rule)) {
  12656. return;
  12657. }
  12658. } catch (\Throwable $e) {
  12659. }
  12660. }
  12661. $this->error('无权查看该订单');
  12662. }
  12663. /**
  12664. * 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
  12665. */
  12666. protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
  12667. {
  12668. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  12669. return ProcuremenStatus::PO_COMPLETED;
  12670. }
  12671. $sid = (int)($row['scydgy_id'] ?? 0);
  12672. if ($sid < 0) {
  12673. if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
  12674. return '已通知业务员';
  12675. }
  12676. if ($hasQuoted) {
  12677. return '供应商已报价';
  12678. }
  12679. if ($hasIssued
  12680. || ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
  12681. || ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
  12682. return '待报价';
  12683. }
  12684. try {
  12685. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  12686. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  12687. if ((int)$detCntQuery->count() > 0) {
  12688. return '待报价';
  12689. }
  12690. } catch (\Throwable $e) {
  12691. }
  12692. return '待询价';
  12693. }
  12694. if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
  12695. return '待入库评分';
  12696. }
  12697. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  12698. return '待采购确认';
  12699. }
  12700. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  12701. return '待确认供应商';
  12702. }
  12703. return '待协助下发';
  12704. }
  12705. /**
  12706. * 协助初选列表 — 批量软删除
  12707. */
  12708. public function pickDelete()
  12709. {
  12710. if (!$this->request->isPost() || !$this->request->isAjax()) {
  12711. $this->error(__('Invalid parameters'));
  12712. }
  12713. if (!$this->procuremenCanPickDelete()) {
  12714. $this->error(__('You have no permission'));
  12715. }
  12716. $rowsRaw = $this->request->post('rows_json', '[]');
  12717. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  12718. if (!is_array($rows) || $rows === []) {
  12719. $this->error('请至少勾选一条工序');
  12720. }
  12721. $done = 0;
  12722. Db::startTrans();
  12723. try {
  12724. foreach ($rows as $row) {
  12725. if (!is_array($row)) {
  12726. continue;
  12727. }
  12728. $this->softDeleteProcuremenPickRow($row);
  12729. $done++;
  12730. }
  12731. if ($done < 1) {
  12732. throw new \Exception('没有可删除的工序');
  12733. }
  12734. Db::commit();
  12735. } catch (\InvalidArgumentException $e) {
  12736. Db::rollback();
  12737. $this->error($e->getMessage());
  12738. } catch (\Throwable $e) {
  12739. Db::rollback();
  12740. $this->error($e->getMessage());
  12741. }
  12742. $this->pickHiddenScydgySetCache = null;
  12743. $this->success('已删除 ' . $done . ' 条工序');
  12744. }
  12745. /**
  12746. * 下发 — 手工新增工序(弹窗)
  12747. */
  12748. public function pickAdd()
  12749. {
  12750. if ($this->request->isPost()) {
  12751. $params = $this->request->post('row/a');
  12752. if (!is_array($params)) {
  12753. $this->error(__('Parameter %s can not be empty', ''));
  12754. }
  12755. try {
  12756. $sid = $this->saveManualPickOrder($params);
  12757. } catch (\InvalidArgumentException $e) {
  12758. $this->error($e->getMessage());
  12759. } catch (\Throwable $e) {
  12760. $this->error($e->getMessage());
  12761. }
  12762. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  12763. }
  12764. return $this->view->fetch('procuremen/pick_add');
  12765. }
  12766. /**
  12767. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  12768. */
  12769. public function pickSubmit()
  12770. {
  12771. if (!$this->request->isPost()) {
  12772. $this->error(__('Invalid parameters'));
  12773. }
  12774. // ---------- 接口订单数据 ----------
  12775. $rowJson = $this->request->post('row_json', '');
  12776. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  12777. $companiesJson = $this->request->post('companies_json', '[]');
  12778. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  12779. $companies = json_decode($companiesJson, true);
  12780. if (!is_array($companies)) {
  12781. $this->error('供应商数据无效');
  12782. }
  12783. $postedCompanyCount = 0;
  12784. $skippedCompanyCount = 0;
  12785. foreach ($companies as $c) {
  12786. if (is_array($c) && (trim((string)($c['name'] ?? $c['company_name'] ?? '')) !== '' || trim((string)($c['id'] ?? '')) !== '')) {
  12787. $postedCompanyCount++;
  12788. }
  12789. }
  12790. $issueCompanies = $this->normalizePickCompanies($companies);
  12791. if ($issueCompanies === []) {
  12792. $this->error('请至少选择一家合作供应商(须同时具备有效手机号与邮箱)');
  12793. }
  12794. // 不可用供应商静默跳过,不向操作员报错;成功提示中说明实际下发家数
  12795. if ($postedCompanyCount > 0 && count($issueCompanies) < $postedCompanyCount) {
  12796. $skippedCompanyCount = $postedCompanyCount - count($issueCompanies);
  12797. Log::write(
  12798. 'procuremen pickSubmit skip companies: posted=' . $postedCompanyCount
  12799. . ' issued=' . count($issueCompanies),
  12800. 'notice'
  12801. );
  12802. }
  12803. $issueNameLabels = [];
  12804. foreach ($issueCompanies as $pc) {
  12805. $issueNameLabels[] = $pc['name'];
  12806. }
  12807. $issueNamesSummary = implode('、', $issueNameLabels);
  12808. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  12809. if ($sysRq === '') {
  12810. $this->error('请选择招标截止日期');
  12811. }
  12812. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  12813. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  12814. (string)$this->request->post('delivery_deadline', ''),
  12815. true
  12816. );
  12817. $scoreRuleId = (int)$this->request->post('score_rule_id', 0);
  12818. if ($scoreRuleId <= 0) {
  12819. $this->error('请选择订单类型');
  12820. }
  12821. $scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
  12822. if ((int)($scoreRule['id'] ?? 0) <= 0) {
  12823. $this->error('订单类型无效,请刷新后重选');
  12824. }
  12825. $scoreRuleId = (int)$scoreRule['id'];
  12826. $this->ensurePurchaseOrderScoreRuleIdColumn();
  12827. $logMsg = '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  12828. $bidDispForLog = $this->formatProcuremenSysRqForDisplay($sysRqDb);
  12829. $delDispForLog = $this->formatProcuremenDeliveryDeadlineForInput($deliveryDeadlineDb);
  12830. if ($delDispForLog === '') {
  12831. $delDispForLog = $this->formatDeliveryYmd($deliveryDeadlineDb);
  12832. }
  12833. $orderTypeForLog = trim((string)($scoreRule['name'] ?? ''));
  12834. $logExtra = [];
  12835. if ($bidDispForLog !== '' && $bidDispForLog !== '—') {
  12836. $logExtra[] = '招标截止日期:' . $bidDispForLog;
  12837. }
  12838. if ($delDispForLog !== '') {
  12839. $logExtra[] = '交货截止日期:' . $delDispForLog;
  12840. }
  12841. if ($orderTypeForLog !== '') {
  12842. $logExtra[] = '订单类型:' . $orderTypeForLog;
  12843. }
  12844. if ($logExtra !== []) {
  12845. $logMsg .= ';' . implode(';', $logExtra);
  12846. }
  12847. $issueTime = date('Y-m-d H:i:s');
  12848. try {
  12849. $issueBatchNo = $this->allocateProcuremenIssueBatchNo();
  12850. } catch (\Throwable $e) {
  12851. $this->error($e->getMessage() !== '' ? $e->getMessage() : '批次号生成失败,请重试');
  12852. }
  12853. $logSidList = [];
  12854. foreach ($mergeRows as $row) {
  12855. if (!is_array($row)) {
  12856. continue;
  12857. }
  12858. $sid = $this->extractScydgyRowId($row);
  12859. if ($this->isValidScydgyRowId($sid)) {
  12860. $logSidList[$sid] = true;
  12861. }
  12862. }
  12863. if ($logSidList === []) {
  12864. $this->error('未找到有效工序,无法下发');
  12865. }
  12866. // 防连点/并发:同一批工序加命名锁,已下发则直接拒绝(避免重复短信邮件)
  12867. $sidKeys = array_keys($logSidList);
  12868. sort($sidKeys, SORT_NUMERIC);
  12869. $pickLockName = 'procuremen_pick_submit_' . md5(implode(',', $sidKeys));
  12870. if (!$this->acquireProcuremenNamedLock($pickLockName, 15)) {
  12871. $this->error('下发处理中,请勿重复点击');
  12872. }
  12873. $existingBySid = [];
  12874. try {
  12875. try {
  12876. $existingRows = Db::table('purchase_order')
  12877. ->where('scydgy_id', 'in', $sidKeys)
  12878. ->select();
  12879. if (is_array($existingRows)) {
  12880. foreach ($existingRows as $poRow) {
  12881. if (!is_array($poRow)) {
  12882. continue;
  12883. }
  12884. $sid = (int)($poRow['scydgy_id'] ?? 0);
  12885. if ($this->isValidScydgyRowId($sid)) {
  12886. $existingBySid[$sid] = $poRow;
  12887. }
  12888. }
  12889. }
  12890. } catch (\Throwable $e) {
  12891. $existingBySid = [];
  12892. }
  12893. foreach ($sidKeys as $sid) {
  12894. $poRow = $existingBySid[$sid] ?? null;
  12895. if (!is_array($poRow)) {
  12896. continue;
  12897. }
  12898. if ($this->isPurchaseOrderSoftDeleted($poRow['mod_rq'] ?? null)) {
  12899. continue;
  12900. }
  12901. $label = $this->formatProcuremenRowLabel(['CCYDH' => $poRow['CCYDH'] ?? '', 'CGYMC' => $poRow['CGYMC'] ?? '']);
  12902. if (ProcuremenStatus::isPoCompleted($poRow['status'] ?? '')) {
  12903. $this->error(($label !== '' ? $label : ('工序#' . $sid)) . '已完结,无法再次下发');
  12904. }
  12905. if (!ProcuremenStatus::isWflowPendingIssue($poRow['wflow_status'] ?? '')) {
  12906. $this->error(($label !== '' ? $label : ('工序#' . $sid)) . '已下发或进入后续流程,请勿重复提交');
  12907. }
  12908. }
  12909. Db::startTrans();
  12910. try {
  12911. $this->enrichProcuremenRowsMbz($mergeRows);
  12912. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  12913. foreach ($mergeRows as $row) {
  12914. if (!is_array($row)) {
  12915. continue;
  12916. }
  12917. $sid = $this->extractScydgyRowId($row);
  12918. $this->upsertPurchaseOrderFromRow(
  12919. $row,
  12920. $sysRqDb,
  12921. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  12922. $issueTime,
  12923. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  12924. $deliveryDeadlineDb,
  12925. $scoreRule,
  12926. $issueBatchNo
  12927. );
  12928. }
  12929. foreach ($issueCompanies as $c) {
  12930. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  12931. }
  12932. Db::commit();
  12933. } catch (\Throwable $e) {
  12934. Db::rollback();
  12935. $this->error($e->getMessage());
  12936. }
  12937. } finally {
  12938. $this->releaseProcuremenNamedLock($pickLockName);
  12939. }
  12940. $poIdBySid = [];
  12941. if ($logSidList !== []) {
  12942. try {
  12943. $poIdBySid = Db::table('purchase_order')
  12944. ->where('scydgy_id', 'in', array_keys($logSidList))
  12945. ->column('id', 'scydgy_id');
  12946. } catch (\Throwable $e) {
  12947. $poIdBySid = [];
  12948. }
  12949. }
  12950. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  12951. if ($logSidList !== []) {
  12952. list($adminId, $adminName) = $this->GetUseName();
  12953. $logRows = [];
  12954. $seenLogSid = [];
  12955. foreach ($mergeRows as $row) {
  12956. if (!is_array($row)) {
  12957. continue;
  12958. }
  12959. $ids = $this->extractScydgyRowId($row);
  12960. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  12961. continue;
  12962. }
  12963. $seenLogSid[$ids] = true;
  12964. $poIdLog = null;
  12965. if (isset($poIdBySid[$ids])) {
  12966. $tid = (int)$poIdBySid[$ids];
  12967. $poIdLog = $tid > 0 ? $tid : null;
  12968. }
  12969. $logRows[] = ProcuremenOperLog::buildInsertRow(
  12970. $ids,
  12971. 'issue_submit',
  12972. $logMsg,
  12973. $poIdLog,
  12974. (int)$adminId,
  12975. (string)$adminName
  12976. );
  12977. }
  12978. if ($logRows !== []) {
  12979. try {
  12980. Db::table('purchase_order_oper_log')->insertAll($logRows);
  12981. } catch (\Throwable $e) {
  12982. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  12983. }
  12984. }
  12985. }
  12986. $posNotify = [];
  12987. if ($logSidList !== []) {
  12988. try {
  12989. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  12990. } catch (\Throwable $e) {
  12991. $posNotify = [];
  12992. }
  12993. }
  12994. if (!is_array($posNotify)) {
  12995. $posNotify = [];
  12996. }
  12997. foreach ($posNotify as $i => $prow) {
  12998. if (is_array($posNotify[$i])) {
  12999. $posNotify[$i]['sys_rq'] = $sysRqDb;
  13000. }
  13001. }
  13002. $ccydhPick = '';
  13003. foreach ($mergeRows as $row) {
  13004. if (!is_array($row)) {
  13005. continue;
  13006. }
  13007. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  13008. if ($ccydhPick !== '') {
  13009. break;
  13010. }
  13011. }
  13012. $notifyBundleBase = [
  13013. 'ccydh' => $ccydhPick,
  13014. 'pos' => $posNotify,
  13015. 'merge_rows' => $mergeRows,
  13016. 'score_rule' => is_array($scoreRule) ? $scoreRule : null,
  13017. ];
  13018. // 写库已成功:先立刻回成功给前端,再后台发短信/邮件(避免多家串行超时转圈/误报失败)
  13019. $okCount = count($issueCompanies);
  13020. $skipHint = '';
  13021. if (!empty($skippedCompanyCount) && (int)$skippedCompanyCount > 0) {
  13022. $skipHint = '(已自动跳过 ' . (int)$skippedCompanyCount . ' 家资料不完整的供应商)';
  13023. }
  13024. $payload = [
  13025. 'issued' => 1,
  13026. 'supplier_count' => $okCount,
  13027. 'notify_pending' => 1,
  13028. 'notify_failed' => 0,
  13029. ];
  13030. $successMsg = '下发成功' . $skipHint . ',已向 ' . $okCount
  13031. . ' 家供应商发起通知。';
  13032. if ($this->isProcuremenNotifyDryRun()) {
  13033. $this->notifyDryRunPreview = [];
  13034. $notifyErrors = [];
  13035. foreach ($issueCompanies as $c) {
  13036. if (!is_array($c)) {
  13037. continue;
  13038. }
  13039. $cname = trim((string)($c['name'] ?? ''));
  13040. if ($cname === '') {
  13041. continue;
  13042. }
  13043. try {
  13044. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  13045. } catch (\Throwable $e) {
  13046. $notifyErrors[] = $cname . ':' . $e->getMessage();
  13047. }
  13048. }
  13049. $this->success('【演练模式】已保存并生成通知预览', '', [
  13050. 'notify_dry_run' => true,
  13051. 'notify_preview' => $this->notifyDryRunPreview,
  13052. 'notify_fail_detail' => $notifyErrors,
  13053. ]);
  13054. }
  13055. $this->respondSuccessThenContinue($successMsg, $payload);
  13056. @set_time_limit(300);
  13057. @ini_set('max_execution_time', '300');
  13058. $notifyOk = 0;
  13059. $notifyErrors = [];
  13060. foreach ($issueCompanies as $c) {
  13061. if (!is_array($c)) {
  13062. continue;
  13063. }
  13064. $cname = trim((string)($c['name'] ?? ''));
  13065. if ($cname === '') {
  13066. continue;
  13067. }
  13068. try {
  13069. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  13070. $notifyOk++;
  13071. } catch (\Throwable $e) {
  13072. $notifyErrors[] = $cname . ':' . $e->getMessage();
  13073. Log::write('procuremen pickSubmit background notify fail ' . $cname . ': ' . $e->getMessage(), 'error');
  13074. }
  13075. }
  13076. if ($notifyErrors !== []) {
  13077. Log::write(
  13078. 'procuremen pickSubmit background notify summary ok=' . $notifyOk
  13079. . ' fail=' . count($notifyErrors) . ' ' . implode(';', $notifyErrors),
  13080. 'error'
  13081. );
  13082. }
  13083. exit;
  13084. }
  13085. /**
  13086. * 确认供应商弹窗
  13087. */
  13088. public function auditIssue()
  13089. {
  13090. $ids = $this->request->param('ids', $this->request->param('id', ''));
  13091. if (is_array($ids)) {
  13092. $ids = isset($ids[0]) ? $ids[0] : '';
  13093. }
  13094. $ids = trim((string)$ids);
  13095. if ($ids === '') {
  13096. $this->error(__('Invalid parameters'));
  13097. }
  13098. if ($this->request->isPost()) {
  13099. $this->error('请使用弹窗内「确认」提交');
  13100. }
  13101. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  13102. $pos = $bundle['pos'];
  13103. if ($pos === []) {
  13104. $this->error('该订单不在待确认供应商状态');
  13105. }
  13106. $po = $pos[0];
  13107. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13108. if ($quoteGroups === []) {
  13109. $toastMsg = '暂无下发明细,请确认该订单已在「供应商初选」完成下发';
  13110. // 弹层内不要走整页跳转提示,仅 Toastr 后关闭
  13111. $this->view->assign('toastMsg', $toastMsg);
  13112. return $this->view->fetch('procuremen/toast_close');
  13113. }
  13114. $pickedName = '';
  13115. foreach ($pos as $poRow) {
  13116. if (!is_array($poRow)) {
  13117. continue;
  13118. }
  13119. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  13120. if ($pn !== '') {
  13121. $pickedName = $pn;
  13122. break;
  13123. }
  13124. }
  13125. $this->view->assign('po', $po);
  13126. $this->view->assign('scydgyId', $ids);
  13127. $this->view->assign('orderCcydh', $bundle['ccydh']);
  13128. $mergeRows = $bundle['merge_rows'];
  13129. $this->view->assign('processRows', $mergeRows);
  13130. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  13131. $this->view->assign('processCount', count($mergeRows));
  13132. $this->view->assign('orderBatchNo', $this->resolveBundleOrderBatchNo($bundle));
  13133. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  13134. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  13135. $this->view->assign('pickedCompanyName', $pickedName);
  13136. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  13137. if ($sysRqForView === '') {
  13138. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  13139. }
  13140. $this->view->assign('sysRq', $sysRqForView);
  13141. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  13142. if ($deliveryDeadlineForView === '') {
  13143. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  13144. }
  13145. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  13146. $this->ensurePurchaseOrderManualPickColumns();
  13147. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
  13148. $manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
  13149. $manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
  13150. $isRejected = 0;
  13151. foreach ($pos as $poRow) {
  13152. if (!is_array($poRow)) {
  13153. continue;
  13154. }
  13155. if (ProcuremenStatus::isWflowRejected($poRow['wflow_status'] ?? '')) {
  13156. $isRejected = 1;
  13157. break;
  13158. }
  13159. }
  13160. $quoteVisible = ($bidOpenVerified || $manualPicked || $isRejected) ? 1 : 0;
  13161. if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
  13162. $pickedName = $manualPickInfo['company'];
  13163. }
  13164. // 驳回后:仅一家供应商时自动选定,便于直接确认;多家则留空供用户选择
  13165. $quoteGroupCount = 0;
  13166. $onlyQuoteCompany = '';
  13167. foreach ($quoteGroups as $g) {
  13168. if (!is_array($g)) {
  13169. continue;
  13170. }
  13171. $nm = trim((string)($g['name'] ?? ''));
  13172. if ($nm === '') {
  13173. continue;
  13174. }
  13175. $quoteGroupCount++;
  13176. if ($onlyQuoteCompany === '') {
  13177. $onlyQuoteCompany = $nm;
  13178. }
  13179. }
  13180. if ($isRejected) {
  13181. // 驳回需重新选定:清空锁定用的已选名;仅一家时再自动勾选
  13182. $pickedName = ($quoteGroupCount === 1) ? $onlyQuoteCompany : '';
  13183. }
  13184. $this->view->assign('pickedCompanyName', $pickedName);
  13185. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  13186. $this->view->assign('manualPicked', $manualPicked);
  13187. $this->view->assign('isRejected', $isRejected);
  13188. $this->view->assign('quoteGroupCount', $quoteGroupCount);
  13189. $this->view->assign('manualPickReason', $manualPickInfo['reason']);
  13190. $this->view->assign('quoteVisible', $quoteVisible);
  13191. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
  13192. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  13193. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
  13194. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
  13195. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  13196. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  13197. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  13198. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  13199. return $this->view->fetch('procuremen/audit_issue');
  13200. }
  13201. /**
  13202. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  13203. *
  13204. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  13205. */
  13206. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  13207. {
  13208. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13209. return false;
  13210. }
  13211. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13212. return false;
  13213. }
  13214. return true;
  13215. }
  13216. /**
  13217. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  13218. *
  13219. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  13220. */
  13221. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  13222. {
  13223. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13224. return false;
  13225. }
  13226. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13227. return false;
  13228. }
  13229. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  13230. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  13231. return true;
  13232. }
  13233. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  13234. }
  13235. /**
  13236. * 确认页 — 补加供应商弹窗
  13237. */
  13238. public function auditAppend()
  13239. {
  13240. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  13241. $this->error(__('You have no permission'));
  13242. }
  13243. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  13244. if (is_array($ids)) {
  13245. $ids = isset($ids[0]) ? $ids[0] : '';
  13246. }
  13247. $ids = trim((string)$ids);
  13248. if ($ids === '') {
  13249. $this->error(__('Invalid parameters'));
  13250. }
  13251. if ($this->request->isPost()) {
  13252. $this->error('请使用弹窗内「确认」提交');
  13253. }
  13254. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  13255. if (($bundle['pos'] ?? []) === []) {
  13256. $this->error('该订单不在待确认供应商状态');
  13257. }
  13258. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  13259. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13260. $this->error('已开标验证,不能再补加供应商');
  13261. }
  13262. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13263. $this->error('已指定供应商,不能再补加供应商');
  13264. }
  13265. $this->error('已经超过了招标截止日期,不可操作');
  13266. }
  13267. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13268. $existingNames = [];
  13269. foreach ($quoteGroups as $g) {
  13270. if (!is_array($g)) {
  13271. continue;
  13272. }
  13273. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  13274. if ($n !== '') {
  13275. $existingNames[$n] = true;
  13276. }
  13277. }
  13278. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  13279. $mergeRows = $bundle['merge_rows'] ?? [];
  13280. $this->view->assign('scydgyId', $ids);
  13281. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  13282. $this->view->assign('po', $po);
  13283. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  13284. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  13285. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  13286. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  13287. if ($sysRqForView === '') {
  13288. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  13289. }
  13290. $this->view->assign('sysRq', $sysRqForView);
  13291. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  13292. if ($deliveryDeadlineForView === '') {
  13293. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  13294. }
  13295. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  13296. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  13297. }
  13298. /**
  13299. * 确认页 — 补加供应商提交
  13300. */
  13301. public function auditAppendSubmit()
  13302. {
  13303. if (!$this->request->isPost()) {
  13304. $this->error(__('Invalid parameters'));
  13305. }
  13306. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  13307. $this->error(__('You have no permission'));
  13308. }
  13309. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  13310. if ($ids === '') {
  13311. $this->error(__('Invalid parameters'));
  13312. }
  13313. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  13314. if (($bundle['pos'] ?? []) === []) {
  13315. $this->error('该订单不在待确认供应商状态');
  13316. }
  13317. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  13318. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13319. $this->error('已开标验证,不能再补加供应商');
  13320. }
  13321. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13322. $this->error('已指定供应商,不能再补加供应商');
  13323. }
  13324. $this->error('已经超过了招标截止日期,不可操作');
  13325. }
  13326. $companiesJson = $this->request->post('companies_json', '[]');
  13327. $companies = json_decode((string)$companiesJson, true);
  13328. if (!is_array($companies)) {
  13329. $this->error('供应商数据无效');
  13330. }
  13331. $issueCompanies = $this->normalizePickCompanies($companies);
  13332. if ($issueCompanies === []) {
  13333. $this->error('请至少选择一家合作供应商');
  13334. }
  13335. $mergeRows = $bundle['merge_rows'] ?? [];
  13336. if (!is_array($mergeRows) || $mergeRows === []) {
  13337. $this->error('未找到工序行,无法补加');
  13338. }
  13339. $existingNames = [];
  13340. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  13341. if (!is_array($g)) {
  13342. continue;
  13343. }
  13344. $n = trim((string)($g['company_name'] ?? ''));
  13345. if ($n !== '') {
  13346. $existingNames[$n] = true;
  13347. }
  13348. }
  13349. $toAdd = [];
  13350. foreach ($issueCompanies as $c) {
  13351. if (!is_array($c)) {
  13352. continue;
  13353. }
  13354. $n = trim((string)($c['name'] ?? ''));
  13355. if ($n === '' || isset($existingNames[$n])) {
  13356. continue;
  13357. }
  13358. $toAdd[] = $c;
  13359. }
  13360. if ($toAdd === []) {
  13361. $this->error('所选供应商均已在本单中,请选择新的供应商');
  13362. }
  13363. $addedNames = [];
  13364. Db::startTrans();
  13365. try {
  13366. foreach ($toAdd as $c) {
  13367. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  13368. $addedNames[] = trim((string)($c['name'] ?? ''));
  13369. }
  13370. Db::commit();
  13371. } catch (\Throwable $e) {
  13372. Db::rollback();
  13373. $this->error($e->getMessage());
  13374. }
  13375. $notifyBundleBase = [
  13376. 'ccydh' => $bundle['ccydh'] ?? '',
  13377. 'pos' => $bundle['pos'] ?? [],
  13378. 'merge_rows' => $mergeRows,
  13379. ];
  13380. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  13381. $seenLogSid = [];
  13382. foreach ($bundle['pos'] ?? [] as $poRow) {
  13383. if (!is_array($poRow)) {
  13384. continue;
  13385. }
  13386. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13387. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  13388. continue;
  13389. }
  13390. $seenLogSid[$sid] = true;
  13391. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  13392. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  13393. }
  13394. if ($seenLogSid === []) {
  13395. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  13396. if ($this->isValidScydgyRowId($logSid)) {
  13397. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  13398. }
  13399. }
  13400. if ($this->isProcuremenNotifyDryRun()) {
  13401. $this->notifyDryRunPreview = [];
  13402. $notifyErrors = [];
  13403. foreach ($toAdd as $c) {
  13404. if (!is_array($c)) {
  13405. continue;
  13406. }
  13407. $cname = trim((string)($c['name'] ?? ''));
  13408. if ($cname === '') {
  13409. continue;
  13410. }
  13411. try {
  13412. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  13413. } catch (\Throwable $e) {
  13414. $notifyErrors[] = $cname . ':' . $e->getMessage();
  13415. }
  13416. }
  13417. $this->success('【演练模式】已补加并生成通知预览', '', [
  13418. 'append_ok' => 1,
  13419. 'notify_dry_run' => true,
  13420. 'notify_preview' => $this->notifyDryRunPreview,
  13421. 'notify_fail_detail' => $notifyErrors,
  13422. ]);
  13423. }
  13424. $this->respondSuccessThenContinue(
  13425. '已补加 ' . count($toAdd) . ' 家供应商并发起通知。',
  13426. ['append_ok' => 1, 'notify_pending' => 1, 'notify_failed' => 0]
  13427. );
  13428. $notifyErrors = [];
  13429. foreach ($toAdd as $c) {
  13430. if (!is_array($c)) {
  13431. continue;
  13432. }
  13433. $cname = trim((string)($c['name'] ?? ''));
  13434. if ($cname === '') {
  13435. continue;
  13436. }
  13437. try {
  13438. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  13439. } catch (\Throwable $e) {
  13440. $notifyErrors[] = $cname . ':' . $e->getMessage();
  13441. Log::write('procuremen auditAppend background notify fail ' . $cname . ': ' . $e->getMessage(), 'error');
  13442. }
  13443. }
  13444. if ($notifyErrors !== []) {
  13445. Log::write('procuremen auditAppend background notify summary: ' . implode(';', $notifyErrors), 'error');
  13446. }
  13447. exit;
  13448. }
  13449. /**
  13450. * 开标双重验证 — 可选验证人列表
  13451. */
  13452. public function bidOpenUsers()
  13453. {
  13454. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  13455. $this->error('无权限');
  13456. }
  13457. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  13458. if ($scydgyId !== '') {
  13459. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13460. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13461. $this->success('已完成开标验证', null, [
  13462. 'verified' => 1,
  13463. 'users' => [],
  13464. ]);
  13465. }
  13466. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13467. $this->error('本单已指定供应商,无需再开标');
  13468. }
  13469. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  13470. }
  13471. $this->success('', null, [
  13472. 'verified' => 0,
  13473. 'users' => $this->listBidOpenVerifierCandidates(),
  13474. ]);
  13475. }
  13476. /**
  13477. * 开标双重验证 — 向指定管理员发送短信验证码
  13478. */
  13479. public function bidOpenSendCode()
  13480. {
  13481. if (!$this->request->isPost()) {
  13482. $this->error(__('Invalid parameters'));
  13483. }
  13484. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  13485. $this->error('无权限');
  13486. }
  13487. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13488. $adminId = (int)$this->request->post('admin_id', 0);
  13489. if ($scydgyId === '' || $adminId <= 0) {
  13490. $this->error('参数无效');
  13491. }
  13492. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13493. if ($bundle['pos'] === []) {
  13494. $this->error('该订单不在待确认供应商状态');
  13495. }
  13496. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13497. $this->success('已完成开标验证,无需重复发送');
  13498. }
  13499. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13500. $this->error('本单已指定供应商,无需再开标');
  13501. }
  13502. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  13503. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  13504. if ($ccydh === '') {
  13505. $this->error('订单号无效');
  13506. }
  13507. $admin = $this->loadBidOpenAdminUser($adminId);
  13508. if ($admin === null) {
  13509. $this->error('验证人无效或未绑定手机号');
  13510. }
  13511. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  13512. $cd = max(30, min(120, $cd));
  13513. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  13514. $this->error('发送过于频繁,请稍后再试');
  13515. }
  13516. $code = (string)random_int(100000, 999999);
  13517. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  13518. $ttl = max(60, min(600, $ttl));
  13519. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  13520. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  13521. try {
  13522. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  13523. } catch (\Throwable $e) {
  13524. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  13525. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  13526. $this->error($e->getMessage());
  13527. }
  13528. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  13529. }
  13530. /**
  13531. * 开标双重验证 — 两人验证码校验并记录
  13532. */
  13533. public function bidOpenVerify()
  13534. {
  13535. if (!$this->request->isPost()) {
  13536. $this->error(__('Invalid parameters'));
  13537. }
  13538. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  13539. $this->error('无权限');
  13540. }
  13541. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13542. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  13543. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  13544. $code1 = trim((string)$this->request->post('code1', ''));
  13545. $code2 = trim((string)$this->request->post('code2', ''));
  13546. if ($scydgyId === '') {
  13547. $this->error('参数无效');
  13548. }
  13549. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  13550. $this->error('请选择两位验证人');
  13551. }
  13552. if ($verifier1Id === $verifier2Id) {
  13553. $this->error('两位验证人不能相同');
  13554. }
  13555. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  13556. $this->error('请输入6位短信验证码');
  13557. }
  13558. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13559. if ($bundle['pos'] === []) {
  13560. $this->error('该订单不在待确认供应商状态');
  13561. }
  13562. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  13563. if ($ccydh === '') {
  13564. $this->error('订单号无效');
  13565. }
  13566. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13567. $this->success('已完成开标验证');
  13568. }
  13569. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13570. $this->error('本单已指定供应商,无需再开标');
  13571. }
  13572. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  13573. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  13574. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  13575. if ($verifier1 === null || $verifier2 === null) {
  13576. $this->error('验证人无效或未绑定手机号');
  13577. }
  13578. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  13579. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  13580. }
  13581. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  13582. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  13583. }
  13584. try {
  13585. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  13586. } catch (\Throwable $e) {
  13587. $this->error($e->getMessage());
  13588. }
  13589. $this->success('开标验证成功,可查看供应商报价与交货日期');
  13590. }
  13591. /**
  13592. * 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
  13593. */
  13594. public function auditManualPick()
  13595. {
  13596. if (!$this->request->isPost()) {
  13597. $this->error(__('Invalid parameters'));
  13598. }
  13599. if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
  13600. $this->error('无权限');
  13601. }
  13602. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13603. if ($scydgyId === '') {
  13604. $this->error('参数无效');
  13605. }
  13606. $companyName = trim((string)$this->request->post('selected_company', ''));
  13607. $reason = trim((string)$this->request->post('pick_reason', ''));
  13608. if ($companyName === '') {
  13609. $this->error('请选择一家供应商');
  13610. }
  13611. if ($reason === '') {
  13612. $this->error('请填写选择说明');
  13613. }
  13614. if (mb_strlen($reason) > 500) {
  13615. $this->error('选择说明不能超过500字');
  13616. }
  13617. $this->ensurePurchaseOrderManualPickColumns();
  13618. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13619. $pos = $bundle['pos'];
  13620. if ($pos === []) {
  13621. $this->error('该订单不在待确认供应商状态');
  13622. }
  13623. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13624. $this->error('本单已开标验证,请直接在列表中选定供应商后确认');
  13625. }
  13626. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13627. if ($quoteGroups === []) {
  13628. $this->error('暂无供应商,请确认已完成协助初选通知');
  13629. }
  13630. $matched = null;
  13631. foreach ($quoteGroups as $g) {
  13632. if (!is_array($g)) {
  13633. continue;
  13634. }
  13635. if (trim((string)($g['name'] ?? '')) === $companyName) {
  13636. $matched = $g;
  13637. break;
  13638. }
  13639. }
  13640. if ($matched === null) {
  13641. $this->error('所选供应商不在本单报价列表中');
  13642. }
  13643. $logMsg = '指定供应商:' . $companyName . ';说明:' . $reason;
  13644. Db::startTrans();
  13645. try {
  13646. foreach ($pos as $poRow) {
  13647. if (!is_array($poRow)) {
  13648. continue;
  13649. }
  13650. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13651. if (!$this->isValidScydgyRowId($sid)) {
  13652. continue;
  13653. }
  13654. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  13655. 'pick_company_name' => $companyName,
  13656. 'manual_pick' => 1,
  13657. 'manual_pick_reason' => $reason,
  13658. ]);
  13659. }
  13660. Db::commit();
  13661. } catch (\Throwable $e) {
  13662. Db::rollback();
  13663. $this->error($e->getMessage());
  13664. }
  13665. foreach ($pos as $poRow) {
  13666. if (!is_array($poRow)) {
  13667. continue;
  13668. }
  13669. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13670. if (!$this->isValidScydgyRowId($sid)) {
  13671. continue;
  13672. }
  13673. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  13674. $this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  13675. }
  13676. // 自选后可见报价:按本批各订单分别计算评分(与开标后一致)
  13677. try {
  13678. $bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13679. $this->saveProcuremenSupplierScoresForBundle($bundleFresh, date('Y-m'));
  13680. } catch (\Throwable $e) {
  13681. Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
  13682. }
  13683. $this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
  13684. }
  13685. /**
  13686. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  13687. */
  13688. public function auditSubmit()
  13689. {
  13690. if (!$this->request->isPost()) {
  13691. $this->error(__('Invalid parameters'));
  13692. }
  13693. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13694. if ($scydgyId === '') {
  13695. $this->error('参数无效');
  13696. }
  13697. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13698. $pos = $bundle['pos'];
  13699. $mergeRows = $bundle['merge_rows'];
  13700. if ($pos === [] || $mergeRows === []) {
  13701. $this->error('该订单不在待确认供应商状态');
  13702. }
  13703. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13704. if ($quoteGroups === []) {
  13705. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  13706. }
  13707. $companyName = trim((string)$this->request->post('selected_company', ''));
  13708. if ($companyName === '') {
  13709. $this->error('请选择一家供应商');
  13710. }
  13711. $matched = null;
  13712. foreach ($quoteGroups as $g) {
  13713. if (!is_array($g)) {
  13714. continue;
  13715. }
  13716. if (trim((string)($g['name'] ?? '')) === $companyName) {
  13717. $matched = $g;
  13718. break;
  13719. }
  13720. }
  13721. if ($matched === null) {
  13722. $this->error('所选供应商不在本单报价列表中');
  13723. }
  13724. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  13725. if ($sysRqDb === '') {
  13726. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  13727. } else {
  13728. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  13729. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  13730. }
  13731. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  13732. $this->error('未到招标截止日期,暂不可确认');
  13733. }
  13734. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
  13735. && !$this->isProcuremenManualPickedForBundle($bundle)
  13736. ) {
  13737. $this->error('请先完成开标双重验证或指定供应商后再确认');
  13738. }
  13739. $logMsg = '确认供应商:' . $companyName;
  13740. Db::startTrans();
  13741. try {
  13742. foreach ($pos as $poRow) {
  13743. if (!is_array($poRow)) {
  13744. continue;
  13745. }
  13746. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13747. if (!$this->isValidScydgyRowId($sid)) {
  13748. continue;
  13749. }
  13750. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  13751. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  13752. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  13753. 'pick_company_name' => $companyName,
  13754. 'sys_rq' => $sysRqDb,
  13755. ]);
  13756. }
  13757. Db::commit();
  13758. } catch (\Throwable $e) {
  13759. Db::rollback();
  13760. $this->error($e->getMessage());
  13761. }
  13762. foreach ($pos as $poRow) {
  13763. if (!is_array($poRow)) {
  13764. continue;
  13765. }
  13766. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13767. if (!$this->isValidScydgyRowId($sid)) {
  13768. continue;
  13769. }
  13770. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  13771. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  13772. }
  13773. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  13774. }
  13775. /**
  13776. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  13777. */
  13778. public function auditResendSms()
  13779. {
  13780. if (!$this->request->isPost()) {
  13781. $this->error(__('Invalid parameters'));
  13782. }
  13783. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13784. if ($scydgyId === '') {
  13785. $this->error('参数无效');
  13786. }
  13787. $loaded = $this->loadAuditResendBundle($scydgyId);
  13788. $mergeRows = $loaded['merge_rows'];
  13789. $bundle = $loaded['bundle'];
  13790. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  13791. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13792. if ($quoteGroups === []) {
  13793. $this->error('暂无可通知的供应商');
  13794. }
  13795. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  13796. $companiesJson = (string)$this->request->post('companies_json', '');
  13797. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  13798. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  13799. }
  13800. /**
  13801. * 确认供应商 — 二次发送邮件(可选单家/批量)
  13802. */
  13803. public function auditResendEmail()
  13804. {
  13805. if (!$this->request->isPost()) {
  13806. $this->error(__('Invalid parameters'));
  13807. }
  13808. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13809. if ($scydgyId === '') {
  13810. $this->error('参数无效');
  13811. }
  13812. $loaded = $this->loadAuditResendBundle($scydgyId);
  13813. $mergeRows = $loaded['merge_rows'];
  13814. $bundle = $loaded['bundle'];
  13815. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  13816. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13817. if ($quoteGroups === []) {
  13818. $this->error('暂无可通知的供应商');
  13819. }
  13820. $companiesJson = (string)$this->request->post('companies_json', '');
  13821. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  13822. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  13823. if ($companiesJson === '' && $selectedCompany === '') {
  13824. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  13825. }
  13826. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  13827. }
  13828. /**
  13829. * 废弃单个订单 bundle(退回供应商初选,明细归档留痕)
  13830. *
  13831. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  13832. * @return array<int, true> 已处理的 scydgy_id 集合
  13833. */
  13834. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回供应商初选'): array
  13835. {
  13836. $pos = $bundle['pos'] ?? [];
  13837. if (!is_array($pos) || $pos === []) {
  13838. return [];
  13839. }
  13840. $sids = [];
  13841. $poIdBySid = [];
  13842. foreach ($pos as $poRow) {
  13843. if (!is_array($poRow)) {
  13844. continue;
  13845. }
  13846. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13847. if ($this->isValidScydgyRowId($sid)) {
  13848. $sids[$sid] = true;
  13849. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  13850. if ($poId > 0) {
  13851. $poIdBySid[$sid] = $poId;
  13852. }
  13853. }
  13854. }
  13855. if ($sids === []) {
  13856. return [];
  13857. }
  13858. $logMsg = '重新下发';
  13859. $suffix = trim((string)$logSuffix, ',, ');
  13860. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  13861. $logMsg .= ':从历史存证退回供应商初选';
  13862. } else {
  13863. $logMsg .= ':退回供应商初选';
  13864. }
  13865. Db::table('purchase_order')
  13866. ->where('scydgy_id', 'in', array_keys($sids))
  13867. ->update([
  13868. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  13869. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  13870. 'pick_company_name' => '',
  13871. 'pick_time' => null,
  13872. 'sys_rq' => null,
  13873. 'mod_rq' => null,
  13874. 'manual_pick' => 0,
  13875. 'manual_pick_reason' => '',
  13876. ]);
  13877. // 重新下发后需重新开标;清掉本批按订单号/批次号记录的开标验证
  13878. $ccydhSet = [];
  13879. $batchSet = [];
  13880. $cgySet = [];
  13881. foreach ($pos as $poRow) {
  13882. if (!is_array($poRow)) {
  13883. continue;
  13884. }
  13885. foreach ($this->expandProcuremenCcydhTokens($poRow['CCYDH'] ?? '') as $dh) {
  13886. $ccydhSet[$dh] = true;
  13887. }
  13888. $bn = $this->resolveProcuremenOrderBatchNo($poRow);
  13889. if ($bn !== '') {
  13890. $batchSet[$bn] = true;
  13891. }
  13892. $cgy = trim((string)($poRow['CGYMC'] ?? ''));
  13893. if ($cgy !== '') {
  13894. $cgySet[$cgy] = true;
  13895. }
  13896. }
  13897. $this->clearProcuremenBidOpenRecords(array_keys($ccydhSet), array_keys($batchSet));
  13898. $this->clearProcuremenSupplierScoresForCcydhs(array_keys($ccydhSet));
  13899. // 同订单其它旧批次(有明确批次号、未完结)软删除,避免列表/弹窗仍读到旧批「已开标/已指定」
  13900. $keepBatch = '';
  13901. if ($batchSet !== []) {
  13902. $batchKeys = array_keys($batchSet);
  13903. $keepBatch = (string)reset($batchKeys);
  13904. }
  13905. // 返回被软删的旧批次 scydgy_id,用于废弃其明细
  13906. $voidedSids = $this->softDeleteOtherBatchPurchaseOrders(array_keys($ccydhSet), array_keys($sids), $keepBatch, array_keys($cgySet));
  13907. // 废弃本批次新工序的明细(重新下发后重新招标)
  13908. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  13909. // 废弃被软删旧批次的明细(防止卡在"已提交"状态)
  13910. if ($voidedSids !== []) {
  13911. $this->voidPurchaseOrderDetailsForScydgyIds($voidedSids);
  13912. // 旧批次被重新下发流程软删,记录日志便于追溯
  13913. foreach ($voidedSids as $oldSid) {
  13914. $oldSidInt = (int)$oldSid;
  13915. if ($this->isValidScydgyRowId($oldSidInt)) {
  13916. $this->addOrderLog($oldSidInt, $logAction, '重新下发:同批次工序旧数据软删', null);
  13917. }
  13918. }
  13919. }
  13920. foreach (array_keys($sids) as $sid) {
  13921. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  13922. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  13923. }
  13924. return $sids;
  13925. }
  13926. /**
  13927. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  13928. *
  13929. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  13930. */
  13931. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  13932. {
  13933. $scydgyId = trim($scydgyId);
  13934. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  13935. if ($scydgyId === '') {
  13936. return $empty;
  13937. }
  13938. try {
  13939. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  13940. } catch (\Throwable $e) {
  13941. $anchor = null;
  13942. }
  13943. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  13944. return $empty;
  13945. }
  13946. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  13947. if ($ccydh === '') {
  13948. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  13949. }
  13950. try {
  13951. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  13952. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  13953. $pos = $query->order('scydgy_id', 'asc')->select();
  13954. } catch (\Throwable $e) {
  13955. $pos = [$anchor];
  13956. }
  13957. if (!is_array($pos) || $pos === []) {
  13958. $pos = [$anchor];
  13959. }
  13960. return [
  13961. 'ccydh' => $ccydh,
  13962. 'pos' => $pos,
  13963. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  13964. ];
  13965. }
  13966. protected function purchaseOrderRowIsCompleted(array $po): bool
  13967. {
  13968. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  13969. }
  13970. /**
  13971. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  13972. *
  13973. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  13974. */
  13975. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  13976. {
  13977. $scydgyId = trim($scydgyId);
  13978. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  13979. if ($scydgyId === '') {
  13980. return $empty;
  13981. }
  13982. try {
  13983. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  13984. } catch (\Throwable $e) {
  13985. $anchor = null;
  13986. }
  13987. if (!is_array($anchor)) {
  13988. return $empty;
  13989. }
  13990. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  13991. if ($ccydh === '') {
  13992. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  13993. }
  13994. try {
  13995. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  13996. } catch (\Throwable $e) {
  13997. $pos = [$anchor];
  13998. }
  13999. if (!is_array($pos) || $pos === []) {
  14000. $pos = [$anchor];
  14001. }
  14002. $pos = $this->filterPurchaseOrdersSameIssueBatch($pos, $anchor);
  14003. return [
  14004. 'ccydh' => $ccydh,
  14005. 'pos' => $pos,
  14006. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  14007. ];
  14008. }
  14009. /**
  14010. * 废弃订单 — 退回供应商初选重新询价(支持单条或批量)
  14011. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  14012. */
  14013. public function auditAbandon()
  14014. {
  14015. if (!$this->request->isPost()) {
  14016. $this->error(__('Invalid parameters'));
  14017. }
  14018. $anchorIds = [];
  14019. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  14020. if ($batchRaw !== '') {
  14021. $decoded = json_decode($batchRaw, true);
  14022. if (is_array($decoded)) {
  14023. foreach ($decoded as $id) {
  14024. $s = trim((string)$id);
  14025. if ($s !== '') {
  14026. $anchorIds[] = $s;
  14027. }
  14028. }
  14029. }
  14030. }
  14031. if ($anchorIds === []) {
  14032. $single = trim((string)$this->request->post('scydgy_id', ''));
  14033. if ($single !== '') {
  14034. $anchorIds[] = $single;
  14035. }
  14036. }
  14037. if ($anchorIds === []) {
  14038. $this->error('请至少选择一条订单');
  14039. }
  14040. $processedCcydh = [];
  14041. $doneOrders = 0;
  14042. $allSids = [];
  14043. Db::startTrans();
  14044. try {
  14045. foreach ($anchorIds as $anchorId) {
  14046. $fromArchive = false;
  14047. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  14048. if (($bundle['pos'] ?? []) === []) {
  14049. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  14050. $fromArchive = ($bundle['pos'] ?? []) !== [];
  14051. }
  14052. if (($bundle['pos'] ?? []) === []) {
  14053. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  14054. $fromArchive = ($bundle['pos'] ?? []) !== [];
  14055. }
  14056. if (($bundle['pos'] ?? []) === []) {
  14057. continue;
  14058. }
  14059. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  14060. $batchTime = '';
  14061. if (!empty($bundle['pos'][0]) && is_array($bundle['pos'][0])) {
  14062. $batchTime = $this->procuremenIssueBatchTime($bundle['pos'][0]);
  14063. }
  14064. $dedupeKey = $ccydh !== '' ? ($ccydh . '|' . $batchTime) : ('sid:' . $anchorId);
  14065. if (isset($processedCcydh[$dedupeKey])) {
  14066. continue;
  14067. }
  14068. $processedCcydh[$dedupeKey] = true;
  14069. $sids = $fromArchive
  14070. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回供应商初选')
  14071. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  14072. if ($sids === []) {
  14073. continue;
  14074. }
  14075. $doneOrders++;
  14076. foreach (array_keys($sids) as $sid) {
  14077. $allSids[(int)$sid] = true;
  14078. }
  14079. }
  14080. if ($doneOrders < 1) {
  14081. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  14082. }
  14083. Db::commit();
  14084. } catch (\Throwable $e) {
  14085. Db::rollback();
  14086. $this->error($e->getMessage());
  14087. }
  14088. $this->pickHiddenScydgySetCache = null;
  14089. $msg = $doneOrders > 1
  14090. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回供应商初选,历史下发与操作记录已保留')
  14091. : '已退回供应商初选,请重新选择供应商下发(历史记录已保留)';
  14092. $this->success($msg);
  14093. }
  14094. /**
  14095. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  14096. */
  14097. public function archiveAbandon()
  14098. {
  14099. return $this->auditAbandon();
  14100. }
  14101. /**
  14102. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  14103. */
  14104. public function purchaseApprovalReject()
  14105. {
  14106. if (!$this->request->isPost() || !$this->request->isAjax()) {
  14107. $this->error(__('Invalid parameters'));
  14108. }
  14109. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  14110. $this->error(__('You have no permission'));
  14111. }
  14112. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  14113. $decoded = json_decode($batchRaw, true);
  14114. if (!is_array($decoded) || $decoded === []) {
  14115. $this->error('提交数据无效');
  14116. }
  14117. $done = 0;
  14118. Db::startTrans();
  14119. try {
  14120. foreach ($decoded as $item) {
  14121. if (!is_array($item)) {
  14122. continue;
  14123. }
  14124. $sid = (int)($item['scydgy_id'] ?? 0);
  14125. if (!$this->isValidScydgyRowId($sid)) {
  14126. continue;
  14127. }
  14128. $this->runPurchaseApprovalRejectForSid($sid);
  14129. $done++;
  14130. }
  14131. if ($done < 1) {
  14132. throw new \Exception('所选订单均不在待审批状态');
  14133. }
  14134. Db::commit();
  14135. } catch (\Throwable $e) {
  14136. Db::rollback();
  14137. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  14138. }
  14139. $this->pickHiddenScydgySetCache = null;
  14140. $this->success('已驳回并退回「确认供应商」');
  14141. }
  14142. /**
  14143. * @throws \Exception
  14144. */
  14145. protected function runPurchaseApprovalRejectForSid(int $sid): void
  14146. {
  14147. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  14148. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  14149. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  14150. $allIds = $this->purchaseOrderDetail($sid);
  14151. if ($allIds === []) {
  14152. throw new \Exception('未找到下发明细');
  14153. }
  14154. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  14155. 'wflow_status' => ProcuremenStatus::WFLOW_REJECTED,
  14156. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  14157. 'pick_company_name' => '',
  14158. ]);
  14159. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  14160. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  14161. $poId = 0;
  14162. try {
  14163. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  14164. if (is_array($po)) {
  14165. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  14166. }
  14167. } catch (\Throwable $e) {
  14168. }
  14169. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  14170. }
  14171. /**
  14172. * 审核弹窗(旧入口,POST 已关闭)
  14173. */
  14174. public function review()
  14175. {
  14176. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  14177. $this->error(__('You have no permission'));
  14178. }
  14179. if ($this->request->isPost()) {
  14180. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  14181. }
  14182. $this->view->assign('pickMode', 0);
  14183. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  14184. }
  14185. /**
  14186. * 审核弹窗获取公司列表
  14187. */
  14188. public function reviewCompanies()
  14189. {
  14190. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  14191. $this->error(__('You have no permission'));
  14192. }
  14193. if (!$this->request->isAjax()) {
  14194. $this->error(__('Invalid parameters'));
  14195. }
  14196. $list = [];
  14197. try {
  14198. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  14199. $rows = Db::table('customer')
  14200. ->where(function ($q) {
  14201. $q->where('status', 1)
  14202. ->whereOr('status', '1')
  14203. ->whereOr('status', '')
  14204. ->whereNull('status');
  14205. })
  14206. ->order('id', 'desc')
  14207. ->select();
  14208. } catch (\Throwable $e) {
  14209. $this->success('', '', []);
  14210. return;
  14211. }
  14212. if (!is_array($rows)) {
  14213. $this->success('', '', []);
  14214. return;
  14215. }
  14216. $detailColCandidates = [
  14217. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  14218. 'company_detail', 'company_desc', 'address',
  14219. ];
  14220. foreach ($rows as $row) {
  14221. if (!is_array($row)) {
  14222. continue;
  14223. }
  14224. $norm = [];
  14225. foreach ($row as $k => $v) {
  14226. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  14227. }
  14228. $row = $norm;
  14229. $st = $row['status'] ?? '';
  14230. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  14231. continue;
  14232. }
  14233. $payload = $this->buildCustomerContactPayloadFromRow($row, false);
  14234. if ($payload === null) {
  14235. continue;
  14236. }
  14237. $detail = '';
  14238. foreach ($detailColCandidates as $dk) {
  14239. if (!isset($row[$dk])) {
  14240. continue;
  14241. }
  14242. $dv = trim((string)$row[$dk]);
  14243. if ($dv !== '') {
  14244. $detail = $dv;
  14245. break;
  14246. }
  14247. }
  14248. $payload['detail'] = $detail;
  14249. $list[] = $this->maskSupplierContactFields($payload);
  14250. }
  14251. $this->success('', '', $list);
  14252. }
  14253. /**
  14254. * 采购确认-下发明细弹窗:
  14255. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  14256. */
  14257. public function outward_detail()
  14258. {
  14259. $ids = $this->request->param('ids', $this->request->param('id', ''));
  14260. if (is_array($ids)) {
  14261. $ids = isset($ids[0]) ? $ids[0] : '';
  14262. }
  14263. $ids = trim((string)$ids);
  14264. if ($ids === '') {
  14265. $this->error(__('Invalid parameters'));
  14266. }
  14267. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  14268. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  14269. $wffTab = 'all';
  14270. }
  14271. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  14272. $purchaseOrderId = 0;
  14273. $po = null;
  14274. try {
  14275. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  14276. if (is_array($po)) {
  14277. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  14278. }
  14279. } catch (\Throwable $e) {
  14280. $purchaseOrderId = 0;
  14281. $po = null;
  14282. }
  14283. if (!$isPurchaseConfirm && is_array($po)) {
  14284. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  14285. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  14286. $isPurchaseConfirm = true;
  14287. }
  14288. }
  14289. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  14290. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  14291. $confirmProcessCount = 1;
  14292. $confirmPickGroups = [];
  14293. $processDisplayRows = [];
  14294. $allDetailsBySid = [];
  14295. $requiredSidList = [];
  14296. $sidList = [$ids];
  14297. if ($isPurchaseConfirm) {
  14298. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  14299. if (!$this->canViewProcuremenSupplierQuotesForBundle($confirmBundle)) {
  14300. $this->error('本单尚未开标或指定供应商,不能审批');
  14301. }
  14302. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  14303. if ($mergeRows !== []) {
  14304. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  14305. }
  14306. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  14307. if ($confirmBundle['pos'] !== []) {
  14308. $sidList = [];
  14309. foreach ($confirmBundle['pos'] as $poRow) {
  14310. if (!is_array($poRow)) {
  14311. continue;
  14312. }
  14313. $sid = (int)($poRow['scydgy_id'] ?? 0);
  14314. if (!$this->isValidScydgyRowId($sid)) {
  14315. continue;
  14316. }
  14317. $sidList[] = (string)$sid;
  14318. $requiredSidList[] = $sid;
  14319. }
  14320. }
  14321. if ($sidList === []) {
  14322. $sidList = [$ids];
  14323. $requiredSidList = [(int)$ids];
  14324. }
  14325. $confirmProcessCount = max(1, count($requiredSidList));
  14326. if (is_array($po) && $purchaseOrderId <= 0) {
  14327. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  14328. }
  14329. }
  14330. $rows = [];
  14331. try {
  14332. if (count($sidList) === 1) {
  14333. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  14334. } else {
  14335. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  14336. }
  14337. } catch (\Throwable $e) {
  14338. $rows = [];
  14339. }
  14340. if ($isPurchaseConfirm) {
  14341. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  14342. }
  14343. foreach ($rows as &$r) {
  14344. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  14345. $r['id'] = $r['ID'];
  14346. }
  14347. if (isset($r['createtime'])) {
  14348. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  14349. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  14350. } else {
  14351. $r['createtime_text'] = (string)$r['createtime'];
  14352. }
  14353. } else {
  14354. $r['createtime_text'] = '';
  14355. }
  14356. if (is_array($r)) {
  14357. $r = $this->maskSupplierContactFields($r);
  14358. }
  14359. }
  14360. unset($r);
  14361. $pickedCompanyName = '';
  14362. $manualPicked = 0;
  14363. $manualPickReason = '';
  14364. $quoteVisible = 0;
  14365. $bidOpenVerified = 0;
  14366. if ($isPurchaseConfirm) {
  14367. // 确认包为空时,用当前主单兜底,避免指定说明读不到
  14368. if (($confirmBundle['ccydh'] ?? '') === '' && is_array($po)) {
  14369. $confirmBundle['ccydh'] = trim((string)($po['CCYDH'] ?? ''));
  14370. }
  14371. if (($confirmBundle['pos'] ?? []) === [] && is_array($po)) {
  14372. $confirmBundle['pos'] = [$po];
  14373. }
  14374. $manualPickInfo = $this->resolveProcuremenManualPickInfo($confirmBundle);
  14375. $manualPicked = $this->isProcuremenManualPickedForBundle($confirmBundle) ? 1 : 0;
  14376. $manualPickReason = (string)($manualPickInfo['reason'] ?? '');
  14377. if ($manualPickInfo['company'] !== '') {
  14378. $pickedCompanyName = $manualPickInfo['company'];
  14379. }
  14380. if ($pickedCompanyName === '') {
  14381. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  14382. if (!is_array($poRow)) {
  14383. continue;
  14384. }
  14385. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  14386. if ($pn !== '') {
  14387. $pickedCompanyName = $pn;
  14388. break;
  14389. }
  14390. }
  14391. }
  14392. // 再兜底:直接读当前主单字段
  14393. if (is_array($po) && (int)($po['manual_pick'] ?? 0) === 1) {
  14394. $manualPicked = 1;
  14395. if ($manualPickReason === '') {
  14396. $manualPickReason = trim((string)($po['manual_pick_reason'] ?? ''));
  14397. }
  14398. if ($pickedCompanyName === '') {
  14399. $pickedCompanyName = trim((string)($po['pick_company_name'] ?? ''));
  14400. }
  14401. }
  14402. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle) ? 1 : 0;
  14403. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  14404. }
  14405. $this->view->assign('rows', $rows ?: []);
  14406. $this->view->assign('rowCount', count($rows ?: []));
  14407. $this->view->assign('scydgyId', $ids);
  14408. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  14409. $this->view->assign('headTitle', $headTitle);
  14410. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  14411. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  14412. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  14413. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  14414. $this->view->assign('orderBatchNo', $this->resolveBundleOrderBatchNo($confirmBundle));
  14415. $this->view->assign('processDisplayRows', $processDisplayRows);
  14416. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  14417. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  14418. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  14419. $this->view->assign('manualPicked', $manualPicked);
  14420. $this->view->assign('manualPickReason', $manualPickReason);
  14421. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  14422. $this->view->assign('quoteVisible', $quoteVisible);
  14423. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
  14424. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  14425. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
  14426. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
  14427. $sysRqDisplay = '—';
  14428. if ($isPurchaseConfirm) {
  14429. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  14430. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  14431. );
  14432. }
  14433. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  14434. $this->view->assign('sysRq', $isPurchaseConfirm
  14435. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  14436. : '');
  14437. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  14438. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  14439. : '');
  14440. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  14441. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  14442. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  14443. if ($isPurchaseConfirm) {
  14444. return $this->view->fetch();
  14445. }
  14446. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  14447. $this->view->engine->layout(false);
  14448. try {
  14449. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  14450. $this->view->assign('dialogBody', $bodyHtml);
  14451. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  14452. } finally {
  14453. if ($restoreLayout) {
  14454. $this->view->engine->layout($restoreLayout);
  14455. }
  14456. }
  14457. }
  14458. /**
  14459. * 月度导出记录表(不存在时自动创建)
  14460. */
  14461. protected function ensurePurchaseMonthExportLogTable(): void
  14462. {
  14463. try {
  14464. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  14465. } catch (\Throwable $e) {
  14466. Db::execute(
  14467. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  14468. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  14469. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  14470. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  14471. `admin_name` varchar(64) NOT NULL DEFAULT '',
  14472. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  14473. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  14474. `createtime` int(10) unsigned DEFAULT NULL,
  14475. PRIMARY KEY (`id`),
  14476. KEY `idx_ym` (`ym`),
  14477. KEY `idx_ct` (`createtime`)
  14478. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  14479. );
  14480. }
  14481. }
  14482. /**
  14483. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  14484. *
  14485. * @param array<int, mixed> $dbRows
  14486. * @return array<int, array<string, mixed>>
  14487. */
  14488. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  14489. {
  14490. $keyword = trim((string)$this->request->get('search', ''));
  14491. if ($keyword === '') {
  14492. $keyword = trim((string)$this->request->request('search', ''));
  14493. }
  14494. $filter = $this->request->get('filter', '');
  14495. $op = $this->request->get('op', '');
  14496. if (is_string($filter) && $filter !== '') {
  14497. $filterArr = (array)json_decode($filter, true);
  14498. } else {
  14499. $filterArr = is_array($filter) ? $filter : [];
  14500. }
  14501. if (is_string($op) && $op !== '') {
  14502. $opArr = (array)json_decode($op, true);
  14503. } else {
  14504. $opArr = is_array($op) ? $op : [];
  14505. }
  14506. if ($keyword === '' && $filterArr === []) {
  14507. return array_values(array_filter($dbRows, 'is_array'));
  14508. }
  14509. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  14510. $out = [];
  14511. foreach ($dbRows as $row) {
  14512. if (!is_array($row)) {
  14513. continue;
  14514. }
  14515. if ($keyword !== '') {
  14516. $hit = false;
  14517. foreach ($searchFields as $f) {
  14518. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  14519. $hit = true;
  14520. break;
  14521. }
  14522. }
  14523. if (!$hit) {
  14524. continue;
  14525. }
  14526. }
  14527. $passFilter = true;
  14528. foreach ($filterArr as $field => $val) {
  14529. $field = (string)$field;
  14530. $val = trim((string)$val);
  14531. if ($field === '' || $val === '') {
  14532. continue;
  14533. }
  14534. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  14535. continue;
  14536. }
  14537. $cell = (string)($row[$field] ?? '');
  14538. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  14539. if ($mode === '=' || $mode === 'EQUAL') {
  14540. if (strcasecmp($cell, $val) !== 0) {
  14541. $passFilter = false;
  14542. break;
  14543. }
  14544. } elseif (mb_stripos($cell, $val) === false) {
  14545. $passFilter = false;
  14546. break;
  14547. }
  14548. }
  14549. if (!$passFilter) {
  14550. continue;
  14551. }
  14552. $out[] = $row;
  14553. }
  14554. return $out;
  14555. }
  14556. /**
  14557. * 按月份导出:审批通过订单(与月度列表一致),按审批月份筛选。
  14558. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  14559. */
  14560. public function export_month_outward()
  14561. {
  14562. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  14563. $this->error(__('You have no permission'));
  14564. }
  14565. $bundle = $this->prepareMonthOutwardExportBundle();
  14566. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  14567. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  14568. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  14569. $spreadsheet = new Spreadsheet();
  14570. $sheet = $spreadsheet->getActiveSheet();
  14571. $sheet->setTitle('外协加工明细');
  14572. $mon = (int)substr($ym, 5, 2);
  14573. $sheet->mergeCells('A1:H1');
  14574. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  14575. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  14576. $sheet->getStyle('A1')->getAlignment()
  14577. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  14578. ->setVertical(Alignment::VERTICAL_CENTER);
  14579. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  14580. $col = 'A';
  14581. foreach ($headers as $h) {
  14582. $sheet->setCellValue($col . '2', $h);
  14583. $col++;
  14584. }
  14585. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  14586. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  14587. $rowNum = 3;
  14588. $sumSubtotalCounts = 0;
  14589. $grandAmount = 0.0;
  14590. $globalSeq = 0;
  14591. if ($groups === []) {
  14592. $sheet->mergeCells('A3:H3');
  14593. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  14594. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  14595. $rowNum = 4;
  14596. } else {
  14597. foreach ($groups as $items) {
  14598. if ($items === []) {
  14599. continue;
  14600. }
  14601. $groupLineCount = count($items);
  14602. $subAmount = 0.0;
  14603. foreach ($items as $line) {
  14604. $globalSeq++;
  14605. $dr = $line['detail'];
  14606. $amt = $this->procuremenExportAmount($dr);
  14607. $subAmount += $amt;
  14608. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  14609. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  14610. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  14611. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  14612. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  14613. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  14614. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  14615. $sheet->setCellValue('H' . $rowNum, $amt);
  14616. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  14617. $rowNum++;
  14618. }
  14619. $sumSubtotalCounts += $groupLineCount;
  14620. $grandAmount += $subAmount;
  14621. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  14622. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  14623. $sheet->getStyle('G' . $rowNum)->getAlignment()
  14624. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  14625. ->setVertical(Alignment::VERTICAL_CENTER);
  14626. $rowNum++;
  14627. }
  14628. }
  14629. $sheet->setCellValue('A' . $rowNum, '总计');
  14630. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  14631. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  14632. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  14633. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  14634. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  14635. $lastRow = $rowNum;
  14636. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  14637. 'borders' => [
  14638. 'allBorders' => [
  14639. 'borderStyle' => Border::BORDER_THIN,
  14640. 'color' => ['rgb' => '000000'],
  14641. ],
  14642. ],
  14643. ]);
  14644. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  14645. if ($lastRow >= 3) {
  14646. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14647. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14648. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14649. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14650. }
  14651. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  14652. $sheet->getColumnDimension('A')->setWidth(7);
  14653. $sheet->getColumnDimension('B')->setWidth(16);
  14654. $sheet->getColumnDimension('C')->setWidth(52);
  14655. $sheet->getColumnDimension('D')->setWidth(32);
  14656. $sheet->getColumnDimension('E')->setWidth(12);
  14657. $sheet->getColumnDimension('F')->setWidth(44);
  14658. $sheet->getColumnDimension('G')->setWidth(26);
  14659. $sheet->getColumnDimension('H')->setWidth(13);
  14660. $sheet->getRowDimension(1)->setRowHeight(28);
  14661. $ymCompact = str_replace('-', '', $ym);
  14662. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  14663. $filename = $fileBase . '.xlsx';
  14664. try {
  14665. $this->ensurePurchaseMonthExportLogTable();
  14666. list($adminId, $adminName) = $this->GetUseName();
  14667. Db::table('purchase_month_export_log')->insert([
  14668. 'ym' => $ym,
  14669. 'admin_id' => (int)$adminId,
  14670. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  14671. 'row_count' => count($exportLines),
  14672. 'total_amount' => round($grandAmount, 2),
  14673. 'createtime' => time(),
  14674. ]);
  14675. } catch (\Throwable $e) {
  14676. Log::write('month export log: ' . $e->getMessage(), 'error');
  14677. }
  14678. if (ob_get_length()) {
  14679. ob_end_clean();
  14680. }
  14681. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  14682. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  14683. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  14684. header('Cache-Control: max-age=0');
  14685. $writer = new Xlsx($spreadsheet);
  14686. $writer->save('php://output');
  14687. $spreadsheet->disconnectWorksheets();
  14688. unset($spreadsheet);
  14689. exit;
  14690. }
  14691. /**
  14692. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  14693. */
  14694. public function export_month_quote()
  14695. {
  14696. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  14697. $this->error(__('You have no permission'));
  14698. }
  14699. $bundle = $this->prepareMonthOutwardExportBundle();
  14700. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  14701. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  14702. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  14703. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  14704. $spreadsheet = new Spreadsheet();
  14705. $sheet = $spreadsheet->getActiveSheet();
  14706. $sheet->setTitle('供应商报价明细');
  14707. $mon = (int)substr($ym, 5, 2);
  14708. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  14709. $sheet->getColumnDimension('A')->setWidth(7);
  14710. $sheet->getColumnDimension('B')->setWidth(16);
  14711. $sheet->getColumnDimension('C')->setWidth(52);
  14712. $sheet->getColumnDimension('D')->setWidth(26);
  14713. $sheet->getColumnDimension('E')->setWidth(32);
  14714. $sheet->getColumnDimension('F')->setWidth(12);
  14715. $sheet->getColumnDimension('G')->setWidth(14);
  14716. $sheet->getColumnDimension('H')->setWidth(12);
  14717. if ($quoteLastRow < 1) {
  14718. $quoteLastRow = 3;
  14719. }
  14720. $ymCompact = str_replace('-', '', $ym);
  14721. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  14722. if (ob_get_length()) {
  14723. ob_end_clean();
  14724. }
  14725. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  14726. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  14727. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  14728. header('Cache-Control: max-age=0');
  14729. $writer = new Xlsx($spreadsheet);
  14730. $writer->save('php://output');
  14731. $spreadsheet->disconnectWorksheets();
  14732. unset($spreadsheet);
  14733. exit;
  14734. }
  14735. /**
  14736. * 月度导出公共数据:审批通过订单按月份/搜索筛选后的主表与明细(不要求已完结)
  14737. *
  14738. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  14739. */
  14740. protected function prepareMonthOutwardExportBundle(): array
  14741. {
  14742. $this->request->filter(['strip_tags', 'trim']);
  14743. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  14744. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  14745. $ym = date('Y-m');
  14746. }
  14747. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  14748. $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%\')';
  14749. $dbRows = [];
  14750. try {
  14751. $dbRows = Db::table('purchase_order')
  14752. ->where('wflow_status', 'in', $approvedVals)
  14753. ->whereRaw($softDel)
  14754. ->select();
  14755. } catch (\Throwable $e) {
  14756. $dbRows = [];
  14757. }
  14758. if (!is_array($dbRows)) {
  14759. $dbRows = [];
  14760. }
  14761. $completeTsMap = [];
  14762. $sidList = [];
  14763. foreach ($dbRows as $dbRow) {
  14764. if (!is_array($dbRow)) {
  14765. continue;
  14766. }
  14767. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  14768. if ($sid > 0) {
  14769. $sidList[$sid] = true;
  14770. }
  14771. }
  14772. if ($sidList !== []) {
  14773. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  14774. }
  14775. // 导出按「查看月份」取当月审批通过单;搜索只在当月内再缩小
  14776. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  14777. if (!is_array($dbRow)) {
  14778. return false;
  14779. }
  14780. if (!ProcuremenStatus::isWflowApproved($dbRow['wflow_status'] ?? '')) {
  14781. return false;
  14782. }
  14783. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  14784. if ($done['ts'] <= 0) {
  14785. return false;
  14786. }
  14787. return date('Y-m', $done['ts']) === $ym;
  14788. }));
  14789. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  14790. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  14791. $mainBySid = [];
  14792. foreach ($pool as $rw) {
  14793. if (!is_array($rw)) {
  14794. continue;
  14795. }
  14796. $rid = (int)($rw['ID'] ?? 0);
  14797. if ($rid > 0) {
  14798. $mainBySid[$rid] = $rw;
  14799. }
  14800. }
  14801. if ($mainBySid === []) {
  14802. $detailRows = [];
  14803. } else {
  14804. try {
  14805. $detailRows = Db::table('purchase_order_detail')
  14806. ->where('scydgy_id', 'in', array_keys($mainBySid))
  14807. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  14808. ->order('status', 'desc')
  14809. ->order('CCYDH', 'asc')
  14810. ->order('company_name', 'asc')
  14811. ->order('id', 'asc')
  14812. ->select();
  14813. } catch (\Throwable $e) {
  14814. try {
  14815. $detailRows = Db::table('purchase_order_detail')
  14816. ->where('scydgy_id', 'in', array_keys($mainBySid))
  14817. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  14818. ->order('status', 'desc')
  14819. ->order('CCYDH', 'asc')
  14820. ->order('company_name', 'asc')
  14821. ->order('ID', 'asc')
  14822. ->select();
  14823. } catch (\Throwable $e2) {
  14824. $detailRows = [];
  14825. }
  14826. }
  14827. }
  14828. if (!is_array($detailRows)) {
  14829. $detailRows = [];
  14830. }
  14831. $exportLines = [];
  14832. $detailSidSeen = [];
  14833. foreach ($detailRows as $dr) {
  14834. if (!is_array($dr)) {
  14835. continue;
  14836. }
  14837. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  14838. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  14839. continue;
  14840. }
  14841. if (isset($detailSidSeen[$sid])) {
  14842. continue;
  14843. }
  14844. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  14845. continue;
  14846. }
  14847. $detailSidSeen[$sid] = true;
  14848. $m = $mainBySid[$sid];
  14849. $company = trim((string)($m['pick_company_name'] ?? ''));
  14850. if ($company === '') {
  14851. $company = trim((string)($dr['company_name'] ?? ''));
  14852. }
  14853. $exportLines[] = [
  14854. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  14855. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  14856. 'company_name' => $company,
  14857. 'CDF' => (string)($m['CDF'] ?? ''),
  14858. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  14859. 'gx' => $this->procuremenExportGxText($m),
  14860. 'detail' => $dr,
  14861. ];
  14862. }
  14863. foreach ($detailRows as $dr) {
  14864. if (!is_array($dr)) {
  14865. continue;
  14866. }
  14867. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  14868. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  14869. continue;
  14870. }
  14871. $detailSidSeen[$sid] = true;
  14872. $m = $mainBySid[$sid];
  14873. $company = trim((string)($m['pick_company_name'] ?? ''));
  14874. if ($company === '') {
  14875. $company = trim((string)($dr['company_name'] ?? ''));
  14876. }
  14877. $exportLines[] = [
  14878. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  14879. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  14880. 'company_name' => $company,
  14881. 'CDF' => (string)($m['CDF'] ?? ''),
  14882. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  14883. 'gx' => $this->procuremenExportGxText($m),
  14884. 'detail' => $dr,
  14885. ];
  14886. }
  14887. foreach ($mainBySid as $sid => $m) {
  14888. if (isset($detailSidSeen[$sid])) {
  14889. continue;
  14890. }
  14891. $company = trim((string)($m['pick_company_name'] ?? ''));
  14892. $exportLines[] = [
  14893. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  14894. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  14895. 'company_name' => $company,
  14896. 'CDF' => (string)($m['CDF'] ?? ''),
  14897. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  14898. 'gx' => $this->procuremenExportGxText($m),
  14899. 'detail' => [],
  14900. ];
  14901. }
  14902. $groups = [];
  14903. foreach ($exportLines as $line) {
  14904. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  14905. if (!isset($groups[$k])) {
  14906. $groups[$k] = [];
  14907. }
  14908. $groups[$k][] = $line;
  14909. }
  14910. ksort($groups, SORT_STRING);
  14911. return [
  14912. 'ym' => $ym,
  14913. 'mainBySid' => $mainBySid,
  14914. 'detailRows' => $detailRows,
  14915. 'exportLines' => $exportLines,
  14916. 'groups' => $groups,
  14917. ];
  14918. }
  14919. /**
  14920. * 导出用:工序列文案
  14921. */
  14922. protected function procuremenExportGxText(array $r)
  14923. {
  14924. return ProcuremenFormat::exportGxText($r);
  14925. }
  14926. /**
  14927. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  14928. */
  14929. protected function procuremenExportAmount(array $r)
  14930. {
  14931. return ProcuremenFormat::exportAmount($r);
  14932. }
  14933. /**
  14934. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  14935. *
  14936. * @param array<int, array<string, mixed>> $detailRows
  14937. * @param array<int, array<string, mixed>> $mainBySid
  14938. * @return array<int, array<string, mixed>>
  14939. */
  14940. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  14941. {
  14942. $lines = [];
  14943. foreach ($detailRows as $dr) {
  14944. if (!is_array($dr)) {
  14945. continue;
  14946. }
  14947. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  14948. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  14949. continue;
  14950. }
  14951. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  14952. continue;
  14953. }
  14954. $cn = trim((string)($dr['company_name'] ?? ''));
  14955. if ($cn === '') {
  14956. continue;
  14957. }
  14958. $m = $mainBySid[$sid];
  14959. $am = trim((string)($dr['amount'] ?? ''));
  14960. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  14961. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  14962. $amountText = $amountFilled
  14963. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  14964. : '未填写';
  14965. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  14966. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  14967. if ($deliveryShow === '' && $deliveryRaw !== '') {
  14968. $deliveryShow = $deliveryRaw;
  14969. }
  14970. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  14971. ? $deliveryShow
  14972. : '未填写';
  14973. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  14974. $lines[] = [
  14975. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  14976. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  14977. 'gx' => $this->procuremenExportGxText($m),
  14978. 'company_name' => $cn,
  14979. 'amount_text' => $amountText,
  14980. 'amount_num' => $amountFilled ? $amountNum : null,
  14981. 'delivery_text' => $deliveryText,
  14982. 'picked_text' => $picked ? '中标' : '未中标',
  14983. 'picked' => $picked,
  14984. ];
  14985. }
  14986. $winnerSupplierByOrder = [];
  14987. foreach ($lines as $line) {
  14988. $dh = trim((string)($line['CCYDH'] ?? ''));
  14989. $cn = trim((string)($line['company_name'] ?? ''));
  14990. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  14991. $winnerSupplierByOrder[$dh][$cn] = true;
  14992. }
  14993. }
  14994. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  14995. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  14996. if ($c !== 0) {
  14997. return $c;
  14998. }
  14999. $dh = trim((string)($a['CCYDH'] ?? ''));
  15000. $aCn = trim((string)($a['company_name'] ?? ''));
  15001. $bCn = trim((string)($b['company_name'] ?? ''));
  15002. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  15003. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  15004. if ($aSupplierWin !== $bSupplierWin) {
  15005. return $aSupplierWin ? -1 : 1;
  15006. }
  15007. $c = strcmp($aCn, $bCn);
  15008. if ($c !== 0) {
  15009. return $c;
  15010. }
  15011. if (!empty($a['picked']) !== !empty($b['picked'])) {
  15012. return !empty($a['picked']) ? -1 : 1;
  15013. }
  15014. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  15015. if ($c !== 0) {
  15016. return $c;
  15017. }
  15018. return 0;
  15019. });
  15020. return $lines;
  15021. }
  15022. /**
  15023. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  15024. *
  15025. * @param array<int, array<string, mixed>> $quoteLines
  15026. */
  15027. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  15028. {
  15029. $mon = (int)substr($ym, 5, 2);
  15030. $titleRow = $startRow;
  15031. $headerRow = $startRow + 1;
  15032. $dataStartRow = $startRow + 2;
  15033. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  15034. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  15035. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  15036. $sheet->getStyle('A' . $titleRow)->getAlignment()
  15037. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  15038. ->setVertical(Alignment::VERTICAL_CENTER);
  15039. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  15040. $col = 'A';
  15041. foreach ($headers as $h) {
  15042. $sheet->setCellValue($col . $headerRow, $h);
  15043. $col++;
  15044. }
  15045. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  15046. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  15047. $rowNum = $dataStartRow;
  15048. if ($quoteLines === []) {
  15049. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  15050. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  15051. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  15052. $rowNum = $dataStartRow + 1;
  15053. } else {
  15054. $i = 0;
  15055. foreach ($quoteLines as $line) {
  15056. $i++;
  15057. $sheet->setCellValue('A' . $rowNum, $i);
  15058. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  15059. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  15060. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  15061. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  15062. if ($line['amount_num'] !== null) {
  15063. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  15064. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  15065. } else {
  15066. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  15067. }
  15068. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  15069. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  15070. if (!empty($line['picked'])) {
  15071. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  15072. }
  15073. $rowNum++;
  15074. }
  15075. }
  15076. $lastRow = $rowNum - 1;
  15077. if ($lastRow >= $headerRow) {
  15078. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  15079. 'borders' => [
  15080. 'allBorders' => [
  15081. 'borderStyle' => Border::BORDER_THIN,
  15082. 'color' => ['rgb' => '000000'],
  15083. ],
  15084. ],
  15085. ]);
  15086. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  15087. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  15088. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  15089. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  15090. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  15091. if ($lastRow >= $dataStartRow) {
  15092. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  15093. }
  15094. }
  15095. return $lastRow;
  15096. }
  15097. /**
  15098. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  15099. */
  15100. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  15101. {
  15102. if ($lastRow < $dataStartRow || $headerRow < 1) {
  15103. return;
  15104. }
  15105. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  15106. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  15107. ->setVertical(Alignment::VERTICAL_CENTER);
  15108. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  15109. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  15110. ->setVertical(Alignment::VERTICAL_CENTER);
  15111. if ($lastCol > 'B') {
  15112. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  15113. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  15114. ->setVertical(Alignment::VERTICAL_CENTER);
  15115. }
  15116. }
  15117. /**
  15118. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  15119. */
  15120. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  15121. {
  15122. return ProcuremenFormat::sanitizePdfOrderKey($ccydh);
  15123. }
  15124. /**
  15125. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  15126. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  15127. *
  15128. * @return array{objectKey: string, webPath: string}
  15129. */
  15130. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  15131. {
  15132. return ProcuremenFormat::buildConfirmPdfPaths($scydgyId, $ccydhRaw);
  15133. }
  15134. /**
  15135. * 采购确认成功后 / 已完结刷新:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  15136. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  15137. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  15138. * 说明:审批通过时会先存一版;质量+交货评分使订单「已完结」后,详情页打开或评分保存完成时会再重存,以含最终步骤与操作记录。
  15139. *
  15140. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  15141. */
  15142. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  15143. {
  15144. if (!$this->isValidScydgyRowId($scydgyId)) {
  15145. return '';
  15146. }
  15147. $ids = trim((string)$scydgyId);
  15148. $prep = $this->prepareProcuremenDetailsView($ids);
  15149. if (!$prep['ok']) {
  15150. return '';
  15151. }
  15152. $ccydh = $prep['ccydh'];
  15153. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  15154. $objectKey = $paths['objectKey'];
  15155. $webPath = $paths['webPath'];
  15156. $cyjmc = '';
  15157. try {
  15158. $poMeta = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->field('CYJMC')->find();
  15159. if (is_array($poMeta)) {
  15160. $cyjmc = trim((string)($poMeta['CYJMC'] ?? ''));
  15161. }
  15162. } catch (\Throwable $e) {
  15163. $cyjmc = '';
  15164. }
  15165. $genTime = date('Y-m-d H:i:s');
  15166. $metaIds = '工序行ID ' . $ids . ' | 主表订单ID ' . (int)$purchaseOrderId;
  15167. $metaLeft = $metaIds . ($cyjmc !== '' ? ' | ' . $cyjmc : '');
  15168. // PDF 进度:去掉「未发」;节点用纯色圆点(不用图片,避免 mPDF 破图)
  15169. $pdfSteps = [];
  15170. $viewSteps = $prep['steps'] ?? [];
  15171. if (is_array($viewSteps)) {
  15172. foreach ($viewSteps as $st) {
  15173. if (!is_array($st)) {
  15174. continue;
  15175. }
  15176. if (trim((string)($st['title'] ?? '')) === '未发') {
  15177. continue;
  15178. }
  15179. $pdfSteps[] = $st;
  15180. }
  15181. }
  15182. $pdfStepW = count($pdfSteps) > 0 ? (round(100 / count($pdfSteps), 2) . '%') : '16.66%';
  15183. $nPdf = count($pdfSteps);
  15184. foreach ($pdfSteps as $idx => &$pst) {
  15185. if ($idx === 0) {
  15186. $pst['pdf_left_bg'] = '';
  15187. } else {
  15188. $pst['pdf_left_bg'] = !empty($pdfSteps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  15189. }
  15190. if ($idx >= $nPdf - 1) {
  15191. $pst['pdf_right_bg'] = '';
  15192. } else {
  15193. $pst['pdf_right_bg'] = !empty($pst['done']) ? '#1890ff' : '#e0e0e0';
  15194. }
  15195. }
  15196. unset($pst);
  15197. $this->view->assign([
  15198. 'pdf_export' => 1,
  15199. 'pdfMetaLine' => $metaLeft,
  15200. 'pdfMetaLeft' => $metaLeft,
  15201. 'pdfMetaIds' => $metaIds,
  15202. 'pdfMetaTitle' => $cyjmc,
  15203. 'pdfMetaTime' => 'PDF生成时间 ' . $genTime,
  15204. 'pdfSteps' => $pdfSteps,
  15205. 'pdfStepWidth' => $pdfStepW,
  15206. ]);
  15207. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  15208. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  15209. $this->view->engine->layout(false);
  15210. try {
  15211. $html = $this->view->fetch('procuremen/details_pdf_shell');
  15212. } catch (\Throwable $e) {
  15213. if ($restoreLayout) {
  15214. $this->view->engine->layout($restoreLayout);
  15215. }
  15216. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  15217. $this->view->assign([
  15218. 'pdf_export' => '', 'pdfMetaLine' => '', 'pdfMetaLeft' => '',
  15219. 'pdfMetaIds' => '', 'pdfMetaTitle' => '', 'pdfMetaTime' => '',
  15220. 'pdfSteps' => [], 'pdfStepWidth' => '',
  15221. ]);
  15222. return '';
  15223. }
  15224. if ($restoreLayout) {
  15225. $this->view->engine->layout($restoreLayout);
  15226. }
  15227. $this->view->assign([
  15228. 'pdf_export' => '', 'pdfMetaLine' => '', 'pdfMetaLeft' => '',
  15229. 'pdfMetaIds' => '', 'pdfMetaTitle' => '', 'pdfMetaTime' => '',
  15230. 'pdfSteps' => [], 'pdfStepWidth' => '',
  15231. ]);
  15232. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  15233. if (!is_dir($tempDir)) {
  15234. @mkdir($tempDir, 0755, true);
  15235. }
  15236. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  15237. try {
  15238. $mpdf = new \Mpdf\Mpdf([
  15239. 'mode' => 'utf-8',
  15240. 'format' => 'A4',
  15241. 'margin_left' => 12,
  15242. 'margin_right' => 12,
  15243. 'margin_top' => 14,
  15244. 'margin_bottom' => 14,
  15245. 'tempDir' => $tempDir,
  15246. 'autoScriptToLang' => true,
  15247. 'autoLangToFont' => true,
  15248. ]);
  15249. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  15250. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  15251. $mpdf->SetBasePath('http://127.0.0.1/');
  15252. $mpdf->WriteHTML($html);
  15253. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  15254. } catch (\Throwable $e) {
  15255. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  15256. if (is_file($tempPdf)) {
  15257. @unlink($tempPdf);
  15258. }
  15259. return '';
  15260. }
  15261. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  15262. if ($ossUrl !== '') {
  15263. @unlink($tempPdf);
  15264. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  15265. return $ossUrl;
  15266. }
  15267. $pi = pathinfo($objectKey);
  15268. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  15269. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  15270. if ($baseFile === '') {
  15271. @unlink($tempPdf);
  15272. return '';
  15273. }
  15274. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  15275. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  15276. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  15277. @unlink($tempPdf);
  15278. return '';
  15279. }
  15280. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  15281. if (!@copy($tempPdf, $fullPath)) {
  15282. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  15283. @unlink($tempPdf);
  15284. return '';
  15285. }
  15286. @unlink($tempPdf);
  15287. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  15288. return $webPath;
  15289. }
  15290. /**
  15291. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  15292. */
  15293. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  15294. {
  15295. if ($scydgyId <= 0 || $webPath === '') {
  15296. return;
  15297. }
  15298. try {
  15299. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  15300. } catch (\Throwable $e) {
  15301. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  15302. }
  15303. }
  15304. /**
  15305. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  15306. *
  15307. * @param array<string, string> $vars
  15308. * @return array<string, string>
  15309. */
  15310. protected function normalizeSmsTemplateVars(array $vars): array
  15311. {
  15312. return ProcuremenFormat::normalizeSmsTemplateVars($vars);
  15313. }
  15314. /**
  15315. * 按手机号或公司名称查 customer 表联系人姓名
  15316. */
  15317. protected function resolveCustomerContactName(string $phone, string $companyName): string
  15318. {
  15319. $phone = trim($phone);
  15320. $companyName = trim($companyName);
  15321. try {
  15322. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  15323. $row = Db::table('customer')
  15324. ->where(function ($q) use ($phone) {
  15325. $q->where('phone', $phone)->whereOr('account', $phone);
  15326. })
  15327. ->order('id', 'asc')
  15328. ->find();
  15329. if (is_array($row)) {
  15330. $nm = trim((string)($row['username'] ?? ''));
  15331. if ($nm !== '') {
  15332. return $nm;
  15333. }
  15334. }
  15335. }
  15336. if ($companyName !== '') {
  15337. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  15338. if (is_array($row)) {
  15339. return trim((string)($row['username'] ?? ''));
  15340. }
  15341. }
  15342. } catch (\Throwable $e) {
  15343. }
  15344. return '';
  15345. }
  15346. /**
  15347. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;;http(s) 链接做成可点的 &lt;a&gt;(微信 QQ 邮箱提醒纯文本 URL 常不可点)
  15348. */
  15349. protected function plainTextToHtmlEmailBody(string $text): string
  15350. {
  15351. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  15352. $parts = explode("\n", $text);
  15353. $out = [];
  15354. foreach ($parts as $line) {
  15355. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  15356. $out[] = $line;
  15357. } else {
  15358. $esc = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  15359. // 保留工序行空格,便于「单位/工作量」列对齐
  15360. $esc = str_replace(' ', '&nbsp;', $esc);
  15361. $esc = preg_replace(
  15362. '#(https?://[^\s<>"\']+)#iu',
  15363. '<a href="$1" style="color:#1565c0;text-decoration:underline;word-break:break-all;">$1</a>',
  15364. $esc
  15365. );
  15366. $out[] = $esc;
  15367. }
  15368. }
  15369. return implode("<br>\n", $out);
  15370. }
  15371. /**
  15372. * 短信场景:去掉链接类变量,避免误填 URL
  15373. *
  15374. * @param array<string, string> $vars
  15375. * @return array<string, string>
  15376. */
  15377. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  15378. {
  15379. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  15380. return $vars;
  15381. }
  15382. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  15383. $vars[$k] = '';
  15384. }
  15385. return $vars;
  15386. }
  15387. /**
  15388. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  15389. *
  15390. * @param array<string, string> $vars
  15391. */
  15392. protected function renderNotifyTemplate(string $scene, array $vars): string
  15393. {
  15394. $vars = $this->normalizeSmsTemplateVars($vars);
  15395. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  15396. $row = $this->loadNotifyTemplateRow($scene);
  15397. if ($row === null) {
  15398. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  15399. }
  15400. $tpl = trim((string)($row['content'] ?? ''));
  15401. if ($tpl === '') {
  15402. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  15403. }
  15404. foreach ($vars as $k => $v) {
  15405. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  15406. }
  15407. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  15408. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  15409. return $tpl;
  15410. }
  15411. protected function resolveProcuremenEmailSubject(string $scene): string
  15412. {
  15413. // 采购确认结果邮箱:title 仅作说明,邮件主题用固定文案(不用 title)
  15414. if (in_array($scene, ['confirm_ok_email', 'confirm_fail_email'], true)) {
  15415. $this->ensureConfirmResultEmailTemplates();
  15416. $fallback = [
  15417. 'confirm_ok_email' => '采购确认结果:已通过',
  15418. 'confirm_fail_email' => '采购确认结果:未通过',
  15419. ];
  15420. return $fallback[$scene] ?? '协助采购通知';
  15421. }
  15422. // 询价 / 交货确认邮箱:沿用模版 title 作邮件主题(与历史配置一致)
  15423. if (in_array($scene, ['rfq_salesman_email', 'rfq_supplier_email', 'delivery_notify_email'], true)) {
  15424. $row = $this->loadNotifyTemplateRow($scene);
  15425. $title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
  15426. if ($title !== '') {
  15427. return $title;
  15428. }
  15429. $fallback = [
  15430. 'rfq_supplier_email' => '供应商询价通知',
  15431. 'rfq_salesman_email' => '协助采购询价通知',
  15432. 'delivery_notify_email' => '交货情况确认通知',
  15433. ];
  15434. return $fallback[$scene] ?? '协助采购通知';
  15435. }
  15436. $map = [
  15437. 'review_email' => '您有新的协助加工订单',
  15438. ];
  15439. $subject = trim((string)($map[$scene] ?? ''));
  15440. if ($subject === '') {
  15441. $this->error('未配置邮件主题:' . $scene);
  15442. }
  15443. return $subject;
  15444. }
  15445. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  15446. {
  15447. $map = [
  15448. 'review_email' => '协助下发-邮箱',
  15449. 'review_sms' => '协助下发-短信',
  15450. 'confirm_ok' => '采购确认-通过',
  15451. 'confirm_fail' => '采购确认-未通过',
  15452. 'confirm_ok_email' => '采购确认通过-邮箱',
  15453. 'confirm_fail_email' => '采购确认未通过-邮箱',
  15454. 'bid_open' => '开标双重验证',
  15455. 'rfq_salesman_email' => '询价通知业务员-邮箱',
  15456. 'rfq_supplier_email' => '供应商询价通知',
  15457. 'delivery_notify_email'=> '交货情况通知生产部-邮箱',
  15458. ];
  15459. $label = $map[$scene] ?? $scene;
  15460. if ($titleRequired) {
  15461. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  15462. }
  15463. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  15464. }
  15465. /**
  15466. * 是否开启协助通知演练(不发真实短信/邮件)
  15467. */
  15468. protected function isProcuremenNotifyDryRun(): bool
  15469. {
  15470. return (bool)Config::get('procuremen_notify_dry_run');
  15471. }
  15472. /**
  15473. * @param array<string, mixed> $payload
  15474. */
  15475. protected function recordNotifyDryRunPreview(array $payload): void
  15476. {
  15477. $this->notifyDryRunPreview[] = $payload;
  15478. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  15479. }
  15480. /**
  15481. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  15482. * @throws \Exception
  15483. */
  15484. protected function smsbao($phone, $content)
  15485. {
  15486. if ($this->isProcuremenNotifyDryRun()) {
  15487. $this->recordNotifyDryRunPreview([
  15488. 'scene' => 'sms_only',
  15489. 'phone' => $phone,
  15490. 'sms_content' => $content,
  15491. ]);
  15492. return;
  15493. }
  15494. $statusStr = [
  15495. '0' => '短信发送成功',
  15496. '-1' => '参数不全',
  15497. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  15498. '30' => '密码错误',
  15499. '40' => '账号不存在',
  15500. '41' => '余额不足',
  15501. '42' => '帐户已过期',
  15502. '43' => 'IP地址限制',
  15503. '50' => '内容含有敏感词',
  15504. ];
  15505. $smsapi = 'http://api.smsbao.com/';
  15506. $user = 'zhuwei123';
  15507. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  15508. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  15509. $result = @file_get_contents($sendurl);
  15510. if ($result === false) {
  15511. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  15512. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  15513. }
  15514. $result = trim((string)$result);
  15515. if ($result !== '0') {
  15516. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  15517. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  15518. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  15519. }
  15520. }
  15521. }