Procuremen.php 603 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenFormat;
  6. use app\common\library\ProcuremenGuard;
  7. use app\common\library\ProcuremenOperLog;
  8. use app\common\library\ProcuremenSchema;
  9. use app\common\library\ProcuremenStatus;
  10. use app\common\library\ProcuremenSupplierScore;
  11. use app\common\library\ProcuremenTime;
  12. use PHPMailer\PHPMailer\PHPMailer;
  13. use think\Config;
  14. use think\Cache;
  15. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  16. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  17. use PhpOffice\PhpSpreadsheet\Style\Border;
  18. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  19. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  20. use think\Db;
  21. use think\Log;
  22. class Procuremen extends Backend
  23. {
  24. /**
  25. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  26. */
  27. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,b.czlyq,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  28. /**
  29. * Procuremen模型对象
  30. * @var \app\admin\model\Procuremen
  31. */
  32. protected $model = null;
  33. /**
  34. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  35. */
  36. protected $notifyDryRunPreview = [];
  37. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  38. protected $procuremenRedisCache = null;
  39. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  40. protected $pickHiddenScydgySetCache = null;
  41. /** 邮件发送日志表结构已就绪缓存键 */
  42. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  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. ];
  85. try {
  86. foreach ($map as $num => $text) {
  87. Db::table('purchase_order')
  88. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  89. ->update(['wflow_status' => $text]);
  90. }
  91. @file_put_contents($flagFile, date('c'));
  92. } catch (\Throwable $e) {
  93. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  94. }
  95. }
  96. /**
  97. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  98. *
  99. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  100. */
  101. protected function hasProcuremenPerm(array $actions): bool
  102. {
  103. foreach ($actions as $action) {
  104. $action = strtolower(trim((string)$action));
  105. if ($action === '') {
  106. continue;
  107. }
  108. if (strpos($action, 'procuremen/') !== 0) {
  109. $action = 'procuremen/' . $action;
  110. }
  111. if ($this->auth->check($action)) {
  112. return true;
  113. }
  114. }
  115. $suffixes = [];
  116. foreach ($actions as $action) {
  117. $action = strtolower(trim((string)$action));
  118. $action = preg_replace('#^procuremen/#', '', $action);
  119. if ($action !== '') {
  120. $suffixes[$action] = true;
  121. }
  122. }
  123. if ($suffixes === []) {
  124. return false;
  125. }
  126. try {
  127. foreach ($this->auth->getRuleList() as $rule) {
  128. $rule = strtolower((string)$rule);
  129. if (strpos($rule, 'procuremen/') !== 0) {
  130. continue;
  131. }
  132. foreach (array_keys($suffixes) as $suffix) {
  133. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  134. return true;
  135. }
  136. }
  137. }
  138. } catch (\Throwable $e) {
  139. }
  140. return false;
  141. }
  142. /**
  143. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  144. *
  145. * @param string[] $actions
  146. */
  147. protected function hasProcuremenPermStrict(array $actions): bool
  148. {
  149. foreach ($actions as $action) {
  150. $action = strtolower(trim((string)$action));
  151. if ($action === '') {
  152. continue;
  153. }
  154. if (strpos($action, 'procuremen/') !== 0) {
  155. $action = 'procuremen/' . $action;
  156. }
  157. if ($this->auth->check($action)) {
  158. return true;
  159. }
  160. }
  161. return false;
  162. }
  163. /**
  164. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  165. *
  166. * @param string[] $titles
  167. */
  168. protected function authHasAssignedRuleTitle(array $titles): bool
  169. {
  170. $titles = array_values(array_filter(array_map('trim', $titles)));
  171. if ($titles === []) {
  172. return false;
  173. }
  174. try {
  175. $ids = $this->auth->getRuleIds();
  176. if (in_array('*', $ids, true)) {
  177. return true;
  178. }
  179. if ($ids === []) {
  180. return false;
  181. }
  182. $rows = Db::name('auth_rule')
  183. ->where('status', 'normal')
  184. ->whereIn('id', $ids)
  185. ->column('title');
  186. foreach ($rows as $title) {
  187. $t = trim((string)$title);
  188. if ($t !== '' && in_array($t, $titles, true)) {
  189. return true;
  190. }
  191. }
  192. } catch (\Throwable $e) {
  193. }
  194. return false;
  195. }
  196. protected function procuremenCanPickDelete(): bool
  197. {
  198. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  199. return true;
  200. }
  201. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  202. }
  203. protected function procuremenCanComplete(): bool
  204. {
  205. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  206. return true;
  207. }
  208. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  209. }
  210. protected function procuremenCanDispatch(): bool
  211. {
  212. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  213. }
  214. /**
  215. * 前端按钮显隐(Config.procuremenAuth)
  216. */
  217. protected function assignProcuremenAuthConfig(): void
  218. {
  219. $authMap = [
  220. 'pickreview' => $this->procuremenCanDispatch(),
  221. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  222. 'pickdelete' => $this->procuremenCanPickDelete(),
  223. 'completedirectly' => $this->procuremenCanComplete(),
  224. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  225. 'auditissue' => $this->hasProcuremenPerm(['auditissue', 'audit']),
  226. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  227. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  228. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  229. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  230. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail', 'confirm']),
  231. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  232. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  233. 'details' => $this->hasProcuremenPerm(['details', 'confirm', 'audit', 'index', 'pick']),
  234. 'confirm' => $this->hasProcuremenPerm(['confirm']),
  235. 'audit' => $this->hasProcuremenPerm(['audit']),
  236. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  237. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  238. 'export_month_quote' => $this->hasProcuremenPerm(['export_month_quote', 'exportMonthQuote', 'export_month_outward', 'exportMonthOutward']),
  239. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  240. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  241. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  242. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  243. 'auditmanualpick' => $this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue']),
  244. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  245. 'add' => $this->hasProcuremenPerm(['add']),
  246. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  247. // 查询询价三个操作按钮:各自独立,不再因有 rfqlist 就全部放开
  248. 'rfqissue' => $this->hasProcuremenPerm(['rfqissue']),
  249. 'rfqquotes' => $this->hasProcuremenPerm(['rfqquotes']),
  250. 'rfqnotifysalesman' => $this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen']),
  251. 'rfqnotifysalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman']),
  252. // 询价附属接口:有「询价」按钮权限即可(无需再单独勾选)
  253. 'rfqissuesuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers']),
  254. 'rfqissuesendmail' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail']),
  255. 'rfqappendsuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers']),
  256. 'rfqsupplieroptions' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions']),
  257. 'rfqsalesmanoptions' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen']),
  258. 'rfqappendsalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen']),
  259. 'deliverynotify' => $this->hasProcuremenPerm(['deliverynotify', 'deliverynotifymen', 'outward_detail', 'outwarddetail', 'purchaseconfirmpick', 'details']),
  260. 'deliverynotifymen' => $this->hasProcuremenPerm(['deliverynotifymen', 'deliverynotify', 'outward_detail', 'outwarddetail', 'purchaseconfirmpick', 'details']),
  261. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  262. ];
  263. $this->assignconfig('procuremenAuth', $authMap);
  264. }
  265. /**
  266. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  267. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  268. * 列表 Tab 写入 hash(mproc_tab),避免邮件客户端拆坏多 query 参数;浏览器端再补全 tab=
  269. *
  270. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  271. * @param string $listTab rfq|draft|submitted|done|rfq_submitted,空则仅靠服务端按状态推断
  272. */
  273. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId, $listTab = '')
  274. {
  275. static $mprocCfgLoaded = false;
  276. if (!$mprocCfgLoaded) {
  277. $mprocCfgLoaded = true;
  278. if (is_file(APP_PATH . 'extra/mproc.php')) {
  279. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  280. }
  281. }
  282. $eid = (int)$purchaseOrderDetailId;
  283. $base = $this->resolveMprocMobilePublicBaseUrl();
  284. if ($base === '') {
  285. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  286. }
  287. $path = trim((string)Config::get('mproc.mobile_index_path'));
  288. if ($path === '') {
  289. $path = '/index.php/index/index/index';
  290. } else {
  291. $path = '/' . ltrim($path, '/');
  292. }
  293. $tab = trim((string)$listTab);
  294. if (!in_array($tab, ['rfq', 'rfq_submitted', 'draft', 'submitted', 'done'], true)) {
  295. $tab = '';
  296. }
  297. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份 Tab
  298. if ($eid > 0) {
  299. $hash = 'mproc_fe=' . $eid;
  300. if ($tab !== '') {
  301. $hash .= '&mproc_tab=' . $tab;
  302. }
  303. return $base . $path . '?focus_eid=' . $eid . '#' . $hash;
  304. }
  305. return $base . $path . '?main_tab=orders' . ($tab !== '' ? ('&tab=' . $tab) : '');
  306. }
  307. /**
  308. * 业务员手机端「订单询价」直达链接(默认待询价)
  309. *
  310. * @param int $scydgyId 手工询价 scydgy_id(负数)
  311. * @param string $status pending|quoted
  312. */
  313. protected function buildMprocMobileRfqAddUrl($scydgyId = 0, $status = 'pending')
  314. {
  315. static $mprocCfgLoaded = false;
  316. if (!$mprocCfgLoaded) {
  317. $mprocCfgLoaded = true;
  318. if (is_file(APP_PATH . 'extra/mproc.php')) {
  319. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  320. }
  321. }
  322. $base = $this->resolveMprocMobilePublicBaseUrl();
  323. if ($base === '') {
  324. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  325. }
  326. $indexPath = trim((string)Config::get('mproc.mobile_index_path'));
  327. if ($indexPath === '') {
  328. $indexPath = '/index.php/index/index/index';
  329. } else {
  330. $indexPath = '/' . ltrim($indexPath, '/');
  331. }
  332. $path = preg_replace('#/index$#', '/rfqadd', rtrim($indexPath, '/'));
  333. if ($path === null || $path === '' || substr($path, -6) === '/index') {
  334. $path = '/index.php/index/index/rfqadd';
  335. }
  336. $status = trim((string)$status) === 'quoted' ? 'quoted' : 'pending';
  337. $sid = (int)$scydgyId;
  338. $q = 'status=' . $status;
  339. $hash = '';
  340. if ($sid < 0) {
  341. $q .= '&focus_sid=' . $sid;
  342. $hash = '#mproc_fs=' . $sid;
  343. }
  344. return $base . $path . '?' . $q . $hash;
  345. }
  346. /**
  347. * 邮件/短信外链:须为带点的公网域名
  348. */
  349. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  350. {
  351. $u = trim((string)$baseUrl);
  352. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  353. return false;
  354. }
  355. $host = parse_url($u, PHP_URL_HOST);
  356. if (!is_string($host) || $host === '') {
  357. return false;
  358. }
  359. if (strcasecmp($host, 'localhost') === 0) {
  360. return false;
  361. }
  362. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  363. return false;
  364. }
  365. if (strpos($host, '.') === false) {
  366. return false;
  367. }
  368. return true;
  369. }
  370. /**
  371. * 解析用于协助邮件/短信的手机端站点根
  372. */
  373. protected function resolveMprocMobilePublicBaseUrl()
  374. {
  375. $candidates = [];
  376. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  377. $candidates[] = trim((string)Config::get('site.indexurl'));
  378. $cdn = trim((string)Config::get('site.cdnurl'));
  379. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  380. $candidates[] = rtrim($cdn, '/');
  381. }
  382. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  383. $candidates[] = $reqBase;
  384. foreach ($candidates as $c) {
  385. if ($c === '') {
  386. continue;
  387. }
  388. $c = rtrim($c, '/');
  389. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  390. return $c;
  391. }
  392. }
  393. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  394. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  395. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  396. return $reqBase;
  397. }
  398. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  399. return '';
  400. }
  401. /**
  402. * 获取 Redis 中 procuremen_redis
  403. */
  404. protected function ProcuremenRedis(): array
  405. {
  406. if ($this->procuremenRedisCache !== null) {
  407. return $this->procuremenRedisCache;
  408. }
  409. try {
  410. $redis = redis();
  411. $raw = $redis->get('procuremen_redis');
  412. if ($raw === false || $raw === '') {
  413. $this->procuremenRedisCache = [];
  414. return $this->procuremenRedisCache;
  415. }
  416. $decoded = json_decode($raw, true);
  417. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  418. $this->procuremenRedisCache = [];
  419. return $this->procuremenRedisCache;
  420. }
  421. $this->procuremenRedisCache = $decoded['data'];
  422. // 整包已解码时顺带补齐侧栏小键,避免下次首屏再扫库
  423. if ($this->loadProcuremenSidebarYmList() === []) {
  424. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($this->procuremenRedisCache));
  425. }
  426. return $this->procuremenRedisCache;
  427. } catch (\Throwable $e) {
  428. $this->procuremenRedisCache = [];
  429. return $this->procuremenRedisCache;
  430. }
  431. }
  432. /**
  433. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  434. *
  435. * @return array<int, array<string, mixed>>
  436. */
  437. protected function procuremenFetchErpPoolFromDb(): array
  438. {
  439. try {
  440. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  441. $endTime = date('Y-m-d 23:59:59');
  442. $list = Db::table('scydgy')
  443. ->alias('a')
  444. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  445. ->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')
  446. ->where([
  447. 'a.bwjg' => 1,
  448. 'a.iEndBz' => 0,
  449. 'a.iType' => 0,
  450. 'a.iStatus' => 10,
  451. ])
  452. ->where('a.dStamp', '>=', $startTime)
  453. ->where('a.dStamp', '<=', $endTime)
  454. ->order('a.dStamp', 'desc')
  455. ->select();
  456. if (!is_array($list)) {
  457. return [];
  458. }
  459. try {
  460. $redis = redis();
  461. $payload = [
  462. 'code' => 200,
  463. 'msg' => 'success',
  464. 'data' => $list,
  465. ];
  466. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  467. $this->procuremenRedisCache = $list;
  468. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($list));
  469. $this->clearPickMonthPoolCaches();
  470. $this->warmPickMonthPoolCachesFromPool($list);
  471. } catch (\Throwable $e) {
  472. }
  473. return $list;
  474. } catch (\Throwable $e) {
  475. Log::write('拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  476. return [];
  477. }
  478. }
  479. /**
  480. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  481. *
  482. * @return array<int, array<string, mixed>>
  483. */
  484. protected function procuremenEnsureRedisPool(): array
  485. {
  486. $pool = $this->ProcuremenRedis();
  487. if (is_array($pool) && $pool !== []) {
  488. return $pool;
  489. }
  490. static $warmed = false;
  491. if ($warmed) {
  492. return is_array($pool) ? $pool : [];
  493. }
  494. $warmed = true;
  495. return $this->procuremenFetchErpPoolFromDb();
  496. }
  497. /**
  498. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  499. *
  500. * @param array<string, mixed> $row
  501. */
  502. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  503. {
  504. $t = $this->procuremenRowListSortTime($row, $primary);
  505. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  506. return null;
  507. }
  508. $mo = (int)$m[2];
  509. if ($mo < 1 || $mo > 12) {
  510. return null;
  511. }
  512. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  513. }
  514. /**
  515. * @param array<int, array{year:string, months:array}> $sidebar
  516. * @return array<int, array{year:string, months:array}>
  517. */
  518. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  519. {
  520. $ym = trim($ym);
  521. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  522. return $sidebar;
  523. }
  524. foreach ($sidebar as $block) {
  525. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  526. continue;
  527. }
  528. foreach ($block['months'] as $item) {
  529. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  530. return $sidebar;
  531. }
  532. }
  533. }
  534. $y = substr($ym, 0, 4);
  535. $mo = (int)substr($ym, 5, 2);
  536. $sidebar[] = [
  537. 'year' => $y,
  538. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  539. ];
  540. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  541. }
  542. /**
  543. * @param array<int, array{year:string, months:array}> $sidebar
  544. * @return string[]
  545. */
  546. protected function flattenProcuremenSidebarYms(array $sidebar): array
  547. {
  548. $yms = [];
  549. foreach ($sidebar as $block) {
  550. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  551. continue;
  552. }
  553. foreach ($block['months'] as $item) {
  554. if (!is_array($item)) {
  555. continue;
  556. }
  557. $ym = trim((string)($item['ym'] ?? ''));
  558. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  559. $yms[$ym] = true;
  560. }
  561. }
  562. }
  563. return array_keys($yms);
  564. }
  565. /**
  566. * 左侧菜单(协助初选)
  567. * 优先 Redis 月份小键;为空时用轻量 DISTINCT 查库补齐(避免只显示空当月、漏掉有数据的月份)。
  568. */
  569. protected function GetIndexYearMonths()
  570. {
  571. $ymList = $this->ensureProcuremenPickSidebarYmList();
  572. if ($ymList === []) {
  573. $def = date('Y-m');
  574. $ymList = [preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m')];
  575. }
  576. return $this->buildYearMonthSidebar($ymList);
  577. }
  578. /**
  579. * 初选侧栏月份:以轻量 DISTINCT 查库为准(有数据才显示),并写回 Redis 小键。
  580. *
  581. * @return string[]
  582. */
  583. protected function ensureProcuremenPickSidebarYmList(bool $forceRefresh = false): array
  584. {
  585. static $memo = null;
  586. if (!$forceRefresh && is_array($memo)) {
  587. return $memo;
  588. }
  589. $fromDb = $this->queryProcuremenPickSidebarYmListLight();
  590. if ($fromDb !== []) {
  591. $this->saveProcuremenSidebarYmList($fromDb);
  592. $memo = $fromDb;
  593. return $memo;
  594. }
  595. // 库侧暂无初选数据时,再回退 Redis / 当月,避免侧栏空白
  596. $cached = $this->loadProcuremenSidebarYmList();
  597. if ($cached !== []) {
  598. $memo = $cached;
  599. return $memo;
  600. }
  601. $memo = [date('Y-m')];
  602. return $memo;
  603. }
  604. /**
  605. * @return string[] 形如 2026-07
  606. */
  607. protected function loadProcuremenSidebarYmList(): array
  608. {
  609. try {
  610. $raw = redis()->get('procuremen_redis_yms');
  611. if ($raw === false || $raw === null || $raw === '') {
  612. return [];
  613. }
  614. $decoded = json_decode((string)$raw, true);
  615. if (!is_array($decoded)) {
  616. return [];
  617. }
  618. $out = [];
  619. foreach ($decoded as $ym) {
  620. $ym = trim((string)$ym);
  621. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  622. $out[$ym] = true;
  623. }
  624. }
  625. return array_keys($out);
  626. } catch (\Throwable $e) {
  627. return [];
  628. }
  629. }
  630. /**
  631. * @param string[] $ymList
  632. */
  633. protected function saveProcuremenSidebarYmList(array $ymList): void
  634. {
  635. $out = [];
  636. foreach ($ymList as $ym) {
  637. $ym = trim((string)$ym);
  638. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  639. $out[$ym] = true;
  640. }
  641. }
  642. if ($out === []) {
  643. return;
  644. }
  645. try {
  646. redis()->set('procuremen_redis_yms', json_encode(array_keys($out), JSON_UNESCAPED_UNICODE));
  647. } catch (\Throwable $e) {
  648. }
  649. }
  650. /**
  651. * @param array<int, array<string, mixed>> $pool
  652. * @return string[]
  653. */
  654. protected function extractYearMonthsFromPoolRows(array $pool): array
  655. {
  656. $ymSet = [];
  657. foreach ($pool as $r) {
  658. if (!is_array($r)) {
  659. continue;
  660. }
  661. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  662. continue;
  663. }
  664. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  665. if ($ym !== null) {
  666. $ymSet[$ym] = true;
  667. }
  668. }
  669. return array_keys($ymSet);
  670. }
  671. /**
  672. * 轻量查询初选侧栏月份(只取 DISTINCT 年月,不拉整包工序)
  673. *
  674. * @return string[]
  675. */
  676. protected function queryProcuremenPickSidebarYmListLight(): array
  677. {
  678. try {
  679. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  680. $endTime = date('Y-m-d 23:59:59');
  681. $sql = 'SELECT DISTINCT DATE_FORMAT('
  682. . 'IF(b.dputrecord IS NOT NULL AND TRIM(CAST(b.dputrecord AS CHAR(32))) <> \'\''
  683. . ' AND TRIM(CAST(b.dputrecord AS CHAR(32))) NOT LIKE \'0000-00-00%\','
  684. . ' b.dputrecord, a.dStamp), \'%Y-%m\') AS ym'
  685. . ' FROM scydgy a'
  686. . ' INNER JOIN mcyd b ON b.ICYDID = a.ICYDID AND b.iStatus >= 10'
  687. . ' WHERE a.bwjg = 1 AND a.iEndBz = 0 AND a.iType = 0 AND a.iStatus = 10'
  688. . ' AND a.dStamp >= ? AND a.dStamp <= ?';
  689. $rows = Db::query($sql, [$startTime, $endTime]);
  690. if (!is_array($rows)) {
  691. return [];
  692. }
  693. $out = [];
  694. foreach ($rows as $r) {
  695. $ym = trim((string)($r['ym'] ?? ''));
  696. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  697. $out[$ym] = true;
  698. }
  699. }
  700. return array_keys($out);
  701. } catch (\Throwable $e) {
  702. Log::write('初选侧栏月份查询失败:' . $e->getMessage(), 'warning');
  703. return [];
  704. }
  705. }
  706. /**
  707. * @return string[] 含当月在内的近 N 个自然月
  708. */
  709. protected function buildRecentCalendarYmList(int $months = 12): array
  710. {
  711. $months = max(1, min(24, $months));
  712. $out = [];
  713. $base = strtotime(date('Y-m-01'));
  714. for ($i = 0; $i < $months; $i++) {
  715. $out[] = date('Y-m', strtotime('-' . $i . ' month', $base));
  716. }
  717. return $out;
  718. }
  719. /**
  720. * 初选按月工序池:优先月缓存;未命中则直接按月查 ERP。
  721. * 禁止为列表去解近一年整包 Redis(解包/连接异常会造成长时间转圈)。
  722. *
  723. * @return array<int, array<string, mixed>>
  724. */
  725. protected function loadPickPoolForYm(string $ym): array
  726. {
  727. $ym = trim($ym);
  728. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  729. return [];
  730. }
  731. $hit = $this->readPickMonthPoolCache($ym);
  732. if ($hit !== null) {
  733. return $hit;
  734. }
  735. return $this->queryPickPoolForYmFromDb($ym);
  736. }
  737. /**
  738. * @return array<int, array<string, mixed>>|null null=无有效缓存(含旧版空数组误缓存)
  739. */
  740. protected function readPickMonthPoolCache(string $ym): ?array
  741. {
  742. try {
  743. $raw = redis()->get('procuremen_pick_pool:' . $ym);
  744. if ($raw === false || $raw === null || $raw === '') {
  745. return null;
  746. }
  747. $decoded = json_decode((string)$raw, true);
  748. if (!is_array($decoded)) {
  749. return null;
  750. }
  751. // 新格式:{ok:1, rows:[...]},空月也算有效(已从整包确认)
  752. if (isset($decoded['ok']) && (int)$decoded['ok'] === 1 && isset($decoded['rows']) && is_array($decoded['rows'])) {
  753. return $decoded['rows'];
  754. }
  755. // 旧格式:仅非空行列表可命中;[] 多半是错误 SQL 写入,视为未命中
  756. if ($decoded === []) {
  757. try {
  758. redis()->del('procuremen_pick_pool:' . $ym);
  759. } catch (\Throwable $e) {
  760. }
  761. return null;
  762. }
  763. if (isset($decoded[0]) && is_array($decoded[0])) {
  764. return $decoded;
  765. }
  766. return null;
  767. } catch (\Throwable $e) {
  768. return null;
  769. }
  770. }
  771. /**
  772. * @param array<int, array<string, mixed>> $rows
  773. */
  774. protected function writePickMonthPoolCache(string $ym, array $rows): void
  775. {
  776. try {
  777. redis()->setex(
  778. 'procuremen_pick_pool:' . $ym,
  779. 600,
  780. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  781. );
  782. } catch (\Throwable $e) {
  783. }
  784. }
  785. /**
  786. * @param array<int, array<string, mixed>> $pool
  787. * @return array<int, array<string, mixed>>
  788. */
  789. protected function filterPoolRowsByYm(array $pool, string $ym): array
  790. {
  791. $out = [];
  792. foreach ($pool as $r) {
  793. if (!is_array($r)) {
  794. continue;
  795. }
  796. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  797. continue;
  798. }
  799. if ($this->procuremenRowYearMonth($r, 'dputrecord') === $ym) {
  800. $out[] = $r;
  801. }
  802. }
  803. return $out;
  804. }
  805. /**
  806. * 按 dStamp 取当月附近数据,再用列表规则(dputrecord 优先)精确到 ym
  807. *
  808. * @return array<int, array<string, mixed>>
  809. */
  810. protected function queryPickPoolForYmFromDb(string $ym): array
  811. {
  812. $monthStart = $ym . '-01 00:00:00';
  813. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  814. // 略放大窗口,避免 dStamp 与 dputrecord 跨月导致漏数;最终仍按 ym 精确过滤
  815. $queryStart = date('Y-m-d 00:00:00', strtotime($monthStart . ' -7 days'));
  816. $queryEnd = date('Y-m-d 23:59:59', strtotime($monthEnd . ' +7 days'));
  817. try {
  818. $list = Db::table('scydgy')
  819. ->alias('a')
  820. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  821. ->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')
  822. ->where([
  823. 'a.bwjg' => 1,
  824. 'a.iEndBz' => 0,
  825. 'a.iType' => 0,
  826. 'a.iStatus' => 10,
  827. ])
  828. ->where('a.dStamp', '>=', $queryStart)
  829. ->where('a.dStamp', '<=', $queryEnd)
  830. ->order('a.dStamp', 'desc')
  831. ->select();
  832. } catch (\Throwable $e) {
  833. Log::write('初选按月取数失败 ym=' . $ym . ':' . $e->getMessage(), 'error');
  834. return [];
  835. }
  836. if (!is_array($list)) {
  837. $list = [];
  838. }
  839. $out = $this->filterPoolRowsByYm($list, $ym);
  840. // 新格式缓存(含空月),避免重复打库;读侧只认 ok=1
  841. $this->writePickMonthPoolCache($ym, $out);
  842. try {
  843. $yms = $this->loadProcuremenSidebarYmList();
  844. if ($out !== [] && ($yms === [] || !in_array($ym, $yms, true))) {
  845. $yms[] = $ym;
  846. $this->saveProcuremenSidebarYmList($yms);
  847. }
  848. } catch (\Throwable $e) {
  849. }
  850. return $out;
  851. }
  852. /**
  853. * 整包写入后拆成按月小缓存,供初选列表秒开
  854. *
  855. * @param array<int, array<string, mixed>> $pool
  856. */
  857. protected function warmPickMonthPoolCachesFromPool(array $pool): void
  858. {
  859. if ($pool === []) {
  860. return;
  861. }
  862. $byYm = [];
  863. foreach ($pool as $r) {
  864. if (!is_array($r)) {
  865. continue;
  866. }
  867. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  868. continue;
  869. }
  870. $rowYm = $this->procuremenRowYearMonth($r, 'dputrecord');
  871. if ($rowYm === null) {
  872. continue;
  873. }
  874. $byYm[$rowYm][] = $r;
  875. }
  876. if ($byYm === []) {
  877. return;
  878. }
  879. try {
  880. $redis = redis();
  881. foreach ($byYm as $rowYm => $rows) {
  882. $redis->setex(
  883. 'procuremen_pick_pool:' . $rowYm,
  884. 600,
  885. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  886. );
  887. }
  888. try {
  889. $redis->del('procuremen_pick_hidden_scydgy_v1');
  890. } catch (\Throwable $e) {
  891. }
  892. } catch (\Throwable $e) {
  893. }
  894. }
  895. /**
  896. * 刷新整包后清理近月缓存,避免脏读
  897. */
  898. protected function clearPickMonthPoolCaches(int $months = 24): void
  899. {
  900. try {
  901. $redis = redis();
  902. foreach ($this->buildRecentCalendarYmList($months) as $ym) {
  903. try {
  904. $redis->del('procuremen_pick_pool:' . $ym);
  905. } catch (\Throwable $e) {
  906. }
  907. }
  908. } catch (\Throwable $e) {
  909. }
  910. $this->invalidatePickHiddenScydgyCache();
  911. }
  912. /**
  913. * 下发/完结后清隐藏集缓存,避免初选列表最多 90 秒仍显示已下发行
  914. */
  915. protected function invalidatePickHiddenScydgyCache(): void
  916. {
  917. $this->pickHiddenScydgySetCache = null;
  918. try {
  919. redis()->del('procuremen_pick_hidden_scydgy_v1');
  920. } catch (\Throwable $e) {
  921. }
  922. }
  923. /** 列表/首屏读完鉴权后尽早释放 session,避免多 iframe 串行卡死 */
  924. protected function procuremenReleaseSessionLock(): void
  925. {
  926. if (session_status() === PHP_SESSION_ACTIVE) {
  927. @session_write_close();
  928. }
  929. }
  930. /**
  931. * @param string[] $ymList 形如 2026-06
  932. * @return array<int, array{year:string, months:array}>
  933. */
  934. protected function buildYearMonthSidebar(array $ymList): array
  935. {
  936. rsort($ymList, SORT_STRING);
  937. $byYear = [];
  938. foreach ($ymList as $ym) {
  939. $y = substr($ym, 0, 4);
  940. $mo = (int)substr($ym, 5, 2);
  941. if (!isset($byYear[$y])) {
  942. $byYear[$y] = [];
  943. }
  944. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  945. }
  946. krsort($byYear, SORT_NUMERIC);
  947. foreach ($byYear as $y => $items) {
  948. usort($byYear[$y], function ($a, $b) {
  949. return strcmp($b['ym'], $a['ym']);
  950. });
  951. }
  952. $sidebar = [];
  953. foreach ($byYear as $y => $months) {
  954. $sidebar[] = ['year' => $y, 'months' => $months];
  955. }
  956. return $sidebar;
  957. }
  958. /**
  959. * 已下发/审批/确认列表左侧月份:SQL DISTINCT,禁止把该阶段全部行拉进 PHP
  960. * 注意:MySQL8 严格模式下勿对 datetime 用 <> '',否则报 Incorrect DATETIME value 被吞掉后侧栏只剩默认月
  961. */
  962. protected function GetIssuedOrderYearMonths(string $stage): array
  963. {
  964. if ($stage !== 'audit' && $stage !== 'confirm') {
  965. return $this->GetIndexYearMonths();
  966. }
  967. $ymSet = [];
  968. $addYm = function ($raw) use (&$ymSet): void {
  969. $ym = trim((string)$raw);
  970. if (preg_match('/^([12]\d{3})-(\d{2})/', $ym, $m)) {
  971. $ymSet[$m[1] . '-' . $m[2]] = true;
  972. }
  973. };
  974. try {
  975. $query = Db::table('purchase_order')->field('pick_time,createtime,dStamp');
  976. $this->applyPurchaseOrderNotDeletedWhere($query);
  977. $this->applyPurchaseOrderConfirmAuditListWhere($query);
  978. $rows = $query->select();
  979. if (is_array($rows)) {
  980. foreach ($rows as $r) {
  981. if (!is_array($r)) {
  982. continue;
  983. }
  984. $pick = trim((string)($r['pick_time'] ?? ''));
  985. if ($pick !== '' && stripos($pick, '0000-00-00') !== 0) {
  986. $addYm($pick);
  987. continue;
  988. }
  989. $ct = $r['createtime'] ?? null;
  990. if (is_numeric($ct) && (int)$ct > 946684800) {
  991. $addYm(date('Y-m-d', (int)$ct));
  992. continue;
  993. }
  994. $ctStr = trim((string)$ct);
  995. if ($ctStr !== '' && stripos($ctStr, '0000-00-00') !== 0) {
  996. $addYm($ctStr);
  997. continue;
  998. }
  999. $ds = trim((string)($r['dStamp'] ?? ''));
  1000. if ($ds !== '' && stripos($ds, '0000-00-00') !== 0) {
  1001. $addYm($ds);
  1002. }
  1003. }
  1004. }
  1005. } catch (\Throwable $e) {
  1006. Log::write('GetIssuedOrderYearMonths: ' . $e->getMessage(), 'error');
  1007. $ymSet = [];
  1008. }
  1009. $ymList = array_keys($ymSet);
  1010. if ($ymList === []) {
  1011. $def = $this->resolveProcuremenDefaultYm($stage);
  1012. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  1013. }
  1014. return $this->buildYearMonthSidebar($ymList);
  1015. }
  1016. /**
  1017. * 列表默认月份:已下发类取最近有数据的月份;初选也取最近有数据月份(避免跨月后落到空当月)
  1018. */
  1019. protected function resolveProcuremenDefaultYm(string $stage): string
  1020. {
  1021. if ($stage === 'pick') {
  1022. $yms = $this->ensureProcuremenPickSidebarYmList();
  1023. if ($yms !== []) {
  1024. rsort($yms, SORT_STRING);
  1025. return $yms[0];
  1026. }
  1027. return date('Y-m');
  1028. }
  1029. try {
  1030. $query = Db::table('purchase_order');
  1031. $this->applyPurchaseOrderNotDeletedWhere($query);
  1032. if ($stage === 'audit') {
  1033. $query->whereIn('wflow_status', ProcuremenStatus::wflowConfirmAndAuditListValues());
  1034. } elseif ($stage === 'confirm') {
  1035. $this->applyPurchaseOrderConfirmStageWhere($query);
  1036. } else {
  1037. return date('Y-m');
  1038. }
  1039. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  1040. if ($latest === null || $latest === '') {
  1041. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  1042. }
  1043. $t = $this->formatProcuremenDetailTime($latest);
  1044. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  1045. return $m[1] . '-' . $m[2];
  1046. }
  1047. } catch (\Throwable $e) {
  1048. }
  1049. return date('Y-m');
  1050. }
  1051. protected function applyPurchaseOrderNotDeletedWhere($query): void
  1052. {
  1053. $query->whereRaw("(mod_rq IS NULL OR mod_rq = '' OR mod_rq LIKE '0000-00-00%')");
  1054. }
  1055. /**
  1056. * 确认/审批列表共用:待确认 + 待审核(待审批) + 已审核
  1057. */
  1058. protected function applyPurchaseOrderConfirmAuditListWhere($query): void
  1059. {
  1060. $vals = ProcuremenStatus::wflowConfirmAndAuditListValues();
  1061. $quoted = [];
  1062. foreach ($vals as $v) {
  1063. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  1064. }
  1065. if ($quoted === []) {
  1066. $query->whereRaw('1 = 0');
  1067. return;
  1068. }
  1069. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  1070. }
  1071. /**
  1072. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  1073. * 完结判断必须走 CAST 文案比较:status 为 0/'0' 时,NOT IN ('已完结','1') 会被 MySQL 把「已完结」转成 0 而整表滤空
  1074. */
  1075. protected function applyPurchaseOrderConfirmStageWhere($query): void
  1076. {
  1077. // 与确认页共用数据范围(待确认/待审核/已审核)
  1078. $this->applyPurchaseOrderConfirmAuditListWhere($query);
  1079. }
  1080. /**
  1081. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  1082. *
  1083. * @param array<string, mixed> $row
  1084. * @return array<string, mixed>
  1085. */
  1086. protected function normalizePurchaseOrderListTimeRow(array $row): array
  1087. {
  1088. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  1089. $pick = trim((string)($row['pick_time'] ?? ''));
  1090. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  1091. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  1092. $t = trim((string)($row[$key] ?? ''));
  1093. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1094. $row['pick_time'] = $t;
  1095. break;
  1096. }
  1097. }
  1098. }
  1099. return $row;
  1100. }
  1101. /**
  1102. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  1103. */
  1104. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  1105. {
  1106. if (!in_array($stage, ['audit', 'confirm'], true)) {
  1107. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1108. }
  1109. if ($pool === []) {
  1110. $def = $this->resolveProcuremenDefaultYm($stage);
  1111. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  1112. }
  1113. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  1114. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1115. return false;
  1116. }
  1117. $monthStart = $ym . '-01 00:00:00';
  1118. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1119. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  1120. return $probe !== [];
  1121. };
  1122. if ($tryYm($requestedYm)) {
  1123. return $requestedYm;
  1124. }
  1125. $fallback = $this->resolveProcuremenDefaultYm($stage);
  1126. if ($tryYm($fallback)) {
  1127. return $fallback;
  1128. }
  1129. $bestYm = '';
  1130. $bestTime = '';
  1131. foreach ($pool as $row) {
  1132. if (!is_array($row)) {
  1133. continue;
  1134. }
  1135. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  1136. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  1137. continue;
  1138. }
  1139. $ymRow = $m[1];
  1140. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  1141. $bestTime = $t;
  1142. $bestYm = $ymRow;
  1143. }
  1144. }
  1145. if ($bestYm !== '') {
  1146. return $bestYm;
  1147. }
  1148. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1149. }
  1150. protected function isPurchaseOrderDetailVoid(array $row): bool
  1151. {
  1152. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  1153. return true;
  1154. }
  1155. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  1156. }
  1157. /**
  1158. * 仅当前有效下发明细(排除废弃归档)
  1159. */
  1160. protected function applyActivePurchaseOrderDetailWhere($query): void
  1161. {
  1162. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1163. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  1164. }
  1165. /**
  1166. * @param array<string, mixed> $detailRow
  1167. */
  1168. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  1169. {
  1170. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  1171. return false;
  1172. }
  1173. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  1174. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  1175. }
  1176. /**
  1177. * 废弃退回初选:下发明细标记归档,不物理删除
  1178. *
  1179. * @param array<int, int|string> $scydgyIds
  1180. */
  1181. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  1182. {
  1183. $ids = [];
  1184. foreach ($scydgyIds as $sid) {
  1185. $n = (int)$sid;
  1186. if ($this->isValidScydgyRowId($n) || $n < 0) {
  1187. $ids[$n] = true;
  1188. }
  1189. }
  1190. if ($ids === []) {
  1191. return;
  1192. }
  1193. $void = ProcuremenStatus::POD_VOID;
  1194. Db::table('purchase_order_detail')
  1195. ->where('scydgy_id', 'in', array_keys($ids))
  1196. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1197. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  1198. ->update([
  1199. 'status' => $void,
  1200. 'status_name' => $void,
  1201. ]);
  1202. }
  1203. /**
  1204. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  1205. */
  1206. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  1207. {
  1208. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  1209. $norm = function (string $col) use ($p): string {
  1210. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  1211. };
  1212. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  1213. $parts = [];
  1214. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  1215. if ($key === 'createtime') {
  1216. $parts[] = $createtime;
  1217. } else {
  1218. $parts[] = $norm($key);
  1219. }
  1220. }
  1221. return 'COALESCE(' . implode(', ', $parts) . ')';
  1222. }
  1223. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  1224. {
  1225. if (!preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $monthStart)
  1226. || !preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $monthEnd)) {
  1227. return;
  1228. }
  1229. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  1230. // 禁止 whereRaw 用 ? :与 whereIn 命名绑定混用时 PDO 会失败,列表被 catch 成空
  1231. $query->whereRaw("({$expr}) >= '{$monthStart}' AND ({$expr}) <= '{$monthEnd}'");
  1232. }
  1233. /**
  1234. * @return array<int, array<string, mixed>>
  1235. */
  1236. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  1237. {
  1238. $this->ensurePurchaseOrderCzlyqColumn();
  1239. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1240. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name,order_batch_no';
  1241. try {
  1242. $this->ensurePurchaseOrderOrderBatchNoColumn();
  1243. $query = Db::table('purchase_order')->field($fields);
  1244. $this->applyPurchaseOrderNotDeletedWhere($query);
  1245. if ($stage === 'audit') {
  1246. $query->whereIn('wflow_status', ProcuremenStatus::wflowConfirmAndAuditListValues());
  1247. } elseif ($stage === 'confirm') {
  1248. $this->applyPurchaseOrderConfirmStageWhere($query);
  1249. } else {
  1250. return [];
  1251. }
  1252. $query->order('pick_time', 'desc')->order('id', 'desc');
  1253. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1254. $monthStart = $ym . '-01 00:00:00';
  1255. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1256. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  1257. }
  1258. $rows = $query->select();
  1259. } catch (\Throwable $e) {
  1260. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  1261. $rows = [];
  1262. }
  1263. return is_array($rows) ? $rows : [];
  1264. }
  1265. /**
  1266. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  1267. */
  1268. protected function resolveProcuremenListStage(): string
  1269. {
  1270. $tab = trim((string)$this->request->request('wff_tab', ''));
  1271. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  1272. return $tab;
  1273. }
  1274. $action = strtolower((string)$this->request->action());
  1275. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  1276. return $action;
  1277. }
  1278. return 'pick';
  1279. }
  1280. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  1281. {
  1282. $this->procuremenReleaseSessionLock();
  1283. $rootTrue = rtrim((string)$this->request->root(true), '/');
  1284. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  1285. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  1286. $indexPhpRoot = $rootTrue . '/index.php';
  1287. }
  1288. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  1289. if ($stage === 'pick') {
  1290. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  1291. $sidebar = $this->GetIndexYearMonths();
  1292. } else {
  1293. $sidebar = $this->GetIssuedOrderYearMonths($stage);
  1294. $defaultYm = $this->latestYmFromSidebar($sidebar);
  1295. }
  1296. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  1297. $this->view->assign('defaultYm', $defaultYm);
  1298. $this->view->assign('sidebarYearMonths', $sidebar);
  1299. $this->view->assign('procuremenStage', $stage);
  1300. $this->view->assign('procuremenPageTitle', $pageTitle);
  1301. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  1302. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  1303. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  1304. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  1305. // 筛选项由列表 AJAX 带回,避免进页再扫 4 次 DISTINCT 白屏
  1306. $this->assignconfig('procuremenFilterOptions', [
  1307. 'czlyq' => [],
  1308. 'CCLBMMC' => [],
  1309. 'cywyxm' => [],
  1310. 'CGYMC' => [],
  1311. ]);
  1312. }
  1313. /**
  1314. * @param array<int, array{year?:string, months?:array}> $sidebar
  1315. */
  1316. protected function latestYmFromSidebar(array $sidebar): string
  1317. {
  1318. $best = '';
  1319. foreach ($sidebar as $block) {
  1320. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  1321. continue;
  1322. }
  1323. foreach ($block['months'] as $item) {
  1324. $ym = is_array($item) ? trim((string)($item['ym'] ?? '')) : '';
  1325. if (preg_match('/^\d{4}-\d{2}$/', $ym) && ($best === '' || strcmp($ym, $best) > 0)) {
  1326. $best = $ym;
  1327. }
  1328. }
  1329. }
  1330. return $best !== '' ? $best : date('Y-m');
  1331. }
  1332. /**
  1333. * 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
  1334. *
  1335. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1336. */
  1337. protected function buildProcuremenFilterOptions(string $stage): array
  1338. {
  1339. $buckets = [
  1340. 'czlyq' => [],
  1341. 'CCLBMMC' => [],
  1342. 'cywyxm' => [],
  1343. 'CGYMC' => [],
  1344. ];
  1345. $maxPerField = 300;
  1346. try {
  1347. if ($stage === 'pick') {
  1348. // 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
  1349. return $buckets;
  1350. }
  1351. if (in_array($stage, ['audit', 'confirm'], true)) {
  1352. $this->ensurePurchaseOrderCzlyqColumn();
  1353. foreach (array_keys($buckets) as $field) {
  1354. try {
  1355. $query = Db::table('purchase_order')->field($field);
  1356. $this->applyPurchaseOrderNotDeletedWhere($query);
  1357. if ($stage === 'audit') {
  1358. $query->whereIn('wflow_status', ProcuremenStatus::wflowConfirmAndAuditListValues());
  1359. } else {
  1360. $this->applyPurchaseOrderConfirmStageWhere($query);
  1361. }
  1362. $query->where($field, '<>', '')->whereNotNull($field);
  1363. $vals = $query->distinct(true)->limit($maxPerField)->column($field);
  1364. if (!is_array($vals)) {
  1365. continue;
  1366. }
  1367. foreach ($vals as $v) {
  1368. $v = trim((string)$v);
  1369. if ($v !== '') {
  1370. $buckets[$field][$v] = $v;
  1371. }
  1372. }
  1373. } catch (\Throwable $e) {
  1374. // 单字段失败不影响其它
  1375. }
  1376. }
  1377. }
  1378. } catch (\Throwable $e) {
  1379. Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
  1380. }
  1381. foreach ($buckets as &$set) {
  1382. if ($set !== []) {
  1383. ksort($set, SORT_STRING);
  1384. }
  1385. }
  1386. unset($set);
  1387. return $buckets;
  1388. }
  1389. /**
  1390. * filter JSON 是否含有效条件
  1391. *
  1392. * @param array<string, mixed> $filterArr
  1393. */
  1394. protected function procuremenFilterArrHasValue(array $filterArr): bool
  1395. {
  1396. foreach ($filterArr as $v) {
  1397. if (is_array($v)) {
  1398. if (array_filter($v, function ($x) {
  1399. return $x !== '' && $x !== null;
  1400. })) {
  1401. return true;
  1402. }
  1403. } elseif ($v !== '' && $v !== null) {
  1404. return true;
  1405. }
  1406. }
  1407. return false;
  1408. }
  1409. /**
  1410. * 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
  1411. *
  1412. * @param array<string, mixed> $filterArr
  1413. * @param array<string, mixed> $opArr
  1414. */
  1415. protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
  1416. {
  1417. if ($search !== '') {
  1418. return false;
  1419. }
  1420. foreach ($filterArr as $fk => $fv) {
  1421. if (is_array($fv)) {
  1422. continue;
  1423. }
  1424. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  1425. continue;
  1426. }
  1427. if ($fv === null) {
  1428. continue;
  1429. }
  1430. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  1431. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  1432. if ($sym === '' || $sym === '=') {
  1433. continue;
  1434. }
  1435. return false;
  1436. }
  1437. return true;
  1438. }
  1439. /**
  1440. * 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
  1441. *
  1442. * @param array<int, mixed> $rows
  1443. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1444. */
  1445. protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
  1446. {
  1447. $buckets = [
  1448. 'czlyq' => [],
  1449. 'CCLBMMC' => [],
  1450. 'cywyxm' => [],
  1451. 'CGYMC' => [],
  1452. ];
  1453. foreach ($rows as $r) {
  1454. if (!is_array($r)) {
  1455. continue;
  1456. }
  1457. foreach ($buckets as $field => &$set) {
  1458. if (count($set) >= $maxPerField) {
  1459. continue;
  1460. }
  1461. $v = trim((string)($r[$field] ?? ''));
  1462. if ($v !== '') {
  1463. $set[$v] = $v;
  1464. }
  1465. }
  1466. unset($set);
  1467. $full = true;
  1468. foreach ($buckets as $set) {
  1469. if (count($set) < $maxPerField) {
  1470. $full = false;
  1471. break;
  1472. }
  1473. }
  1474. if ($full) {
  1475. break;
  1476. }
  1477. }
  1478. foreach ($buckets as &$set) {
  1479. if ($set !== []) {
  1480. // 保证 json 编码为对象(避免 list 下标 0,1,2… 被前端当选项)
  1481. $normalized = [];
  1482. foreach ($set as $k => $v) {
  1483. $s = trim((string)(is_scalar($v) ? $v : $k));
  1484. if ($s === '') {
  1485. continue;
  1486. }
  1487. $normalized[$s] = $s;
  1488. }
  1489. ksort($normalized, SORT_STRING);
  1490. $set = $normalized;
  1491. }
  1492. }
  1493. unset($set);
  1494. return $buckets;
  1495. }
  1496. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  1497. public function pick()
  1498. {
  1499. $this->request->filter(['strip_tags', 'trim']);
  1500. if (!$this->request->isAjax()) {
  1501. $this->assignProcuremenListPage('pick', '协助下发');
  1502. return $this->view->fetch('procuremen/index');
  1503. }
  1504. return $this->index();
  1505. }
  1506. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  1507. public function audit()
  1508. {
  1509. $this->request->filter(['strip_tags', 'trim']);
  1510. if (!$this->request->isAjax()) {
  1511. $this->assignProcuremenListPage('audit', '确认供应商');
  1512. return $this->view->fetch('procuremen/index');
  1513. }
  1514. return $this->index();
  1515. }
  1516. /** 采购确认(定标) */
  1517. public function confirm()
  1518. {
  1519. $this->request->filter(['strip_tags', 'trim']);
  1520. if (!$this->request->isAjax()) {
  1521. $this->assignProcuremenListPage('confirm', '采购确认');
  1522. return $this->view->fetch('procuremen/index');
  1523. }
  1524. return $this->index();
  1525. }
  1526. /**
  1527. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  1528. */
  1529. public function index()
  1530. {
  1531. $this->request->filter(['strip_tags', 'trim']);
  1532. if (!$this->request->isAjax()) {
  1533. $this->assignProcuremenListPage('pick', '协助下发');
  1534. return $this->view->fetch('procuremen/index');
  1535. }
  1536. if ($this->request->request('keyField')) {
  1537. return $this->selectpage();
  1538. }
  1539. $this->procuremenReleaseSessionLock();
  1540. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  1541. $limit = max(10, min(500, (int)$limit));
  1542. $ym = $this->request->request('ym', '');
  1543. $ym = is_string($ym) ? trim($ym) : '';
  1544. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  1545. $wffTab = $this->resolveProcuremenListStage();
  1546. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1547. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  1548. ? $this->resolveProcuremenDefaultYm($wffTab)
  1549. : date('Y-m');
  1550. }
  1551. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1552. $ym = date('Y-m');
  1553. }
  1554. $monthStart = $ym . '-01 00:00:00';
  1555. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1556. $search = trim((string)$this->request->get('search', ''));
  1557. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  1558. $opArr = (array)json_decode($this->request->get('op', ''), true);
  1559. if (!is_array($filterArr)) {
  1560. $filterArr = [];
  1561. }
  1562. if (!is_array($opArr)) {
  1563. $opArr = [];
  1564. }
  1565. // 开标状态 / 订单状态为计算字段,不能进池内等值筛选;单独抽出后在合并后再滤
  1566. $bidOpenStatusFilter = '';
  1567. foreach (['bid_open_status_text', 'a.bid_open_status_text'] as $bidFk) {
  1568. if (!array_key_exists($bidFk, $filterArr)) {
  1569. continue;
  1570. }
  1571. $bidOpenStatusFilter = trim((string)$filterArr[$bidFk]);
  1572. unset($filterArr[$bidFk], $opArr[$bidFk]);
  1573. }
  1574. $orderStatusFilter = '';
  1575. foreach (['order_status_text', 'a.order_status_text'] as $osFk) {
  1576. if (!array_key_exists($osFk, $filterArr)) {
  1577. continue;
  1578. }
  1579. $orderStatusFilter = trim((string)$filterArr[$osFk]);
  1580. unset($filterArr[$osFk], $opArr[$osFk]);
  1581. }
  1582. // 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
  1583. $applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
  1584. $hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
  1585. try {
  1586. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  1587. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1588. $dbRows = $this->loadPurchaseOrderRowsForListStage($wffTab, $ym, $applyMonthRange);
  1589. if ($applyMonthRange && $dbRows === []) {
  1590. $fallbackYm = $this->resolveProcuremenDefaultYm($wffTab);
  1591. if ($fallbackYm !== $ym && preg_match('/^\d{4}-\d{2}$/', $fallbackYm)) {
  1592. $ym = $fallbackYm;
  1593. $monthStart = $ym . '-01 00:00:00';
  1594. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1595. $dbRows = $this->loadPurchaseOrderRowsForListStage($wffTab, $ym, true);
  1596. }
  1597. }
  1598. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(is_array($dbRows) ? $dbRows : []);
  1599. if ($wffTab === 'confirm' && $pool === []) {
  1600. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1601. }
  1602. } else {
  1603. // 初选:按月直查 ERP(不解整包 Redis,避免长时间转圈)
  1604. if ($applyMonthRange) {
  1605. $pool = $this->loadPickPoolForYm($ym);
  1606. } else {
  1607. $pool = $this->procuremenEnsureRedisPool();
  1608. }
  1609. if (!is_array($pool)) {
  1610. $pool = [];
  1611. }
  1612. // 只针对本页候选 ID 查隐藏集,避免全表扫 purchase_order_detail
  1613. $hideSet = $this->loadPickHiddenScydgySetForIds($this->extractScydgyIdsFromPool($pool));
  1614. if ($pool !== [] && $hideSet !== []) {
  1615. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1616. if (!is_array($r)) {
  1617. return false;
  1618. }
  1619. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1620. return $id <= 0 || !isset($hideSet[$id]);
  1621. }));
  1622. }
  1623. // 手工新增(YW / scydgy_id<0)只走「新增询价/查询询价」,不进初选表格
  1624. if ($pool === []) {
  1625. return json([
  1626. 'total' => 0,
  1627. 'rows' => [],
  1628. 'activeYm' => $ym,
  1629. 'filterOptions' => (
  1630. (int)$offset === 0
  1631. && !$hasActiveSearch
  1632. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1633. )
  1634. ? $this->extractProcuremenFilterOptionsFromRows([])
  1635. : new \stdClass(),
  1636. ]);
  1637. }
  1638. }
  1639. $filtered = $this->filterProcuremenIndexPool(
  1640. $pool,
  1641. $monthStart,
  1642. $monthEnd,
  1643. $applyMonthRange,
  1644. $search,
  1645. $filterArr,
  1646. $opArr,
  1647. $listTimePrimary
  1648. );
  1649. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1650. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1651. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1652. }
  1653. if (in_array($wffTab, ['audit', 'confirm'], true) && $bidOpenStatusFilter !== '') {
  1654. $filtered = $this->filterProcuremenPoolByBidOpenStatus($filtered, $bidOpenStatusFilter);
  1655. }
  1656. if (in_array($wffTab, ['audit', 'confirm'], true) && $orderStatusFilter !== '') {
  1657. $filtered = $this->filterProcuremenPoolByOrderStatus($filtered, $orderStatusFilter);
  1658. }
  1659. $sortField = 'ID';
  1660. if (is_string($sort) && $sort !== '') {
  1661. $parts = explode(',', $sort);
  1662. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1663. if ($sortField === '') {
  1664. $sortField = 'ID';
  1665. }
  1666. }
  1667. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1668. $nFiltered = count($filtered);
  1669. if ($nFiltered > 1) {
  1670. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1671. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1672. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1673. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1674. if ($ta === $tb) {
  1675. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1676. }
  1677. if ($ta === '') {
  1678. return 1;
  1679. }
  1680. if ($tb === '') {
  1681. return -1;
  1682. }
  1683. return strcmp($ta, $tb) * $ord;
  1684. });
  1685. } elseif ($sortField === 'ID') {
  1686. $sortKeys = [];
  1687. foreach ($filtered as $i => $row) {
  1688. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1689. }
  1690. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1691. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1692. } elseif ($sortField === 'CCYDH') {
  1693. usort($filtered, function ($a, $b) use ($ord) {
  1694. $sa = trim((string)($a['CCYDH'] ?? ''));
  1695. $sb = trim((string)($b['CCYDH'] ?? ''));
  1696. if ($sa === $sb) {
  1697. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1698. }
  1699. if ($sa === '') {
  1700. return 1;
  1701. }
  1702. if ($sb === '') {
  1703. return -1;
  1704. }
  1705. return strcmp($sa, $sb) * $ord;
  1706. });
  1707. } else {
  1708. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1709. $va = $a[$sortField] ?? null;
  1710. $vb = $b[$sortField] ?? null;
  1711. $sa = (string)$va;
  1712. $sb = (string)$vb;
  1713. if ($sa === $sb) {
  1714. return 0;
  1715. }
  1716. return strcmp($sa, $sb) * $ord;
  1717. });
  1718. }
  1719. }
  1720. // 确认/审批:订单状态优先(同状态内保留上面时间等排序)
  1721. if (in_array($wffTab, ['audit', 'confirm'], true) && count($filtered) > 1) {
  1722. $statusWeights = [];
  1723. foreach ($filtered as $i => $row) {
  1724. if (!is_array($row)) {
  1725. $statusWeights[$i] = 99;
  1726. continue;
  1727. }
  1728. $statusKey = $row['order_status_text'] ?? $row['wflow_status'] ?? '';
  1729. if (trim((string)$statusKey) === '') {
  1730. $statusKey = $row['wflow_status'] ?? '';
  1731. }
  1732. $statusWeights[$i] = ProcuremenStatus::orderStatusSortWeight($wffTab, $statusKey);
  1733. }
  1734. array_multisort($statusWeights, SORT_ASC, SORT_NUMERIC, $filtered);
  1735. }
  1736. $offset = max(0, (int)$offset);
  1737. $limit = max(1, (int)$limit);
  1738. $rows = array_slice($filtered, $offset, $limit);
  1739. foreach ($rows as &$rw) {
  1740. if (!is_array($rw)) {
  1741. continue;
  1742. }
  1743. $rid = (int)($rw['ID'] ?? 0);
  1744. $rw['_iss_out'] = ($wffTab !== 'pick');
  1745. }
  1746. unset($rw);
  1747. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1748. $idList = [];
  1749. foreach ($rows as $rw) {
  1750. if (!is_array($rw)) {
  1751. continue;
  1752. }
  1753. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1754. foreach ($rw['_order_merge_rows'] as $mr) {
  1755. $mid = (int)($mr['ID'] ?? 0);
  1756. if ($this->isValidScydgyRowId($mid)) {
  1757. $idList[$mid] = true;
  1758. }
  1759. }
  1760. }
  1761. $id = (int)($rw['ID'] ?? 0);
  1762. if ($this->isValidScydgyRowId($id)) {
  1763. $idList[$id] = true;
  1764. }
  1765. }
  1766. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1767. foreach ($rows as &$rw) {
  1768. if (!is_array($rw)) {
  1769. continue;
  1770. }
  1771. $mergeIds = [];
  1772. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1773. foreach ($rw['_order_merge_rows'] as $mr) {
  1774. $mid = (int)($mr['ID'] ?? 0);
  1775. if ($this->isValidScydgyRowId($mid)) {
  1776. $mergeIds[$mid] = true;
  1777. }
  1778. }
  1779. }
  1780. $rid = (int)($rw['ID'] ?? 0);
  1781. if ($this->isValidScydgyRowId($rid)) {
  1782. $mergeIds[$rid] = true;
  1783. }
  1784. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1785. $rw['po_detail_count'] = $s['cnt'];
  1786. $rw['po_amount_fill_cnt'] = $s['amt'];
  1787. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1788. }
  1789. unset($rw);
  1790. }
  1791. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1792. $idList = [];
  1793. foreach ($rows as $rw) {
  1794. if (!is_array($rw)) {
  1795. continue;
  1796. }
  1797. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1798. foreach ($rw['_order_merge_rows'] as $mr) {
  1799. $mid = (int)($mr['ID'] ?? 0);
  1800. if ($this->isValidScydgyRowId($mid)) {
  1801. $idList[$mid] = true;
  1802. }
  1803. }
  1804. }
  1805. $id = (int)($rw['ID'] ?? 0);
  1806. if ($this->isValidScydgyRowId($id)) {
  1807. $idList[$id] = true;
  1808. }
  1809. }
  1810. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1811. $bidOpenSet = [];
  1812. $manualPickSet = [];
  1813. $bidOpenBatchSet = [];
  1814. $ccydhList = [];
  1815. $batchList = [];
  1816. foreach ($rows as $rw0) {
  1817. if (!is_array($rw0)) {
  1818. continue;
  1819. }
  1820. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1821. if ($c0 !== '') {
  1822. $ccydhList[] = $c0;
  1823. }
  1824. $b0 = $this->resolveProcuremenOrderBatchNo($rw0);
  1825. if ($b0 !== '') {
  1826. $batchList[] = $b0;
  1827. }
  1828. if (!empty($rw0['_order_merge_rows']) && is_array($rw0['_order_merge_rows'])) {
  1829. foreach ($rw0['_order_merge_rows'] as $mr0) {
  1830. if (!is_array($mr0)) {
  1831. continue;
  1832. }
  1833. $cm = trim((string)($mr0['CCYDH'] ?? ''));
  1834. if ($cm !== '') {
  1835. $ccydhList[] = $cm;
  1836. }
  1837. $bm = $this->resolveProcuremenOrderBatchNo($mr0);
  1838. if ($bm !== '') {
  1839. $batchList[] = $bm;
  1840. }
  1841. }
  1842. }
  1843. }
  1844. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1845. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  1846. $bidOpenBatchSet = $this->loadProcuremenBidOpenVerifiedBatchSet($batchList);
  1847. foreach ($rows as &$rw) {
  1848. if (!is_array($rw)) {
  1849. continue;
  1850. }
  1851. $mergeIds = [];
  1852. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1853. foreach ($rw['_order_merge_rows'] as $mr) {
  1854. $mid = (int)($mr['ID'] ?? 0);
  1855. if ($this->isValidScydgyRowId($mid)) {
  1856. $mergeIds[$mid] = true;
  1857. }
  1858. }
  1859. }
  1860. $rid = (int)($rw['ID'] ?? 0);
  1861. if ($this->isValidScydgyRowId($rid)) {
  1862. $mergeIds[$rid] = true;
  1863. }
  1864. $buckets = [];
  1865. foreach (array_keys($mergeIds) as $mid) {
  1866. if (isset($quoteBucket[$mid])) {
  1867. $buckets[] = $quoteBucket[$mid];
  1868. }
  1869. }
  1870. $supplierText = $buckets !== []
  1871. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1872. : '';
  1873. $picked = trim((string)($rw['pick_company_name'] ?? $rw['picked_supplier_name'] ?? ''));
  1874. if ($picked === '') {
  1875. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1876. foreach ($rw['_order_merge_rows'] as $mr) {
  1877. if (!is_array($mr)) {
  1878. continue;
  1879. }
  1880. $pn = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  1881. if ($pn !== '') {
  1882. $picked = $pn;
  1883. break;
  1884. }
  1885. }
  1886. }
  1887. }
  1888. $rw['picked_supplier_name'] = $picked;
  1889. $rw['notify_supplier_text'] = $supplierText;
  1890. $wflowRaw = trim((string)($rw['wflow_status'] ?? ''));
  1891. if ($wflowRaw === '' && !empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1892. foreach ($rw['_order_merge_rows'] as $mr) {
  1893. if (!is_array($mr)) {
  1894. continue;
  1895. }
  1896. $wf = trim((string)($mr['wflow_status'] ?? ''));
  1897. if ($wf !== '') {
  1898. $wflowRaw = $wf;
  1899. break;
  1900. }
  1901. }
  1902. }
  1903. $rw['wflow_status'] = $wflowRaw;
  1904. $rw['order_status_text'] = ProcuremenStatus::orderStatusLabelForList($wflowRaw);
  1905. $bidState = $this->resolveProcuremenListBidOpenState($rw, $bidOpenSet, $manualPickSet, $bidOpenBatchSet);
  1906. $rw['bid_open_verified'] = !empty($bidState['verified']) ? 1 : 0;
  1907. $rw['manual_picked'] = !empty($bidState['manual']) ? 1 : 0;
  1908. $rw['bid_open_status_text'] = (string)($bidState['text'] ?? '待开标');
  1909. }
  1910. unset($rw);
  1911. }
  1912. if (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
  1913. $this->enrichProcuremenListMilestoneTimes($rows);
  1914. $this->syncCollapsedOrderQtyPriceForList($rows);
  1915. }
  1916. if ($wffTab === 'all' && count($rows) > 0) {
  1917. $this->mergePurchaseOrder($rows);
  1918. }
  1919. if ($wffTab === 'pick' && count($rows) > 0) {
  1920. $this->mergePurchaseOrder($rows);
  1921. }
  1922. foreach ($rows as &$rwClean) {
  1923. if (is_array($rwClean)) {
  1924. unset($rwClean['_order_merge_rows']);
  1925. if (array_key_exists('NGZL', $rwClean)) {
  1926. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1927. }
  1928. }
  1929. }
  1930. unset($rwClean);
  1931. return json([
  1932. 'total' => count($filtered),
  1933. 'rows' => $rows,
  1934. 'activeYm' => $ym,
  1935. // 初选:把有数据的月份带回,替换「空月份日历」侧栏
  1936. 'sidebarYms' => (in_array($wffTab, ['pick', 'audit', 'confirm'], true) && (int)$offset === 0)
  1937. ? (
  1938. $wffTab === 'pick'
  1939. ? $this->ensureProcuremenPickSidebarYmList()
  1940. : $this->flattenProcuremenSidebarYms($this->GetIssuedOrderYearMonths($wffTab))
  1941. )
  1942. : [],
  1943. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1944. 'filterOptions' => (
  1945. (int)$offset === 0
  1946. && !$hasActiveSearch
  1947. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1948. )
  1949. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1950. : new \stdClass(),
  1951. ]);
  1952. } catch (\Throwable $e) {
  1953. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1954. return json([
  1955. 'total' => 0,
  1956. 'rows' => [],
  1957. ]);
  1958. }
  1959. }
  1960. /**
  1961. * @param array<int, array<string, mixed>> $pool
  1962. * @return int[]
  1963. */
  1964. protected function extractScydgyIdsFromPool(array $pool): array
  1965. {
  1966. $ids = [];
  1967. foreach ($pool as $r) {
  1968. if (!is_array($r)) {
  1969. continue;
  1970. }
  1971. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1972. if ($id > 0) {
  1973. $ids[$id] = $id;
  1974. }
  1975. }
  1976. return array_values($ids);
  1977. }
  1978. /**
  1979. * 仅查询指定工序 ID 是否已下发/进入后续流程(初选列表加速)
  1980. *
  1981. * @param int[] $scydgyIds
  1982. * @return array<int, true>
  1983. */
  1984. protected function loadPickHiddenScydgySetForIds(array $scydgyIds): array
  1985. {
  1986. $hideSet = [];
  1987. $scydgyIds = array_values(array_filter(array_map('intval', $scydgyIds), function ($id) {
  1988. return $id > 0;
  1989. }));
  1990. if ($scydgyIds === []) {
  1991. return $hideSet;
  1992. }
  1993. // 分批,避免 whereIn 过长
  1994. foreach (array_chunk($scydgyIds, 500) as $chunk) {
  1995. try {
  1996. $poIds = Db::table('purchase_order')
  1997. ->where('scydgy_id', 'in', $chunk)
  1998. ->where(function ($q) {
  1999. $q->whereIn('wflow_status', array_merge(
  2000. ProcuremenStatus::wflowPendingConfirmValues(),
  2001. ProcuremenStatus::wflowPendingApprovalValues()
  2002. ))
  2003. ->whereOr(function ($q1) {
  2004. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  2005. })
  2006. ->whereOr(function ($q2) {
  2007. $q2->whereNotNull('pick_time')
  2008. ->where('pick_time', '<>', '')
  2009. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  2010. })
  2011. ->whereOr(function ($q3) {
  2012. $q3->whereNotNull('mod_rq')
  2013. ->where('mod_rq', '<>', '')
  2014. ->where('mod_rq', 'not like', '0000-00-00%');
  2015. });
  2016. })
  2017. ->column('scydgy_id');
  2018. if (is_array($poIds)) {
  2019. foreach ($poIds as $pid) {
  2020. $k = (int)$pid;
  2021. if ($k !== 0) {
  2022. $hideSet[$k] = true;
  2023. }
  2024. }
  2025. }
  2026. } catch (\Throwable $e) {
  2027. }
  2028. try {
  2029. $detIdsQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $chunk);
  2030. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  2031. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  2032. if (is_array($detIds)) {
  2033. foreach ($detIds as $pid) {
  2034. $k = (int)$pid;
  2035. if ($this->isValidScydgyRowId($k)) {
  2036. $hideSet[$k] = true;
  2037. }
  2038. }
  2039. }
  2040. } catch (\Throwable $e) {
  2041. }
  2042. }
  2043. return $hideSet;
  2044. }
  2045. /**
  2046. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  2047. *
  2048. * @return array<int, true>
  2049. */
  2050. protected function loadPickHiddenScydgySet(): array
  2051. {
  2052. if ($this->pickHiddenScydgySetCache !== null) {
  2053. return $this->pickHiddenScydgySetCache;
  2054. }
  2055. $cacheKey = 'procuremen_pick_hidden_scydgy_v1';
  2056. try {
  2057. $raw = redis()->get($cacheKey);
  2058. if ($raw !== false && $raw !== null && $raw !== '') {
  2059. $ids = json_decode((string)$raw, true);
  2060. if (is_array($ids)) {
  2061. $hideSet = [];
  2062. foreach ($ids as $pid) {
  2063. $k = (int)$pid;
  2064. if ($k !== 0) {
  2065. $hideSet[$k] = true;
  2066. }
  2067. }
  2068. $this->pickHiddenScydgySetCache = $hideSet;
  2069. return $hideSet;
  2070. }
  2071. }
  2072. } catch (\Throwable $e) {
  2073. }
  2074. $hideSet = [];
  2075. try {
  2076. $poIds = Db::table('purchase_order')
  2077. ->where(function ($q) {
  2078. $q->whereIn('wflow_status', array_merge(
  2079. ProcuremenStatus::wflowPendingConfirmValues(),
  2080. ProcuremenStatus::wflowPendingApprovalValues()
  2081. ))
  2082. ->whereOr(function ($q1) {
  2083. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  2084. })
  2085. ->whereOr(function ($q2) {
  2086. $q2->whereNotNull('pick_time')
  2087. ->where('pick_time', '<>', '')
  2088. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  2089. })
  2090. ->whereOr(function ($q3) {
  2091. $q3->whereNotNull('mod_rq')
  2092. ->where('mod_rq', '<>', '')
  2093. ->where('mod_rq', 'not like', '0000-00-00%');
  2094. });
  2095. })
  2096. ->column('scydgy_id');
  2097. if (is_array($poIds)) {
  2098. foreach ($poIds as $pid) {
  2099. $k = (int)$pid;
  2100. if ($k !== 0) {
  2101. $hideSet[$k] = true;
  2102. }
  2103. }
  2104. }
  2105. } catch (\Throwable $e) {
  2106. }
  2107. try {
  2108. $detIdsQuery = Db::table('purchase_order_detail');
  2109. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  2110. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  2111. if (is_array($detIds)) {
  2112. foreach ($detIds as $pid) {
  2113. $k = (int)$pid;
  2114. if ($this->isValidScydgyRowId($k)) {
  2115. $hideSet[$k] = true;
  2116. }
  2117. }
  2118. }
  2119. } catch (\Throwable $e) {
  2120. }
  2121. $this->pickHiddenScydgySetCache = $hideSet;
  2122. try {
  2123. redis()->setex($cacheKey, 90, json_encode(array_map('intval', array_keys($hideSet))));
  2124. } catch (\Throwable $e) {
  2125. }
  2126. return $hideSet;
  2127. }
  2128. /**
  2129. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  2130. *
  2131. * @return array<int, array<string, mixed>>
  2132. */
  2133. protected function loadPickManualOrderRows(): array
  2134. {
  2135. try {
  2136. $dbRows = Db::table('purchase_order')
  2137. ->where('scydgy_id', '<', 0)
  2138. ->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%\')')
  2139. ->order('scydgy_id', 'asc')
  2140. ->select();
  2141. } catch (\Throwable $e) {
  2142. try {
  2143. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  2144. } catch (\Throwable $e2) {
  2145. return [];
  2146. }
  2147. }
  2148. if (!is_array($dbRows) || $dbRows === []) {
  2149. return [];
  2150. }
  2151. $detailSidSet = [];
  2152. try {
  2153. $negIds = [];
  2154. foreach ($dbRows as $dbRow) {
  2155. if (!is_array($dbRow)) {
  2156. continue;
  2157. }
  2158. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2159. if ($sid < 0) {
  2160. $negIds[$sid] = true;
  2161. }
  2162. }
  2163. if ($negIds !== []) {
  2164. $detQuery = Db::table('purchase_order_detail')
  2165. ->where('scydgy_id', 'in', array_keys($negIds));
  2166. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  2167. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  2168. if (is_array($detRows)) {
  2169. foreach ($detRows as $did) {
  2170. $detailSidSet[(int)$did] = true;
  2171. }
  2172. }
  2173. }
  2174. } catch (\Throwable $e) {
  2175. }
  2176. $pool = [];
  2177. foreach ($dbRows as $dbRow) {
  2178. if (!is_array($dbRow)) {
  2179. continue;
  2180. }
  2181. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2182. if ($sid >= 0) {
  2183. continue;
  2184. }
  2185. // 已进入确认/审批的不进初选;仅废弃明细残留的仍算可下发
  2186. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  2187. continue;
  2188. }
  2189. // 仅排除已完结;空 status / 「进行中」/ 0 均保留(新建手工单)
  2190. if (ProcuremenStatus::isPoCompleted($dbRow['status'] ?? '')) {
  2191. continue;
  2192. }
  2193. if (isset($detailSidSet[$sid])) {
  2194. continue;
  2195. }
  2196. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  2197. $r['_is_manual'] = 1;
  2198. $pool[] = $r;
  2199. }
  2200. return $pool;
  2201. }
  2202. /**
  2203. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  2204. */
  2205. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  2206. {
  2207. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  2208. foreach ($keys as $k) {
  2209. $t = trim((string)($row[$k] ?? ''));
  2210. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2211. return $t;
  2212. }
  2213. }
  2214. return '';
  2215. }
  2216. /**
  2217. * 分配手工新增工序行 ID(负数递减)
  2218. * 调用方须在命名锁内执行,避免并发重复
  2219. */
  2220. protected function allocateManualScydgyId(): int
  2221. {
  2222. try {
  2223. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  2224. $min = (int)$min;
  2225. return $min < 0 ? $min - 1 : -1;
  2226. } catch (\Throwable $e) {
  2227. return -1;
  2228. }
  2229. }
  2230. /**
  2231. * 手工新增订单号:YW + 年月日 + 当日序号(如 YW20260618001)
  2232. * 调用方须在命名锁内执行,避免并发重复
  2233. */
  2234. protected function allocateManualOrderCcydh(): string
  2235. {
  2236. $prefix = 'YW' . date('Ymd');
  2237. $maxSeq = 0;
  2238. try {
  2239. $rows = Db::table('purchase_order')
  2240. ->where('CCYDH', 'like', $prefix . '%')
  2241. ->column('CCYDH');
  2242. if (is_array($rows)) {
  2243. foreach ($rows as $ccydh) {
  2244. $ccydh = trim((string)$ccydh);
  2245. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3,})$/', $ccydh, $m)) {
  2246. $maxSeq = max($maxSeq, (int)$m[1]);
  2247. }
  2248. }
  2249. }
  2250. } catch (\Throwable $e) {
  2251. }
  2252. $next = $maxSeq + 1;
  2253. $width = $next > 999 ? strlen((string)$next) : 3;
  2254. return $prefix . str_pad((string)$next, $width, '0', STR_PAD_LEFT);
  2255. }
  2256. /**
  2257. * MySQL 命名锁(跨连接防并发撞号)
  2258. */
  2259. protected function acquireProcuremenNamedLock(string $name, int $timeoutSec = 10): bool
  2260. {
  2261. $name = trim($name);
  2262. if ($name === '') {
  2263. return false;
  2264. }
  2265. try {
  2266. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2267. $rows = Db::query('SELECT GET_LOCK(\'' . $nameSql . '\', ' . max(1, $timeoutSec) . ') AS locked');
  2268. if (!is_array($rows) || $rows === []) {
  2269. return false;
  2270. }
  2271. $v = $rows[0]['locked'] ?? $rows[0]['LOCKED'] ?? null;
  2272. return (int)$v === 1;
  2273. } catch (\Throwable $e) {
  2274. return false;
  2275. }
  2276. }
  2277. protected function releaseProcuremenNamedLock(string $name): void
  2278. {
  2279. $name = trim($name);
  2280. if ($name === '') {
  2281. return;
  2282. }
  2283. try {
  2284. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2285. Db::query('SELECT RELEASE_LOCK(\'' . $nameSql . '\')');
  2286. } catch (\Throwable $e) {
  2287. }
  2288. }
  2289. /**
  2290. * purchase_order.mod_rq 是否有有效软删除时间
  2291. */
  2292. protected function isPurchaseOrderSoftDeleted($modRq): bool
  2293. {
  2294. $t = trim((string)$modRq);
  2295. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  2296. }
  2297. /**
  2298. * 列表行 → purchase_order 写入字段
  2299. *
  2300. * @return array<string, mixed>
  2301. */
  2302. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  2303. {
  2304. return $this->normalizePurchaseOrderWritePayload([
  2305. 'scydgy_id' => $scydgyId,
  2306. 'CCYDH' => $row['CCYDH'] ?? null,
  2307. 'CYJMC' => $row['CYJMC'] ?? null,
  2308. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2309. 'CDXMC' => $row['CDXMC'] ?? null,
  2310. 'CGYBH' => $row['CGYBH'] ?? null,
  2311. 'CGYMC' => $row['CGYMC'] ?? null,
  2312. 'CDW' => $row['CDW'] ?? null,
  2313. 'czlyq' => $row['czlyq'] ?? null,
  2314. 'NGZL' => $row['NGZL'] ?? null,
  2315. 'CDF' => $row['CDF'] ?? null,
  2316. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2317. 'MBZ' => $row['MBZ'] ?? null,
  2318. 'bwjg' => $row['bwjg'] ?? null,
  2319. 'iStatus' => $row['iStatus'] ?? null,
  2320. 'dStamp' => $row['dStamp'] ?? null,
  2321. 'dputrecord' => $row['dputrecord'] ?? null,
  2322. 'cywyxm' => $row['cywyxm'] ?? null,
  2323. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2324. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2325. ], $row);
  2326. }
  2327. /**
  2328. * purchase_order 写入前规范化:NOT NULL 列勿显式传 null(会绕过 DEFAULT 触发 1048)
  2329. *
  2330. * @param array<string, mixed> $data
  2331. * @param array<string, mixed> $row 原始列表行(可用于补齐 czlyq)
  2332. * @return array<string, mixed>
  2333. */
  2334. protected function normalizePurchaseOrderWritePayload(array $data, array $row = []): array
  2335. {
  2336. $this->ensurePurchaseOrderCzlyqColumn();
  2337. $cz = '';
  2338. foreach (['czlyq', 'CZLYQ'] as $k) {
  2339. if (isset($data[$k]) && trim((string)$data[$k]) !== '') {
  2340. $cz = trim((string)$data[$k]);
  2341. break;
  2342. }
  2343. if (isset($row[$k]) && trim((string)$row[$k]) !== '') {
  2344. $cz = trim((string)$row[$k]);
  2345. break;
  2346. }
  2347. }
  2348. if ($cz === '') {
  2349. $ccydh = trim((string)($data['CCYDH'] ?? $row['CCYDH'] ?? ''));
  2350. if ($ccydh !== '') {
  2351. try {
  2352. $fromMcyd = Db::table('mcyd')->where('CCYDH', $ccydh)->value('czlyq');
  2353. $cz = trim((string)$fromMcyd);
  2354. } catch (\Throwable $e) {
  2355. $cz = '';
  2356. }
  2357. }
  2358. }
  2359. $data['czlyq'] = $cz;
  2360. // 显式 NULL 的字符串 NOT NULL 列改为空串
  2361. foreach (['czlyq', 'notify_salesman', 'manual_pick_reason', 'score_rule_name'] as $col) {
  2362. if (!array_key_exists($col, $data)) {
  2363. continue;
  2364. }
  2365. if ($data[$col] === null || !is_scalar($data[$col])) {
  2366. $data[$col] = '';
  2367. } else {
  2368. $data[$col] = (string)$data[$col];
  2369. }
  2370. }
  2371. foreach (['rfq_salesman_notified', 'manual_pick', 'score_rule_id', 'score_quality_weight', 'score_price_weight', 'score_lead_weight'] as $col) {
  2372. if (array_key_exists($col, $data) && $data[$col] === null) {
  2373. $data[$col] = 0;
  2374. }
  2375. }
  2376. return $data;
  2377. }
  2378. /**
  2379. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  2380. *
  2381. * @return array{po:?array<string,mixed>, hidden:bool}
  2382. */
  2383. protected function resolvePickRowPoContext(int $sid): array
  2384. {
  2385. $po = null;
  2386. try {
  2387. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2388. if (is_array($found)) {
  2389. $po = $found;
  2390. }
  2391. } catch (\Throwable $e) {
  2392. }
  2393. $hideSet = $this->loadPickHiddenScydgySet();
  2394. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  2395. }
  2396. /**
  2397. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  2398. */
  2399. protected function assertPickRowCanDelete(int $sid, array $row): void
  2400. {
  2401. $ctx = $this->resolvePickRowPoContext($sid);
  2402. $po = $ctx['po'];
  2403. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2404. return;
  2405. }
  2406. if (is_array($po)) {
  2407. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2408. throw new \InvalidArgumentException('该工序已完结,无法删除');
  2409. }
  2410. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2411. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  2412. }
  2413. }
  2414. if ($ctx['hidden']) {
  2415. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2416. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  2417. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  2418. }
  2419. }
  2420. /**
  2421. * 初选直接完结前校验
  2422. */
  2423. protected function assertPickRowCanComplete(int $sid, array $row): void
  2424. {
  2425. $ctx = $this->resolvePickRowPoContext($sid);
  2426. $po = $ctx['po'];
  2427. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2428. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  2429. }
  2430. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2431. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  2432. }
  2433. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  2434. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  2435. }
  2436. }
  2437. /**
  2438. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  2439. */
  2440. protected function softDeleteProcuremenPickRow(array $row): void
  2441. {
  2442. $sid = $this->extractScydgyRowId($row);
  2443. if (!$this->isValidScydgyRowId($sid)) {
  2444. throw new \InvalidArgumentException('无效的行主键');
  2445. }
  2446. $this->assertPickRowCanDelete($sid, $row);
  2447. $po = $this->resolvePickRowPoContext($sid)['po'];
  2448. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2449. return;
  2450. }
  2451. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2452. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  2453. }
  2454. $now = date('Y-m-d H:i:s');
  2455. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2456. if (is_array($exists)) {
  2457. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  2458. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  2459. } else {
  2460. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  2461. $data['mod_rq'] = $now;
  2462. $data['createtime'] = $now;
  2463. Db::table('purchase_order')->insert($data);
  2464. $poIdLog = (int)Db::getLastInsID();
  2465. }
  2466. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  2467. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  2468. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  2469. if ($gymcLog !== '') {
  2470. $logTail .= ' / ' . $gymcLog;
  2471. }
  2472. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  2473. }
  2474. /**
  2475. * 手工新增协助工序(写入 purchase_order)
  2476. *
  2477. * @param array<string, mixed> $params
  2478. * @return int scydgy_id
  2479. */
  2480. protected function saveManualPickOrder(array $params): int
  2481. {
  2482. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  2483. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  2484. $ccydhIn = trim((string)($params['CCYDH'] ?? ''));
  2485. $lockName = 'procuremen_manual_order_alloc';
  2486. if (!$this->acquireProcuremenNamedLock($lockName, 10)) {
  2487. throw new \RuntimeException('系统繁忙,请稍后重试');
  2488. }
  2489. try {
  2490. $ccydh = $ccydhIn !== '' ? $ccydhIn : $this->allocateManualOrderCcydh();
  2491. $now = date('Y-m-d H:i:s');
  2492. $sid = $this->allocateManualScydgyId();
  2493. $this->ensurePurchaseOrderNotifySalesmanColumn();
  2494. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  2495. // 选择供应商 / 通知业务员:支持多选,落库用顿号拼接
  2496. $supplierName = $this->joinRfqMultiSelectValues($params['cGzzxMc'] ?? ($params['pick_company_name'] ?? ''));
  2497. $notifySalesman = $this->joinRfqMultiSelectValues($params['notify_salesman'] ?? '');
  2498. $data = [
  2499. 'scydgy_id' => $sid,
  2500. 'CCYDH' => $ccydh,
  2501. 'CYJMC' => $cyjmc,
  2502. 'CGYMC' => $cgymc,
  2503. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  2504. 'CDW' => trim((string)($params['CDW'] ?? '')),
  2505. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  2506. 'CDF' => trim((string)($params['CDF'] ?? '')),
  2507. 'cGzzxMc' => $supplierName,
  2508. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  2509. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  2510. 'notify_salesman' => $notifySalesman,
  2511. 'rfq_salesman_notified' => 0,
  2512. 'rfq_salesman_notify_time' => null,
  2513. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  2514. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  2515. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  2516. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  2517. 'createtime' => $now,
  2518. 'dStamp' => $now,
  2519. 'dputrecord' => $now,
  2520. ];
  2521. Db::table('purchase_order')->insert($data);
  2522. $poId = (int)Db::getLastInsID();
  2523. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  2524. return $sid;
  2525. } finally {
  2526. $this->releaseProcuremenNamedLock($lockName);
  2527. }
  2528. }
  2529. protected function formatProcuremenRowLabel(array $row): string
  2530. {
  2531. return ProcuremenFormat::rowLabel($row);
  2532. }
  2533. /**
  2534. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  2535. */
  2536. protected function extractScydgyRowId(array $row): int
  2537. {
  2538. return ProcuremenFormat::extractScydgyRowId($row);
  2539. }
  2540. protected function isValidScydgyRowId(int $id): bool
  2541. {
  2542. return ProcuremenGuard::isValidScydgyId($id);
  2543. }
  2544. protected function isManualScydgyRowId(int $id): bool
  2545. {
  2546. return $id < 0;
  2547. }
  2548. /**
  2549. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  2550. *
  2551. * @param int[] $scydgyIds
  2552. * @return array<int, string[]>
  2553. */
  2554. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  2555. {
  2556. $out = [];
  2557. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2558. if ($scydgyIds === []) {
  2559. return $out;
  2560. }
  2561. try {
  2562. $rows = Db::table('purchase_order_detail')
  2563. ->where('scydgy_id', 'in', $scydgyIds)
  2564. ->field('scydgy_id,company_name')
  2565. ->order('company_name', 'asc')
  2566. ->select();
  2567. } catch (\Throwable $e) {
  2568. $rows = [];
  2569. }
  2570. if (!is_array($rows)) {
  2571. return $out;
  2572. }
  2573. foreach ($rows as $r) {
  2574. if (!is_array($r)) {
  2575. continue;
  2576. }
  2577. $sid = (int)($r['scydgy_id'] ?? 0);
  2578. $cn = trim((string)($r['company_name'] ?? ''));
  2579. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2580. continue;
  2581. }
  2582. if (!isset($out[$sid])) {
  2583. $out[$sid] = [];
  2584. }
  2585. if (!in_array($cn, $out[$sid], true)) {
  2586. $out[$sid][] = $cn;
  2587. }
  2588. }
  2589. return $out;
  2590. }
  2591. /**
  2592. * 列表展示通知供应商(完整列表,前端单行省略展开)
  2593. *
  2594. * @param string[] $names
  2595. */
  2596. protected function formatNotifySupplierDisplay(array $names): string
  2597. {
  2598. return ProcuremenFormat::notifySupplierDisplay($names);
  2599. }
  2600. /**
  2601. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  2602. *
  2603. * @param int[] $scydgyIds
  2604. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  2605. */
  2606. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  2607. {
  2608. $out = [];
  2609. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2610. if ($scydgyIds === []) {
  2611. return $out;
  2612. }
  2613. try {
  2614. $rows = Db::table('purchase_order_detail')
  2615. ->where('scydgy_id', 'in', $scydgyIds)
  2616. ->field('scydgy_id,company_name,amount')
  2617. ->select();
  2618. } catch (\Throwable $e) {
  2619. $rows = [];
  2620. }
  2621. if (!is_array($rows)) {
  2622. return $out;
  2623. }
  2624. foreach ($rows as $r) {
  2625. if (!is_array($r)) {
  2626. continue;
  2627. }
  2628. $sid = (int)($r['scydgy_id'] ?? 0);
  2629. $cn = trim((string)($r['company_name'] ?? ''));
  2630. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2631. continue;
  2632. }
  2633. if (!isset($out[$sid])) {
  2634. $out[$sid] = ['all' => [], 'quoted' => []];
  2635. }
  2636. $out[$sid]['all'][$cn] = true;
  2637. $am = trim((string)($r['amount'] ?? ''));
  2638. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2639. $out[$sid]['quoted'][$cn] = true;
  2640. }
  2641. }
  2642. return $out;
  2643. }
  2644. /**
  2645. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  2646. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  2647. */
  2648. protected function mergeQuotedSupplierBuckets(array $buckets): array
  2649. {
  2650. $merged = ['all' => [], 'quoted' => []];
  2651. foreach ($buckets as $b) {
  2652. if (!is_array($b)) {
  2653. continue;
  2654. }
  2655. foreach ($b['all'] ?? [] as $cn => $_) {
  2656. $merged['all'][$cn] = true;
  2657. }
  2658. foreach ($b['quoted'] ?? [] as $cn => $_) {
  2659. $merged['quoted'][$cn] = true;
  2660. }
  2661. }
  2662. return $merged;
  2663. }
  2664. /**
  2665. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  2666. */
  2667. protected function formatQuotedSupplierLines(array $bucket): string
  2668. {
  2669. return ProcuremenFormat::quotedSupplierLines($bucket);
  2670. }
  2671. /**
  2672. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  2673. */
  2674. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  2675. {
  2676. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2677. $this->view->engine->layout(false);
  2678. try {
  2679. $bodyHtml = $this->view->fetch($view);
  2680. $this->view->assign('dialogBody', $bodyHtml);
  2681. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  2682. return $this->view->fetch('procuremen/dialog_lite_shell');
  2683. } finally {
  2684. if ($restoreLayout) {
  2685. $this->view->engine->layout($restoreLayout);
  2686. }
  2687. }
  2688. }
  2689. /**
  2690. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  2691. */
  2692. protected function resolveBundleSysRq(array $bundle): string
  2693. {
  2694. foreach ($bundle['pos'] ?? [] as $po) {
  2695. if (!is_array($po)) {
  2696. continue;
  2697. }
  2698. $sr = trim((string)($po['sys_rq'] ?? ''));
  2699. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  2700. return $sr;
  2701. }
  2702. }
  2703. return '';
  2704. }
  2705. /**
  2706. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  2707. */
  2708. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  2709. {
  2710. $raw = trim((string)$sysRq);
  2711. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  2712. return true;
  2713. }
  2714. $ts = strtotime(str_replace('T', ' ', $raw));
  2715. if ($ts === false || $ts <= 0) {
  2716. return true;
  2717. }
  2718. return time() >= $ts;
  2719. }
  2720. /**
  2721. * 开标前校验:必须已过报价截止时间
  2722. *
  2723. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2724. */
  2725. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  2726. {
  2727. $sysRq = $this->resolveBundleSysRq($bundle);
  2728. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  2729. $this->error('未到招标截止日期');
  2730. }
  2731. }
  2732. /**
  2733. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  2734. *
  2735. * @param array<string, mixed> $d
  2736. * @param string $deliveryYmd
  2737. */
  2738. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  2739. {
  2740. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  2741. return max(0, (int)$d['lead_days']);
  2742. }
  2743. if ($deliveryYmd === '') {
  2744. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  2745. }
  2746. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  2747. return null;
  2748. }
  2749. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2750. $t2 = strtotime($m[1] . ' 00:00:00');
  2751. if ($t1 === false || $t2 === false) {
  2752. return null;
  2753. }
  2754. return max(0, (int)round(($t2 - $t1) / 86400));
  2755. }
  2756. /**
  2757. * @param int|null $days
  2758. */
  2759. protected function formatProcuremenLeadDaysText($days): string
  2760. {
  2761. return ProcuremenFormat::leadDaysText($days);
  2762. }
  2763. /**
  2764. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2765. *
  2766. * @param array<string, mixed> $line
  2767. */
  2768. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2769. {
  2770. $amountFilled = !empty($line['amount_filled']);
  2771. $deliveryFilled = !empty($line['delivery_filled']);
  2772. $leadFilled = !empty($line['lead_days_filled']);
  2773. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2774. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2775. $line['amount_show'] = '';
  2776. if (array_key_exists('amount_text', $line)) {
  2777. $line['amount_text'] = $line['unit_price_text'];
  2778. }
  2779. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2780. $line['delivery_show'] = $deliveryText;
  2781. if (array_key_exists('delivery_text', $line)) {
  2782. $line['delivery_text'] = $deliveryText;
  2783. }
  2784. $line['delivery_ymd'] = '';
  2785. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2786. $line['lead_days_show'] = $leadText;
  2787. $line['lead_days_text'] = $leadText;
  2788. $line['lead_days'] = '';
  2789. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2790. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2791. $line['subtotal_num'] = null;
  2792. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2793. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2794. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2795. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2796. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2797. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2798. $line['amount_filled'] = false;
  2799. $line['delivery_filled'] = false;
  2800. $line['lead_days_filled'] = false;
  2801. $line['is_quoted'] = false;
  2802. if (array_key_exists('quote_label', $line)) {
  2803. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2804. }
  2805. }
  2806. protected function ensurePurchaseOrderBidOpenTable(): void
  2807. {
  2808. static $ready = false;
  2809. if ($ready) {
  2810. return;
  2811. }
  2812. $cacheKey = 'procuremen_bid_open_table_ok_v2';
  2813. try {
  2814. if (Cache::get($cacheKey)) {
  2815. $ready = true;
  2816. return;
  2817. }
  2818. } catch (\Throwable $e) {
  2819. }
  2820. try {
  2821. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2822. $ready = true;
  2823. try {
  2824. Cache::set($cacheKey, 1, 86400);
  2825. } catch (\Throwable $e) {
  2826. }
  2827. } catch (\Throwable $e) {
  2828. Db::execute(
  2829. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2830. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2831. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2832. `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号(多订单同批开标)',
  2833. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2834. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2835. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2836. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2837. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2838. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2839. `createtime` datetime DEFAULT NULL,
  2840. PRIMARY KEY (`id`),
  2841. UNIQUE KEY `uk_ccydh` (`ccydh`),
  2842. KEY `idx_order_batch_no` (`order_batch_no`)
  2843. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2844. );
  2845. $ready = true;
  2846. try {
  2847. Cache::set($cacheKey, 1, 86400);
  2848. } catch (\Throwable $e2) {
  2849. }
  2850. }
  2851. // 旧表兼容:补批次号列(不影响已有按订单号的开标记录)
  2852. try {
  2853. $cols = Db::query("SHOW COLUMNS FROM `purchase_order_bid_open` LIKE 'order_batch_no'");
  2854. if (!is_array($cols) || $cols === []) {
  2855. Db::execute(
  2856. "ALTER TABLE `purchase_order_bid_open` ADD COLUMN `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号(多订单同批开标)' AFTER `ccydh`"
  2857. );
  2858. }
  2859. } catch (\Throwable $e) {
  2860. // ignore
  2861. }
  2862. try {
  2863. $idx = Db::query("SHOW INDEX FROM `purchase_order_bid_open` WHERE Key_name = 'idx_order_batch_no'");
  2864. if (!is_array($idx) || $idx === []) {
  2865. Db::execute('ALTER TABLE `purchase_order_bid_open` ADD INDEX `idx_order_batch_no` (`order_batch_no`)');
  2866. }
  2867. } catch (\Throwable $e) {
  2868. // ignore
  2869. }
  2870. }
  2871. /**
  2872. * 列表/合并行订单号可能为「A、B」拼接,拆成单个订单号
  2873. *
  2874. * @param mixed $raw
  2875. * @return array<int, string>
  2876. */
  2877. protected function expandProcuremenCcydhTokens($raw): array
  2878. {
  2879. $s = trim((string)$raw);
  2880. if ($s === '') {
  2881. return [];
  2882. }
  2883. $parts = preg_split('/[、;;,\n\r]+/u', $s);
  2884. if (!is_array($parts)) {
  2885. return [$s];
  2886. }
  2887. $out = [];
  2888. foreach ($parts as $p) {
  2889. $p = trim((string)$p);
  2890. if ($p !== '' && !in_array($p, $out, true)) {
  2891. $out[] = $p;
  2892. }
  2893. }
  2894. return $out;
  2895. }
  2896. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  2897. {
  2898. $ccydh = trim($ccydh);
  2899. if ($ccydh === '') {
  2900. return false;
  2901. }
  2902. $this->ensurePurchaseOrderBidOpenTable();
  2903. try {
  2904. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2905. return is_array($row);
  2906. } catch (\Throwable $e) {
  2907. return false;
  2908. }
  2909. }
  2910. protected function isProcuremenBidOpenVerifiedByBatchNo(string $batchNo): bool
  2911. {
  2912. $batchNo = trim($batchNo);
  2913. if ($batchNo === '') {
  2914. return false;
  2915. }
  2916. $this->ensurePurchaseOrderBidOpenTable();
  2917. try {
  2918. $row = Db::table('purchase_order_bid_open')
  2919. ->where('order_batch_no', $batchNo)
  2920. ->find();
  2921. return is_array($row);
  2922. } catch (\Throwable $e) {
  2923. return false;
  2924. }
  2925. }
  2926. /**
  2927. * 批量查询订单是否已开标验证(入参支持「A、B」拼接)
  2928. *
  2929. * @param array<int, string> $ccydhs
  2930. * @return array<string, bool> ccydh => true
  2931. */
  2932. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  2933. {
  2934. $set = [];
  2935. $list = [];
  2936. foreach ($ccydhs as $c) {
  2937. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  2938. $list[$one] = true;
  2939. }
  2940. }
  2941. if ($list === []) {
  2942. return $set;
  2943. }
  2944. $this->ensurePurchaseOrderBidOpenTable();
  2945. try {
  2946. $rows = Db::table('purchase_order_bid_open')
  2947. ->where('ccydh', 'in', array_keys($list))
  2948. ->field('ccydh')
  2949. ->select();
  2950. foreach ($rows as $row) {
  2951. if (!is_array($row)) {
  2952. continue;
  2953. }
  2954. $c = trim((string)($row['ccydh'] ?? ''));
  2955. if ($c !== '') {
  2956. $set[$c] = true;
  2957. }
  2958. }
  2959. } catch (\Throwable $e) {
  2960. return [];
  2961. }
  2962. return $set;
  2963. }
  2964. /**
  2965. * 批量查询批次是否已开标
  2966. *
  2967. * @param array<int, string> $batchNos
  2968. * @return array<string, bool>
  2969. */
  2970. protected function loadProcuremenBidOpenVerifiedBatchSet(array $batchNos): array
  2971. {
  2972. $set = [];
  2973. $list = [];
  2974. foreach ($batchNos as $b) {
  2975. $b = trim((string)$b);
  2976. if ($b !== '') {
  2977. $list[$b] = true;
  2978. }
  2979. }
  2980. if ($list === []) {
  2981. return $set;
  2982. }
  2983. $this->ensurePurchaseOrderBidOpenTable();
  2984. try {
  2985. $rows = Db::table('purchase_order_bid_open')
  2986. ->where('order_batch_no', 'in', array_keys($list))
  2987. ->field('order_batch_no')
  2988. ->select();
  2989. foreach ($rows as $row) {
  2990. if (!is_array($row)) {
  2991. continue;
  2992. }
  2993. $b = trim((string)($row['order_batch_no'] ?? ''));
  2994. if ($b !== '') {
  2995. $set[$b] = true;
  2996. }
  2997. }
  2998. } catch (\Throwable $e) {
  2999. return [];
  3000. }
  3001. return $set;
  3002. }
  3003. /**
  3004. * 批量查询订单是否已指定供应商(免开标;入参支持「A、B」拼接)
  3005. * 仅统计未软删除行(mod_rq 空)
  3006. *
  3007. * @param array<int, string> $ccydhs
  3008. * @return array<string, bool> ccydh => true
  3009. */
  3010. protected function loadProcuremenManualPickedCcydhSet(array $ccydhs): array
  3011. {
  3012. $set = [];
  3013. $list = [];
  3014. foreach ($ccydhs as $c) {
  3015. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  3016. $list[$one] = true;
  3017. }
  3018. }
  3019. if ($list === []) {
  3020. return $set;
  3021. }
  3022. $this->ensurePurchaseOrderManualPickColumns();
  3023. try {
  3024. $q = Db::table('purchase_order')
  3025. ->where('CCYDH', 'in', array_keys($list))
  3026. ->where('manual_pick', 1)
  3027. ->whereRaw("(mod_rq IS NULL OR mod_rq = '' OR mod_rq LIKE '0000-00-00%')")
  3028. ->field('CCYDH');
  3029. $rows = $q->select();
  3030. foreach ($rows as $row) {
  3031. if (!is_array($row)) {
  3032. continue;
  3033. }
  3034. $c = trim((string)($row['CCYDH'] ?? ''));
  3035. if ($c !== '') {
  3036. $set[$c] = true;
  3037. }
  3038. }
  3039. } catch (\Throwable $e) {
  3040. return [];
  3041. }
  3042. return $set;
  3043. }
  3044. /**
  3045. * 清除开标验证记录(按订单号 + 批次号)
  3046. *
  3047. * @param array<int, string> $ccydhs
  3048. * @param array<int, string> $batchNos
  3049. */
  3050. protected function clearProcuremenBidOpenRecords(array $ccydhs = [], array $batchNos = []): void
  3051. {
  3052. $ccydhList = [];
  3053. foreach ($ccydhs as $c) {
  3054. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  3055. $ccydhList[$one] = true;
  3056. }
  3057. }
  3058. $batchList = [];
  3059. foreach ($batchNos as $b) {
  3060. $b = trim((string)$b);
  3061. if ($b !== '') {
  3062. $batchList[$b] = true;
  3063. }
  3064. }
  3065. if ($ccydhList === [] && $batchList === []) {
  3066. return;
  3067. }
  3068. try {
  3069. $this->ensurePurchaseOrderBidOpenTable();
  3070. if ($ccydhList !== []) {
  3071. Db::table('purchase_order_bid_open')->where('ccydh', 'in', array_keys($ccydhList))->delete();
  3072. }
  3073. if ($batchList !== []) {
  3074. Db::table('purchase_order_bid_open')->where('order_batch_no', 'in', array_keys($batchList))->delete();
  3075. }
  3076. } catch (\Throwable $e) {
  3077. // ignore
  3078. }
  3079. }
  3080. /**
  3081. * 新下发/重新下发:同订单号下「其它有明确批次号」的未完结主单记 mod_rq 软删除。
  3082. * 不处理:本批保留行、无批次号旧数据、已完结单(避免误伤生产并行工序)。
  3083. *
  3084. * @param array<int, string> $ccydhs
  3085. * @param array<int, int|string> $keepScydgyIds 保留的工序 ID(本批)
  3086. * @param string $keepBatchNo 本批批次号(同批其它工序行也保留)
  3087. */
  3088. protected function softDeleteOtherBatchPurchaseOrders(array $ccydhs, array $keepScydgyIds = [], string $keepBatchNo = ''): void
  3089. {
  3090. $ccydhList = [];
  3091. foreach ($ccydhs as $c) {
  3092. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  3093. $ccydhList[$one] = true;
  3094. }
  3095. }
  3096. $keepBatchNo = trim($keepBatchNo);
  3097. // 无本批批次号时不做软删,避免把同订单其它有效工序一并清掉
  3098. if ($ccydhList === [] || $keepBatchNo === '') {
  3099. return;
  3100. }
  3101. $keepSid = [];
  3102. foreach ($keepScydgyIds as $sid) {
  3103. $sid = (int)$sid;
  3104. if ($this->isValidScydgyRowId($sid)) {
  3105. $keepSid[$sid] = true;
  3106. }
  3107. }
  3108. $now = date('Y-m-d H:i:s');
  3109. $bnEsc = str_replace(["\\", "'"], ["\\\\", "''"], $keepBatchNo);
  3110. try {
  3111. $q = Db::table('purchase_order')
  3112. ->where('CCYDH', 'in', array_keys($ccydhList))
  3113. ->whereRaw("(mod_rq IS NULL OR mod_rq = '' OR mod_rq LIKE '0000-00-00%')")
  3114. // 仅软删「其它非空批次」;空批次号旧数据留给展示层按批次隔离
  3115. ->whereRaw("TRIM(CAST(order_batch_no AS CHAR(64))) <> ''")
  3116. ->whereRaw("order_batch_no <> '{$bnEsc}'")
  3117. // 已完结不软删
  3118. ->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  3119. if ($keepSid !== []) {
  3120. $q->where('scydgy_id', 'not in', array_keys($keepSid));
  3121. }
  3122. $q->update([
  3123. 'mod_rq' => $now,
  3124. 'manual_pick' => 0,
  3125. 'manual_pick_reason' => '',
  3126. ]);
  3127. } catch (\Throwable $e) {
  3128. Log::write('softDeleteOtherBatchPurchaseOrders: ' . $e->getMessage(), 'error');
  3129. }
  3130. }
  3131. /**
  3132. * 重新下发/新下发:清掉按订单号落库的供应商评分,避免旧批 0 分/旧排名串到新批
  3133. *
  3134. * @param array<int, string> $ccydhs
  3135. */
  3136. protected function clearProcuremenSupplierScoresForCcydhs(array $ccydhs): void
  3137. {
  3138. $list = [];
  3139. foreach ($ccydhs as $c) {
  3140. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  3141. $list[$one] = true;
  3142. }
  3143. }
  3144. if ($list === []) {
  3145. return;
  3146. }
  3147. try {
  3148. Db::table('supplier_service_score')->where('ccydh', 'in', array_keys($list))->delete();
  3149. } catch (\Throwable $e) {
  3150. Log::write('clearProcuremenSupplierScoresForCcydhs: ' . $e->getMessage(), 'error');
  3151. }
  3152. }
  3153. /**
  3154. * 列表行开标状态:有批次号时只认本批次开标/本行指定,避免同订单号旧批串读
  3155. *
  3156. * @param array<string, mixed> $rw
  3157. * @param array<string, bool> $bidOpenSet
  3158. * @param array<string, bool> $manualPickSet
  3159. * @param array<string, bool> $bidOpenBatchSet
  3160. * @return array{verified:bool,manual:bool,text:string}
  3161. */
  3162. protected function resolveProcuremenListBidOpenState(
  3163. array $rw,
  3164. array $bidOpenSet,
  3165. array $manualPickSet,
  3166. array $bidOpenBatchSet = []
  3167. ): array {
  3168. $batchNo = $this->resolveProcuremenOrderBatchNo($rw);
  3169. if ($batchNo === '' && !empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3170. foreach ($rw['_order_merge_rows'] as $mr) {
  3171. if (!is_array($mr)) {
  3172. continue;
  3173. }
  3174. $batchNo = $this->resolveProcuremenOrderBatchNo($mr);
  3175. if ($batchNo !== '') {
  3176. break;
  3177. }
  3178. }
  3179. }
  3180. $manual = ((int)($rw['manual_pick'] ?? 0) === 1);
  3181. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3182. foreach ($rw['_order_merge_rows'] as $mr) {
  3183. if (!is_array($mr)) {
  3184. continue;
  3185. }
  3186. // 合并行仅认同一批次(无批次号时退回同订单兼容)
  3187. if ($batchNo !== '') {
  3188. $mrBatch = $this->resolveProcuremenOrderBatchNo($mr);
  3189. if ($mrBatch !== '' && $mrBatch !== $batchNo) {
  3190. continue;
  3191. }
  3192. }
  3193. if ((int)($mr['manual_pick'] ?? 0) === 1) {
  3194. $manual = true;
  3195. }
  3196. }
  3197. }
  3198. if ($batchNo !== '') {
  3199. // 有正式批次号:开标只看本批;指定只看本行/同批合并行,不按订单号全局查
  3200. $verified = isset($bidOpenBatchSet[$batchNo]);
  3201. } else {
  3202. // 旧数据无批次号:兼容按订单号开标/指定
  3203. $verified = false;
  3204. $ccydhTokens = $this->expandProcuremenCcydhTokens($rw['CCYDH'] ?? '');
  3205. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3206. foreach ($rw['_order_merge_rows'] as $mr) {
  3207. if (!is_array($mr)) {
  3208. continue;
  3209. }
  3210. foreach ($this->expandProcuremenCcydhTokens($mr['CCYDH'] ?? '') as $one) {
  3211. if (!in_array($one, $ccydhTokens, true)) {
  3212. $ccydhTokens[] = $one;
  3213. }
  3214. }
  3215. }
  3216. }
  3217. foreach ($ccydhTokens as $c) {
  3218. if (isset($bidOpenSet[$c])) {
  3219. $verified = true;
  3220. }
  3221. if (isset($manualPickSet[$c])) {
  3222. $manual = true;
  3223. }
  3224. }
  3225. }
  3226. if ($verified) {
  3227. $text = '已开标';
  3228. } elseif ($manual) {
  3229. $text = '已指定供应商';
  3230. } else {
  3231. $text = '待开标';
  3232. }
  3233. return ['verified' => $verified, 'manual' => $manual, 'text' => $text];
  3234. }
  3235. /**
  3236. * 确认供应商列表:按开标状态筛选(已开标 / 已指定供应商 / 待开标)
  3237. *
  3238. * @param array<int, array<string, mixed>> $pool
  3239. * @return array<int, array<string, mixed>>
  3240. */
  3241. protected function filterProcuremenPoolByBidOpenStatus(array $pool, string $status): array
  3242. {
  3243. $status = trim($status);
  3244. if ($status === '' || !in_array($status, ['待开标', '已开标', '已指定供应商'], true)) {
  3245. return $pool;
  3246. }
  3247. $ccydhList = [];
  3248. $batchList = [];
  3249. foreach ($pool as $rw) {
  3250. if (!is_array($rw)) {
  3251. continue;
  3252. }
  3253. $c = trim((string)($rw['CCYDH'] ?? ''));
  3254. if ($c !== '') {
  3255. $ccydhList[] = $c;
  3256. }
  3257. $b = $this->resolveProcuremenOrderBatchNo($rw);
  3258. if ($b !== '') {
  3259. $batchList[] = $b;
  3260. }
  3261. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3262. foreach ($rw['_order_merge_rows'] as $mr) {
  3263. if (!is_array($mr)) {
  3264. continue;
  3265. }
  3266. $cm = trim((string)($mr['CCYDH'] ?? ''));
  3267. if ($cm !== '') {
  3268. $ccydhList[] = $cm;
  3269. }
  3270. $bm = $this->resolveProcuremenOrderBatchNo($mr);
  3271. if ($bm !== '') {
  3272. $batchList[] = $bm;
  3273. }
  3274. }
  3275. }
  3276. }
  3277. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  3278. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  3279. $bidOpenBatchSet = $this->loadProcuremenBidOpenVerifiedBatchSet($batchList);
  3280. $out = [];
  3281. foreach ($pool as $rw) {
  3282. if (!is_array($rw)) {
  3283. continue;
  3284. }
  3285. $state = $this->resolveProcuremenListBidOpenState($rw, $bidOpenSet, $manualPickSet, $bidOpenBatchSet);
  3286. if (($state['text'] ?? '') === $status) {
  3287. $out[] = $rw;
  3288. }
  3289. }
  3290. return $out;
  3291. }
  3292. /**
  3293. * 按订单状态筛选(待确认 / 待审核 / 已审核)
  3294. *
  3295. * @param array<int, array<string, mixed>> $pool
  3296. * @return array<int, array<string, mixed>>
  3297. */
  3298. protected function filterProcuremenPoolByOrderStatus(array $pool, string $status): array
  3299. {
  3300. $status = trim($status);
  3301. if ($status === '' || !in_array($status, ['待确认', '待审核', '已审核'], true)) {
  3302. return $pool;
  3303. }
  3304. $out = [];
  3305. foreach ($pool as $rw) {
  3306. if (!is_array($rw)) {
  3307. continue;
  3308. }
  3309. $label = trim((string)($rw['order_status_text'] ?? ''));
  3310. if ($label === '') {
  3311. $label = ProcuremenStatus::orderStatusLabelForList($rw['wflow_status'] ?? '');
  3312. }
  3313. if ($label === $status) {
  3314. $out[] = $rw;
  3315. }
  3316. }
  3317. return $out;
  3318. }
  3319. /**
  3320. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  3321. *
  3322. * @param array<string, mixed> $group
  3323. */
  3324. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  3325. {
  3326. if ($quoteVisible) {
  3327. $group['remark_quote_pending'] = 0;
  3328. return;
  3329. }
  3330. $group['remark'] = '';
  3331. $group['remark_quote_pending'] = 0;
  3332. }
  3333. /**
  3334. * 下发订单备注 MBZ(印件规格),不是供应商填写
  3335. *
  3336. * @param array{pos?:array, merge_rows?:array} $bundle
  3337. */
  3338. protected function resolveBundleOrderMbz(array $bundle): string
  3339. {
  3340. foreach (['pos', 'merge_rows'] as $key) {
  3341. foreach ($bundle[$key] ?? [] as $row) {
  3342. if (!is_array($row)) {
  3343. continue;
  3344. }
  3345. $mbz = trim((string)($row['MBZ'] ?? $row['mbz'] ?? ''));
  3346. if ($mbz !== '') {
  3347. return $mbz;
  3348. }
  3349. }
  3350. }
  3351. return '';
  3352. }
  3353. /**
  3354. * 供应商自己填的备注;与订单 MBZ 相同视为未填(历史误把规格写入明细)
  3355. */
  3356. protected function resolveSupplierOwnRemark($detailRemark, $orderMbz = ''): string
  3357. {
  3358. $own = trim((string)$detailRemark);
  3359. $mbz = trim((string)$orderMbz);
  3360. if ($own === '' || ($mbz !== '' && $own === $mbz)) {
  3361. return '';
  3362. }
  3363. return $own;
  3364. }
  3365. /**
  3366. * 供应商备注展示:仅自己填写的;有工序行时始终占一行「投标备注」(空也显示标签)
  3367. *
  3368. * @param array<string, mixed> $group
  3369. */
  3370. protected function finalizeSupplierRemarkDisplay(array &$group, string $orderMbz, bool $quoteVisible): void
  3371. {
  3372. $group['remark'] = $this->resolveSupplierOwnRemark($group['remark'] ?? '', $orderMbz);
  3373. $this->maskSupplierRemarkBeforeBidOpen($group, $quoteVisible);
  3374. $lineCount = (int)($group['line_count'] ?? 0);
  3375. if ($lineCount <= 0) {
  3376. $lines = $group['lines'] ?? $group['pick_lines'] ?? [];
  3377. $lineCount = is_array($lines) ? count($lines) : 0;
  3378. }
  3379. // 与手机端一致:有供应商工序行就显示投标备注行,内容可为空
  3380. $group['has_remark'] = $lineCount > 0;
  3381. $extra = (!empty($group['has_remark']) ? 1 : 0) + (!empty($group['has_total']) ? 1 : 0);
  3382. $group['display_rowspan'] = $lineCount > 0 ? ($lineCount + $extra) : 0;
  3383. }
  3384. /**
  3385. * @param array{ccydh?:string,pos?:array,order_batch_no?:string} $bundle
  3386. */
  3387. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  3388. {
  3389. $batchNo = $this->resolveBundleOrderBatchNo($bundle);
  3390. // 有批次号:只认本批开标,避免同订单号历史开标串到新批
  3391. if ($batchNo !== '') {
  3392. return $this->isProcuremenBidOpenVerifiedByBatchNo($batchNo);
  3393. }
  3394. $list = [];
  3395. foreach ($bundle['pos'] ?? [] as $po) {
  3396. if (!is_array($po)) {
  3397. continue;
  3398. }
  3399. foreach ($this->expandProcuremenCcydhTokens($po['CCYDH'] ?? '') as $dh) {
  3400. $list[$dh] = true;
  3401. }
  3402. }
  3403. $primary = trim((string)($bundle['ccydh'] ?? ''));
  3404. foreach ($this->expandProcuremenCcydhTokens($primary) as $dh) {
  3405. $list[$dh] = true;
  3406. }
  3407. if ($list === []) {
  3408. return false;
  3409. }
  3410. // 旧数据无批次号:全部订单号都有开标记录才算已开标
  3411. foreach (array_keys($list) as $ccydh) {
  3412. if (!$this->isProcuremenBidOpenVerified($ccydh)) {
  3413. return false;
  3414. }
  3415. }
  3416. return true;
  3417. }
  3418. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  3419. {
  3420. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  3421. return true;
  3422. }
  3423. return $this->isProcuremenManualPickedForBundle($bundle);
  3424. }
  3425. /**
  3426. * 确保 purchase_order 自选供应商字段
  3427. */
  3428. protected function ensurePurchaseOrderManualPickColumns(): void
  3429. {
  3430. static $done = false;
  3431. if ($done) {
  3432. return;
  3433. }
  3434. $done = true;
  3435. $adds = [
  3436. 'manual_pick' => "ADD COLUMN `manual_pick` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=自选供应商(免开标)' AFTER `pick_company_name`",
  3437. 'manual_pick_reason' => "ADD COLUMN `manual_pick_reason` varchar(500) NOT NULL DEFAULT '' COMMENT '自选供应商选择说明' AFTER `manual_pick`",
  3438. ];
  3439. foreach ($adds as $col => $ddl) {
  3440. try {
  3441. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  3442. if (!is_array($cols) || $cols === []) {
  3443. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  3444. }
  3445. } catch (\Throwable $e) {
  3446. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  3447. }
  3448. }
  3449. }
  3450. /**
  3451. * 是否已自选供应商(免开标查看报价)——仅看本 bundle 行,不按订单号串旧批
  3452. *
  3453. * @param array{pos?:array} $bundle
  3454. */
  3455. protected function isProcuremenManualPickedForBundle(array $bundle): bool
  3456. {
  3457. $this->ensurePurchaseOrderManualPickColumns();
  3458. foreach ($bundle['pos'] ?? [] as $poRow) {
  3459. if (!is_array($poRow)) {
  3460. continue;
  3461. }
  3462. if ((int)($poRow['manual_pick'] ?? 0) === 1) {
  3463. return true;
  3464. }
  3465. }
  3466. return false;
  3467. }
  3468. /**
  3469. * @param array{pos?:array} $bundle
  3470. * @return array{company:string,reason:string}
  3471. */
  3472. protected function resolveProcuremenManualPickInfo(array $bundle): array
  3473. {
  3474. $this->ensurePurchaseOrderManualPickColumns();
  3475. foreach ($bundle['pos'] ?? [] as $poRow) {
  3476. if (!is_array($poRow)) {
  3477. continue;
  3478. }
  3479. if ((int)($poRow['manual_pick'] ?? 0) !== 1) {
  3480. continue;
  3481. }
  3482. $cn = trim((string)($poRow['pick_company_name'] ?? ''));
  3483. $reason = trim((string)($poRow['manual_pick_reason'] ?? ''));
  3484. return ['company' => $cn, 'reason' => $reason];
  3485. }
  3486. return ['company' => '', 'reason' => ''];
  3487. }
  3488. protected function loadBidOpenAdminUser(int $adminId): ?array
  3489. {
  3490. if ($adminId <= 0) {
  3491. return null;
  3492. }
  3493. try {
  3494. $row = Db::name('admin')->where('id', $adminId)->find();
  3495. } catch (\Throwable $e) {
  3496. return null;
  3497. }
  3498. if (!is_array($row)) {
  3499. return null;
  3500. }
  3501. $status = strtolower(trim((string)($row['status'] ?? '')));
  3502. if ($status !== '' && $status !== 'normal') {
  3503. return null;
  3504. }
  3505. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  3506. return null;
  3507. }
  3508. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  3509. if (!preg_match('/^1\d{10}$/', $phone)) {
  3510. return null;
  3511. }
  3512. $name = trim((string)($row['nickname'] ?? ''));
  3513. if ($name === '') {
  3514. $name = trim((string)($row['username'] ?? ''));
  3515. }
  3516. return [
  3517. 'id' => (int)$row['id'],
  3518. 'username' => trim((string)($row['username'] ?? '')),
  3519. 'nickname' => $name,
  3520. 'mobile' => $phone,
  3521. ];
  3522. }
  3523. /**
  3524. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  3525. */
  3526. protected function bidOpenVerifierAuthGroupRootId(): int
  3527. {
  3528. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  3529. return $id > 0 ? $id : 10;
  3530. }
  3531. /**
  3532. * @return int[]
  3533. */
  3534. protected function loadBidOpenVerifierAuthGroupIds(): array
  3535. {
  3536. static $memo = [];
  3537. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  3538. if (isset($memo[$rootId])) {
  3539. return $memo[$rootId];
  3540. }
  3541. try {
  3542. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  3543. } catch (\Throwable $e) {
  3544. $memo[$rootId] = [$rootId];
  3545. return $memo[$rootId];
  3546. }
  3547. if (!is_array($groups) || $groups === []) {
  3548. $memo[$rootId] = [$rootId];
  3549. return $memo[$rootId];
  3550. }
  3551. $groupList = [];
  3552. foreach ($groups as $g) {
  3553. if (is_array($g)) {
  3554. $groupList[] = $g;
  3555. }
  3556. }
  3557. if ($groupList === []) {
  3558. $memo[$rootId] = [$rootId];
  3559. return $memo[$rootId];
  3560. }
  3561. $tree = \fast\Tree::instance();
  3562. $tree->init($groupList);
  3563. $ids = $tree->getChildrenIds($rootId, true);
  3564. if (!is_array($ids) || $ids === []) {
  3565. $memo[$rootId] = [$rootId];
  3566. return $memo[$rootId];
  3567. }
  3568. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  3569. return $memo[$rootId];
  3570. }
  3571. protected function isBidOpenVerifierAdmin(int $adminId): bool
  3572. {
  3573. if ($adminId <= 0) {
  3574. return false;
  3575. }
  3576. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3577. if ($groupIds === []) {
  3578. return false;
  3579. }
  3580. try {
  3581. return (bool)Db::name('auth_group_access')
  3582. ->where('uid', $adminId)
  3583. ->where('group_id', 'in', $groupIds)
  3584. ->count();
  3585. } catch (\Throwable $e) {
  3586. return false;
  3587. }
  3588. }
  3589. /**
  3590. * @return array<int, array<string, mixed>>
  3591. */
  3592. protected function listBidOpenVerifierCandidates(): array
  3593. {
  3594. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3595. if ($groupIds === []) {
  3596. return [];
  3597. }
  3598. try {
  3599. $adminIds = Db::name('auth_group_access')
  3600. ->where('group_id', 'in', $groupIds)
  3601. ->column('uid');
  3602. } catch (\Throwable $e) {
  3603. $adminIds = [];
  3604. }
  3605. $adminIds = is_array($adminIds)
  3606. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  3607. : [];
  3608. if ($adminIds === []) {
  3609. return [];
  3610. }
  3611. try {
  3612. $rows = Db::name('admin')
  3613. ->where('status', 'normal')
  3614. ->where('id', 'in', $adminIds)
  3615. ->where('mobile', '<>', '')
  3616. ->order('id', 'asc')
  3617. ->select();
  3618. } catch (\Throwable $e) {
  3619. return [];
  3620. }
  3621. if (!is_array($rows)) {
  3622. return [];
  3623. }
  3624. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  3625. $out = [];
  3626. foreach ($rows as $row) {
  3627. if (!is_array($row)) {
  3628. continue;
  3629. }
  3630. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  3631. if ($one === null) {
  3632. continue;
  3633. }
  3634. $out[] = [
  3635. 'id' => $one['id'],
  3636. 'username' => $one['username'],
  3637. 'nickname' => $one['nickname'],
  3638. 'group_name' => $groupNameMap[$one['id']] ?? '',
  3639. 'mobile' => mask_phone($one['mobile']),
  3640. 'mobile_plain' => (string)$one['mobile'],
  3641. ];
  3642. }
  3643. return $out;
  3644. }
  3645. /**
  3646. * @param int[] $adminIds
  3647. * @return array<int, string>
  3648. */
  3649. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  3650. {
  3651. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  3652. if ($adminIds === []) {
  3653. return [];
  3654. }
  3655. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3656. try {
  3657. $rows = Db::name('auth_group_access')
  3658. ->alias('aga')
  3659. ->join('auth_group ag', 'aga.group_id = ag.id')
  3660. ->where('aga.uid', 'in', $adminIds)
  3661. ->where('aga.group_id', 'in', $groupIds)
  3662. ->field('aga.uid,ag.name')
  3663. ->order('aga.uid', 'asc')
  3664. ->order('aga.group_id', 'asc')
  3665. ->select();
  3666. } catch (\Throwable $e) {
  3667. return [];
  3668. }
  3669. if (!is_array($rows)) {
  3670. return [];
  3671. }
  3672. $out = [];
  3673. foreach ($rows as $row) {
  3674. if (!is_array($row)) {
  3675. continue;
  3676. }
  3677. $uid = (int)($row['uid'] ?? 0);
  3678. $name = trim((string)($row['name'] ?? ''));
  3679. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  3680. continue;
  3681. }
  3682. $out[$uid] = $name;
  3683. }
  3684. return $out;
  3685. }
  3686. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  3687. {
  3688. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  3689. }
  3690. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  3691. {
  3692. return 'procuremen_bidopen_wait_' . $adminId;
  3693. }
  3694. protected function renderBidOpenVerifySms(string $code): string
  3695. {
  3696. $tpl = '';
  3697. try {
  3698. $row = $this->loadNotifyTemplateRow('bid_open');
  3699. if (is_array($row)) {
  3700. $tpl = trim((string)($row['content'] ?? ''));
  3701. }
  3702. } catch (\Throwable $e) {
  3703. $tpl = '';
  3704. }
  3705. if ($tpl === '') {
  3706. $tpl = '【可集达】您的短信验证码是{code}';
  3707. }
  3708. return str_replace('{code}', $code, $tpl);
  3709. }
  3710. protected function sendBidOpenVerifySms(string $phone, string $code): void
  3711. {
  3712. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  3713. }
  3714. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  3715. {
  3716. $code = trim($code);
  3717. if (!preg_match('/^\d{6}$/', $code)) {
  3718. return false;
  3719. }
  3720. $mock = Config::get('mproc.mock_sms_code');
  3721. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3722. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3723. return true;
  3724. }
  3725. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3726. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3727. return false;
  3728. }
  3729. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3730. return true;
  3731. }
  3732. /**
  3733. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3734. */
  3735. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  3736. {
  3737. $ccydhList = [];
  3738. $batchNo = $this->resolveBundleOrderBatchNo($bundle);
  3739. foreach ($bundle['pos'] ?? [] as $poRow) {
  3740. if (!is_array($poRow)) {
  3741. continue;
  3742. }
  3743. foreach ($this->expandProcuremenCcydhTokens($poRow['CCYDH'] ?? '') as $dh) {
  3744. $ccydhList[$dh] = true;
  3745. }
  3746. if ($batchNo === '') {
  3747. $batchNo = $this->resolveProcuremenOrderBatchNo($poRow);
  3748. }
  3749. }
  3750. $primaryCcydh = trim((string)($bundle['ccydh'] ?? ''));
  3751. foreach ($this->expandProcuremenCcydhTokens($primaryCcydh) as $dh) {
  3752. $ccydhList[$dh] = true;
  3753. }
  3754. if ($ccydhList === []) {
  3755. throw new \InvalidArgumentException('订单号无效');
  3756. }
  3757. $this->ensurePurchaseOrderBidOpenTable();
  3758. list($operatorId, $operatorName) = $this->GetUseName();
  3759. $now = date('Y-m-d H:i:s');
  3760. $payloadBase = [
  3761. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  3762. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  3763. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  3764. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  3765. 'operator_id' => (int)$operatorId,
  3766. 'operator_name' => trim((string)$operatorName),
  3767. 'createtime' => $now,
  3768. 'order_batch_no' => $batchNo,
  3769. ];
  3770. foreach (array_keys($ccydhList) as $ccydh) {
  3771. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3772. $payload = $payloadBase;
  3773. $payload['ccydh'] = $ccydh;
  3774. if (is_array($exists)) {
  3775. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  3776. } else {
  3777. Db::table('purchase_order_bid_open')->insert($payload);
  3778. }
  3779. }
  3780. $name1 = $payloadBase['verifier1_name'] !== '' ? $payloadBase['verifier1_name'] : ('ID' . $payloadBase['verifier1_id']);
  3781. $name2 = $payloadBase['verifier2_name'] !== '' ? $payloadBase['verifier2_name'] : ('ID' . $payloadBase['verifier2_id']);
  3782. $labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
  3783. (int)$payloadBase['verifier1_id'],
  3784. (int)$payloadBase['verifier2_id'],
  3785. ]);
  3786. if (isset($labelMap[(int)$payloadBase['verifier1_id']]) && (int)$payloadBase['verifier1_id'] > 0) {
  3787. $name1 = $labelMap[(int)$payloadBase['verifier1_id']];
  3788. }
  3789. if (isset($labelMap[(int)$payloadBase['verifier2_id']]) && (int)$payloadBase['verifier2_id'] > 0) {
  3790. $name2 = $labelMap[(int)$payloadBase['verifier2_id']];
  3791. }
  3792. $logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
  3793. $seenSid = [];
  3794. foreach ($bundle['pos'] ?? [] as $poRow) {
  3795. if (!is_array($poRow)) {
  3796. continue;
  3797. }
  3798. $sid = (int)($poRow['scydgy_id'] ?? 0);
  3799. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  3800. continue;
  3801. }
  3802. $seenSid[$sid] = true;
  3803. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  3804. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  3805. }
  3806. if ($seenSid === []) {
  3807. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  3808. if ($this->isValidScydgyRowId($anchor)) {
  3809. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  3810. }
  3811. }
  3812. // 开标通过后:按订单号分别计算并写入供应商服务评分(避免多订单串分)
  3813. try {
  3814. $ym = date('Y-m', strtotime($now) ?: time());
  3815. $this->saveProcuremenSupplierScoresForBundle($bundle, $ym);
  3816. } catch (\Throwable $e) {
  3817. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  3818. }
  3819. }
  3820. /**
  3821. * 按 bundle 内各订单分别计分落库(价格分不跨订单混算)
  3822. *
  3823. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3824. */
  3825. protected function saveProcuremenSupplierScoresForBundle(array $bundle, ?string $ym = null): void
  3826. {
  3827. $posByCcydh = [];
  3828. foreach ($bundle['pos'] ?? [] as $po) {
  3829. if (!is_array($po)) {
  3830. continue;
  3831. }
  3832. $dh = trim((string)($po['CCYDH'] ?? ''));
  3833. if ($dh === '') {
  3834. continue;
  3835. }
  3836. if (!isset($posByCcydh[$dh])) {
  3837. $posByCcydh[$dh] = [];
  3838. }
  3839. $posByCcydh[$dh][] = $po;
  3840. }
  3841. if ($posByCcydh === []) {
  3842. $fallback = trim((string)($bundle['ccydh'] ?? ''));
  3843. if ($fallback === '') {
  3844. return;
  3845. }
  3846. $groups = $this->loadAuditSupplierQuoteGroups($bundle);
  3847. ProcuremenSupplierScore::saveForOrder($fallback, $groups, $ym);
  3848. return;
  3849. }
  3850. $mergeAll = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  3851. foreach ($posByCcydh as $ccydh => $posList) {
  3852. $sidSet = [];
  3853. foreach ($posList as $po) {
  3854. $sid = (int)($po['scydgy_id'] ?? 0);
  3855. if ($this->isValidScydgyRowId($sid)) {
  3856. $sidSet[$sid] = true;
  3857. }
  3858. }
  3859. $mergeRows = [];
  3860. foreach ($mergeAll as $mr) {
  3861. if (!is_array($mr)) {
  3862. continue;
  3863. }
  3864. $gid = $this->extractScydgyRowId($mr);
  3865. if ($this->isValidScydgyRowId($gid) && isset($sidSet[$gid])) {
  3866. $mergeRows[] = $mr;
  3867. }
  3868. }
  3869. $subBundle = [
  3870. 'ccydh' => $ccydh,
  3871. 'pos' => $posList,
  3872. 'merge_rows' => $mergeRows !== [] ? $mergeRows : $this->scydgyRowsForPurchaseOrders($posList),
  3873. ];
  3874. $groups = $this->loadAuditSupplierQuoteGroups($subBundle);
  3875. ProcuremenSupplierScore::saveForOrder($ccydh, $groups, $ym);
  3876. }
  3877. }
  3878. /**
  3879. * 报价行展示字段默认值(模板安全访问)
  3880. *
  3881. * @param array<string, mixed> $line
  3882. * @return array<string, mixed>
  3883. */
  3884. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  3885. {
  3886. if (!array_key_exists('amount_quote_pending', $line)) {
  3887. $line['amount_quote_pending'] = 0;
  3888. }
  3889. if (!array_key_exists('delivery_quote_pending', $line)) {
  3890. $line['delivery_quote_pending'] = 0;
  3891. }
  3892. if (!array_key_exists('quote_before_deadline', $line)) {
  3893. $line['quote_before_deadline'] = 0;
  3894. }
  3895. if (!array_key_exists('amount_filled', $line)) {
  3896. $line['amount_filled'] = 0;
  3897. }
  3898. if (!array_key_exists('delivery_filled', $line)) {
  3899. $line['delivery_filled'] = 0;
  3900. }
  3901. if (!array_key_exists('lead_days_filled', $line)) {
  3902. $line['lead_days_filled'] = 0;
  3903. }
  3904. if (!array_key_exists('lead_days_quote_pending', $line)) {
  3905. $line['lead_days_quote_pending'] = 0;
  3906. }
  3907. if (!array_key_exists('lead_days_show', $line)) {
  3908. $line['lead_days_show'] = '未填写';
  3909. }
  3910. if (!array_key_exists('lead_days_text', $line)) {
  3911. $line['lead_days_text'] = $line['lead_days_show'];
  3912. }
  3913. if (!array_key_exists('ccydh', $line)) {
  3914. $line['ccydh'] = '';
  3915. }
  3916. if (!array_key_exists('cgymc', $line)) {
  3917. $line['cgymc'] = '';
  3918. }
  3919. // 工序列展示文案:上行订单号、下行工序(无括号;兼容旧模板)
  3920. if (!array_key_exists('cgymc_display', $line) || trim((string)$line['cgymc_display']) === '') {
  3921. $dh = trim((string)$line['ccydh']);
  3922. $gy = trim((string)$line['cgymc']);
  3923. $line['cgymc_display'] = $dh !== '' ? ($dh . "\n" . $gy) : $gy;
  3924. }
  3925. return $line;
  3926. }
  3927. /**
  3928. * 供应商报价表「工序名称」列:订单号 + 工序名(不加 [])
  3929. *
  3930. * @return array{ccydh:string,cgymc:string,cgymc_display:string}
  3931. */
  3932. protected function buildSupplierProcessNameFields(string $ccydh, string $cgymc): array
  3933. {
  3934. $ccydh = trim($ccydh);
  3935. $cgymc = trim($cgymc);
  3936. if ($cgymc === '') {
  3937. $cgymc = '工序';
  3938. }
  3939. return [
  3940. 'ccydh' => $ccydh,
  3941. 'cgymc' => $cgymc,
  3942. 'cgymc_display' => $ccydh !== '' ? ($ccydh . "\n" . $cgymc) : $cgymc,
  3943. ];
  3944. }
  3945. /**
  3946. * 审核弹窗:按供应商汇总报价明细
  3947. *
  3948. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3949. * @return array<int, array<string, mixed>>
  3950. */
  3951. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  3952. {
  3953. $sids = [];
  3954. foreach ($bundle['pos'] ?? [] as $po) {
  3955. if (!is_array($po)) {
  3956. continue;
  3957. }
  3958. $sid = (int)($po['scydgy_id'] ?? 0);
  3959. if ($this->isValidScydgyRowId($sid)) {
  3960. $sids[$sid] = true;
  3961. }
  3962. }
  3963. if ($sids === []) {
  3964. return [];
  3965. }
  3966. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3967. $orderMbz = $this->resolveBundleOrderMbz($bundle);
  3968. $orderDeadlineMap = $this->buildBundleOrderDeliveryDeadlineMap($bundle);
  3969. $gymcMap = [];
  3970. $ccydhBySid = [];
  3971. $qtyBySid = [];
  3972. $orderedSids = [];
  3973. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3974. if (!is_array($mr)) {
  3975. continue;
  3976. }
  3977. $gid = $this->extractScydgyRowId($mr);
  3978. if ($this->isValidScydgyRowId($gid)) {
  3979. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3980. $dh = trim((string)($mr['CCYDH'] ?? ''));
  3981. if ($dh !== '') {
  3982. $ccydhBySid[$gid] = $dh;
  3983. }
  3984. $orderedSids[] = $gid;
  3985. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3986. if ($qty === '') {
  3987. $qty = trim((string)($mr['NGZL'] ?? ''));
  3988. }
  3989. $qtyBySid[$gid] = $qty;
  3990. }
  3991. }
  3992. foreach ($bundle['pos'] ?? [] as $po) {
  3993. if (!is_array($po)) {
  3994. continue;
  3995. }
  3996. $gid = (int)($po['scydgy_id'] ?? 0);
  3997. if ($this->isValidScydgyRowId($gid)) {
  3998. $nm = trim((string)($po['CGYMC'] ?? ''));
  3999. if ($nm !== '') {
  4000. $gymcMap[$gid] = $nm;
  4001. }
  4002. $dh = trim((string)($po['CCYDH'] ?? ''));
  4003. if ($dh !== '' && empty($ccydhBySid[$gid])) {
  4004. $ccydhBySid[$gid] = $dh;
  4005. }
  4006. if (!in_array($gid, $orderedSids, true)) {
  4007. $orderedSids[] = $gid;
  4008. }
  4009. }
  4010. }
  4011. try {
  4012. $detailsQuery = Db::table('purchase_order_detail')
  4013. ->where('scydgy_id', 'in', array_keys($sids));
  4014. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  4015. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  4016. } catch (\Throwable $e) {
  4017. try {
  4018. $detailsQuery = Db::table('purchase_order_detail')
  4019. ->where('scydgy_id', 'in', array_keys($sids));
  4020. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  4021. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  4022. } catch (\Throwable $e2) {
  4023. $details = [];
  4024. }
  4025. }
  4026. if (!is_array($details)) {
  4027. $details = [];
  4028. }
  4029. $byCompany = [];
  4030. foreach ($details as $d) {
  4031. if (!is_array($d)) {
  4032. continue;
  4033. }
  4034. $cn = trim((string)($d['company_name'] ?? ''));
  4035. if ($cn === '') {
  4036. continue;
  4037. }
  4038. if (!isset($byCompany[$cn])) {
  4039. $ph = trim((string)($d['phone'] ?? ''));
  4040. $username = trim((string)($d['username'] ?? ''));
  4041. if ($username === '') {
  4042. $username = $this->resolveCustomerContactName($ph, $cn);
  4043. }
  4044. $byCompany[$cn] = [
  4045. 'name' => $cn,
  4046. 'email' => trim((string)($d['email'] ?? '')),
  4047. 'phone' => $ph,
  4048. 'username' => $username,
  4049. 'remark' => '',
  4050. 'has_quote' => false,
  4051. 'lines_map' => [],
  4052. ];
  4053. }
  4054. if ($byCompany[$cn]['remark'] === '') {
  4055. $rm = '';
  4056. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  4057. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  4058. $rm = trim((string)$d[$rk]);
  4059. break;
  4060. }
  4061. }
  4062. if ($rm !== '') {
  4063. $byCompany[$cn]['remark'] = $rm;
  4064. }
  4065. }
  4066. $sid = (int)($d['scydgy_id'] ?? 0);
  4067. $am = trim((string)($d['amount'] ?? ''));
  4068. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  4069. $ccydhLine = trim((string)($ccydhBySid[$sid] ?? ''));
  4070. $processName = $this->buildSupplierProcessNameFields($ccydhLine, $gymc);
  4071. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  4072. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  4073. if ($deliveryShow === '' && $deliveryRaw !== '') {
  4074. $deliveryShow = $deliveryRaw;
  4075. }
  4076. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  4077. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  4078. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  4079. $subtotal = null;
  4080. if ($amountNum !== null) {
  4081. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  4082. }
  4083. $unitPriceText = $amountFilled
  4084. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  4085. : '未填写';
  4086. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  4087. $leadFilled = ($leadDays !== null);
  4088. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  4089. $lineRow = array_merge($processName, [
  4090. 'amount' => $am,
  4091. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  4092. 'amount_filled' => $amountFilled,
  4093. 'unit_price_text' => $unitPriceText,
  4094. 'delivery' => $deliveryRaw,
  4095. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  4096. 'delivery_filled' => $deliveryFilled,
  4097. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  4098. 'order_delivery_deadline' => $orderDeadlineMap[$ccydhLine] ?? '',
  4099. 'lead_days' => $leadFilled ? $leadDays : '',
  4100. 'lead_days_filled' => $leadFilled,
  4101. 'lead_days_show' => $leadText,
  4102. 'lead_days_text' => $leadText,
  4103. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  4104. 'subtotal_num' => $subtotal,
  4105. 'status_name' => trim((string)($d['status_name'] ?? '')),
  4106. 'is_quoted' => $amountFilled,
  4107. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  4108. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  4109. ]);
  4110. if (!$quoteVisible) {
  4111. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  4112. }
  4113. // 按工序 id 暂存,下面再按上方工序表顺序输出
  4114. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  4115. }
  4116. foreach ($byCompany as $cn => $g) {
  4117. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  4118. $lines = [];
  4119. $usedSids = [];
  4120. foreach ($orderedSids as $sid) {
  4121. if (!isset($linesMap[$sid])) {
  4122. continue;
  4123. }
  4124. $lines[] = $linesMap[$sid];
  4125. $usedSids[$sid] = true;
  4126. }
  4127. foreach ($linesMap as $sid => $ln) {
  4128. if (isset($usedSids[$sid])) {
  4129. continue;
  4130. }
  4131. $lines[] = $ln;
  4132. }
  4133. $total = count($lines);
  4134. $quoted = 0;
  4135. $groupTotal = 0.0;
  4136. $groupHasTotal = false;
  4137. if ($quoteVisible) {
  4138. foreach ($lines as $ln) {
  4139. $am = trim((string)($ln['amount'] ?? ''));
  4140. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  4141. $quoted++;
  4142. }
  4143. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  4144. $groupTotal += (float)$ln['subtotal_num'];
  4145. $groupHasTotal = true;
  4146. }
  4147. }
  4148. }
  4149. unset($byCompany[$cn]['lines_map']);
  4150. $byCompany[$cn]['lines'] = $lines;
  4151. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  4152. $byCompany[$cn]['line_count'] = $total;
  4153. $byCompany[$cn]['has_total'] = $total > 0;
  4154. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  4155. $this->finalizeSupplierRemarkDisplay($byCompany[$cn], $orderMbz, $quoteVisible);
  4156. }
  4157. $groups = array_values($byCompany);
  4158. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  4159. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  4160. }
  4161. /**
  4162. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  4163. *
  4164. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  4165. * @return array<int, array<string, mixed>>
  4166. */
  4167. protected function loadConfirmSupplierPickGroups(array $bundle): array
  4168. {
  4169. $sids = [];
  4170. $poIdMap = [];
  4171. foreach ($bundle['pos'] ?? [] as $po) {
  4172. if (!is_array($po)) {
  4173. continue;
  4174. }
  4175. $sid = (int)($po['scydgy_id'] ?? 0);
  4176. if ($this->isValidScydgyRowId($sid)) {
  4177. $sids[$sid] = true;
  4178. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  4179. }
  4180. }
  4181. if ($sids === []) {
  4182. return [];
  4183. }
  4184. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  4185. $orderMbz = $this->resolveBundleOrderMbz($bundle);
  4186. $orderDeadlineMap = $this->buildBundleOrderDeliveryDeadlineMap($bundle);
  4187. $gymcMap = [];
  4188. $ccydhBySid = [];
  4189. $qtyBySid = [];
  4190. $orderedSids = [];
  4191. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  4192. if (!is_array($mr)) {
  4193. continue;
  4194. }
  4195. $gid = $this->extractScydgyRowId($mr);
  4196. if ($this->isValidScydgyRowId($gid)) {
  4197. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  4198. $dh = trim((string)($mr['CCYDH'] ?? ''));
  4199. if ($dh !== '') {
  4200. $ccydhBySid[$gid] = $dh;
  4201. }
  4202. $orderedSids[] = $gid;
  4203. $qty = trim((string)($mr['This_quantity'] ?? ''));
  4204. if ($qty === '') {
  4205. $qty = trim((string)($mr['NGZL'] ?? ''));
  4206. }
  4207. $qtyBySid[$gid] = $qty;
  4208. }
  4209. }
  4210. foreach ($bundle['pos'] ?? [] as $po) {
  4211. if (!is_array($po)) {
  4212. continue;
  4213. }
  4214. $gid = (int)($po['scydgy_id'] ?? 0);
  4215. if ($this->isValidScydgyRowId($gid)) {
  4216. $nm = trim((string)($po['CGYMC'] ?? ''));
  4217. if ($nm !== '') {
  4218. $gymcMap[$gid] = $nm;
  4219. }
  4220. $dh = trim((string)($po['CCYDH'] ?? ''));
  4221. if ($dh !== '' && empty($ccydhBySid[$gid])) {
  4222. $ccydhBySid[$gid] = $dh;
  4223. }
  4224. }
  4225. }
  4226. try {
  4227. $details = Db::table('purchase_order_detail')
  4228. ->where('scydgy_id', 'in', array_keys($sids))
  4229. ->order('company_name', 'asc')
  4230. ->order('id', 'asc')
  4231. ->select();
  4232. } catch (\Throwable $e) {
  4233. try {
  4234. $details = Db::table('purchase_order_detail')
  4235. ->where('scydgy_id', 'in', array_keys($sids))
  4236. ->order('company_name', 'asc')
  4237. ->order('ID', 'asc')
  4238. ->select();
  4239. } catch (\Throwable $e2) {
  4240. $details = [];
  4241. }
  4242. }
  4243. if (!is_array($details)) {
  4244. $details = [];
  4245. }
  4246. $byCompany = [];
  4247. foreach ($details as $d) {
  4248. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  4249. continue;
  4250. }
  4251. $cn = trim((string)($d['company_name'] ?? ''));
  4252. if ($cn === '') {
  4253. continue;
  4254. }
  4255. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  4256. $sid = (int)($d['scydgy_id'] ?? 0);
  4257. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  4258. continue;
  4259. }
  4260. if (!isset($byCompany[$cn])) {
  4261. $ph = trim((string)($d['phone'] ?? ''));
  4262. $username = trim((string)($d['username'] ?? ''));
  4263. if ($username === '') {
  4264. $username = $this->resolveCustomerContactName($ph, $cn);
  4265. }
  4266. $byCompany[$cn] = [
  4267. 'name' => $cn,
  4268. 'email' => trim((string)($d['email'] ?? '')),
  4269. 'phone' => $ph,
  4270. 'username' => $username,
  4271. 'remark' => '',
  4272. 'pick_lines' => [],
  4273. 'detail_picks' => [],
  4274. ];
  4275. }
  4276. if ($byCompany[$cn]['remark'] === '') {
  4277. $rm = '';
  4278. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  4279. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  4280. $rm = trim((string)$d[$rk]);
  4281. break;
  4282. }
  4283. }
  4284. if ($rm !== '') {
  4285. $byCompany[$cn]['remark'] = $rm;
  4286. }
  4287. }
  4288. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  4289. $ccydhLine = trim((string)($ccydhBySid[$sid] ?? ''));
  4290. $processName = $this->buildSupplierProcessNameFields($ccydhLine, $gymc);
  4291. $am = trim((string)($d['amount'] ?? ''));
  4292. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  4293. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  4294. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  4295. if ($deliveryShow === '' && $deliveryRaw !== '') {
  4296. $deliveryShow = $deliveryRaw;
  4297. }
  4298. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  4299. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  4300. $subtotal = null;
  4301. if ($amountNum !== null) {
  4302. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  4303. }
  4304. $unitPriceText = $amountFilled
  4305. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  4306. : '未填写';
  4307. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  4308. $leadFilled = ($leadDays !== null);
  4309. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  4310. $pickLine = array_merge($processName, [
  4311. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  4312. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  4313. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  4314. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  4315. 'order_delivery_deadline' => $orderDeadlineMap[$ccydhLine] ?? '',
  4316. 'amount_filled' => $amountFilled,
  4317. 'delivery_filled' => $deliveryFilled,
  4318. 'unit_price_text' => $unitPriceText,
  4319. 'lead_days' => $leadFilled ? $leadDays : '',
  4320. 'lead_days_filled' => $leadFilled,
  4321. 'lead_days_show' => $leadText,
  4322. 'lead_days_text' => $leadText,
  4323. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  4324. 'subtotal_num' => $subtotal,
  4325. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  4326. 'is_quoted' => $amountFilled,
  4327. ]);
  4328. if (!$quoteVisible) {
  4329. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  4330. }
  4331. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  4332. $byCompany[$cn]['detail_picks'][$sid] = [
  4333. 'scydgy_id' => $sid,
  4334. 'detail_id' => $detailId,
  4335. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  4336. 'cgymc' => $processName['cgymc'],
  4337. 'ccydh' => $processName['ccydh'],
  4338. ];
  4339. }
  4340. $out = [];
  4341. foreach ($byCompany as $g) {
  4342. $pickLinesMap = $g['pick_lines'] ?? [];
  4343. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  4344. continue;
  4345. }
  4346. $pickLines = [];
  4347. $usedLineSids = [];
  4348. foreach ($orderedSids as $sid) {
  4349. if (!isset($pickLinesMap[$sid])) {
  4350. continue;
  4351. }
  4352. $pickLines[] = $pickLinesMap[$sid];
  4353. $usedLineSids[$sid] = true;
  4354. }
  4355. foreach ($pickLinesMap as $sid => $ln) {
  4356. if (isset($usedLineSids[$sid])) {
  4357. continue;
  4358. }
  4359. $pickLines[] = $ln;
  4360. }
  4361. $groupTotal = 0.0;
  4362. $groupHasTotal = false;
  4363. if ($quoteVisible) {
  4364. foreach ($pickLines as $ln) {
  4365. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  4366. $groupTotal += (float)$ln['subtotal_num'];
  4367. $groupHasTotal = true;
  4368. }
  4369. }
  4370. }
  4371. $lineCount = count($pickLines);
  4372. $g['pick_lines'] = $pickLines;
  4373. $g['line_count'] = $lineCount;
  4374. $g['has_total'] = $lineCount > 0;
  4375. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  4376. $this->finalizeSupplierRemarkDisplay($g, $orderMbz, $quoteVisible);
  4377. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  4378. $detailPicks = [];
  4379. $usedPickSids = [];
  4380. foreach ($orderedSids as $sid) {
  4381. if (!isset($detailPicksMap[$sid])) {
  4382. continue;
  4383. }
  4384. $detailPicks[] = $detailPicksMap[$sid];
  4385. $usedPickSids[$sid] = true;
  4386. }
  4387. foreach ($detailPicksMap as $sid => $dp) {
  4388. if (isset($usedPickSids[$sid])) {
  4389. continue;
  4390. }
  4391. $detailPicks[] = $dp;
  4392. }
  4393. $g['detail_picks'] = $detailPicks;
  4394. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  4395. unset($g['detail_picks']);
  4396. $out[] = $g;
  4397. }
  4398. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  4399. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  4400. }
  4401. /**
  4402. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  4403. * @return array<int, int[]> scydgy_id => detail_id[]
  4404. */
  4405. protected function mapDetailIdsByScydgyId(array $details): array
  4406. {
  4407. $out = [];
  4408. foreach ($details as $d) {
  4409. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  4410. continue;
  4411. }
  4412. $sid = (int)($d['scydgy_id'] ?? 0);
  4413. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  4414. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  4415. continue;
  4416. }
  4417. if (!isset($out[$sid])) {
  4418. $out[$sid] = [];
  4419. }
  4420. $out[$sid][] = $pk;
  4421. }
  4422. foreach ($out as $sid => $ids) {
  4423. $out[$sid] = array_values(array_unique($ids));
  4424. }
  4425. return $out;
  4426. }
  4427. /**
  4428. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  4429. *
  4430. * @param array<string, mixed> $dbRow
  4431. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  4432. */
  4433. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  4434. {
  4435. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  4436. $r = [
  4437. 'ID' => $sid,
  4438. 'scydgy_id' => $sid,
  4439. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  4440. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  4441. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  4442. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  4443. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  4444. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  4445. 'CDW' => $dbRow['CDW'] ?? '',
  4446. 'czlyq' => $dbRow['czlyq'] ?? '',
  4447. 'NGZL' => $dbRow['NGZL'] ?? '',
  4448. 'CDF' => $dbRow['CDF'] ?? '',
  4449. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  4450. 'MBZ' => $dbRow['MBZ'] ?? '',
  4451. 'bwjg' => $dbRow['bwjg'] ?? '',
  4452. 'iStatus' => $dbRow['iStatus'] ?? '',
  4453. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  4454. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  4455. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  4456. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  4457. 'dStamp' => $dbRow['dStamp'] ?? '',
  4458. 'pick_time' => $dbRow['pick_time'] ?? '',
  4459. 'order_batch_no' => $this->resolveProcuremenOrderBatchNo($dbRow),
  4460. ];
  4461. $r['This_quantity'] = $this->resolveProcuremenThisQuantity($r);
  4462. $r['ceilingPrice'] = $this->resolveProcuremenCeilingPrice($r);
  4463. if ($sid > 0 && isset($dStampMap[$sid])) {
  4464. $t = trim((string)$dStampMap[$sid]);
  4465. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  4466. $r['dStamp'] = $dStampMap[$sid];
  4467. }
  4468. }
  4469. $dsOut = trim((string)($r['dStamp'] ?? ''));
  4470. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  4471. $ct = $dbRow['createtime'];
  4472. if (is_numeric($ct) && (int)$ct > 946684800) {
  4473. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  4474. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  4475. $r['dStamp'] = trim($ct);
  4476. }
  4477. }
  4478. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  4479. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  4480. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  4481. $fallback = trim((string)($r['dStamp'] ?? ''));
  4482. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  4483. $r['dputrecord'] = $fallback;
  4484. }
  4485. }
  4486. if (array_key_exists('id', $dbRow)) {
  4487. $r['purchase_order_id'] = (int)$dbRow['id'];
  4488. }
  4489. if ($sid < 0) {
  4490. $r['_is_manual'] = 1;
  4491. }
  4492. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  4493. $pickOut = trim((string)($r['pick_time'] ?? ''));
  4494. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  4495. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  4496. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  4497. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  4498. $r['pick_time'] = $pickFallback;
  4499. break;
  4500. }
  4501. }
  4502. }
  4503. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  4504. if ($pickNm !== '') {
  4505. $r['pick_company_name'] = $pickNm;
  4506. $r['picked_supplier_name'] = $pickNm;
  4507. }
  4508. $r['wflow_status'] = trim((string)($dbRow['wflow_status'] ?? ''));
  4509. $r['order_status_text'] = ProcuremenStatus::orderStatusLabelForList($r['wflow_status']);
  4510. if (array_key_exists('status', $dbRow)) {
  4511. $r['status'] = $dbRow['status'];
  4512. }
  4513. return $r;
  4514. }
  4515. /**
  4516. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  4517. *
  4518. * @return array<int, array<string, mixed>>
  4519. */
  4520. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  4521. {
  4522. $pool = [];
  4523. if (!is_array($dbRows) || $dbRows === []) {
  4524. return $pool;
  4525. }
  4526. $dStampMap = [];
  4527. $sidList = [];
  4528. foreach ($dbRows as $tmpRow) {
  4529. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  4530. $sid = (int)$tmpRow['scydgy_id'];
  4531. if ($sid > 0) {
  4532. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  4533. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  4534. $sidList[$sid] = true;
  4535. }
  4536. }
  4537. }
  4538. }
  4539. if ($sidList !== []) {
  4540. try {
  4541. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  4542. } catch (\Throwable $e) {
  4543. $dStampMap = [];
  4544. }
  4545. }
  4546. foreach ($dbRows as $dbRow) {
  4547. if (!is_array($dbRow)) {
  4548. continue;
  4549. }
  4550. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  4551. }
  4552. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  4553. $needCcydh = [];
  4554. foreach ($pool as $row) {
  4555. if (!is_array($row)) {
  4556. continue;
  4557. }
  4558. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  4559. continue;
  4560. }
  4561. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  4562. if ($ccydh !== '') {
  4563. $needCcydh[$ccydh] = true;
  4564. }
  4565. }
  4566. if ($needCcydh !== []) {
  4567. $czMap = [];
  4568. try {
  4569. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  4570. } catch (\Throwable $e) {
  4571. $czMap = [];
  4572. }
  4573. if (is_array($czMap) && $czMap !== []) {
  4574. foreach ($pool as &$row) {
  4575. if (!is_array($row)) {
  4576. continue;
  4577. }
  4578. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  4579. continue;
  4580. }
  4581. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  4582. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  4583. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  4584. }
  4585. }
  4586. unset($row);
  4587. }
  4588. }
  4589. return $pool;
  4590. }
  4591. /**
  4592. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  4593. *
  4594. * @param int[] $scydgyIds
  4595. * @return array<int, array<string, mixed>>
  4596. */
  4597. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  4598. {
  4599. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4600. if ($scydgyIds === []) {
  4601. return [];
  4602. }
  4603. try {
  4604. $list = Db::table('purchase_order_detail')
  4605. ->where('scydgy_id', 'in', $scydgyIds)
  4606. ->field('scydgy_id,company_name,amount,delivery')
  4607. ->select();
  4608. } catch (\Throwable $e) {
  4609. $list = [];
  4610. }
  4611. return is_array($list) ? $list : [];
  4612. }
  4613. /**
  4614. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  4615. *
  4616. * @param int[] $scydgyIds
  4617. * @param array<int, array<string, mixed>> $allRows
  4618. * @return array{cnt:int, amt:int, deliv:int}
  4619. */
  4620. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  4621. {
  4622. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4623. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4624. if ($scydgyIds === [] || $allRows === []) {
  4625. return $out;
  4626. }
  4627. $idSet = array_flip($scydgyIds);
  4628. $all = [];
  4629. $withAmt = [];
  4630. $withDeliv = [];
  4631. foreach ($allRows as $r) {
  4632. if (!is_array($r)) {
  4633. continue;
  4634. }
  4635. $sid = (int)($r['scydgy_id'] ?? 0);
  4636. if (!isset($idSet[$sid])) {
  4637. continue;
  4638. }
  4639. $cn = trim((string)($r['company_name'] ?? ''));
  4640. if ($cn === '') {
  4641. continue;
  4642. }
  4643. $all[$cn] = true;
  4644. $am = $r['amount'] ?? null;
  4645. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  4646. $withAmt[$cn] = true;
  4647. }
  4648. $dv = $r['delivery'] ?? null;
  4649. if ($dv !== null && trim((string)$dv) !== '') {
  4650. $withDeliv[$cn] = true;
  4651. }
  4652. }
  4653. return [
  4654. 'cnt' => count($all),
  4655. 'amt' => count($withAmt),
  4656. 'deliv' => count($withDeliv),
  4657. ];
  4658. }
  4659. /**
  4660. * 本次数量:优先 This_quantity,空则回退工作量 NGZL(与下发/确认/审批弹窗一致)
  4661. *
  4662. * @param array<string, mixed> $row
  4663. */
  4664. protected function resolveProcuremenThisQuantity(array $row): string
  4665. {
  4666. $q = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  4667. if ($q !== '') {
  4668. return $q;
  4669. }
  4670. $ngzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  4671. if (!is_scalar($ngzl)) {
  4672. return '';
  4673. }
  4674. $s = trim((string)$ngzl);
  4675. if ($s === '') {
  4676. return '';
  4677. }
  4678. if (is_numeric($s) && (float)$s === 0.0) {
  4679. return '';
  4680. }
  4681. return $s;
  4682. }
  4683. /**
  4684. * @param array<string, mixed> $row
  4685. */
  4686. protected function resolveProcuremenCeilingPrice(array $row): string
  4687. {
  4688. return trim((string)($row['ceilingPrice'] ?? $row['ceiling_price'] ?? ''));
  4689. }
  4690. /**
  4691. * 多工序数量/限价拼接:跳过空值,避免出现「、10」「304、」
  4692. *
  4693. * @param array<int, mixed> $parts
  4694. */
  4695. protected function joinProcuremenNonEmpty(array $parts, string $sep = '、'): string
  4696. {
  4697. $out = [];
  4698. foreach ($parts as $p) {
  4699. $s = trim((string)$p);
  4700. if ($s !== '') {
  4701. $out[] = $s;
  4702. }
  4703. }
  4704. return $out === [] ? '' : implode($sep, $out);
  4705. }
  4706. /**
  4707. * 确认/审批列表:合并行按各工序同步本次数量、最高限价(顿号间隔)
  4708. *
  4709. * @param array<int, array<string, mixed>> $rows
  4710. */
  4711. protected function syncCollapsedOrderQtyPriceForList(array &$rows): void
  4712. {
  4713. if ($rows === []) {
  4714. return;
  4715. }
  4716. $idList = [];
  4717. foreach ($rows as $rw) {
  4718. if (!is_array($rw)) {
  4719. continue;
  4720. }
  4721. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4722. foreach ($rw['_order_merge_rows'] as $mr) {
  4723. if (!is_array($mr)) {
  4724. continue;
  4725. }
  4726. $mid = (int)($mr['ID'] ?? 0);
  4727. if ($this->isValidScydgyRowId($mid)) {
  4728. $idList[$mid] = true;
  4729. }
  4730. }
  4731. }
  4732. $id = (int)($rw['ID'] ?? 0);
  4733. if ($this->isValidScydgyRowId($id)) {
  4734. $idList[$id] = true;
  4735. }
  4736. }
  4737. if ($idList === []) {
  4738. return;
  4739. }
  4740. try {
  4741. $list = Db::table('purchase_order')
  4742. ->where('scydgy_id', 'in', array_keys($idList))
  4743. ->field('scydgy_id,This_quantity,ceilingPrice,NGZL,pick_company_name')
  4744. ->select();
  4745. } catch (\Throwable $e) {
  4746. return;
  4747. }
  4748. if (!is_array($list)) {
  4749. return;
  4750. }
  4751. $byId = [];
  4752. foreach ($list as $dbRow) {
  4753. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4754. continue;
  4755. }
  4756. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4757. }
  4758. foreach ($rows as &$rw) {
  4759. if (!is_array($rw)) {
  4760. continue;
  4761. }
  4762. $mergeRows = [];
  4763. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4764. $mergeRows = $rw['_order_merge_rows'];
  4765. } else {
  4766. $mergeRows = [$rw];
  4767. }
  4768. $qtyList = [];
  4769. $priceList = [];
  4770. $picked = '';
  4771. foreach ($mergeRows as $mr) {
  4772. if (!is_array($mr)) {
  4773. continue;
  4774. }
  4775. $sid = (int)($mr['ID'] ?? 0);
  4776. $db = ($sid !== 0 && isset($byId[$sid])) ? $byId[$sid] : null;
  4777. $src = $mr;
  4778. if (is_array($db)) {
  4779. $qDb = trim((string)($db['This_quantity'] ?? $db['this_quantity'] ?? ''));
  4780. $pDb = trim((string)($db['ceilingPrice'] ?? $db['ceiling_price'] ?? ''));
  4781. $ngzlDb = $db['NGZL'] ?? $db['ngzl'] ?? null;
  4782. if ($qDb !== '') {
  4783. $src['This_quantity'] = $qDb;
  4784. }
  4785. if ($pDb !== '') {
  4786. $src['ceilingPrice'] = $pDb;
  4787. }
  4788. if ($ngzlDb !== null && trim((string)$ngzlDb) !== '') {
  4789. $src['NGZL'] = $ngzlDb;
  4790. }
  4791. if ($picked === '') {
  4792. $picked = trim((string)($db['pick_company_name'] ?? ''));
  4793. }
  4794. }
  4795. if ($picked === '') {
  4796. $picked = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  4797. }
  4798. $qtyList[] = $this->resolveProcuremenThisQuantity($src);
  4799. $priceList[] = $this->resolveProcuremenCeilingPrice($src);
  4800. }
  4801. $rw['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  4802. $rw['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  4803. if ($picked !== '') {
  4804. $rw['pick_company_name'] = $picked;
  4805. $rw['picked_supplier_name'] = $picked;
  4806. }
  4807. }
  4808. unset($rw);
  4809. }
  4810. /**
  4811. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  4812. *
  4813. * @param int[] $scydgyIds
  4814. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  4815. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  4816. */
  4817. protected function OrderDetailSummary(array $scydgyIds)
  4818. {
  4819. $out = [];
  4820. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4821. if ($scydgyIds === []) {
  4822. return $out;
  4823. }
  4824. $list = [];
  4825. try {
  4826. $list = Db::table('purchase_order_detail')
  4827. ->where('scydgy_id', 'in', $scydgyIds)
  4828. ->field('id,scydgy_id,amount,delivery')
  4829. ->select();
  4830. } catch (\Throwable $e) {
  4831. $list = [];
  4832. }
  4833. if (!is_array($list)) {
  4834. return $out;
  4835. }
  4836. foreach ($list as $r) {
  4837. if (!is_array($r)) {
  4838. continue;
  4839. }
  4840. $ids = (int)($r['scydgy_id'] ?? 0);
  4841. if (!$this->isValidScydgyRowId($ids)) {
  4842. continue;
  4843. }
  4844. if (!isset($out[$ids])) {
  4845. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4846. }
  4847. $out[$ids]['cnt']++;
  4848. $am = $r['amount'] ?? null;
  4849. if ($am !== null && $am !== '') {
  4850. if (!(is_string($am) && trim($am) === '')) {
  4851. $out[$ids]['amt']++;
  4852. }
  4853. }
  4854. $dv = $r['delivery'] ?? null;
  4855. if ($dv !== null && trim((string)$dv) !== '') {
  4856. $out[$ids]['deliv']++;
  4857. }
  4858. }
  4859. return $out;
  4860. }
  4861. /**
  4862. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  4863. *
  4864. * @return array
  4865. */
  4866. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  4867. {
  4868. $strContains = function ($haystack, $needle) {
  4869. if ($needle === '') {
  4870. return false;
  4871. }
  4872. $haystack = (string)$haystack;
  4873. if (function_exists('mb_stripos')) {
  4874. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  4875. }
  4876. return stripos($haystack, $needle) !== false;
  4877. };
  4878. $stripAlias = function ($f) {
  4879. return preg_replace('/^[ab]\./i', '', (string)$f);
  4880. };
  4881. $searchColNames = [];
  4882. foreach (explode(',', $this->searchFields) as $colRaw) {
  4883. $c = $stripAlias(trim($colRaw));
  4884. if ($c !== '') {
  4885. $searchColNames[] = $c;
  4886. }
  4887. }
  4888. // 等值条件先行(表头下拉),减少后续日期解析量
  4889. $eqFilters = [];
  4890. $otherFilters = [];
  4891. foreach ($filterArr as $fk => $fv) {
  4892. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  4893. continue;
  4894. }
  4895. if (is_array($fv)) {
  4896. continue;
  4897. }
  4898. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  4899. continue;
  4900. }
  4901. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  4902. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  4903. $field = $stripAlias($fk);
  4904. if ($sym === '=' || $sym === '') {
  4905. $eqFilters[$field] = trim((string)$fv);
  4906. } else {
  4907. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  4908. }
  4909. }
  4910. $ymTarget = '';
  4911. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  4912. $ymTarget = $ymM[1];
  4913. }
  4914. $filtered = [];
  4915. foreach ($pool as $r) {
  4916. if (!is_array($r)) {
  4917. continue;
  4918. }
  4919. foreach ($eqFilters as $field => $fv) {
  4920. if (trim((string)($r[$field] ?? '')) !== $fv) {
  4921. continue 2;
  4922. }
  4923. }
  4924. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  4925. // 初选池不应含手工单;若混入则直接剔除
  4926. if ($isManual) {
  4927. continue;
  4928. }
  4929. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  4930. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  4931. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  4932. continue;
  4933. }
  4934. if ($applyMonthRange) {
  4935. $mo = (int)$m[2];
  4936. if ($mo < 1 || $mo > 12) {
  4937. continue;
  4938. }
  4939. if ($ymTarget !== '') {
  4940. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4941. if ($ymRow !== $ymTarget) {
  4942. continue;
  4943. }
  4944. } else {
  4945. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4946. $rowMonthStart = $ymRow . '-01 00:00:00';
  4947. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  4948. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  4949. continue;
  4950. }
  4951. }
  4952. }
  4953. if ($search !== '') {
  4954. $hitSearch = false;
  4955. foreach ($searchColNames as $c) {
  4956. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  4957. if ($cell !== '' && $strContains($cell, $search)) {
  4958. $hitSearch = true;
  4959. break;
  4960. }
  4961. }
  4962. if (!$hitSearch) {
  4963. continue;
  4964. }
  4965. }
  4966. foreach ($otherFilters as $item) {
  4967. $fv = $item['fv'];
  4968. $sym = $item['sym'];
  4969. $field = $item['field'];
  4970. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  4971. $cellStr = trim((string)$cell);
  4972. switch ($sym) {
  4973. case '<>':
  4974. if ((string)$cell === (string)$fv) {
  4975. continue 3;
  4976. }
  4977. break;
  4978. case 'LIKE':
  4979. case 'NOT LIKE':
  4980. $needle = trim((string)$fv);
  4981. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  4982. if ($sym === 'LIKE' && !$hit) {
  4983. continue 3;
  4984. }
  4985. if ($sym === 'NOT LIKE' && $hit) {
  4986. continue 3;
  4987. }
  4988. break;
  4989. case 'BETWEEN':
  4990. case 'RANGE':
  4991. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  4992. if (count($parts) < 2) {
  4993. $parts = is_string($fv) ? explode(',', $fv) : [];
  4994. }
  4995. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  4996. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  4997. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  4998. continue 3;
  4999. }
  5000. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  5001. continue 3;
  5002. }
  5003. break;
  5004. case '>':
  5005. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  5006. continue 3;
  5007. }
  5008. break;
  5009. case '>=':
  5010. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  5011. continue 3;
  5012. }
  5013. break;
  5014. case '<':
  5015. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  5016. continue 3;
  5017. }
  5018. break;
  5019. case '<=':
  5020. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  5021. continue 3;
  5022. }
  5023. break;
  5024. default:
  5025. if ((string)$cell !== (string)$fv) {
  5026. continue 3;
  5027. }
  5028. break;
  5029. }
  5030. }
  5031. $filtered[] = $r;
  5032. }
  5033. return $filtered;
  5034. }
  5035. /**
  5036. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  5037. */
  5038. public function snapshotToProcure()
  5039. {
  5040. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5041. $this->error(__('Invalid parameters'));
  5042. }
  5043. $row = json_decode($this->request->post('row_json', ''), true);
  5044. if (!is_array($row)) {
  5045. $this->error(__('Invalid parameters'));
  5046. }
  5047. try {
  5048. $ids = $this->extractScydgyRowId($row);
  5049. if (!$this->isValidScydgyRowId($ids)) {
  5050. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  5051. }
  5052. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5053. $data = $this->normalizePurchaseOrderWritePayload([
  5054. 'scydgy_id' => $ids,
  5055. 'CCYDH' => $row['CCYDH'] ?? null,
  5056. 'CYJMC' => $row['CYJMC'] ?? null,
  5057. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  5058. 'CDXMC' => $row['CDXMC'] ?? null,
  5059. 'CGYBH' => $row['CGYBH'] ?? null,
  5060. 'CGYMC' => $row['CGYMC'] ?? null,
  5061. 'CDW' => $row['CDW'] ?? null,
  5062. 'czlyq' => $row['czlyq'] ?? null,
  5063. 'NGZL' => $row['NGZL'] ?? null,
  5064. 'CDF' => $row['CDF'] ?? null,
  5065. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  5066. 'MBZ' => $row['MBZ'] ?? null,
  5067. 'bwjg' => $row['bwjg'] ?? null,
  5068. 'iStatus' => $row['iStatus'] ?? null,
  5069. 'dStamp' => $row['dStamp'] ?? null,
  5070. 'dputrecord' => $row['dputrecord'] ?? null,
  5071. 'cywyxm' => $row['cywyxm'] ?? null,
  5072. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  5073. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  5074. ], $row);
  5075. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  5076. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  5077. $mbzSnap = trim((string)($data['MBZ'] ?? ''));
  5078. if (!$exists && $qtySnap === '' && $priceSnap === '' && $mbzSnap === '') {
  5079. $this->success('操作成功');
  5080. return;
  5081. }
  5082. if ($exists) {
  5083. $upd = $data;
  5084. unset($upd['scydgy_id'], $upd['status']);
  5085. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  5086. } else {
  5087. // 新增:不写 status(空/走库默认);仅写创建时间
  5088. $data['createtime'] = date('Y-m-d H:i:s');
  5089. Db::table('purchase_order')->insert($data);
  5090. }
  5091. } catch (\Throwable $e) {
  5092. $this->error($e->getMessage());
  5093. }
  5094. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  5095. $this->success('操作成功');
  5096. }
  5097. /**
  5098. * 未发列表
  5099. * 「完结」或「仅保存本次数量/最高限价/备注」:有则改、无则插
  5100. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  5101. */
  5102. public function completeDirectly()
  5103. {
  5104. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5105. $this->error(__('参数错误'));
  5106. }
  5107. if (!$this->procuremenCanComplete()) {
  5108. $this->error(__('You have no permission'));
  5109. }
  5110. $row = json_decode($this->request->post('row_json', ''), true);
  5111. if (!is_array($row)) {
  5112. $this->error(__('Invalid parameters'));
  5113. }
  5114. $finishRaw = $this->request->post('finish', '1');
  5115. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  5116. $poIdLog = null;
  5117. try {
  5118. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  5119. $ids = $this->extractScydgyRowId($row);
  5120. if (!$this->isValidScydgyRowId($ids)) {
  5121. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  5122. }
  5123. if ($asComplete) {
  5124. $this->assertPickRowCanComplete($ids, $row);
  5125. }
  5126. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5127. $data = $this->normalizePurchaseOrderWritePayload([
  5128. 'scydgy_id' => $ids,
  5129. 'CCYDH' => $row['CCYDH'] ?? null,
  5130. 'CYJMC' => $row['CYJMC'] ?? null,
  5131. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  5132. 'CDXMC' => $row['CDXMC'] ?? null,
  5133. 'CGYBH' => $row['CGYBH'] ?? null,
  5134. 'CGYMC' => $row['CGYMC'] ?? null,
  5135. 'CDW' => $row['CDW'] ?? null,
  5136. 'czlyq' => $row['czlyq'] ?? null,
  5137. 'NGZL' => $row['NGZL'] ?? null,
  5138. 'CDF' => $row['CDF'] ?? null,
  5139. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  5140. 'MBZ' => $row['MBZ'] ?? null,
  5141. 'bwjg' => $row['bwjg'] ?? null,
  5142. 'iStatus' => $row['iStatus'] ?? null,
  5143. 'dStamp' => $row['dStamp'] ?? null,
  5144. 'dputrecord' => $row['dputrecord'] ?? null,
  5145. 'cywyxm' => $row['cywyxm'] ?? null,
  5146. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  5147. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  5148. ], $row);
  5149. if ($asComplete) {
  5150. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  5151. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  5152. }
  5153. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  5154. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  5155. $mbzCd = trim((string)($data['MBZ'] ?? ''));
  5156. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '' && $mbzCd === '') {
  5157. $this->success('操作成功');
  5158. return;
  5159. }
  5160. if ($exists) {
  5161. $upd = $data;
  5162. unset($upd['scydgy_id']);
  5163. if (!$asComplete) {
  5164. unset($upd['status']);
  5165. }
  5166. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  5167. } else {
  5168. // 新增:不写 status;完结时 $data 已含 status=1
  5169. $data['createtime'] = date('Y-m-d H:i:s');
  5170. Db::table('purchase_order')->insert($data);
  5171. }
  5172. } catch (\Throwable $e) {
  5173. $this->error($e->getMessage());
  5174. }
  5175. try {
  5176. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5177. if (is_array($rpo)) {
  5178. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  5179. $poIdLog = $tid > 0 ? $tid : null;
  5180. }
  5181. } catch (\Throwable $e) {
  5182. $poIdLog = null;
  5183. }
  5184. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  5185. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  5186. if ($asComplete) {
  5187. $this->addOrderLog(
  5188. $ids,
  5189. 'mark_complete',
  5190. '点击「完结」,已标记为已完结',
  5191. $poIdLog
  5192. );
  5193. try {
  5194. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  5195. if ($pdfPublicPath === '') {
  5196. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  5197. }
  5198. } catch (\Throwable $e) {
  5199. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  5200. }
  5201. } else {
  5202. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  5203. $mbz = isset($data['MBZ']) ? trim((string)$data['MBZ']) : '';
  5204. $parts = [];
  5205. if ($q !== '') {
  5206. $parts[] = ($gymc !== '' ? ($gymc . '本次数量') : '本次数量') . '「' . $q . '」';
  5207. } elseif ($gymc !== '') {
  5208. // 仅改限价/备注时仍带工序名便于辨认
  5209. $parts[] = $gymc;
  5210. }
  5211. if ($p !== '') {
  5212. $parts[] = '最高限价「' . $p . '」';
  5213. }
  5214. if ($mbz !== '') {
  5215. $parts[] = '招标备注「' . $mbz . '」';
  5216. }
  5217. $detail = $parts !== [] ? implode(',', $parts) : '(未改数量/限价/招标备注)';
  5218. $this->addOrderLog(
  5219. $ids,
  5220. 'save_qty_price',
  5221. '保存本次数量、最高限价、招标备注:' . $detail,
  5222. $poIdLog
  5223. );
  5224. }
  5225. $this->pickHiddenScydgySetCache = null;
  5226. $this->success("操作成功");
  5227. }
  5228. /**
  5229. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价、备注(若表中有对应列)
  5230. *
  5231. * @param array<int, array> $rows 引用传递当前页行
  5232. */
  5233. protected function mergePurchaseOrder(array &$rows)
  5234. {
  5235. if ($rows === []) {
  5236. return;
  5237. }
  5238. $ids = [];
  5239. foreach ($rows as $rw) {
  5240. if (!is_array($rw)) {
  5241. continue;
  5242. }
  5243. $id = (int)($rw['ID'] ?? 0);
  5244. // 含手工新增负数 scydgy_id,避免限价/数量不同步
  5245. if ($this->isValidScydgyRowId($id)) {
  5246. $ids[$id] = true;
  5247. }
  5248. }
  5249. $idList = array_keys($ids);
  5250. if ($idList === []) {
  5251. return;
  5252. }
  5253. try {
  5254. $list = Db::table('purchase_order')
  5255. ->where('scydgy_id', 'in', $idList)
  5256. ->field('scydgy_id,This_quantity,ceilingPrice,MBZ')
  5257. ->select();
  5258. } catch (\Throwable $e) {
  5259. return;
  5260. }
  5261. if (!is_array($list)) {
  5262. return;
  5263. }
  5264. $byId = [];
  5265. foreach ($list as $dbRow) {
  5266. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  5267. continue;
  5268. }
  5269. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  5270. }
  5271. foreach ($rows as &$rw) {
  5272. if (!is_array($rw)) {
  5273. continue;
  5274. }
  5275. $sid = (int)($rw['ID'] ?? 0);
  5276. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  5277. continue;
  5278. }
  5279. $db = $byId[$sid];
  5280. // 有 purchase_order 记录时同步数量/限价/备注(含清空后的空串,避免刷新后又冒出来)
  5281. if (array_key_exists('This_quantity', $db)) {
  5282. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  5283. }
  5284. if (array_key_exists('ceilingPrice', $db)) {
  5285. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  5286. } elseif (array_key_exists('ceiling_price', $db)) {
  5287. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  5288. }
  5289. if (array_key_exists('MBZ', $db)) {
  5290. $poMbz = $db['MBZ'] === null ? '' : trim((string)$db['MBZ']);
  5291. if ($poMbz !== '') {
  5292. $rw['MBZ'] = $poMbz;
  5293. }
  5294. }
  5295. }
  5296. unset($rw);
  5297. }
  5298. /**
  5299. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  5300. */
  5301. public function purchaseConfirmPick()
  5302. {
  5303. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5304. $this->error(__('Invalid parameters'));
  5305. }
  5306. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  5307. $this->error(__('You have no permission'));
  5308. }
  5309. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  5310. if ($batchRaw !== '') {
  5311. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  5312. return;
  5313. }
  5314. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5315. $sid = (int)$scydgyId;
  5316. if (!$this->isValidScydgyRowId($sid)) {
  5317. $this->error('参数无效');
  5318. }
  5319. $parseIdList = function ($raw) {
  5320. if (is_array($raw)) {
  5321. $arr = $raw;
  5322. } else {
  5323. $decoded = json_decode((string)$raw, true);
  5324. $arr = is_array($decoded) ? $decoded : [];
  5325. }
  5326. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  5327. };
  5328. $selectedRaw = $this->request->post('selected_ids', null);
  5329. if ($selectedRaw === null || $selectedRaw === '') {
  5330. $legacy = (int)$this->request->post('selected_id', 0);
  5331. $selectedIds = $legacy > 0 ? [$legacy] : [];
  5332. } else {
  5333. $selectedIds = $parseIdList($selectedRaw);
  5334. }
  5335. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  5336. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  5337. try {
  5338. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  5339. } catch (\InvalidArgumentException $e) {
  5340. $this->error($e->getMessage());
  5341. } catch (\Throwable $e) {
  5342. $this->error($e->getMessage());
  5343. }
  5344. $this->pickHiddenScydgySetCache = null;
  5345. $this->success('操作成功', '', $result);
  5346. }
  5347. /**
  5348. * 整单采购确认(多道工序一次提交)
  5349. */
  5350. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  5351. {
  5352. $decoded = json_decode($batchRaw, true);
  5353. if (!is_array($decoded) || $decoded === []) {
  5354. $this->error('提交数据无效');
  5355. }
  5356. $picks = [];
  5357. foreach ($decoded as $item) {
  5358. if (!is_array($item)) {
  5359. continue;
  5360. }
  5361. $sid = (int)($item['scydgy_id'] ?? 0);
  5362. if (!$this->isValidScydgyRowId($sid)) {
  5363. continue;
  5364. }
  5365. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  5366. if (!is_array($sel)) {
  5367. $sel = [(int)$sel];
  5368. }
  5369. $unsel = $item['unselected_ids'] ?? [];
  5370. if (!is_array($unsel)) {
  5371. $unsel = json_decode((string)$unsel, true);
  5372. $unsel = is_array($unsel) ? $unsel : [];
  5373. }
  5374. $picks[] = [
  5375. 'scydgy_id' => $sid,
  5376. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  5377. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  5378. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  5379. ];
  5380. }
  5381. if ($picks === []) {
  5382. $this->error('提交数据无效');
  5383. }
  5384. Db::startTrans();
  5385. $results = [];
  5386. try {
  5387. foreach ($picks as $pick) {
  5388. $results[] = $this->runPurchaseConfirmPick(
  5389. (int)$pick['scydgy_id'],
  5390. $pick['selected_ids'],
  5391. $pick['unselected_ids'],
  5392. (int)$pick['purchase_order_id'],
  5393. false,
  5394. false
  5395. );
  5396. }
  5397. Db::commit();
  5398. } catch (\Throwable $e) {
  5399. Db::rollback();
  5400. $msg = $e->getMessage();
  5401. $this->error($msg !== '' ? $msg : '提交失败');
  5402. }
  5403. try {
  5404. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  5405. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  5406. } catch (\Throwable $e) {
  5407. Log::write('采购确认通知批量发送异常: ' . $e->getMessage(), 'error');
  5408. }
  5409. $this->pickHiddenScydgySetCache = null;
  5410. $this->success('操作成功', '', ['batch' => $results]);
  5411. }
  5412. /**
  5413. * @return array<string, mixed>
  5414. */
  5415. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  5416. {
  5417. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  5418. ProcuremenGuard::assertWflowPendingApproval($poRow);
  5419. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  5420. $scydgyId = (string)$sid;
  5421. if ($selectedIds === []) {
  5422. throw new \InvalidArgumentException('请至少勾选一条明细');
  5423. }
  5424. $inter = array_intersect($selectedIds, $unselectedIds);
  5425. if ($inter !== []) {
  5426. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  5427. }
  5428. $allIds = $this->purchaseOrderDetail($sid);
  5429. if ($allIds === []) {
  5430. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  5431. }
  5432. foreach ($selectedIds as $id) {
  5433. if (!in_array($id, $allIds, true)) {
  5434. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  5435. }
  5436. }
  5437. foreach ($unselectedIds as $id) {
  5438. if (!in_array($id, $allIds, true)) {
  5439. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  5440. }
  5441. }
  5442. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  5443. sort($union, SORT_NUMERIC);
  5444. $expect = $allIds;
  5445. sort($expect, SORT_NUMERIC);
  5446. if ($union !== $expect) {
  5447. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  5448. }
  5449. if ($manageTransaction) {
  5450. Db::startTrans();
  5451. }
  5452. try {
  5453. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  5454. $aff = 0;
  5455. try {
  5456. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  5457. } catch (\Throwable $e) {
  5458. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  5459. }
  5460. if ($aff < 1) {
  5461. throw new \Exception('更新选中状态失败');
  5462. }
  5463. $poPayload = [
  5464. // 审核通过后进入「待入库评分」;合格/不合格后才置已完结
  5465. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5466. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  5467. ];
  5468. if ($purchaseOrderId > 0) {
  5469. $poAff = (int)Db::table('purchase_order')
  5470. ->where('id', $purchaseOrderId)
  5471. ->where('scydgy_id', $sid)
  5472. ->update($poPayload);
  5473. if ($poAff < 1) {
  5474. throw new \Exception('主表订单不存在或与工序行不匹配');
  5475. }
  5476. } else {
  5477. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  5478. if ($poAff < 1) {
  5479. throw new \Exception('未找到');
  5480. }
  5481. }
  5482. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  5483. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  5484. if ($manageTransaction) {
  5485. Db::commit();
  5486. }
  5487. } catch (\Throwable $e) {
  5488. if ($manageTransaction) {
  5489. Db::rollback();
  5490. }
  5491. throw $e;
  5492. }
  5493. $poIdFinal = $purchaseOrderId;
  5494. if ($poIdFinal <= 0) {
  5495. try {
  5496. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  5497. if (is_array($rpo)) {
  5498. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  5499. }
  5500. } catch (\Throwable $e) {
  5501. $poIdFinal = 0;
  5502. }
  5503. }
  5504. $pickNames = [];
  5505. foreach ($selectedIds as $pid) {
  5506. $dr = $this->purchaseOrderDetai($sid, $pid);
  5507. $nm = trim((string)($dr['company_name'] ?? ''));
  5508. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  5509. }
  5510. $this->addOrderLog(
  5511. $sid,
  5512. 'purchase_confirm',
  5513. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  5514. $poIdFinal > 0 ? $poIdFinal : null
  5515. );
  5516. if ($sendNotifications) {
  5517. try {
  5518. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  5519. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  5520. 'scydgy_id' => $sid,
  5521. 'selected_ids' => $selectedIds,
  5522. 'unselected_ids' => $unselectedIds,
  5523. 'purchase_order_id' => $purchaseOrderId,
  5524. ]]);
  5525. } catch (\Throwable $e) {
  5526. Log::write('采购确认通知发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  5527. }
  5528. }
  5529. Log::write(sprintf(
  5530. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  5531. $scydgyId,
  5532. $purchaseOrderId,
  5533. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  5534. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  5535. ), 'notice');
  5536. $pdfPublicPath = '';
  5537. try {
  5538. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  5539. } catch (\Throwable $e) {
  5540. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  5541. }
  5542. return [
  5543. 'scydgy_id' => $scydgyId,
  5544. 'purchase_order_id' => $purchaseOrderId,
  5545. 'selected_ids' => $selectedIds,
  5546. 'unselected_ids' => $unselectedIds,
  5547. 'purchase_confirm_pdf' => $pdfPublicPath,
  5548. ];
  5549. }
  5550. /**
  5551. * 审批通过短信:按本次涉及的工序汇总 process_lines
  5552. *
  5553. * @param int[]|string[] $scydgyIds
  5554. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  5555. */
  5556. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  5557. {
  5558. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  5559. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  5560. if ($scydgyIds === []) {
  5561. return $empty;
  5562. }
  5563. $pos = [];
  5564. try {
  5565. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  5566. } catch (\Throwable $e) {
  5567. $rows = [];
  5568. }
  5569. if (is_array($rows)) {
  5570. foreach ($rows as $po) {
  5571. if (is_array($po)) {
  5572. $pos[] = $po;
  5573. }
  5574. }
  5575. }
  5576. if ($pos === []) {
  5577. return $empty;
  5578. }
  5579. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  5580. return [
  5581. 'ccydh' => $ccydh,
  5582. 'pos' => $pos,
  5583. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  5584. ];
  5585. }
  5586. /**
  5587. * 审批通过/未通过:短信 + 邮件(同一供应商只发一条;邮件含平台链接)
  5588. *
  5589. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  5590. * @param array<int, array<string, mixed>> $picks
  5591. */
  5592. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  5593. {
  5594. if ($picks === []) {
  5595. return;
  5596. }
  5597. $this->ensureConfirmResultEmailTemplates();
  5598. $fallbackDetailId = 0;
  5599. $winners = [];
  5600. $losers = [];
  5601. foreach ($picks as $pick) {
  5602. if (!is_array($pick)) {
  5603. continue;
  5604. }
  5605. $sid = (int)($pick['scydgy_id'] ?? 0);
  5606. if (!$this->isValidScydgyRowId($sid)) {
  5607. continue;
  5608. }
  5609. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  5610. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  5611. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  5612. $fallbackDetailId = (int)$selectedIds[0];
  5613. }
  5614. foreach ($selectedIds as $pid) {
  5615. $dr = $this->purchaseOrderDetai($sid, $pid);
  5616. if (!is_array($dr)) {
  5617. continue;
  5618. }
  5619. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  5620. }
  5621. foreach ($unselectedIds as $pid) {
  5622. $dr = $this->purchaseOrderDetai($sid, $pid);
  5623. if (!is_array($dr)) {
  5624. continue;
  5625. }
  5626. $key = $this->notifySupplierDedupeKey($dr);
  5627. if (!isset($winners[$key])) {
  5628. $losers[$key] = $dr;
  5629. }
  5630. }
  5631. }
  5632. if ($winners === [] && $losers === []) {
  5633. return;
  5634. }
  5635. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  5636. $poIdLog = 0;
  5637. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5638. if (isset($pos[0]) && is_array($pos[0])) {
  5639. $poIdLog = (int)($pos[0]['id'] ?? 0);
  5640. }
  5641. $sendSmsSafe = function ($phone, $content) {
  5642. $phone = trim((string)$phone);
  5643. if ($phone === '') {
  5644. return;
  5645. }
  5646. try {
  5647. $this->smsbao($phone, $content);
  5648. } catch (\Throwable $e) {
  5649. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  5650. }
  5651. };
  5652. $sendConfirmEmailSafe = function (array $dr, string $emailScene) use ($confirmNotifyVars, $poIdLog) {
  5653. $cname = trim((string)($dr['company_name'] ?? ''));
  5654. $ph = trim((string)($dr['phone'] ?? ''));
  5655. $toEmail = trim((string)($dr['email'] ?? ''));
  5656. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5657. Log::write('采购确认邮件跳过:无有效邮箱 company=' . $cname, 'error');
  5658. return;
  5659. }
  5660. $detailId = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5661. if ($detailId <= 0) {
  5662. $detailId = (int)($confirmNotifyVars['_fallback_detail_id'] ?? 0);
  5663. }
  5664. try {
  5665. $platformUrl = $this->buildMprocMobileOrderUrl($detailId);
  5666. } catch (\Throwable $e) {
  5667. Log::write('采购确认邮件链接失败: ' . $e->getMessage(), 'error');
  5668. $platformUrl = '';
  5669. }
  5670. $vars = array_merge($confirmNotifyVars, [
  5671. 'company_name' => $cname,
  5672. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5673. 'phone' => $ph,
  5674. 'email' => $toEmail,
  5675. 'platform_url' => $platformUrl,
  5676. ]);
  5677. unset($vars['_fallback_detail_id']);
  5678. try {
  5679. $mailPlain = $this->renderNotifyTemplate($emailScene, $vars);
  5680. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  5681. $mailSubject = $this->resolveProcuremenEmailSubject($emailScene);
  5682. $mailConfig = $this->loadMailerConfig();
  5683. $this->issueSendSupplierEmail([
  5684. 'company_name' => $cname,
  5685. 'email' => $toEmail,
  5686. 'mail_plain' => $mailPlain,
  5687. 'mail_body' => $mailBody,
  5688. 'notify_vars' => $vars,
  5689. 'sms_content' => '',
  5690. 'detail_links' => $platformUrl !== '' ? [['url' => $platformUrl, 'cgymc' => '']] : [],
  5691. 'email_log_scene' => (strpos((string)$emailScene, 'confirm_ok') !== false) ? 'confirm_ok' : 'confirm_fail',
  5692. 'email_log_scydgy_id' => (int)($dr['scydgy_id'] ?? 0),
  5693. 'email_log_purchase_order_id' => $poIdLog,
  5694. ], $mailConfig, $mailSubject);
  5695. } catch (\Throwable $e) {
  5696. Log::write('采购确认邮件失败 company=' . $cname . ' email=' . $toEmail . ' ' . $e->getMessage(), 'error');
  5697. }
  5698. };
  5699. $confirmNotifyVars['_fallback_detail_id'] = $fallbackDetailId;
  5700. foreach ($winners as $dr) {
  5701. $cname = trim((string)($dr['company_name'] ?? ''));
  5702. $ph = trim((string)($dr['phone'] ?? ''));
  5703. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  5704. 'company_name' => $cname,
  5705. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5706. 'phone' => $ph,
  5707. ]));
  5708. $sendSmsSafe($ph, $sms);
  5709. $sendConfirmEmailSafe($dr, 'confirm_ok_email');
  5710. }
  5711. foreach ($losers as $dr) {
  5712. $cname = trim((string)($dr['company_name'] ?? ''));
  5713. $ph = trim((string)($dr['phone'] ?? ''));
  5714. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  5715. 'company_name' => $cname,
  5716. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5717. 'phone' => $ph,
  5718. ]));
  5719. $sendSmsSafe($ph, $sms);
  5720. $sendConfirmEmailSafe($dr, 'confirm_fail_email');
  5721. }
  5722. }
  5723. /**
  5724. * 短信去重键:优先手机号,否则公司名
  5725. */
  5726. protected function notifySupplierDedupeKey(array $detailRow): string
  5727. {
  5728. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  5729. if ($ph !== '') {
  5730. return 'p:' . $ph;
  5731. }
  5732. $cn = trim((string)($detailRow['company_name'] ?? ''));
  5733. return 'c:' . $cn;
  5734. }
  5735. /**
  5736. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  5737. *
  5738. * @param int[] $detailIds
  5739. */
  5740. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  5741. {
  5742. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  5743. if ($detailIds === []) {
  5744. return;
  5745. }
  5746. $payload = ['status_name' => $statusName];
  5747. try {
  5748. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  5749. } catch (\Throwable $e) {
  5750. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  5751. }
  5752. }
  5753. /**
  5754. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  5755. */
  5756. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  5757. {
  5758. try {
  5759. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  5760. } catch (\Throwable $e) {
  5761. return;
  5762. }
  5763. if (!is_array($rows)) {
  5764. return;
  5765. }
  5766. foreach ($rows as $dr) {
  5767. if (!is_array($dr)) {
  5768. continue;
  5769. }
  5770. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5771. if ($id <= 0) {
  5772. continue;
  5773. }
  5774. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  5775. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  5776. try {
  5777. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  5778. } catch (\Throwable $e) {
  5779. }
  5780. }
  5781. }
  5782. /**
  5783. * @param array<string, mixed> $detailRow
  5784. */
  5785. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  5786. {
  5787. $am = $detailRow['amount'] ?? null;
  5788. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  5789. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  5790. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  5791. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  5792. }
  5793. /**
  5794. * @return int[]
  5795. */
  5796. protected function purchaseOrderDetail(int $scydgyId): array
  5797. {
  5798. if (!$this->isValidScydgyRowId($scydgyId)) {
  5799. return [];
  5800. }
  5801. try {
  5802. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  5803. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  5804. $list = $listQuery->select();
  5805. } catch (\Throwable $e) {
  5806. return [];
  5807. }
  5808. if (!is_array($list)) {
  5809. return [];
  5810. }
  5811. $ids = [];
  5812. foreach ($list as $r) {
  5813. if (!is_array($r)) {
  5814. continue;
  5815. }
  5816. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  5817. if ($pk > 0) {
  5818. $ids[] = $pk;
  5819. }
  5820. }
  5821. return array_values(array_unique($ids));
  5822. }
  5823. /**
  5824. * 获取当前登录用户信息 [id, 展示名]
  5825. * admin_name 一律记「名称」(昵称),无昵称再回退账号
  5826. */
  5827. protected function GetUseName(): array
  5828. {
  5829. $id = 0;
  5830. $name = '';
  5831. try {
  5832. if ($this->auth && $this->auth->isLogin()) {
  5833. $u = $this->auth->getUserInfo();
  5834. if (is_array($u)) {
  5835. $id = (int)($u['id'] ?? 0);
  5836. $name = trim((string)($u['nickname'] ?? ''));
  5837. // 会话昵称缺失或等于登录账号时,再查库取正式昵称
  5838. $sessionUser = trim((string)($u['username'] ?? ''));
  5839. if ($id > 0 && ($name === '' || ($sessionUser !== '' && strcasecmp($name, $sessionUser) === 0))) {
  5840. try {
  5841. $row = Db::name('admin')->where('id', $id)->field('nickname,username')->find();
  5842. if (is_array($row)) {
  5843. $nick = trim((string)($row['nickname'] ?? ''));
  5844. if ($nick !== '') {
  5845. $name = $nick;
  5846. } elseif ($name === '') {
  5847. $name = trim((string)($row['username'] ?? ''));
  5848. }
  5849. }
  5850. } catch (\Throwable $e) {
  5851. }
  5852. }
  5853. if ($name === '') {
  5854. $name = $sessionUser;
  5855. }
  5856. }
  5857. }
  5858. } catch (\Throwable $e) {
  5859. }
  5860. if ($name === '') {
  5861. $name = '未知用户';
  5862. }
  5863. return [$id, $name];
  5864. }
  5865. /**
  5866. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  5867. */
  5868. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  5869. {
  5870. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  5871. }
  5872. /**
  5873. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  5874. *
  5875. * @param array<int, array<string, mixed>> $rows
  5876. */
  5877. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  5878. {
  5879. $sidList = [];
  5880. foreach ($rows as $rw) {
  5881. if (!is_array($rw)) {
  5882. continue;
  5883. }
  5884. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5885. foreach ($rw['_order_merge_rows'] as $mr) {
  5886. $mid = (int)($mr['ID'] ?? 0);
  5887. if ($this->isValidScydgyRowId($mid)) {
  5888. $sidList[$mid] = true;
  5889. }
  5890. }
  5891. }
  5892. $id = (int)($rw['ID'] ?? 0);
  5893. if ($this->isValidScydgyRowId($id)) {
  5894. $sidList[$id] = true;
  5895. }
  5896. }
  5897. $sids = array_keys($sidList);
  5898. $issueBySid = [];
  5899. $confirmBySid = [];
  5900. $approveBySid = [];
  5901. if ($sids !== []) {
  5902. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  5903. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  5904. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  5905. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  5906. try {
  5907. $logs = Db::table('purchase_order_oper_log')
  5908. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  5909. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  5910. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  5911. ->order('id', 'asc')
  5912. ->select();
  5913. } catch (\Throwable $e) {
  5914. $logs = [];
  5915. }
  5916. if (is_array($logs)) {
  5917. $issueSet = array_fill_keys($issueActs, true);
  5918. $confirmSet = array_fill_keys($confirmActs, true);
  5919. $approveSet = array_fill_keys($approveActs, true);
  5920. foreach ($logs as $lg) {
  5921. if (!is_array($lg)) {
  5922. continue;
  5923. }
  5924. $lg = ProcuremenOperLog::normalizeRow($lg);
  5925. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  5926. if ($sid === 0) {
  5927. continue;
  5928. }
  5929. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  5930. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  5931. if ($t === '') {
  5932. continue;
  5933. }
  5934. if (isset($issueSet[$action])) {
  5935. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  5936. $issueBySid[$sid] = $t;
  5937. }
  5938. }
  5939. if (isset($confirmSet[$action])) {
  5940. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  5941. $confirmBySid[$sid] = $t;
  5942. }
  5943. }
  5944. if (isset($approveSet[$action])) {
  5945. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  5946. $approveBySid[$sid] = $t;
  5947. }
  5948. }
  5949. }
  5950. }
  5951. }
  5952. foreach ($rows as &$rw) {
  5953. if (!is_array($rw)) {
  5954. continue;
  5955. }
  5956. $mergeSids = [];
  5957. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5958. foreach ($rw['_order_merge_rows'] as $mr) {
  5959. $mid = (int)($mr['ID'] ?? 0);
  5960. if ($this->isValidScydgyRowId($mid)) {
  5961. $mergeSids[] = $mid;
  5962. }
  5963. }
  5964. }
  5965. $rid = (int)($rw['ID'] ?? 0);
  5966. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  5967. $mergeSids[] = $rid;
  5968. }
  5969. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  5970. $issue = $pick;
  5971. $confirm = '';
  5972. $approve = '';
  5973. foreach ($mergeSids as $sid) {
  5974. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  5975. $issue = $issueBySid[$sid];
  5976. }
  5977. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  5978. $confirm = $confirmBySid[$sid];
  5979. }
  5980. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  5981. $approve = $approveBySid[$sid];
  5982. }
  5983. }
  5984. if ($issue === '' && $pick !== '') {
  5985. $issue = $pick;
  5986. }
  5987. $rw['issue_time'] = $issue;
  5988. $rw['confirm_time'] = $confirm;
  5989. $rw['approve_time'] = $approve;
  5990. }
  5991. unset($rw);
  5992. }
  5993. /**
  5994. * 按主键取一条
  5995. */
  5996. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  5997. {
  5998. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  5999. return [];
  6000. }
  6001. try {
  6002. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  6003. if (is_array($one)) {
  6004. return $one;
  6005. }
  6006. } catch (\Throwable $e) {
  6007. }
  6008. try {
  6009. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  6010. if (is_array($one)) {
  6011. return $one;
  6012. }
  6013. } catch (\Throwable $e) {
  6014. }
  6015. return [];
  6016. }
  6017. /**
  6018. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  6019. */
  6020. protected function formatProcuremenDetailTime($v): string
  6021. {
  6022. return ProcuremenFormat::detailTime($v);
  6023. }
  6024. /**
  6025. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  6026. */
  6027. protected function formatDeliveryYmd($v): string
  6028. {
  6029. return ProcuremenFormat::deliveryYmd($v);
  6030. }
  6031. /**
  6032. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  6033. */
  6034. protected function detailRowSupplierOperated(array $r): bool
  6035. {
  6036. $am = $r['amount'] ?? null;
  6037. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  6038. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  6039. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  6040. return $okAmt || $okDel;
  6041. }
  6042. /**
  6043. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  6044. */
  6045. protected function resolveDetailSupplierOperTime(array $r): string
  6046. {
  6047. if (!$this->detailRowSupplierOperated($r)) {
  6048. return '';
  6049. }
  6050. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  6051. if ($t !== '') {
  6052. return $t;
  6053. }
  6054. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  6055. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  6056. continue;
  6057. }
  6058. $t = $this->formatProcuremenDetailTime($r[$col]);
  6059. if ($t !== '') {
  6060. return $t;
  6061. }
  6062. }
  6063. return '';
  6064. }
  6065. /**
  6066. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  6067. */
  6068. protected function detailRowSupplierAccepted(array $r): bool
  6069. {
  6070. $am = $r['amount'] ?? null;
  6071. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  6072. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  6073. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  6074. return $okAmt && $okDel;
  6075. }
  6076. /**
  6077. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  6078. */
  6079. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  6080. {
  6081. if ($detailCount > 0) {
  6082. return true;
  6083. }
  6084. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  6085. return true;
  6086. }
  6087. $pickTime = trim((string)($main['pick_time'] ?? ''));
  6088. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  6089. return true;
  6090. }
  6091. return false;
  6092. }
  6093. /**
  6094. * 下发时间:优先 pick_time,其次首条下发明细时间
  6095. */
  6096. protected function resolveProcuremenIssueTime(array $main, array $details): string
  6097. {
  6098. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  6099. if ($issueTime !== '') {
  6100. return $issueTime;
  6101. }
  6102. foreach ($details as $dr) {
  6103. if (!is_array($dr)) {
  6104. continue;
  6105. }
  6106. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  6107. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  6108. $issueTime = $t;
  6109. }
  6110. }
  6111. if ($issueTime !== '') {
  6112. return $issueTime;
  6113. }
  6114. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  6115. }
  6116. /**
  6117. * 直接点「完结」时间:优先操作记录 mark_complete
  6118. */
  6119. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  6120. {
  6121. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  6122. }
  6123. /**
  6124. * 操作记录时间(取指定 action 最近一条)
  6125. *
  6126. * @param string|array<int, string> $actions
  6127. */
  6128. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  6129. {
  6130. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  6131. }
  6132. /**
  6133. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  6134. *
  6135. * @param array $main purchase_order 一行
  6136. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  6137. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  6138. */
  6139. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  6140. {
  6141. $issueCnt = count($details);
  6142. $acceptCnt = 0;
  6143. $pickedName = '';
  6144. $pickedTime = '';
  6145. foreach ($details as $dr) {
  6146. if (!is_array($dr)) {
  6147. continue;
  6148. }
  6149. if ($this->detailRowSupplierAccepted($dr)) {
  6150. $acceptCnt++;
  6151. }
  6152. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  6153. if ($pickedName === '') {
  6154. $pickedName = trim((string)($dr['company_name'] ?? ''));
  6155. }
  6156. if ($pickedTime === '') {
  6157. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  6158. if ($pickedTime === '') {
  6159. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  6160. }
  6161. }
  6162. }
  6163. }
  6164. $hasMain = $main !== [];
  6165. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  6166. if ($poTime === '') {
  6167. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  6168. }
  6169. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  6170. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  6171. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  6172. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  6173. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  6174. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  6175. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  6176. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  6177. $inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
  6178. $inboundResult = '';
  6179. if ($scydgyId > 0) {
  6180. try {
  6181. $inRow = Db::table('purchase_order_inbound_score')
  6182. ->where('scydgy_id', $scydgyId)
  6183. ->field('result,updatetime,createtime')
  6184. ->find();
  6185. } catch (\Throwable $e) {
  6186. $inRow = null;
  6187. }
  6188. if (is_array($inRow) && $inRow !== []) {
  6189. $inboundResult = trim((string)($inRow['result'] ?? ''));
  6190. if ($inboundScoreTime === '') {
  6191. $inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
  6192. }
  6193. }
  6194. }
  6195. $inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
  6196. $supplierTime = '';
  6197. if ($acceptCnt > 0) {
  6198. foreach ($details as $dr) {
  6199. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  6200. continue;
  6201. }
  6202. $t = $this->resolveDetailSupplierOperTime($dr);
  6203. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  6204. $supplierTime = $t;
  6205. }
  6206. }
  6207. }
  6208. $directComplete = ($mainCompleted && !$issued);
  6209. $doneTime = '';
  6210. if ($mainCompleted) {
  6211. if ($directComplete) {
  6212. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  6213. }
  6214. if ($doneTime === '' && $inboundScoreTime !== '') {
  6215. $doneTime = $inboundScoreTime;
  6216. }
  6217. if ($doneTime === '') {
  6218. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  6219. }
  6220. if ($doneTime === '') {
  6221. foreach ($details as $dr) {
  6222. if (!is_array($dr)) {
  6223. continue;
  6224. }
  6225. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  6226. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  6227. $doneTime = $t;
  6228. }
  6229. }
  6230. }
  6231. if ($doneTime === '') {
  6232. $doneTime = $poTime;
  6233. }
  6234. // 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
  6235. if ($doneTime === '' && $confirmApproveTime !== '') {
  6236. $doneTime = $confirmApproveTime;
  6237. }
  6238. }
  6239. if ($directComplete) {
  6240. // 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
  6241. $step1Done = $hasMain;
  6242. $step2Done = false;
  6243. $step3Done = false;
  6244. $step4Done = false;
  6245. $step5Done = false;
  6246. $stepInboundDone = $inboundScored;
  6247. $step6Done = $mainCompleted && $inboundScored;
  6248. } else {
  6249. $step1Done = $issued;
  6250. $step2Done = $issued;
  6251. $step3Done = $acceptCnt > 0;
  6252. $step4Done = $wflowPendingApproval;
  6253. if (!$step4Done) {
  6254. foreach ($details as $dr) {
  6255. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  6256. $step4Done = true;
  6257. break;
  6258. }
  6259. }
  6260. }
  6261. $step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
  6262. $stepInboundDone = $inboundScored;
  6263. // 未确认合格/不合格时,「已完结」保持未点亮(灰色)
  6264. $step6Done = $mainCompleted && $inboundScored;
  6265. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  6266. if ($mainCompleted && $issued) {
  6267. $step3Done = true;
  6268. $step4Done = true;
  6269. $step5Done = true;
  6270. // 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
  6271. if ($supplierTime === '') {
  6272. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6273. if ($fillT !== '') {
  6274. $supplierTime = $fillT;
  6275. }
  6276. }
  6277. if ($pickedTime === '') {
  6278. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6279. if ($fillT !== '') {
  6280. $pickedTime = $fillT;
  6281. }
  6282. }
  6283. if ($auditSelectTime === '') {
  6284. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6285. if ($fillT !== '') {
  6286. $auditSelectTime = $fillT;
  6287. }
  6288. }
  6289. if ($confirmApproveTime === '') {
  6290. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6291. if ($fillT !== '') {
  6292. $confirmApproveTime = $fillT;
  6293. }
  6294. }
  6295. }
  6296. }
  6297. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  6298. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  6299. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  6300. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  6301. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  6302. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  6303. $inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
  6304. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  6305. $deadlineLines = [];
  6306. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  6307. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  6308. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  6309. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  6310. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  6311. }
  6312. }
  6313. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  6314. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  6315. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  6316. if ($deliveryDisp === '') {
  6317. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  6318. }
  6319. if ($deliveryDisp !== '') {
  6320. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  6321. }
  6322. }
  6323. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  6324. $deadlineText = implode("\n", $deadlineLines);
  6325. $prefixOperTime = static function (string $t): string {
  6326. $t = trim($t);
  6327. if ($t === '' || $t === '—') {
  6328. return $t;
  6329. }
  6330. if (strpos($t, '操作时间') === 0) {
  6331. return $t;
  6332. }
  6333. return '操作时间:' . $t;
  6334. };
  6335. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  6336. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  6337. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
  6338. $stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  6339. $step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  6340. $steps = [
  6341. [
  6342. 'title' => '未发',
  6343. 'subtitle' => '',
  6344. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  6345. 'done' => $step1Done,
  6346. ],
  6347. [
  6348. 'title' => '下发',
  6349. 'subtitle' => $deadlineText,
  6350. 'time' => $prefixOperTime($step2Time),
  6351. 'done' => $step2Done,
  6352. ],
  6353. [
  6354. 'title' => '供应商接单',
  6355. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  6356. 'time' => '',
  6357. 'done' => $step3Done,
  6358. ],
  6359. [
  6360. 'title' => '待确认',
  6361. 'subtitle' => $step4Done
  6362. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  6363. : ($issued ? '待选供应商' : ''),
  6364. 'time' => $prefixOperTime($step4Time),
  6365. 'done' => $step4Done,
  6366. ],
  6367. [
  6368. 'title' => '待审批',
  6369. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  6370. 'time' => $prefixOperTime($step5Time),
  6371. 'done' => $step5Done,
  6372. ],
  6373. [
  6374. 'title' => '是否合格',
  6375. 'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
  6376. 'time' => $prefixOperTime($stepInboundTime),
  6377. 'done' => $stepInboundDone,
  6378. ],
  6379. [
  6380. 'title' => '已完结',
  6381. 'subtitle' => '',
  6382. 'time' => $prefixOperTime($step6Time),
  6383. 'done' => $step6Done,
  6384. ],
  6385. ];
  6386. $currentIdx = count($steps) - 1;
  6387. if ($directComplete) {
  6388. // 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
  6389. if (!$step6Done) {
  6390. foreach ($steps as $i => $s) {
  6391. if (($s['title'] ?? '') === '是否合格') {
  6392. $currentIdx = $i;
  6393. break;
  6394. }
  6395. }
  6396. }
  6397. } else {
  6398. foreach ($steps as $i => $s) {
  6399. if (!$s['done']) {
  6400. $currentIdx = $i;
  6401. break;
  6402. }
  6403. }
  6404. }
  6405. $nSteps = count($steps);
  6406. foreach ($steps as $idx => &$s) {
  6407. $s['current'] = ($idx === $currentIdx);
  6408. if ($idx === 0) {
  6409. $s['pdf_left_bg'] = '';
  6410. } else {
  6411. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  6412. }
  6413. if ($idx >= $nSteps - 1) {
  6414. $s['pdf_right_bg'] = '';
  6415. } else {
  6416. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  6417. }
  6418. }
  6419. unset($s);
  6420. $labelMap = [
  6421. 'CCYDH' => '订单号',
  6422. 'CYJMC' => '印件名称',
  6423. 'CCLBMMC' => '承揽部门',
  6424. 'CGYMC' => '工序名称',
  6425. 'CDW' => '单位',
  6426. 'czlyq' => '类型',
  6427. 'NGZL' => '工作量',
  6428. 'CDF' => '单价',
  6429. 'cGzzxMc' => '工作中心',
  6430. 'MBZ' => '招标备注',
  6431. 'This_quantity' => '本次数量',
  6432. 'ceilingPrice' => '最高限价',
  6433. ];
  6434. $orderSummary = [];
  6435. foreach ($labelMap as $key => $lab) {
  6436. if (!array_key_exists($key, $main)) {
  6437. continue;
  6438. }
  6439. $val = $main[$key];
  6440. if ($val === null) {
  6441. $val = '';
  6442. } elseif (!is_scalar($val)) {
  6443. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  6444. } else {
  6445. $val = (string)$val;
  6446. }
  6447. $orderSummary[] = ['label' => $lab, 'value' => $val];
  6448. }
  6449. $orderSummary[] = [
  6450. 'label' => '是否合格',
  6451. 'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
  6452. ];
  6453. $orderSummaryGrid = [];
  6454. $n = count($orderSummary);
  6455. for ($i = 0; $i < $n; $i += 2) {
  6456. $left = $orderSummary[$i];
  6457. $hasRight = ($i + 1) < $n;
  6458. $orderSummaryGrid[] = [
  6459. 'l1' => $left['label'],
  6460. 'v1' => $left['value'],
  6461. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  6462. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  6463. ];
  6464. }
  6465. return [
  6466. 'steps' => $steps,
  6467. 'orderSummary' => $orderSummary,
  6468. 'orderSummaryGrid' => $orderSummaryGrid,
  6469. 'inbound_result' => $inboundResult,
  6470. 'inbound_score_time'=> $inboundScoreTime,
  6471. 'detailRows' => $details,
  6472. ];
  6473. }
  6474. /**
  6475. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  6476. *
  6477. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  6478. */
  6479. protected function prepareProcuremenDetailsView(string $ids): array
  6480. {
  6481. $main = [];
  6482. try {
  6483. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  6484. $main = is_array($one) ? $one : [];
  6485. } catch (\Throwable $e) {
  6486. $main = [];
  6487. }
  6488. $details = [];
  6489. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  6490. if ($mergeRows === []) {
  6491. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  6492. if ($mergeRows === [] && $main !== []) {
  6493. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  6494. }
  6495. }
  6496. $detailSidList = [];
  6497. $anchorSid = (int)$ids;
  6498. if ($anchorSid !== 0) {
  6499. $detailSidList[$anchorSid] = true;
  6500. }
  6501. foreach ($mergeRows as $mr) {
  6502. if (!is_array($mr)) {
  6503. continue;
  6504. }
  6505. $sid = $this->extractScydgyRowId($mr);
  6506. if ($sid !== 0) {
  6507. $detailSidList[$sid] = true;
  6508. }
  6509. }
  6510. try {
  6511. if ($detailSidList !== []) {
  6512. $details = Db::table('purchase_order_detail')
  6513. ->where('scydgy_id', 'in', array_keys($detailSidList))
  6514. ->order('id', 'asc')
  6515. ->select();
  6516. }
  6517. } catch (\Throwable $e) {
  6518. $details = [];
  6519. }
  6520. if (!is_array($details)) {
  6521. $details = [];
  6522. }
  6523. foreach ($details as &$r) {
  6524. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  6525. $r['id'] = $r['ID'];
  6526. }
  6527. if (isset($r['createtime'])) {
  6528. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  6529. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  6530. } else {
  6531. $r['createtime_text'] = (string)$r['createtime'];
  6532. }
  6533. } else {
  6534. $r['createtime_text'] = '';
  6535. }
  6536. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  6537. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  6538. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  6539. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  6540. if (is_array($r)) {
  6541. $r = $this->maskSupplierContactFields($r);
  6542. }
  6543. }
  6544. unset($r);
  6545. $activeDetails = [];
  6546. foreach ($details as $r) {
  6547. if (is_array($r) && empty($r['is_void'])) {
  6548. $activeDetails[] = $r;
  6549. }
  6550. }
  6551. $operLogs = [];
  6552. try {
  6553. $operSidList = array_keys($detailSidList);
  6554. if ($operSidList === [] && (int)$ids !== 0) {
  6555. $operSidList = [(int)$ids];
  6556. }
  6557. if ($operSidList !== []) {
  6558. $operLogs = Db::table('purchase_order_oper_log')
  6559. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  6560. ->order('id', 'asc')
  6561. ->select();
  6562. }
  6563. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  6564. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  6565. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  6566. if ($poId > 0) {
  6567. $operLogs = Db::table('purchase_order_oper_log')
  6568. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  6569. ->order('id', 'asc')
  6570. ->select();
  6571. }
  6572. }
  6573. } catch (\Throwable $e) {
  6574. $operLogs = [];
  6575. }
  6576. if (!is_array($operLogs)) {
  6577. $operLogs = [];
  6578. }
  6579. $operLogsRaw = $operLogs;
  6580. $processNameBySid = [];
  6581. foreach ($mergeRows as $mr) {
  6582. if (!is_array($mr)) {
  6583. continue;
  6584. }
  6585. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  6586. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  6587. if ($psid !== 0 && $gymc !== '') {
  6588. $processNameBySid[$psid] = $gymc;
  6589. }
  6590. }
  6591. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  6592. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
  6593. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  6594. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  6595. if ($ccydh === '') {
  6596. foreach ($details as $r) {
  6597. if (!is_array($r)) {
  6598. continue;
  6599. }
  6600. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  6601. if ($ccydh !== '') {
  6602. break;
  6603. }
  6604. }
  6605. }
  6606. $this->view->assign('ccydh', $ccydh);
  6607. $this->view->assign('steps', $bundle['steps']);
  6608. $this->view->assign('orderSummary', $bundle['orderSummary']);
  6609. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  6610. $this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
  6611. $this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
  6612. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  6613. $this->view->assign('processCount', count($mergeRows));
  6614. $orderBatchNo = $this->resolveProcuremenOrderBatchNo($main);
  6615. if ($orderBatchNo === '' && $detailSidList !== []) {
  6616. try {
  6617. $poBn = Db::table('purchase_order')
  6618. ->where('scydgy_id', 'in', array_keys($detailSidList))
  6619. ->order('id', 'desc')
  6620. ->find();
  6621. if (is_array($poBn)) {
  6622. $orderBatchNo = $this->resolveProcuremenOrderBatchNo($poBn);
  6623. }
  6624. } catch (\Throwable $e) {
  6625. $orderBatchNo = '';
  6626. }
  6627. }
  6628. $this->view->assign('orderBatchNo', $orderBatchNo);
  6629. $this->view->assign('detailRows', $details);
  6630. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  6631. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  6632. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  6633. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  6634. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  6635. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  6636. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  6637. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  6638. $this->view->assign('operLogs', $operLogs);
  6639. $sg = $quoteView['supplier_groups'] ?? [];
  6640. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
  6641. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  6642. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
  6643. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
  6644. return [
  6645. 'ok' => $main !== [] || $details !== [],
  6646. 'ccydh' => $ccydh,
  6647. 'steps' => $bundle['steps'],
  6648. ];
  6649. }
  6650. /**
  6651. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  6652. */
  6653. public function details()
  6654. {
  6655. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6656. if (is_array($ids)) {
  6657. $ids = isset($ids[0]) ? $ids[0] : '';
  6658. }
  6659. $ids = trim((string)$ids);
  6660. if ($ids === '') {
  6661. $this->error(__('Invalid parameters'));
  6662. }
  6663. $this->assertManualOrderDetailsViewable((int)$ids);
  6664. // 已完结:打开详情时按最新进度/操作记录重存存证 PDF(含质量/交货评分)
  6665. $sid = (int)$ids;
  6666. if ($this->isValidScydgyRowId($sid)) {
  6667. try {
  6668. $poCheck = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  6669. if (is_array($poCheck) && ProcuremenStatus::isPoCompleted($poCheck['status'] ?? '')) {
  6670. $this->refreshCompletedOrderArchivePdf($sid, true);
  6671. }
  6672. } catch (\Throwable $e) {
  6673. Log::write('详情页刷新完结存证PDF失败 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'notice');
  6674. }
  6675. }
  6676. $this->prepareProcuremenDetailsView($ids);
  6677. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  6678. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  6679. $this->view->engine->layout(false);
  6680. try {
  6681. return $this->view->fetch('procuremen/details_dialog_shell');
  6682. } finally {
  6683. if ($restoreLayout) {
  6684. $this->view->engine->layout($restoreLayout);
  6685. }
  6686. }
  6687. }
  6688. /**
  6689. * 已完结订单重生成存证 PDF(与详情页一致,含质量/交货评分与「已完结」节点)
  6690. *
  6691. * @param bool $requireCompleted true 时仅已完结才重生成;false 强制按当前详情重存
  6692. * @return string 本地 web 路径或 OSS URL,失败为空串
  6693. */
  6694. protected function refreshCompletedOrderArchivePdf(int $scydgyId, bool $requireCompleted = true): string
  6695. {
  6696. if (!$this->isValidScydgyRowId($scydgyId)) {
  6697. return '';
  6698. }
  6699. try {
  6700. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6701. } catch (\Throwable $e) {
  6702. $po = null;
  6703. }
  6704. if (!is_array($po) || $po === []) {
  6705. return '';
  6706. }
  6707. if ($requireCompleted && !ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6708. return trim((string)($po['pdf_url'] ?? ''));
  6709. }
  6710. $poId = (int)($po['id'] ?? 0);
  6711. return $this->savePurchaseConfirmDetailPdf($scydgyId, $poId);
  6712. }
  6713. /**
  6714. * CLI / 手机端评分完结后调用:无后台登录态重生成存证 PDF
  6715. */
  6716. public static function regenerateArchivePdfWithoutAuth(int $scydgyId, bool $requireCompleted = true): string
  6717. {
  6718. if ((int)$scydgyId === 0) {
  6719. return '';
  6720. }
  6721. try {
  6722. $ctl = new class extends Procuremen {
  6723. public function _initialize()
  6724. {
  6725. $this->request = \think\Request::instance();
  6726. $tpl = \think\Config::get('template');
  6727. if (!is_array($tpl)) {
  6728. $tpl = [];
  6729. }
  6730. // CLI / 跨模块调用时无 admin 视图目录
  6731. $tpl['view_path'] = APP_PATH . 'admin' . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR;
  6732. $this->view = new \think\View($tpl, \think\Config::get('view_replace_str'));
  6733. $this->model = new \app\admin\model\Procuremen();
  6734. try {
  6735. ProcuremenSchema::ensureAll();
  6736. } catch (\Throwable $e) {
  6737. }
  6738. }
  6739. public function runRegen(int $sid, bool $requireCompleted): string
  6740. {
  6741. return $this->refreshCompletedOrderArchivePdf($sid, $requireCompleted);
  6742. }
  6743. };
  6744. return $ctl->runRegen($scydgyId, $requireCompleted);
  6745. } catch (\Throwable $e) {
  6746. Log::write('regenerateArchivePdfWithoutAuth 失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'error');
  6747. return '';
  6748. }
  6749. }
  6750. /**
  6751. * 解析合并下发工序行(可跨订单,且均未协助)
  6752. *
  6753. * @return array<int, array<string, mixed>>
  6754. */
  6755. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  6756. {
  6757. $primary = json_decode($rowJson, true);
  6758. if (!is_array($primary)) {
  6759. $this->error(__('Invalid parameters'));
  6760. }
  6761. $merge = json_decode($mergeRowsJson, true);
  6762. if (!is_array($merge) || $merge === []) {
  6763. $merge = [$primary];
  6764. }
  6765. $seen = [];
  6766. $out = [];
  6767. foreach ($merge as $r) {
  6768. if (!is_array($r)) {
  6769. continue;
  6770. }
  6771. $id = $this->extractScydgyRowId($r);
  6772. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  6773. continue;
  6774. }
  6775. $seen[$id] = true;
  6776. $out[] = $r;
  6777. }
  6778. if ($out === []) {
  6779. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  6780. }
  6781. // 允许多订单同批下发:不再校验订单号一致
  6782. $ids = [];
  6783. foreach ($out as $r) {
  6784. $id = $this->extractScydgyRowId($r);
  6785. if ($this->isValidScydgyRowId($id)) {
  6786. $ids[$id] = true;
  6787. }
  6788. }
  6789. $poBySid = [];
  6790. $detCntBySid = [];
  6791. if ($ids !== []) {
  6792. $idList = array_keys($ids);
  6793. try {
  6794. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  6795. if (is_array($poList)) {
  6796. foreach ($poList as $po) {
  6797. if (!is_array($po)) {
  6798. continue;
  6799. }
  6800. $sid = (int)($po['scydgy_id'] ?? 0);
  6801. if ($this->isValidScydgyRowId($sid)) {
  6802. $poBySid[$sid] = $po;
  6803. }
  6804. }
  6805. }
  6806. } catch (\Throwable $e) {
  6807. }
  6808. try {
  6809. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  6810. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  6811. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  6812. if (is_array($detRows)) {
  6813. foreach ($detRows as $dr) {
  6814. if (!is_array($dr)) {
  6815. continue;
  6816. }
  6817. $sid = (int)($dr['scydgy_id'] ?? 0);
  6818. if ($this->isValidScydgyRowId($sid)) {
  6819. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  6820. }
  6821. }
  6822. }
  6823. } catch (\Throwable $e) {
  6824. }
  6825. }
  6826. foreach ($out as $r) {
  6827. $id = $this->extractScydgyRowId($r);
  6828. if (!$this->isValidScydgyRowId($id)) {
  6829. continue;
  6830. }
  6831. $po = $poBySid[$id] ?? null;
  6832. if (!is_array($po)) {
  6833. continue;
  6834. }
  6835. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6836. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6837. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  6838. }
  6839. $detCnt = (int)($detCntBySid[$id] ?? 0);
  6840. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  6841. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6842. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  6843. }
  6844. }
  6845. return $out;
  6846. }
  6847. /**
  6848. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  6849. */
  6850. protected function maskSupplierContactFields(array $item): array
  6851. {
  6852. if (array_key_exists('email', $item)) {
  6853. $item['email'] = mask_email((string)$item['email']);
  6854. }
  6855. if (array_key_exists('phone', $item)) {
  6856. $item['phone'] = mask_phone((string)$item['phone']);
  6857. }
  6858. return $item;
  6859. }
  6860. /**
  6861. * @param array<int, array<string, mixed>> $list
  6862. * @return array<int, array<string, mixed>>
  6863. */
  6864. protected function maskSupplierContactList(array $list): array
  6865. {
  6866. $out = [];
  6867. foreach ($list as $item) {
  6868. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  6869. }
  6870. return $out;
  6871. }
  6872. /**
  6873. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  6874. *
  6875. * @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
  6876. * @return array<string, string>|null
  6877. */
  6878. protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
  6879. {
  6880. if (!is_array($row)) {
  6881. return null;
  6882. }
  6883. $norm = [];
  6884. foreach ($row as $k => $v) {
  6885. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  6886. }
  6887. $row = $norm;
  6888. $st = $row['status'] ?? '';
  6889. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  6890. return null;
  6891. }
  6892. $companyName = '';
  6893. foreach (['company_name', 'name'] as $nk) {
  6894. if (!empty($row[$nk])) {
  6895. $companyName = trim((string)$row[$nk]);
  6896. break;
  6897. }
  6898. }
  6899. if ($companyName === '') {
  6900. return null;
  6901. }
  6902. $username = '';
  6903. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  6904. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  6905. $username = trim((string)$row[$uk]);
  6906. break;
  6907. }
  6908. }
  6909. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  6910. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  6911. if ($phone === '' && isset($row['account'])) {
  6912. $phone = trim((string)$row['account']);
  6913. }
  6914. if ($phone === '' && isset($row['mobile'])) {
  6915. $phone = trim((string)$row['mobile']);
  6916. }
  6917. if ($requireContactChannels && $email === '' && $phone === '') {
  6918. return null;
  6919. }
  6920. $category = '';
  6921. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6922. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6923. $category = trim((string)$row[$ck]);
  6924. break;
  6925. }
  6926. }
  6927. return [
  6928. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  6929. 'name' => $companyName,
  6930. 'company_name' => $companyName,
  6931. 'username' => $username,
  6932. 'email' => $email,
  6933. 'phone' => $phone,
  6934. 'category' => $category,
  6935. 'company_type' => $category,
  6936. 'can_select' => ($email !== '' && $phone !== '') ? 1 : 0,
  6937. ];
  6938. }
  6939. /**
  6940. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  6941. */
  6942. protected function resolveCustomerContactById(string $id): ?array
  6943. {
  6944. $id = trim($id);
  6945. if ($id === '' || !ctype_digit($id)) {
  6946. return null;
  6947. }
  6948. try {
  6949. $row = Db::table('customer')->where('id', (int)$id)->find();
  6950. } catch (\Throwable $e) {
  6951. return null;
  6952. }
  6953. return $this->buildCustomerContactPayloadFromRow($row);
  6954. }
  6955. /**
  6956. * 按供应商名称解析联系信息(兼容旧提交数据)
  6957. *
  6958. * @param bool $requireContactChannels true 时须有邮箱或手机
  6959. */
  6960. protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
  6961. {
  6962. $name = trim($name);
  6963. if ($name === '') {
  6964. return null;
  6965. }
  6966. try {
  6967. // customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
  6968. $row = Db::table('customer')
  6969. ->where('company_name', $name)
  6970. ->order('id', 'desc')
  6971. ->find();
  6972. } catch (\Throwable $e) {
  6973. return null;
  6974. }
  6975. return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
  6976. }
  6977. /**
  6978. * 规范化下发/确认时勾选的供应商
  6979. *
  6980. * @param array<int, mixed> $companies
  6981. * @return array<int, array<string, string>>
  6982. */
  6983. protected function normalizePickCompanies(array $companies): array
  6984. {
  6985. $out = [];
  6986. foreach ($companies as $c) {
  6987. if (!is_array($c)) {
  6988. continue;
  6989. }
  6990. $resolved = null;
  6991. $cid = trim((string)($c['id'] ?? ''));
  6992. if ($cid !== '') {
  6993. $resolved = $this->resolveCustomerContactById($cid);
  6994. }
  6995. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  6996. if ($resolved === null && $name !== '') {
  6997. $resolved = $this->resolveCustomerContactByCompanyName($name);
  6998. }
  6999. if ($resolved === null) {
  7000. continue;
  7001. }
  7002. $email = trim((string)($resolved['email'] ?? ''));
  7003. $phone = trim((string)($resolved['phone'] ?? ''));
  7004. // 下发须同时有邮箱和手机号(与初选弹窗可选规则一致)
  7005. if ($email === '' || $phone === '') {
  7006. continue;
  7007. }
  7008. $out[] = $resolved;
  7009. }
  7010. return $out;
  7011. }
  7012. /**
  7013. * 同一次下发批次的时间(优先 pick_time,空则 createtime)
  7014. */
  7015. protected function procuremenIssueBatchTime(array $row): string
  7016. {
  7017. $t = $this->procuremenRowListSortTime($row, 'pick_time');
  7018. if ($t !== '') {
  7019. return $t;
  7020. }
  7021. $t = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  7022. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  7023. return $t;
  7024. }
  7025. return '';
  7026. }
  7027. /**
  7028. * 读取下发批次号(兼容旧字段 issue_batch_no)
  7029. *
  7030. * @param array<string, mixed> $row
  7031. */
  7032. protected function resolveProcuremenOrderBatchNo(array $row): string
  7033. {
  7034. foreach (['order_batch_no', 'issue_batch_no'] as $k) {
  7035. $v = trim((string)($row[$k] ?? ''));
  7036. if ($v !== '') {
  7037. return $v;
  7038. }
  7039. }
  7040. return '';
  7041. }
  7042. /**
  7043. * 从订单 bundle 取下发批次号
  7044. *
  7045. * @param array{order_batch_no?:mixed,pos?:array} $bundle
  7046. */
  7047. protected function resolveBundleOrderBatchNo(array $bundle): string
  7048. {
  7049. $direct = trim((string)($bundle['order_batch_no'] ?? ''));
  7050. if ($direct !== '') {
  7051. return $direct;
  7052. }
  7053. foreach ($bundle['pos'] ?? [] as $po) {
  7054. if (!is_array($po)) {
  7055. continue;
  7056. }
  7057. $bn = $this->resolveProcuremenOrderBatchNo($po);
  7058. if ($bn !== '') {
  7059. return $bn;
  7060. }
  7061. }
  7062. return '';
  7063. }
  7064. /**
  7065. * @param int[] $sidList
  7066. * @return array<int, string> scydgy_id => MBZ
  7067. */
  7068. protected function loadScydgyMbzByIds(array $sidList): array
  7069. {
  7070. $ids = [];
  7071. foreach ($sidList as $sid) {
  7072. $sid = (int)$sid;
  7073. if ($this->isValidScydgyRowId($sid)) {
  7074. $ids[$sid] = true;
  7075. }
  7076. }
  7077. if ($ids === []) {
  7078. return [];
  7079. }
  7080. try {
  7081. $map = Db::table('scydgy')->where('ID', 'in', array_keys($ids))->column('MBZ', 'ID');
  7082. } catch (\Throwable $e) {
  7083. return [];
  7084. }
  7085. return is_array($map) ? $map : [];
  7086. }
  7087. /**
  7088. * purchase_order / 列表行 MBZ 为空时,回退 ERP 工序表 scydgy.MBZ
  7089. *
  7090. * @param array<int, array<string, mixed>> $rows
  7091. */
  7092. protected function enrichProcuremenRowsMbz(array &$rows): void
  7093. {
  7094. if ($rows === []) {
  7095. return;
  7096. }
  7097. $need = [];
  7098. foreach ($rows as $r) {
  7099. if (!is_array($r)) {
  7100. continue;
  7101. }
  7102. if (trim((string)($r['MBZ'] ?? $r['mbz'] ?? '')) !== '') {
  7103. continue;
  7104. }
  7105. $sid = $this->extractScydgyRowId($r);
  7106. if ($this->isValidScydgyRowId($sid)) {
  7107. $need[$sid] = true;
  7108. }
  7109. }
  7110. if ($need === []) {
  7111. return;
  7112. }
  7113. $mbzMap = $this->loadScydgyMbzByIds(array_keys($need));
  7114. if ($mbzMap === []) {
  7115. return;
  7116. }
  7117. foreach ($rows as &$r) {
  7118. if (!is_array($r)) {
  7119. continue;
  7120. }
  7121. if (trim((string)($r['MBZ'] ?? $r['mbz'] ?? '')) !== '') {
  7122. continue;
  7123. }
  7124. $sid = $this->extractScydgyRowId($r);
  7125. if (!$this->isValidScydgyRowId($sid) || !isset($mbzMap[$sid])) {
  7126. continue;
  7127. }
  7128. $mbz = trim((string)$mbzMap[$sid]);
  7129. if ($mbz !== '') {
  7130. $r['MBZ'] = $mbz;
  7131. }
  7132. }
  7133. unset($r);
  7134. }
  7135. /**
  7136. * 列表/弹窗合并键:优先正式批次号 order_batch_no;
  7137. * 旧数据无批次号时回退为「同一订单号 + 同一次下发时间」。
  7138. */
  7139. protected function procuremenIssueBatchGroupKey(array $row): string
  7140. {
  7141. $batchNo = $this->resolveProcuremenOrderBatchNo($row);
  7142. if ($batchNo !== '') {
  7143. return 'bn:' . $batchNo;
  7144. }
  7145. $dh = trim((string)($row['CCYDH'] ?? ''));
  7146. $sid = (int)($row['scydgy_id'] ?? $row['ID'] ?? $row['id'] ?? 0);
  7147. if ($dh === '') {
  7148. return '_id_' . $sid;
  7149. }
  7150. $batch = $this->procuremenIssueBatchTime($row);
  7151. return $batch !== '' ? ($dh . '|' . $batch) : ($dh . '|sid:' . $sid);
  7152. }
  7153. /**
  7154. * 是否同一次下发(同批次号,或旧数据同订单号且下发时间一致)
  7155. */
  7156. protected function isSameProcuremenIssueBatch(array $anchor, array $po): bool
  7157. {
  7158. return $this->procuremenIssueBatchGroupKey($anchor) === $this->procuremenIssueBatchGroupKey($po);
  7159. }
  7160. /**
  7161. * @param array<int, mixed> $pos
  7162. * @return array<int, array<string, mixed>>
  7163. */
  7164. protected function filterPurchaseOrdersSameIssueBatch(array $pos, array $anchor): array
  7165. {
  7166. $out = [];
  7167. foreach ($pos as $po) {
  7168. if (is_array($po) && $this->isSameProcuremenIssueBatch($anchor, $po)) {
  7169. $out[] = $po;
  7170. }
  7171. }
  7172. return $out !== [] ? $out : [$anchor];
  7173. }
  7174. /**
  7175. * 确认供应商列表:同一订单号且同一次下发才合并为一行
  7176. *
  7177. * @param array<int, array<string, mixed>> $pool
  7178. * @return array<int, array<string, mixed>>
  7179. */
  7180. protected function collapseProcuremenPoolByOrder(array $pool): array
  7181. {
  7182. if ($pool === []) {
  7183. return [];
  7184. }
  7185. $groups = [];
  7186. foreach ($pool as $row) {
  7187. if (!is_array($row)) {
  7188. continue;
  7189. }
  7190. $key = $this->procuremenIssueBatchGroupKey($row);
  7191. if (!isset($groups[$key])) {
  7192. $groups[$key] = [];
  7193. }
  7194. $groups[$key][] = $row;
  7195. }
  7196. $out = [];
  7197. foreach ($groups as $ccydh => $rows) {
  7198. if ($rows === []) {
  7199. continue;
  7200. }
  7201. // 与确认/审批弹窗「本单工序」一致:按订单号 → 印件名称 → 工序名称 → 工序ID
  7202. usort($rows, function ($a, $b) {
  7203. $oa = trim((string)($a['CCYDH'] ?? ''));
  7204. $ob = trim((string)($b['CCYDH'] ?? ''));
  7205. if ($oa !== $ob) {
  7206. return strcmp($oa, $ob);
  7207. }
  7208. $na = trim((string)($a['CYJMC'] ?? ''));
  7209. $nb = trim((string)($b['CYJMC'] ?? ''));
  7210. if ($na !== $nb) {
  7211. return strcmp($na, $nb);
  7212. }
  7213. $ga = trim((string)($a['CGYMC'] ?? ''));
  7214. $gb = trim((string)($b['CGYMC'] ?? ''));
  7215. if ($ga !== $gb) {
  7216. return strcmp($ga, $gb);
  7217. }
  7218. $ida = (int)($a['ID'] ?? $a['scydgy_id'] ?? 0);
  7219. $idb = (int)($b['ID'] ?? $b['scydgy_id'] ?? 0);
  7220. return $ida <=> $idb;
  7221. });
  7222. $head = $rows[0];
  7223. $gymcList = [];
  7224. foreach ($rows as $r) {
  7225. $g = trim((string)($r['CGYMC'] ?? ''));
  7226. if ($g !== '' && !in_array($g, $gymcList, true)) {
  7227. $gymcList[] = $g;
  7228. }
  7229. }
  7230. $merged = $head;
  7231. $orderDhList = [];
  7232. $nameList = [];
  7233. foreach ($rows as $r) {
  7234. if (!is_array($r)) {
  7235. continue;
  7236. }
  7237. $odh = trim((string)($r['CCYDH'] ?? ''));
  7238. if ($odh !== '' && !in_array($odh, $orderDhList, true)) {
  7239. $orderDhList[] = $odh;
  7240. }
  7241. $onm = trim((string)($r['CYJMC'] ?? ''));
  7242. if ($onm !== '' && !in_array($onm, $nameList, true)) {
  7243. $nameList[] = $onm;
  7244. }
  7245. }
  7246. $orderDh = $orderDhList !== [] ? implode('、', $orderDhList) : trim((string)($head['CCYDH'] ?? ''));
  7247. $merged['CCYDH'] = $orderDh;
  7248. $merged['order_key'] = $orderDh;
  7249. if ($nameList !== []) {
  7250. $merged['CYJMC'] = implode('、', $nameList);
  7251. }
  7252. $merged['order_batch_no'] = $this->resolveProcuremenOrderBatchNo($head);
  7253. $merged['process_count'] = count($rows);
  7254. $merged['_order_merge_rows'] = $rows;
  7255. $qtyList = [];
  7256. $priceList = [];
  7257. foreach ($rows as $r) {
  7258. if (!is_array($r)) {
  7259. continue;
  7260. }
  7261. $qtyList[] = $this->resolveProcuremenThisQuantity($r);
  7262. $priceList[] = $this->resolveProcuremenCeilingPrice($r);
  7263. }
  7264. if (count($rows) > 1) {
  7265. $merged['CGYMC'] = implode('、', $gymcList);
  7266. // 多工序:数量/限价按有值项顿号间隔(空值不占位)
  7267. $merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  7268. $merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  7269. } else {
  7270. $merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
  7271. $merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
  7272. }
  7273. // 已选供应商:取合并行中首个非空 pick_company_name
  7274. $pickedName = '';
  7275. foreach ($rows as $r) {
  7276. if (!is_array($r)) {
  7277. continue;
  7278. }
  7279. $pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
  7280. if ($pn !== '') {
  7281. $pickedName = $pn;
  7282. break;
  7283. }
  7284. }
  7285. if ($pickedName !== '') {
  7286. $merged['pick_company_name'] = $pickedName;
  7287. $merged['picked_supplier_name'] = $pickedName;
  7288. }
  7289. $mergedPickTime = '';
  7290. foreach ($rows as $r) {
  7291. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  7292. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  7293. $mergedPickTime = $t;
  7294. }
  7295. }
  7296. if ($mergedPickTime !== '') {
  7297. $merged['pick_time'] = $mergedPickTime;
  7298. }
  7299. $out[] = $merged;
  7300. }
  7301. usort($out, function ($a, $b) {
  7302. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  7303. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  7304. if ($ta === $tb) {
  7305. $ida = (int)($a['purchase_order_id'] ?? 0);
  7306. $idb = (int)($b['purchase_order_id'] ?? 0);
  7307. if ($ida !== $idb) {
  7308. return $idb <=> $ida;
  7309. }
  7310. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  7311. }
  7312. if ($ta === '') {
  7313. return 1;
  7314. }
  7315. if ($tb === '') {
  7316. return -1;
  7317. }
  7318. return strcmp($tb, $ta);
  7319. });
  7320. return $out;
  7321. }
  7322. /**
  7323. * 待确认供应商:同一次下发批次的工序(优先 order_batch_no;旧数据回退同订单+同下发时间)
  7324. *
  7325. * @return array{ccydh:string, order_batch_no?:string, pos:array<int,array>, merge_rows:array<int,array>}
  7326. */
  7327. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  7328. {
  7329. $scydgyId = trim($scydgyId);
  7330. $empty = ['ccydh' => '', 'order_batch_no' => '', 'pos' => [], 'merge_rows' => []];
  7331. if ($scydgyId === '') {
  7332. return $empty;
  7333. }
  7334. try {
  7335. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7336. } catch (\Throwable $e) {
  7337. $anchor = null;
  7338. }
  7339. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  7340. return $empty;
  7341. }
  7342. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7343. $batchNo = $this->resolveProcuremenOrderBatchNo($anchor);
  7344. try {
  7345. if ($batchNo !== '') {
  7346. $pos = Db::table('purchase_order')
  7347. ->where('order_batch_no', $batchNo)
  7348. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())
  7349. ->order('scydgy_id', 'asc')
  7350. ->select();
  7351. } elseif ($ccydh !== '') {
  7352. $pos = Db::table('purchase_order')
  7353. ->where('CCYDH', $ccydh)
  7354. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())
  7355. ->order('scydgy_id', 'asc')
  7356. ->select();
  7357. } else {
  7358. $pos = [$anchor];
  7359. }
  7360. } catch (\Throwable $e) {
  7361. $pos = [$anchor];
  7362. }
  7363. if (!is_array($pos) || $pos === []) {
  7364. $pos = [$anchor];
  7365. }
  7366. $pos = $this->filterPurchaseOrdersSameIssueBatch($pos, $anchor);
  7367. return [
  7368. 'ccydh' => $ccydh,
  7369. 'order_batch_no' => $batchNo,
  7370. 'pos' => $pos,
  7371. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  7372. ];
  7373. }
  7374. /**
  7375. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  7376. */
  7377. protected function purchaseOrderRowInConfirmStage(array $po): bool
  7378. {
  7379. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  7380. return false;
  7381. }
  7382. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  7383. return false;
  7384. }
  7385. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  7386. return true;
  7387. }
  7388. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  7389. $sid = (int)($po['scydgy_id'] ?? 0);
  7390. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  7391. }
  7392. return false;
  7393. }
  7394. /**
  7395. * 采购确认:同一次下发批次的待审批工序(优先 order_batch_no)
  7396. *
  7397. * @return array{ccydh:string, order_batch_no?:string, pos:array<int,array>, merge_rows:array<int,array>}
  7398. */
  7399. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  7400. {
  7401. $scydgyId = trim($scydgyId);
  7402. $empty = ['ccydh' => '', 'order_batch_no' => '', 'pos' => [], 'merge_rows' => []];
  7403. if ($scydgyId === '') {
  7404. return $empty;
  7405. }
  7406. try {
  7407. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7408. } catch (\Throwable $e) {
  7409. $anchor = null;
  7410. }
  7411. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  7412. return $empty;
  7413. }
  7414. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7415. $batchNo = $this->resolveProcuremenOrderBatchNo($anchor);
  7416. try {
  7417. if ($batchNo !== '') {
  7418. $posQuery = Db::table('purchase_order')->where('order_batch_no', $batchNo);
  7419. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  7420. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  7421. } elseif ($ccydh !== '') {
  7422. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  7423. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  7424. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  7425. } else {
  7426. $pos = [$anchor];
  7427. }
  7428. } catch (\Throwable $e) {
  7429. $pos = [$anchor];
  7430. }
  7431. if (!is_array($pos) || $pos === []) {
  7432. $pos = [$anchor];
  7433. }
  7434. $pos = array_values(array_filter($pos, function ($po) {
  7435. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  7436. }));
  7437. if ($pos === []) {
  7438. $pos = [$anchor];
  7439. }
  7440. $pos = $this->filterPurchaseOrdersSameIssueBatch($pos, $anchor);
  7441. return [
  7442. 'ccydh' => $ccydh,
  7443. 'order_batch_no' => $batchNo,
  7444. 'pos' => $pos,
  7445. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  7446. ];
  7447. }
  7448. /**
  7449. * @param array<int, array<string, mixed>> $purchaseOrders
  7450. * @return array<int, array<string, mixed>>
  7451. */
  7452. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  7453. {
  7454. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  7455. $byId = [];
  7456. foreach ($pool as $r) {
  7457. if (!is_array($r)) {
  7458. continue;
  7459. }
  7460. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  7461. if ($this->isValidScydgyRowId($sid)) {
  7462. $byId[$sid] = $r;
  7463. }
  7464. }
  7465. $out = [];
  7466. foreach ($purchaseOrders as $po) {
  7467. if (!is_array($po)) {
  7468. continue;
  7469. }
  7470. $sid = (int)($po['scydgy_id'] ?? 0);
  7471. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  7472. $out[] = $byId[$sid];
  7473. }
  7474. }
  7475. $this->enrichProcuremenRowsMbz($out);
  7476. return $out;
  7477. }
  7478. /**
  7479. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  7480. *
  7481. * @return array<int, array<string, mixed>>
  7482. */
  7483. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  7484. {
  7485. $scydgyId = trim($scydgyId);
  7486. if ($scydgyId === '') {
  7487. return [];
  7488. }
  7489. try {
  7490. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7491. } catch (\Throwable $e) {
  7492. $anchor = null;
  7493. }
  7494. if (!is_array($anchor)) {
  7495. return [];
  7496. }
  7497. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  7498. return [];
  7499. }
  7500. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7501. $batchNo = $this->resolveProcuremenOrderBatchNo($anchor);
  7502. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  7503. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  7504. try {
  7505. $q = Db::table('purchase_order');
  7506. if ($batchNo !== '') {
  7507. $q->where('order_batch_no', $batchNo);
  7508. } elseif ($ccydh !== '' && $isValidPick) {
  7509. $q->where('CCYDH', $ccydh)->where('pick_time', $pickTime);
  7510. } else {
  7511. $q->where('scydgy_id', $scydgyId);
  7512. }
  7513. $pos = $q->order('scydgy_id', 'asc')->select();
  7514. } catch (\Throwable $e) {
  7515. $pos = [$anchor];
  7516. }
  7517. if (!is_array($pos) || $pos === []) {
  7518. $pos = [$anchor];
  7519. }
  7520. $pos = array_values(array_filter($pos, function ($po) {
  7521. if (!is_array($po)) {
  7522. return false;
  7523. }
  7524. $mr = $po['mod_rq'] ?? null;
  7525. if ($mr === null || $mr === '') {
  7526. return true;
  7527. }
  7528. $mrs = trim((string)$mr);
  7529. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  7530. }));
  7531. if ($pos === []) {
  7532. $pos = [$anchor];
  7533. }
  7534. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  7535. if ($rows === []) {
  7536. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  7537. }
  7538. return $rows;
  7539. }
  7540. /**
  7541. * 审核弹窗工序表展示行(与下发弹窗列一致;按订单号排序,同订单合并订单号/印件名称单元格)
  7542. *
  7543. * @param array<int, array<string, mixed>> $mergeRows
  7544. * @return array<int, array<string, mixed>>
  7545. */
  7546. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  7547. {
  7548. $list = [];
  7549. foreach ($mergeRows as $r) {
  7550. if (is_array($r)) {
  7551. $list[] = $r;
  7552. }
  7553. }
  7554. usort($list, function ($a, $b) {
  7555. $oa = trim((string)($a['CCYDH'] ?? ''));
  7556. $ob = trim((string)($b['CCYDH'] ?? ''));
  7557. if ($oa !== $ob) {
  7558. return strcmp($oa, $ob);
  7559. }
  7560. $na = trim((string)($a['CYJMC'] ?? ''));
  7561. $nb = trim((string)($b['CYJMC'] ?? ''));
  7562. if ($na !== $nb) {
  7563. return strcmp($na, $nb);
  7564. }
  7565. $ga = trim((string)($a['CGYMC'] ?? ''));
  7566. $gb = trim((string)($b['CGYMC'] ?? ''));
  7567. if ($ga !== $gb) {
  7568. return strcmp($ga, $gb);
  7569. }
  7570. $ida = $this->extractScydgyRowId($a);
  7571. $idb = $this->extractScydgyRowId($b);
  7572. return $ida <=> $idb;
  7573. });
  7574. $n = count($list);
  7575. // 连续同订单号+印件名称:合并单元格 rowspan
  7576. $groupSpan = array_fill(0, $n, 1);
  7577. $groupStart = array_fill(0, $n, true);
  7578. $i = 0;
  7579. while ($i < $n) {
  7580. $key = trim((string)($list[$i]['CCYDH'] ?? '')) . "\0" . trim((string)($list[$i]['CYJMC'] ?? ''));
  7581. $j = $i + 1;
  7582. while ($j < $n) {
  7583. $key2 = trim((string)($list[$j]['CCYDH'] ?? '')) . "\0" . trim((string)($list[$j]['CYJMC'] ?? ''));
  7584. if ($key === '' || $key2 !== $key) {
  7585. break;
  7586. }
  7587. $j++;
  7588. }
  7589. $span = $j - $i;
  7590. $groupSpan[$i] = $span;
  7591. for ($k = $i + 1; $k < $j; $k++) {
  7592. $groupStart[$k] = false;
  7593. $groupSpan[$k] = 1;
  7594. }
  7595. $i = $j;
  7596. }
  7597. $out = [];
  7598. foreach ($list as $idx => $r) {
  7599. $qty = $this->resolveProcuremenThisQuantity($r);
  7600. $price = $this->resolveProcuremenCeilingPrice($r);
  7601. $sid = $this->extractScydgyRowId($r);
  7602. $out[] = [
  7603. 'seq' => $idx + 1,
  7604. 'scydgy_id' => $sid,
  7605. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  7606. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  7607. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  7608. 'CDW' => trim((string)($r['CDW'] ?? '')),
  7609. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  7610. 'NGZL' => $r['NGZL'] ?? '',
  7611. 'This_quantity' => $qty,
  7612. 'ceilingPrice' => $price,
  7613. 'CDF' => trim((string)($r['CDF'] ?? '')),
  7614. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  7615. 'show_order_cells' => !empty($groupStart[$idx]),
  7616. 'order_rowspan' => (int)($groupSpan[$idx] ?? 1),
  7617. ];
  7618. }
  7619. return $out;
  7620. }
  7621. /**
  7622. * 解析金额/数量(去千分位等非数字字符)
  7623. */
  7624. protected function parseProcuremenMoneyNumber($value): ?float
  7625. {
  7626. return ProcuremenFormat::moneyNumber($value);
  7627. }
  7628. protected function formatProcuremenMoneyDisplay(?float $amount): string
  7629. {
  7630. return ProcuremenFormat::moneyDisplay($amount);
  7631. }
  7632. /**
  7633. * 列表/详情展示:工作量为 0 时显示空
  7634. */
  7635. protected function formatProcuremenWorkloadDisplay($value): string
  7636. {
  7637. return ProcuremenFormat::workloadDisplay($value);
  7638. }
  7639. /**
  7640. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  7641. */
  7642. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  7643. {
  7644. foreach ($details as $d) {
  7645. if (!is_array($d)) {
  7646. continue;
  7647. }
  7648. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  7649. $cn = trim((string)($d['company_name'] ?? ''));
  7650. if ($cn !== '') {
  7651. return $cn;
  7652. }
  7653. }
  7654. }
  7655. return trim((string)($main['pick_company_name'] ?? ''));
  7656. }
  7657. /**
  7658. * 详情报价小计:单价 × 本工序本次数量
  7659. */
  7660. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  7661. {
  7662. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  7663. if ($unit === null) {
  7664. return null;
  7665. }
  7666. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  7667. if ($qty === null || $qty <= 0) {
  7668. return null;
  7669. }
  7670. return $unit * $qty;
  7671. }
  7672. /**
  7673. * 详情页:工序小计 + 供应商分组报价与总计
  7674. *
  7675. * @param array<int, array<string, mixed>> $mergeRows
  7676. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  7677. * @return array{
  7678. * process_rows: array,
  7679. * supplier_groups: array,
  7680. * order_total_text: string,
  7681. * order_total_has: bool,
  7682. * selected_company: string
  7683. * }
  7684. */
  7685. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  7686. {
  7687. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  7688. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  7689. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
  7690. || ((int)($main['manual_pick'] ?? 0) === 1);
  7691. $orderMbz = trim((string)($main['MBZ'] ?? $main['mbz'] ?? ''));
  7692. if ($orderMbz === '') {
  7693. $orderMbz = $this->resolveBundleOrderMbz(['pos' => [$main], 'merge_rows' => $mergeRows]);
  7694. }
  7695. $qtyBySid = [];
  7696. $gymcBySid = [];
  7697. $ccydhBySid = [];
  7698. $orderedSids = [];
  7699. foreach ($mergeRows as $mr) {
  7700. if (!is_array($mr)) {
  7701. continue;
  7702. }
  7703. $sid = $this->extractScydgyRowId($mr);
  7704. if ($this->isValidScydgyRowId($sid)) {
  7705. $orderedSids[] = $sid;
  7706. }
  7707. $qty = trim((string)($mr['This_quantity'] ?? ''));
  7708. if ($qty === '') {
  7709. $qty = trim((string)($mr['NGZL'] ?? ''));
  7710. }
  7711. $qtyBySid[$sid] = $qty;
  7712. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  7713. $dh = trim((string)($mr['CCYDH'] ?? ''));
  7714. if ($dh !== '') {
  7715. $ccydhBySid[$sid] = $dh;
  7716. }
  7717. }
  7718. $mainCcydh = trim((string)($main['CCYDH'] ?? $ccydh));
  7719. if ($mainCcydh !== '') {
  7720. foreach ($orderedSids as $sid) {
  7721. if (empty($ccydhBySid[$sid])) {
  7722. $ccydhBySid[$sid] = $mainCcydh;
  7723. }
  7724. }
  7725. }
  7726. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  7727. $detailByCompanySid = [];
  7728. foreach ($details as $d) {
  7729. if (!is_array($d)) {
  7730. continue;
  7731. }
  7732. $cn = trim((string)($d['company_name'] ?? ''));
  7733. $sid = (int)($d['scydgy_id'] ?? 0);
  7734. if ($cn === '' || $sid === 0) {
  7735. continue;
  7736. }
  7737. if (!isset($detailByCompanySid[$cn])) {
  7738. $detailByCompanySid[$cn] = [];
  7739. }
  7740. $detailByCompanySid[$cn][$sid] = $d;
  7741. }
  7742. $supplierGroups = [];
  7743. foreach ($detailByCompanySid as $cn => $bySid) {
  7744. $lines = [];
  7745. $groupTotal = 0.0;
  7746. $groupHas = false;
  7747. $groupVoid = true;
  7748. $usedSids = [];
  7749. $appendLine = function (int $sid, array $d) use (
  7750. &$lines,
  7751. &$groupTotal,
  7752. &$groupHas,
  7753. &$groupVoid,
  7754. $qtyBySid,
  7755. $gymcBySid,
  7756. $ccydhBySid,
  7757. $quoteVisible
  7758. ) {
  7759. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  7760. if (!$isVoid) {
  7761. $groupVoid = false;
  7762. }
  7763. $qtyStr = $qtyBySid[$sid] ?? '';
  7764. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  7765. $am = trim((string)($d['amount'] ?? ''));
  7766. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  7767. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  7768. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  7769. $sub = null;
  7770. if (!$isVoid && $amountNum !== null) {
  7771. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  7772. }
  7773. $ct = $this->resolveDetailSupplierOperTime($d);
  7774. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  7775. $leadFilled = ($leadDays !== null);
  7776. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  7777. $processName = $this->buildSupplierProcessNameFields(
  7778. (string)($ccydhBySid[$sid] ?? ''),
  7779. (string)($gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')))
  7780. );
  7781. $line = array_merge($processName, [
  7782. 'amount' => $am,
  7783. 'unit_price_text' => $amountFilled
  7784. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  7785. : '未填写',
  7786. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  7787. 'delivery_ymd' => $deliveryYmd,
  7788. 'amount_filled' => $amountFilled,
  7789. 'delivery_filled' => $deliveryFilled,
  7790. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  7791. 'lead_days' => $leadFilled ? $leadDays : '',
  7792. 'lead_days_filled'=> $leadFilled,
  7793. 'lead_days_show' => $leadText,
  7794. 'lead_days_text' => $leadText,
  7795. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  7796. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  7797. 'is_void' => $isVoid,
  7798. 'oper_time_text' => $ct,
  7799. ]);
  7800. if (!$quoteVisible && !$isVoid) {
  7801. $this->maskSupplierQuoteLineBeforeDeadline($line);
  7802. } elseif ($sub !== null) {
  7803. $groupTotal += $sub;
  7804. $groupHas = true;
  7805. }
  7806. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  7807. };
  7808. foreach ($orderedSids as $sid) {
  7809. if (!isset($bySid[$sid])) {
  7810. continue;
  7811. }
  7812. $usedSids[$sid] = true;
  7813. $appendLine($sid, $bySid[$sid]);
  7814. }
  7815. foreach ($bySid as $sid => $d) {
  7816. if (isset($usedSids[$sid])) {
  7817. continue;
  7818. }
  7819. $appendLine((int)$sid, $d);
  7820. }
  7821. $firstDetail = null;
  7822. foreach ($bySid as $d) {
  7823. if (is_array($d)) {
  7824. $firstDetail = $d;
  7825. break;
  7826. }
  7827. }
  7828. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  7829. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  7830. if ($username === '' && $ph !== '') {
  7831. $username = $this->resolveCustomerContactName($ph, $cn);
  7832. }
  7833. $remark = '';
  7834. foreach ($bySid as $d) {
  7835. if (!is_array($d)) {
  7836. continue;
  7837. }
  7838. $rm = '';
  7839. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  7840. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  7841. $rm = trim((string)$d[$rk]);
  7842. break;
  7843. }
  7844. }
  7845. if ($rm !== '') {
  7846. $remark = $rm;
  7847. break;
  7848. }
  7849. }
  7850. $lineCount = count($lines);
  7851. $supplierGroup = [
  7852. 'company_name' => $cn,
  7853. 'username' => $username,
  7854. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  7855. 'phone' => $ph,
  7856. 'remark' => $remark,
  7857. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  7858. 'is_void' => $groupVoid,
  7859. 'lines' => $lines,
  7860. 'line_count' => $lineCount,
  7861. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  7862. 'has_total' => $lineCount > 0,
  7863. ];
  7864. $this->finalizeSupplierRemarkDisplay($supplierGroup, $orderMbz, $quoteVisible);
  7865. $supplierGroups[] = $supplierGroup;
  7866. }
  7867. usort($supplierGroups, function ($a, $b) {
  7868. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  7869. return ($a['is_void'] ?? false) ? 1 : -1;
  7870. }
  7871. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  7872. return ($a['is_selected'] ?? false) ? -1 : 1;
  7873. }
  7874. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  7875. });
  7876. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  7877. return [
  7878. 'process_rows' => $processRows,
  7879. 'supplier_groups' => $supplierGroups,
  7880. 'order_total_text' => '',
  7881. 'order_total_has' => false,
  7882. 'selected_company' => $selectedCompany,
  7883. ];
  7884. }
  7885. /**
  7886. * 短信用工序明细。
  7887. * 单订单:仅工序行(订单号/印件名称由模版 {ccydh}{cyjmc} 排版);
  7888. * 多订单同批:每个订单各自输出「订单号 + 印件名称 + 工序列表」,组间空行。
  7889. */
  7890. protected function buildProcessLinesPlain(array $mergeRows): string
  7891. {
  7892. $groups = [];
  7893. foreach ($mergeRows as $r) {
  7894. if (!is_array($r)) {
  7895. continue;
  7896. }
  7897. $dh = trim((string)($r['CCYDH'] ?? ''));
  7898. $key = $dh !== '' ? $dh : ('__sid_' . (int)($r['ID'] ?? $r['id'] ?? $r['scydgy_id'] ?? 0));
  7899. if (!isset($groups[$key])) {
  7900. $groups[$key] = [
  7901. 'ccydh' => $dh,
  7902. 'cyjmc' => trim((string)($r['CYJMC'] ?? '')),
  7903. 'rows' => [],
  7904. ];
  7905. } elseif ($groups[$key]['cyjmc'] === '') {
  7906. $groups[$key]['cyjmc'] = trim((string)($r['CYJMC'] ?? ''));
  7907. }
  7908. $groups[$key]['rows'][] = $r;
  7909. }
  7910. if ($groups === []) {
  7911. return '';
  7912. }
  7913. $multiOrder = count($groups) > 1;
  7914. $blocks = [];
  7915. foreach ($groups as $g) {
  7916. $lines = [];
  7917. if ($multiOrder) {
  7918. if ($g['ccydh'] !== '') {
  7919. $lines[] = '订单号:' . $g['ccydh'];
  7920. }
  7921. if ($g['cyjmc'] !== '') {
  7922. $lines[] = '印件名称:' . $g['cyjmc'];
  7923. }
  7924. }
  7925. foreach ($g['rows'] as $r) {
  7926. if (!is_array($r)) {
  7927. continue;
  7928. }
  7929. $gymc = trim((string)($r['CGYMC'] ?? ''));
  7930. if ($gymc === '') {
  7931. $gymc = '—';
  7932. }
  7933. $dw = trim((string)($r['CDW'] ?? ''));
  7934. // 下发通知展示「本次数量」(优先 This_quantity,空则回退 NGZL),与确认/审批弹窗一致
  7935. $qty = $this->resolveProcuremenThisQuantity($r);
  7936. $parts = ['工序名称:' . $gymc];
  7937. if ($dw !== '') {
  7938. $parts[] = '单位:' . $dw;
  7939. }
  7940. if ($qty !== '') {
  7941. $parts[] = '本次数量:' . $qty;
  7942. }
  7943. $lines[] = implode(' ', $parts);
  7944. }
  7945. if ($lines !== []) {
  7946. $blocks[] = implode("\n", $lines);
  7947. }
  7948. }
  7949. return implode("\n\n", $blocks);
  7950. }
  7951. /** 中文友好显示宽度(全角约 2,半角 1) */
  7952. protected function mbDisplayWidth(string $s): int
  7953. {
  7954. if ($s === '') {
  7955. return 0;
  7956. }
  7957. if (function_exists('mb_strwidth')) {
  7958. return (int)mb_strwidth($s, 'UTF-8');
  7959. }
  7960. if (function_exists('mb_strlen')) {
  7961. return (int)mb_strlen($s, 'UTF-8');
  7962. }
  7963. return strlen($s);
  7964. }
  7965. /** 按显示宽度右侧补空格,便于短信/邮件工序行对齐 */
  7966. protected function mbPadRight(string $s, int $width): string
  7967. {
  7968. $cur = $this->mbDisplayWidth($s);
  7969. if ($cur >= $width) {
  7970. return $s;
  7971. }
  7972. return $s . str_repeat(' ', $width - $cur);
  7973. }
  7974. /**
  7975. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  7976. *
  7977. * @return array<string, string>
  7978. */
  7979. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  7980. {
  7981. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  7982. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  7983. }
  7984. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  7985. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  7986. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7987. $cyjmc = '';
  7988. foreach ($mergeRows as $mr) {
  7989. if (!is_array($mr)) {
  7990. continue;
  7991. }
  7992. if ($ccydh === '') {
  7993. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  7994. }
  7995. if ($cyjmc === '') {
  7996. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  7997. }
  7998. }
  7999. if ($pos !== []) {
  8000. $firstPo = $pos[0];
  8001. if (is_array($firstPo)) {
  8002. if ($ccydh === '') {
  8003. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  8004. }
  8005. if ($cyjmc === '') {
  8006. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  8007. }
  8008. }
  8009. }
  8010. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  8011. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  8012. if (is_array($any)) {
  8013. if ($ccydh === '') {
  8014. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  8015. }
  8016. if ($cyjmc === '') {
  8017. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  8018. }
  8019. }
  8020. }
  8021. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  8022. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  8023. $cgymc = '';
  8024. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  8025. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  8026. }
  8027. return [
  8028. 'ccydh' => $ccydh,
  8029. 'cyjmc' => $cyjmc,
  8030. 'cgymc' => $cgymc,
  8031. 'process_lines' => $processLines,
  8032. 'process_lines_html' => '',
  8033. ];
  8034. }
  8035. /**
  8036. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  8037. * 多订单时 processPlain 已含各订单头,不再重复拼订单号/印件名称。
  8038. */
  8039. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  8040. {
  8041. $processPlain = trim($processPlain);
  8042. if ($processPlain !== '' && preg_match('/^订单号:/u', $processPlain)) {
  8043. return $processPlain;
  8044. }
  8045. $lines = [];
  8046. if ($ccydh !== '') {
  8047. $lines[] = '订单号:' . $ccydh;
  8048. }
  8049. if ($cyjmc !== '') {
  8050. $lines[] = '印件名称:' . $cyjmc;
  8051. }
  8052. if ($processPlain !== '') {
  8053. $lines[] = $processPlain;
  8054. }
  8055. return implode("\n", $lines);
  8056. }
  8057. /**
  8058. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  8059. *
  8060. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  8061. */
  8062. protected function buildPlatformLinksPlain(array $detailLinks): string
  8063. {
  8064. $lines = [];
  8065. $i = 1;
  8066. foreach ($detailLinks as $lk) {
  8067. if (!is_array($lk)) {
  8068. continue;
  8069. }
  8070. $url = trim((string)($lk['url'] ?? ''));
  8071. if ($url === '') {
  8072. continue;
  8073. }
  8074. $label = trim((string)($lk['cgymc'] ?? ''));
  8075. if ($label === '') {
  8076. $label = '工序' . $i;
  8077. }
  8078. $lines[] = $label . ':' . $url;
  8079. $i++;
  8080. }
  8081. return implode("\n", $lines);
  8082. }
  8083. /**
  8084. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  8085. *
  8086. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  8087. */
  8088. protected function buildPlatformLinksHtml(array $detailLinks): string
  8089. {
  8090. $parts = [];
  8091. $i = 1;
  8092. foreach ($detailLinks as $lk) {
  8093. if (!is_array($lk)) {
  8094. continue;
  8095. }
  8096. $url = trim((string)($lk['url'] ?? ''));
  8097. if ($url === '') {
  8098. continue;
  8099. }
  8100. $label = trim((string)($lk['cgymc'] ?? ''));
  8101. if ($label === '') {
  8102. $label = '工序' . $i;
  8103. }
  8104. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  8105. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  8106. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  8107. $i++;
  8108. }
  8109. return implode("<br>\n", $parts);
  8110. }
  8111. /**
  8112. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  8113. *
  8114. * @return array<string, mixed>
  8115. */
  8116. protected function loadMailerConfig(): array
  8117. {
  8118. try {
  8119. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  8120. } catch (\Throwable $e) {
  8121. $cfg = [];
  8122. }
  8123. return is_array($cfg) ? $cfg : [];
  8124. }
  8125. protected function loadNotifyTemplateRow(string $scene): ?array
  8126. {
  8127. if (in_array($scene, ['confirm_ok_email', 'confirm_fail_email'], true)) {
  8128. $this->ensureConfirmResultEmailTemplates();
  8129. }
  8130. try {
  8131. $row = Db::table('purchase_sms_template')
  8132. ->where('scene', $scene)
  8133. ->where(function ($q) {
  8134. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  8135. })
  8136. ->order('id', 'asc')
  8137. ->find();
  8138. } catch (\Throwable $e) {
  8139. return null;
  8140. }
  8141. if (!is_array($row) || $row === []) {
  8142. return null;
  8143. }
  8144. return [
  8145. 'title' => trim((string)($row['title'] ?? '')),
  8146. 'content' => trim((string)($row['content'] ?? '')),
  8147. ];
  8148. }
  8149. /**
  8150. * 邮件用工序明细 HTML。
  8151. * 多订单同批时按订单分组;单订单保持原表格/单行样式。
  8152. */
  8153. protected function buildProcessLinesHtml(array $mergeRows): string
  8154. {
  8155. $groups = [];
  8156. foreach ($mergeRows as $r) {
  8157. if (!is_array($r)) {
  8158. continue;
  8159. }
  8160. $dh = trim((string)($r['CCYDH'] ?? ''));
  8161. $key = $dh !== '' ? $dh : ('__sid_' . (int)($r['ID'] ?? $r['id'] ?? $r['scydgy_id'] ?? 0));
  8162. if (!isset($groups[$key])) {
  8163. $groups[$key] = [
  8164. 'ccydh' => $dh,
  8165. 'cyjmc' => trim((string)($r['CYJMC'] ?? '')),
  8166. 'rows' => [],
  8167. ];
  8168. } elseif ($groups[$key]['cyjmc'] === '') {
  8169. $groups[$key]['cyjmc'] = trim((string)($r['CYJMC'] ?? ''));
  8170. }
  8171. $groups[$key]['rows'][] = $r;
  8172. }
  8173. if ($groups === []) {
  8174. return '';
  8175. }
  8176. $multiOrder = count($groups) > 1;
  8177. $flatRows = [];
  8178. foreach ($groups as $g) {
  8179. foreach ($g['rows'] as $r) {
  8180. $flatRows[] = $r;
  8181. }
  8182. }
  8183. if (!$multiOrder && count($flatRows) <= 1) {
  8184. $r = $flatRows[0] ?? [];
  8185. if (!is_array($r)) {
  8186. return '';
  8187. }
  8188. $gymc = trim((string)($r['CGYMC'] ?? ''));
  8189. $dw = trim((string)($r['CDW'] ?? ''));
  8190. $qty = $this->resolveProcuremenThisQuantity($r);
  8191. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  8192. if ($dw !== '') {
  8193. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  8194. }
  8195. if ($qty !== '') {
  8196. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  8197. }
  8198. return $html;
  8199. }
  8200. $blocks = [];
  8201. foreach ($groups as $g) {
  8202. $head = '';
  8203. if ($multiOrder) {
  8204. if ($g['ccydh'] !== '') {
  8205. $head .= '<div style="margin:10px 0 4px;font-weight:700;">订单号:'
  8206. . htmlspecialchars($g['ccydh'], ENT_QUOTES, 'UTF-8') . '</div>';
  8207. }
  8208. if ($g['cyjmc'] !== '') {
  8209. $head .= '<div style="margin:0 0 6px;color:#333;">印件名称:'
  8210. . htmlspecialchars($g['cyjmc'], ENT_QUOTES, 'UTF-8') . '</div>';
  8211. }
  8212. }
  8213. $rows = '';
  8214. $i = 1;
  8215. foreach ($g['rows'] as $r) {
  8216. if (!is_array($r)) {
  8217. continue;
  8218. }
  8219. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  8220. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  8221. $qty = htmlspecialchars($this->resolveProcuremenThisQuantity($r), ENT_QUOTES, 'UTF-8');
  8222. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  8223. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  8224. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  8225. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  8226. $i++;
  8227. }
  8228. if ($rows === '') {
  8229. continue;
  8230. }
  8231. $table = '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:4px 0 12px;font-size:14px;width:100%;max-width:560px;">'
  8232. . '<thead><tr style="background:#f5f5f5;">'
  8233. . '<th style="padding:6px 8px;border:1px solid #ddd;width:48px;">序号</th>'
  8234. . '<th style="padding:6px 8px;border:1px solid #ddd;text-align:left;">工序名称</th>'
  8235. . '<th style="padding:6px 8px;border:1px solid #ddd;width:64px;">单位</th>'
  8236. . '<th style="padding:6px 8px;border:1px solid #ddd;width:88px;">本次数量</th>'
  8237. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  8238. $blocks[] = $head . $table;
  8239. }
  8240. return implode('', $blocks);
  8241. }
  8242. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  8243. {
  8244. $sysRq = trim($sysRq);
  8245. if ($sysRq === '') {
  8246. if ($required) {
  8247. $this->error('请选择招标截止日期');
  8248. }
  8249. return '';
  8250. }
  8251. $ts = strtotime($sysRq);
  8252. if ($ts === false || $ts <= 0) {
  8253. $this->error('招标截止日期格式无效');
  8254. }
  8255. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  8256. if (!$allowPast) {
  8257. $ymd = date('Y-m-d', $ts);
  8258. if ($ymd < date('Y-m-d')) {
  8259. $this->error('招标截止日期不能早于今天');
  8260. }
  8261. if ($ts <= time()) {
  8262. $this->error('招标截止时间不能早于当前时间');
  8263. }
  8264. }
  8265. return date('Y-m-d H:i:s', $ts);
  8266. }
  8267. /**
  8268. * 确保 purchase_order.czlyq(类型)存在
  8269. */
  8270. protected function ensurePurchaseOrderCzlyqColumn(): void
  8271. {
  8272. static $done = false;
  8273. if ($done) {
  8274. return;
  8275. }
  8276. $done = true;
  8277. try {
  8278. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  8279. if (empty($cols)) {
  8280. Db::execute(
  8281. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  8282. );
  8283. }
  8284. } catch (\Throwable $e) {
  8285. // ignore
  8286. }
  8287. }
  8288. /**
  8289. * 确保 purchase_order.delivery_deadline 存在
  8290. */
  8291. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  8292. {
  8293. static $done = false;
  8294. if ($done) {
  8295. return;
  8296. }
  8297. $done = true;
  8298. try {
  8299. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  8300. if (empty($cols)) {
  8301. Db::execute(
  8302. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  8303. );
  8304. }
  8305. } catch (\Throwable $e) {
  8306. // ignore
  8307. }
  8308. }
  8309. /**
  8310. * 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
  8311. */
  8312. protected function ensurePurchaseOrderScoreRuleIdColumn(): void
  8313. {
  8314. static $done = false;
  8315. if ($done) {
  8316. return;
  8317. }
  8318. $done = true;
  8319. // 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
  8320. $adds = [
  8321. 'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
  8322. 'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
  8323. 'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
  8324. 'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
  8325. 'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
  8326. ];
  8327. $changed = false;
  8328. foreach ($adds as $col => $ddl) {
  8329. try {
  8330. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  8331. if (!is_array($cols) || $cols === []) {
  8332. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  8333. $changed = true;
  8334. }
  8335. } catch (\Throwable $e) {
  8336. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  8337. }
  8338. }
  8339. if ($changed) {
  8340. $this->clearPurchaseOrderTableFieldsCache();
  8341. }
  8342. }
  8343. /**
  8344. * 确保 purchase_order.order_batch_no(下发批次号)存在
  8345. */
  8346. protected function ensurePurchaseOrderOrderBatchNoColumn(): void
  8347. {
  8348. static $done = false;
  8349. if ($done) {
  8350. return;
  8351. }
  8352. $done = true;
  8353. try {
  8354. $hasNew = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'order_batch_no'");
  8355. if (is_array($hasNew) && $hasNew !== []) {
  8356. return;
  8357. }
  8358. $hasOld = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'issue_batch_no'");
  8359. if (is_array($hasOld) && $hasOld !== []) {
  8360. Db::execute(
  8361. "ALTER TABLE `purchase_order` CHANGE COLUMN `issue_batch_no` `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号(如XH202608240001)'"
  8362. );
  8363. try {
  8364. Db::execute('ALTER TABLE `purchase_order` DROP INDEX `idx_issue_batch_no`');
  8365. } catch (\Throwable $eDrop) {
  8366. }
  8367. try {
  8368. Db::execute('ALTER TABLE `purchase_order` ADD INDEX `idx_order_batch_no` (`order_batch_no`)');
  8369. } catch (\Throwable $eIdx) {
  8370. }
  8371. } else {
  8372. Db::execute(
  8373. "ALTER TABLE `purchase_order` ADD COLUMN `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号(如XH202608240001)'"
  8374. );
  8375. try {
  8376. Db::execute('ALTER TABLE `purchase_order` ADD INDEX `idx_order_batch_no` (`order_batch_no`)');
  8377. } catch (\Throwable $eIdx) {
  8378. }
  8379. }
  8380. $this->clearPurchaseOrderTableFieldsCache();
  8381. } catch (\Throwable $e) {
  8382. Log::write('purchase_order.order_batch_no: ' . $e->getMessage(), 'error');
  8383. }
  8384. }
  8385. /** @deprecated 兼容旧调用 */
  8386. protected function ensurePurchaseOrderIssueBatchNoColumn(): void
  8387. {
  8388. $this->ensurePurchaseOrderOrderBatchNoColumn();
  8389. }
  8390. /**
  8391. * 批次号日流水表:取号时立刻落库递增,避免并发下发撞号
  8392. */
  8393. protected function ensurePurchaseIssueBatchSeqTable(): void
  8394. {
  8395. static $done = false;
  8396. if ($done) {
  8397. return;
  8398. }
  8399. $done = true;
  8400. try {
  8401. Db::execute(
  8402. "CREATE TABLE IF NOT EXISTS `purchase_issue_batch_seq` (
  8403. `ymd` char(8) NOT NULL COMMENT '日期Ymd',
  8404. `last_no` int unsigned NOT NULL DEFAULT 0 COMMENT '当日已分配最大流水',
  8405. `updatetime` datetime DEFAULT NULL,
  8406. PRIMARY KEY (`ymd`)
  8407. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助下发批次号日流水'"
  8408. );
  8409. } catch (\Throwable $e) {
  8410. Log::write('purchase_issue_batch_seq: ' . $e->getMessage(), 'error');
  8411. }
  8412. }
  8413. /**
  8414. * 生成下发批次号:XH + Ymd + 当日4位流水(如 XH202608240001)
  8415. * 必须拿到日锁后先递增流水表再返回,避免两笔下发同时取到同一号。
  8416. *
  8417. * @throws \RuntimeException
  8418. */
  8419. protected function allocateProcuremenIssueBatchNo(): string
  8420. {
  8421. $this->ensurePurchaseOrderOrderBatchNoColumn();
  8422. $this->ensurePurchaseIssueBatchSeqTable();
  8423. $ymd = date('Ymd');
  8424. $prefix = 'XH' . $ymd;
  8425. $lockName = 'procuremen_issue_batch_' . $ymd;
  8426. if (!$this->acquireProcuremenNamedLock($lockName, 15)) {
  8427. throw new \RuntimeException('批次号生成繁忙,请稍后重试');
  8428. }
  8429. try {
  8430. $last = 0;
  8431. $hasSeqRow = false;
  8432. try {
  8433. $row = Db::table('purchase_issue_batch_seq')->where('ymd', $ymd)->find();
  8434. if (is_array($row) && $row !== []) {
  8435. $hasSeqRow = true;
  8436. $last = (int)($row['last_no'] ?? 0);
  8437. }
  8438. } catch (\Throwable $e) {
  8439. $last = 0;
  8440. }
  8441. // 兼容:流水表为空时,用已有 purchase_order.order_batch_no 最大值对齐
  8442. try {
  8443. $maxPo = Db::table('purchase_order')
  8444. ->where('order_batch_no', 'like', $prefix . '%')
  8445. ->order('order_batch_no', 'desc')
  8446. ->value('order_batch_no');
  8447. if (is_string($maxPo) && preg_match('/^XH\d{8}(\d{4})$/', $maxPo, $m)) {
  8448. $last = max($last, (int)$m[1]);
  8449. }
  8450. } catch (\Throwable $e) {
  8451. }
  8452. $seq = $last + 1;
  8453. if ($seq < 1) {
  8454. $seq = 1;
  8455. }
  8456. if ($seq > 9999) {
  8457. throw new \RuntimeException('当日批次号已用尽,请联系管理员');
  8458. }
  8459. $now = date('Y-m-d H:i:s');
  8460. try {
  8461. if ($hasSeqRow) {
  8462. Db::table('purchase_issue_batch_seq')->where('ymd', $ymd)->update([
  8463. 'last_no' => $seq,
  8464. 'updatetime' => $now,
  8465. ]);
  8466. } else {
  8467. try {
  8468. Db::table('purchase_issue_batch_seq')->insert([
  8469. 'ymd' => $ymd,
  8470. 'last_no' => $seq,
  8471. 'updatetime' => $now,
  8472. ]);
  8473. } catch (\Throwable $eIns) {
  8474. Db::table('purchase_issue_batch_seq')->where('ymd', $ymd)->update([
  8475. 'last_no' => $seq,
  8476. 'updatetime' => $now,
  8477. ]);
  8478. }
  8479. }
  8480. } catch (\Throwable $e) {
  8481. throw new \RuntimeException('批次号写入失败,请重试');
  8482. }
  8483. return $prefix . str_pad((string)$seq, 4, '0', STR_PAD_LEFT);
  8484. } finally {
  8485. $this->releaseProcuremenNamedLock($lockName);
  8486. }
  8487. }
  8488. /**
  8489. * ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
  8490. */
  8491. protected function clearPurchaseOrderTableFieldsCache(): void
  8492. {
  8493. try {
  8494. $db = (string)Config::get('database.database');
  8495. $key = $db . '.purchase_order';
  8496. $ref = new \ReflectionProperty(\think\db\Query::class, 'info');
  8497. $ref->setAccessible(true);
  8498. $info = $ref->getValue();
  8499. if (is_array($info) && isset($info[$key])) {
  8500. unset($info[$key]);
  8501. $ref->setValue(null, $info);
  8502. }
  8503. } catch (\Throwable $e) {
  8504. }
  8505. try {
  8506. $db = (string)Config::get('database.database');
  8507. $schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
  8508. if (is_file($schemaFile)) {
  8509. @unlink($schemaFile);
  8510. }
  8511. } catch (\Throwable $e) {
  8512. }
  8513. }
  8514. /**
  8515. * @return array<string, bool>
  8516. */
  8517. protected function loadPurchaseOrderColumnSet(): array
  8518. {
  8519. static $set = null;
  8520. if (is_array($set)) {
  8521. return $set;
  8522. }
  8523. $set = [];
  8524. try {
  8525. $cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
  8526. } catch (\Throwable $e) {
  8527. return $set;
  8528. }
  8529. if (!is_array($cols)) {
  8530. return $set;
  8531. }
  8532. foreach ($cols as $c) {
  8533. if (!is_array($c)) {
  8534. continue;
  8535. }
  8536. $f = (string)($c['Field'] ?? $c['field'] ?? '');
  8537. if ($f !== '') {
  8538. $set[$f] = true;
  8539. }
  8540. }
  8541. return $set;
  8542. }
  8543. /**
  8544. * 解析交货截止日期(仅年月日)
  8545. */
  8546. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  8547. {
  8548. $raw = trim($raw);
  8549. if ($raw === '') {
  8550. if ($required) {
  8551. $this->error('请选择交货截止日期');
  8552. }
  8553. return '';
  8554. }
  8555. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  8556. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  8557. } else {
  8558. $ts = strtotime(str_replace('/', '-', $raw));
  8559. if ($ts === false || $ts <= 0) {
  8560. $this->error('交货截止日期格式无效');
  8561. }
  8562. $ymd = date('Y-m-d', $ts);
  8563. }
  8564. if ($ymd < date('Y-m-d')) {
  8565. $this->error('交货截止日期不能早于今天');
  8566. }
  8567. return $ymd;
  8568. }
  8569. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  8570. {
  8571. return ProcuremenFormat::deliveryDeadlineForInput($value);
  8572. }
  8573. /**
  8574. * @param array{pos?:array} $bundle
  8575. * @return array<string, string> CCYDH => Y-m-d
  8576. */
  8577. protected function buildBundleOrderDeliveryDeadlineMap(array $bundle): array
  8578. {
  8579. $map = [];
  8580. foreach ($bundle['pos'] ?? [] as $po) {
  8581. if (!is_array($po)) {
  8582. continue;
  8583. }
  8584. $dh = trim((string)($po['CCYDH'] ?? ''));
  8585. if ($dh === '' || isset($map[$dh])) {
  8586. continue;
  8587. }
  8588. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  8589. if ($d !== '') {
  8590. $map[$dh] = $d;
  8591. }
  8592. }
  8593. return $map;
  8594. }
  8595. /**
  8596. * @param array{pos?:array} $bundle
  8597. */
  8598. protected function resolveBundleDeliveryDeadline(array $bundle): string
  8599. {
  8600. $map = $this->buildBundleOrderDeliveryDeadlineMap($bundle);
  8601. if ($map !== []) {
  8602. return (string)reset($map);
  8603. }
  8604. return '';
  8605. }
  8606. protected function formatProcuremenSysRqForInput($sysRq): string
  8607. {
  8608. return ProcuremenFormat::sysRqForInput($sysRq);
  8609. }
  8610. protected function formatProcuremenSysRqForDisplay($sysRq): string
  8611. {
  8612. return ProcuremenFormat::sysRqForDisplay($sysRq);
  8613. }
  8614. /**
  8615. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  8616. *
  8617. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  8618. * @return array{ccydh?:string,pos:array,merge_rows:array}
  8619. */
  8620. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  8621. {
  8622. return $bundle;
  8623. }
  8624. /**
  8625. * 写入/更新 purchase_order(单道工序行)
  8626. *
  8627. * @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
  8628. */
  8629. protected function upsertPurchaseOrderFromRow(
  8630. array $row,
  8631. string $sysRqDb,
  8632. $wflowStatus = null,
  8633. ?string $pickTime = null,
  8634. ?array $exists = null,
  8635. ?string $deliveryDeadline = null,
  8636. $scoreRuleId = null,
  8637. ?string $issueBatchNo = null
  8638. ): void {
  8639. $ids = $this->extractScydgyRowId($row);
  8640. if (!$this->isValidScydgyRowId($ids)) {
  8641. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  8642. }
  8643. if ($exists === null) {
  8644. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  8645. }
  8646. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  8647. $this->ensurePurchaseOrderScoreRuleIdColumn();
  8648. $this->ensurePurchaseOrderOrderBatchNoColumn();
  8649. $this->ensurePurchaseOrderCzlyqColumn();
  8650. $data = $this->normalizePurchaseOrderWritePayload([
  8651. 'scydgy_id' => $ids,
  8652. 'CCYDH' => $row['CCYDH'] ?? null,
  8653. 'CYJMC' => $row['CYJMC'] ?? null,
  8654. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  8655. 'CDXMC' => $row['CDXMC'] ?? null,
  8656. 'CGYBH' => $row['CGYBH'] ?? null,
  8657. 'CGYMC' => $row['CGYMC'] ?? null,
  8658. 'CDW' => $row['CDW'] ?? null,
  8659. 'czlyq' => $row['czlyq'] ?? null,
  8660. 'NGZL' => $row['NGZL'] ?? null,
  8661. 'CDF' => $row['CDF'] ?? null,
  8662. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  8663. 'MBZ' => trim((string)($row['MBZ'] ?? $row['mbz'] ?? '')),
  8664. 'bwjg' => $row['bwjg'] ?? null,
  8665. 'iStatus' => $row['iStatus'] ?? null,
  8666. 'dStamp' => $row['dStamp'] ?? null,
  8667. 'dputrecord' => $row['dputrecord'] ?? null,
  8668. 'cywyxm' => $row['cywyxm'] ?? null,
  8669. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  8670. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  8671. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  8672. 'sys_rq' => $sysRqDb,
  8673. ], $row);
  8674. // 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
  8675. $qtyUp = trim((string)($data['This_quantity'] ?? ''));
  8676. if ($qtyUp === '') {
  8677. $qtyFallback = $this->resolveProcuremenThisQuantity([
  8678. 'This_quantity' => '',
  8679. 'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
  8680. ]);
  8681. if ($qtyFallback !== '') {
  8682. $data['This_quantity'] = $qtyFallback;
  8683. }
  8684. }
  8685. if ($deliveryDeadline !== null) {
  8686. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  8687. }
  8688. // 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
  8689. $scoreRule = null;
  8690. if (is_array($scoreRuleId)) {
  8691. $scoreRule = $scoreRuleId;
  8692. $scoreRuleId = (int)($scoreRule['id'] ?? 0);
  8693. } else {
  8694. $scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
  8695. }
  8696. if ($scoreRuleId !== null && $scoreRuleId > 0) {
  8697. $poCols = $this->loadPurchaseOrderColumnSet();
  8698. if (!empty($poCols['score_rule_id'])) {
  8699. $data['score_rule_id'] = $scoreRuleId;
  8700. if (is_array($scoreRule)) {
  8701. if (!empty($poCols['score_rule_name'])) {
  8702. $data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
  8703. }
  8704. if (!empty($poCols['score_quality_weight'])) {
  8705. $data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
  8706. }
  8707. if (!empty($poCols['score_price_weight'])) {
  8708. $data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
  8709. }
  8710. if (!empty($poCols['score_lead_weight'])) {
  8711. $data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
  8712. }
  8713. }
  8714. }
  8715. }
  8716. if ($wflowStatus !== null && $wflowStatus !== '') {
  8717. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  8718. }
  8719. if ($pickTime !== null && $pickTime !== '') {
  8720. $data['pick_time'] = $pickTime;
  8721. $data['pick_company_name'] = '';
  8722. // 新下发批次:清空「指定供应商」,避免沿用上轮免开标状态导致提前可见报价
  8723. $this->ensurePurchaseOrderManualPickColumns();
  8724. $data['manual_pick'] = 0;
  8725. $data['manual_pick_reason'] = '';
  8726. // 同订单重新下发后需重新开标(按订单号 + 批次号);并软删同订单其它旧批
  8727. $dh = trim((string)($data['CCYDH'] ?? $row['CCYDH'] ?? ''));
  8728. $bn = trim((string)($issueBatchNo ?? ''));
  8729. if ($bn === '') {
  8730. $bn = $this->resolveProcuremenOrderBatchNo(array_merge(is_array($exists) ? $exists : [], $data, $row));
  8731. }
  8732. $this->clearProcuremenBidOpenRecords($dh !== '' ? [$dh] : [], $bn !== '' ? [$bn] : []);
  8733. if ($dh !== '') {
  8734. // 新下发只清开标/评分;软删其它批仅在「重新下发」入口做,避免正常补发工序误伤并行单
  8735. $this->clearProcuremenSupplierScoresForCcydhs([$dh]);
  8736. }
  8737. }
  8738. if ($issueBatchNo !== null) {
  8739. $batchNo = trim($issueBatchNo);
  8740. $poCols = $this->loadPurchaseOrderColumnSet();
  8741. if (!empty($poCols['order_batch_no'])) {
  8742. $data['order_batch_no'] = $batchNo;
  8743. }
  8744. }
  8745. if ($exists) {
  8746. $upd = $data;
  8747. unset($upd['scydgy_id']);
  8748. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  8749. } else {
  8750. $data['createtime'] = date('Y-m-d H:i:s');
  8751. Db::table('purchase_order')->insert($data);
  8752. }
  8753. }
  8754. /**
  8755. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  8756. *
  8757. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  8758. */
  8759. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
  8760. {
  8761. $toDb = function ($value) {
  8762. if ($value === null) {
  8763. return null;
  8764. }
  8765. if (is_scalar($value)) {
  8766. return $value;
  8767. }
  8768. return json_encode($value, JSON_UNESCAPED_UNICODE);
  8769. };
  8770. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  8771. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  8772. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  8773. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  8774. if ($username === '') {
  8775. $username = $this->resolveCustomerContactName($phone, $companyName);
  8776. }
  8777. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  8778. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  8779. }
  8780. if ($requirePhone && $phone === '') {
  8781. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  8782. }
  8783. $detailLinks = [];
  8784. foreach ($mergeRows as $row) {
  8785. if (!is_array($row)) {
  8786. continue;
  8787. }
  8788. $sid = $this->extractScydgyRowId($row);
  8789. $detailId = 0;
  8790. if ($skipExisting) {
  8791. try {
  8792. $existsQuery = Db::table('purchase_order_detail')
  8793. ->where('scydgy_id', $sid)
  8794. ->where('company_name', $companyName);
  8795. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  8796. $exists = $existsQuery->find();
  8797. } catch (\Throwable $e) {
  8798. $exists = null;
  8799. }
  8800. if (is_array($exists)) {
  8801. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  8802. }
  8803. }
  8804. if ($detailId <= 0) {
  8805. $one = [
  8806. 'scydgy_id' => $toDb($sid),
  8807. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  8808. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  8809. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  8810. 'username' => $username !== '' ? $username : null,
  8811. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  8812. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  8813. 'createtime' => date('Y-m-d H:i:s'),
  8814. 'status' => ProcuremenStatus::POD_UNPICKED,
  8815. 'status_name' => '未提交',
  8816. ];
  8817. // 新下发/重新下发均不继承历史报价,供应商需对本批次重新填报
  8818. Db::table('purchase_order_detail')->insert($one);
  8819. $detailId = (int)Db::getLastInsID();
  8820. }
  8821. $mprocUrl = '';
  8822. if ($buildMobileLinks && $detailId > 0) {
  8823. // 手工询价 → 待报价;协助下发 → 未提交
  8824. $listTab = ($sid < 0) ? 'rfq' : 'draft';
  8825. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId, $listTab);
  8826. }
  8827. $detailLinks[] = [
  8828. 'detail_id' => $detailId,
  8829. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  8830. 'url' => $mprocUrl,
  8831. ];
  8832. }
  8833. $this->invalidatePickHiddenScydgyCache();
  8834. return $detailLinks;
  8835. }
  8836. /**
  8837. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  8838. * @return array<string, mixed>
  8839. */
  8840. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks, string $emailTplScene = 'review_email'): array
  8841. {
  8842. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  8843. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  8844. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  8845. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  8846. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  8847. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  8848. $isMerge = !empty($ctx['is_merge']);
  8849. $contactName = trim((string)($c['username'] ?? ''));
  8850. if ($contactName === '') {
  8851. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  8852. }
  8853. $notifyVars = [
  8854. 'company_name' => $companyName,
  8855. 'contact_name' => $contactName,
  8856. 'phone' => $phone,
  8857. 'email' => $toEmail,
  8858. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  8859. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  8860. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  8861. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  8862. 'deadline' => (string)($ctx['deadline'] ?? ''),
  8863. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  8864. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  8865. 'order_type' => (string)($ctx['order_type'] ?? ''),
  8866. 'score_weights' => (string)($ctx['score_weights'] ?? ''),
  8867. 'platform_url' => $platformUrl,
  8868. 'platform_links' => $platformLinksPlain,
  8869. 'platform_links_html' => $platformLinksHtml,
  8870. ];
  8871. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  8872. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  8873. $mailPlain = $this->renderNotifyTemplate($emailTplScene, $notifyVars);
  8874. if (!empty($ctx['multi_order'])) {
  8875. $smsContent = $this->stripEmptyOrderHeaderLines($smsContent);
  8876. $mailPlain = $this->stripEmptyOrderHeaderLines($mailPlain);
  8877. }
  8878. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  8879. // 邮件:用表格替换纯文本工序块,列对齐更整齐
  8880. $processHtml = trim((string)($ctx['process_html'] ?? ''));
  8881. $processPlain = trim((string)($ctx['process_plain'] ?? ''));
  8882. if ($processHtml !== '' && $processPlain !== '') {
  8883. $plainBlockHtml = $this->plainTextToHtmlEmailBody($processPlain);
  8884. if ($plainBlockHtml !== '' && strpos($mailBody, $plainBlockHtml) !== false) {
  8885. $mailBody = str_replace($plainBlockHtml, $processHtml, $mailBody);
  8886. }
  8887. }
  8888. return [
  8889. 'company_name' => $companyName,
  8890. 'phone' => $phone,
  8891. 'email' => $toEmail,
  8892. 'sms_content' => $smsContent,
  8893. 'mail_plain' => $mailPlain,
  8894. 'mail_body' => $mailBody,
  8895. 'notify_vars' => $notifyVars,
  8896. 'detail_links' => $detailLinks,
  8897. ];
  8898. }
  8899. /**
  8900. * 多订单下发时模版里「订单号:{ccydh}」可能变成空行,去掉以免重复
  8901. */
  8902. protected function stripEmptyOrderHeaderLines(string $text): string
  8903. {
  8904. $text = str_replace(["\r\n", "\r"], "\n", $text);
  8905. $text = preg_replace('/^订单号:\s*\n/mu', '', $text);
  8906. $text = preg_replace('/^印件名称:\s*\n/mu', '', $text);
  8907. $text = preg_replace("/\n{3,}/", "\n\n", (string)$text);
  8908. return (string)$text;
  8909. }
  8910. /**
  8911. * @param array<string, mixed> $chosen
  8912. * @param array<int, array<string, mixed>> $mergeRows
  8913. * @param array{ccydh:string, pos:array} $bundle
  8914. */
  8915. /**
  8916. * 先把成功 JSON 回给浏览器,再继续后台任务(发短信/邮件)。
  8917. * 避免多家供应商通知串行导致页面一直转圈、网关超时被当成系统失败。
  8918. *
  8919. * @param array<string, mixed>|string|null $data
  8920. */
  8921. protected function respondSuccessThenContinue(string $msg, $data = null): void
  8922. {
  8923. $result = [
  8924. 'code' => 1,
  8925. 'msg' => $msg,
  8926. 'data' => $data,
  8927. 'url' => '',
  8928. 'wait' => 3,
  8929. ];
  8930. $json = json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  8931. if ($json === false) {
  8932. $json = '{"code":1,"msg":"操作成功","data":null,"url":"","wait":3}';
  8933. }
  8934. while (ob_get_level() > 0) {
  8935. @ob_end_clean();
  8936. }
  8937. if (!headers_sent()) {
  8938. header('Content-Type: application/json; charset=utf-8');
  8939. header('Cache-Control: no-store, no-cache, must-revalidate');
  8940. header('Connection: close');
  8941. header('Content-Length: ' . strlen($json));
  8942. }
  8943. echo $json;
  8944. if (session_status() === PHP_SESSION_ACTIVE) {
  8945. @session_write_close();
  8946. }
  8947. if (function_exists('fastcgi_finish_request')) {
  8948. @fastcgi_finish_request();
  8949. } else {
  8950. @flush();
  8951. }
  8952. @ignore_user_abort(true);
  8953. @set_time_limit(300);
  8954. @ini_set('max_execution_time', '300');
  8955. }
  8956. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue', string $emailTplScene = 'review_email'): void
  8957. {
  8958. if (!$sendSms && !$sendEmail) {
  8959. return;
  8960. }
  8961. $companyName = trim((string)($chosen['name'] ?? ''));
  8962. $phone = trim((string)($chosen['phone'] ?? ''));
  8963. $toEmail = trim((string)($chosen['email'] ?? ''));
  8964. if ($companyName === '') {
  8965. throw new \Exception('供应商名称无效');
  8966. }
  8967. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  8968. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  8969. }
  8970. if ($sendSms && $phone === '') {
  8971. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  8972. }
  8973. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  8974. $linkListTab = (strpos($emailTplScene, 'rfq_') === 0) ? 'rfq' : 'draft';
  8975. $sids = [];
  8976. foreach ($mergeRows as $mr) {
  8977. if (!is_array($mr)) {
  8978. continue;
  8979. }
  8980. $sid = $this->extractScydgyRowId($mr);
  8981. if ($this->isValidScydgyRowId($sid)) {
  8982. $sids[$sid] = true;
  8983. }
  8984. }
  8985. if ($sids === []) {
  8986. throw new \Exception('未找到工序行,无法发送通知');
  8987. }
  8988. $sysRqNotify = '';
  8989. $pos = $bundle['pos'] ?? [];
  8990. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  8991. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  8992. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  8993. $ts = strtotime($sr);
  8994. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  8995. }
  8996. }
  8997. try {
  8998. $detailsQuery = Db::table('purchase_order_detail')
  8999. ->where('scydgy_id', 'in', array_keys($sids))
  9000. ->where('company_name', $companyName);
  9001. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  9002. $details = $detailsQuery->order('id', 'asc')->select();
  9003. } catch (\Throwable $e) {
  9004. $details = [];
  9005. }
  9006. if (!is_array($details) || $details === []) {
  9007. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  9008. try {
  9009. $detailsQuery = Db::table('purchase_order_detail')
  9010. ->where('scydgy_id', 'in', array_keys($sids))
  9011. ->where('company_name', $companyName);
  9012. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  9013. $details = $detailsQuery->order('id', 'asc')->select();
  9014. } catch (\Throwable $e) {
  9015. $details = [];
  9016. }
  9017. }
  9018. if (!is_array($details) || $details === []) {
  9019. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  9020. }
  9021. $detailLinks = [];
  9022. foreach ($details as $d) {
  9023. if (!is_array($d)) {
  9024. continue;
  9025. }
  9026. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  9027. if ($detailId <= 0) {
  9028. continue;
  9029. }
  9030. $sid = (int)($d['scydgy_id'] ?? 0);
  9031. $gymc = '';
  9032. foreach ($mergeRows as $mr) {
  9033. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  9034. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  9035. break;
  9036. }
  9037. }
  9038. $detailLinks[] = [
  9039. 'detail_id' => $detailId,
  9040. 'cgymc' => $gymc,
  9041. // 询价邮件 → 待报价;下发报价 → 未提交
  9042. 'url' => $this->buildMprocMobileOrderUrl(
  9043. $detailId,
  9044. ($linkListTab === 'rfq' || $sid < 0) ? 'rfq' : 'draft'
  9045. ),
  9046. ];
  9047. }
  9048. if ($detailLinks === []) {
  9049. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  9050. }
  9051. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  9052. $orderTypeCtx = $this->resolveIssueNotifyOrderTypeFromBundle($bundle);
  9053. $ctx['order_type'] = (string)($orderTypeCtx['order_type'] ?? '');
  9054. $ctx['score_weights'] = (string)($orderTypeCtx['score_weights'] ?? '');
  9055. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks, $emailTplScene);
  9056. $notifyBundle['email_log_scene'] = $emailLogScene;
  9057. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  9058. $poIdLog = 0;
  9059. $pos = $bundle['pos'] ?? [];
  9060. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  9061. $poIdLog = (int)($pos[0]['id'] ?? 0);
  9062. }
  9063. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  9064. if ($sendEmail) {
  9065. $mailTplRow = $this->loadNotifyTemplateRow($emailTplScene);
  9066. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  9067. throw new \Exception($this->notifyTemplateMissingMessage($emailTplScene));
  9068. }
  9069. $mailSubject = $this->resolveProcuremenEmailSubject($emailTplScene);
  9070. $mailConfig = $this->loadMailerConfig();
  9071. if (!$this->isProcuremenNotifyDryRun()) {
  9072. if (empty($mailConfig['host'])) {
  9073. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9074. }
  9075. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9076. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9077. }
  9078. }
  9079. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  9080. }
  9081. if ($sendSms) {
  9082. $this->issueSendSupplierSms($notifyBundle);
  9083. }
  9084. }
  9085. /**
  9086. * @param array<int, array<string, mixed>> $quoteGroups
  9087. * @return array<int, array<string, mixed>>
  9088. */
  9089. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  9090. {
  9091. $names = [];
  9092. if (is_string($companiesJson) && $companiesJson !== '') {
  9093. $decoded = json_decode($companiesJson, true);
  9094. if (is_array($decoded)) {
  9095. foreach ($decoded as $nm) {
  9096. $nm = trim((string)$nm);
  9097. if ($nm !== '') {
  9098. $names[] = $nm;
  9099. }
  9100. }
  9101. }
  9102. }
  9103. $names = array_values(array_unique($names));
  9104. if ($names === [] && $selectedCompany !== '') {
  9105. $names = [$selectedCompany];
  9106. }
  9107. if ($names === []) {
  9108. return $quoteGroups;
  9109. }
  9110. $targets = [];
  9111. foreach ($quoteGroups as $g) {
  9112. if (!is_array($g)) {
  9113. continue;
  9114. }
  9115. $cn = trim((string)($g['name'] ?? ''));
  9116. if ($cn !== '' && in_array($cn, $names, true)) {
  9117. $targets[] = $g;
  9118. }
  9119. }
  9120. return $targets;
  9121. }
  9122. /**
  9123. * @return array{pos:array, merge_rows:array, bundle:array}
  9124. */
  9125. protected function loadAuditResendBundle(string $scydgyId): array
  9126. {
  9127. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  9128. $pos = $bundle['pos'];
  9129. $mergeRows = $bundle['merge_rows'];
  9130. if ($pos === [] || $mergeRows === []) {
  9131. $this->error('该订单不在待确认供应商状态');
  9132. }
  9133. $sysRqDb = '';
  9134. if (isset($pos[0]) && is_array($pos[0])) {
  9135. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  9136. }
  9137. foreach ($pos as $i => $poRow) {
  9138. if (is_array($pos[$i]) && $sysRqDb !== '') {
  9139. $pos[$i]['sys_rq'] = $sysRqDb;
  9140. }
  9141. }
  9142. $bundle['pos'] = $pos;
  9143. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  9144. }
  9145. /**
  9146. * @param array<int, array<string, mixed>> $targets
  9147. */
  9148. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  9149. {
  9150. if ($targets === []) {
  9151. $this->error('未找到可通知的供应商');
  9152. }
  9153. $notifyErrors = [];
  9154. try {
  9155. $this->notifyDryRunPreview = [];
  9156. foreach ($targets as $g) {
  9157. if (!is_array($g)) {
  9158. continue;
  9159. }
  9160. $cname = trim((string)($g['name'] ?? ''));
  9161. if ($cname === '') {
  9162. continue;
  9163. }
  9164. $chosen = [
  9165. 'name' => $cname,
  9166. 'company_name' => $cname,
  9167. 'email' => trim((string)($g['email'] ?? '')),
  9168. 'phone' => trim((string)($g['phone'] ?? '')),
  9169. 'username' => trim((string)($g['username'] ?? '')),
  9170. ];
  9171. try {
  9172. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  9173. } catch (\Throwable $e) {
  9174. $notifyErrors[] = $cname . ':' . $e->getMessage();
  9175. }
  9176. }
  9177. } catch (\Throwable $e) {
  9178. Log::write('procuremen auditResend notify fatal: ' . $e->getMessage(), 'error');
  9179. $this->success('重发未全部完成,请核对联系方式后稍后再试', '', [
  9180. 'notify_failed' => 1,
  9181. ]);
  9182. }
  9183. if ($notifyErrors !== []) {
  9184. Log::write('procuremen auditResend partial fail: ' . implode(';', $notifyErrors), 'error');
  9185. $ok = max(0, count($targets) - count($notifyErrors));
  9186. $this->success(
  9187. '已向 ' . $ok . ' 家发送成功;个别未送达请核对手机号/邮箱后重试',
  9188. '',
  9189. [
  9190. 'notify_failed' => 1,
  9191. 'notify_fail_detail' => $notifyErrors,
  9192. ]
  9193. );
  9194. }
  9195. if ($this->isProcuremenNotifyDryRun()) {
  9196. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  9197. 'notify_dry_run' => true,
  9198. 'notify_preview' => $this->notifyDryRunPreview,
  9199. ]);
  9200. }
  9201. $nameLabels = [];
  9202. foreach ($targets as $g) {
  9203. if (!is_array($g)) {
  9204. continue;
  9205. }
  9206. $n = trim((string)($g['name'] ?? ''));
  9207. if ($n !== '') {
  9208. $nameLabels[] = $n;
  9209. }
  9210. }
  9211. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  9212. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  9213. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  9214. $seenLogSid = [];
  9215. foreach ($bundle['pos'] ?? [] as $poRow) {
  9216. if (!is_array($poRow)) {
  9217. continue;
  9218. }
  9219. $sid = (int)($poRow['scydgy_id'] ?? 0);
  9220. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  9221. continue;
  9222. }
  9223. $seenLogSid[$sid] = true;
  9224. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  9225. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  9226. }
  9227. if ($seenLogSid === []) {
  9228. foreach ($mergeRows as $mr) {
  9229. if (!is_array($mr)) {
  9230. continue;
  9231. }
  9232. $sid = $this->extractScydgyRowId($mr);
  9233. if ($this->isValidScydgyRowId($sid)) {
  9234. $this->addOrderLog($sid, $logAction, $logMsg, null);
  9235. break;
  9236. }
  9237. }
  9238. }
  9239. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  9240. }
  9241. /**
  9242. * 协助下发 — 发送短信(一家供应商)
  9243. *
  9244. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  9245. */
  9246. protected function issueSendSupplierSms(array $bundle): void
  9247. {
  9248. $companyName = (string)($bundle['company_name'] ?? '');
  9249. $phone = (string)($bundle['phone'] ?? '');
  9250. $smsContent = (string)($bundle['sms_content'] ?? '');
  9251. $this->logIssueNotifyDebug('短信', [
  9252. 'company' => $companyName,
  9253. 'phone' => $phone,
  9254. 'sms_content' => $smsContent,
  9255. ]);
  9256. if ($this->isProcuremenNotifyDryRun()) {
  9257. $this->recordNotifyDryRunPreview([
  9258. 'scene' => 'issue_sms',
  9259. 'company_name' => $companyName,
  9260. 'phone' => $phone,
  9261. 'sms_content' => $smsContent,
  9262. ]);
  9263. return;
  9264. }
  9265. $this->smsbao($phone, $smsContent);
  9266. }
  9267. /**
  9268. * 协助下发 — 发送邮件(一家供应商)
  9269. *
  9270. * @param array<string, mixed> $bundle
  9271. * @param array<string, mixed> $mailConfig
  9272. */
  9273. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  9274. {
  9275. $companyName = (string)($bundle['company_name'] ?? '');
  9276. $toEmail = (string)($bundle['email'] ?? '');
  9277. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  9278. $mailBody = (string)($bundle['mail_body'] ?? '');
  9279. $this->logIssueNotifyDebug('邮件', [
  9280. 'company' => $companyName,
  9281. 'email' => $toEmail,
  9282. 'cc_email' => $this->resolveMprocNotifyCcEmails($toEmail),
  9283. 'mail_subject' => $mailSubject,
  9284. 'mail_body' => $mailPlain,
  9285. ]);
  9286. if ($this->isProcuremenNotifyDryRun()) {
  9287. $this->recordNotifyDryRunPreview([
  9288. 'scene' => 'issue_email',
  9289. 'company_name' => $companyName,
  9290. 'email' => $toEmail,
  9291. 'cc_email' => $this->resolveMprocNotifyCcEmails($toEmail),
  9292. 'mail_subject' => $mailSubject,
  9293. 'mail_body' => $mailPlain,
  9294. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  9295. 'notify_vars' => $bundle['notify_vars'] ?? [],
  9296. 'detail_links' => $bundle['detail_links'] ?? [],
  9297. ]);
  9298. return;
  9299. }
  9300. $mail = new PHPMailer(true);
  9301. $mail->isSMTP();
  9302. $mail->Host = $mailConfig['host'];
  9303. $mail->SMTPAuth = true;
  9304. $mail->Username = $mailConfig['addr'];
  9305. $mail->Password = $mailConfig['pass'];
  9306. $mail->SMTPSecure = $mailConfig['security'];
  9307. $mail->Port = $mailConfig['port'];
  9308. $mail->CharSet = $mailConfig['charset'];
  9309. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  9310. $mail->addAddress($toEmail, $companyName);
  9311. $ccList = $this->resolveMprocNotifyCcEmails($toEmail);
  9312. foreach ($ccList as $cc) {
  9313. $mail->addCC($cc);
  9314. }
  9315. $mail->isHTML(true);
  9316. $mail->Subject = $mailSubject;
  9317. $mail->Body = $mailBody;
  9318. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  9319. $sendOk = true;
  9320. $failReason = '';
  9321. try {
  9322. $mail->send();
  9323. } catch (\Throwable $e) {
  9324. $sendOk = false;
  9325. $failReason = $e->getMessage();
  9326. $this->persistEmailSendLog([
  9327. 'from_email' => $fromEmail,
  9328. 'to_email' => $toEmail,
  9329. 'send_time' => date('Y-m-d H:i:s'),
  9330. 'scene' => (string)($bundle['email_log_scene'] ?? '初选下发'),
  9331. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  9332. 'company_name' => $companyName,
  9333. 'mail_subject' => $mailSubject,
  9334. 'status' => 0,
  9335. 'fail_reason' => $failReason,
  9336. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  9337. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  9338. ]);
  9339. throw $e;
  9340. }
  9341. $this->persistEmailSendLog([
  9342. 'from_email' => $fromEmail,
  9343. 'to_email' => $toEmail,
  9344. 'send_time' => date('Y-m-d H:i:s'),
  9345. 'scene' => (string)($bundle['email_log_scene'] ?? '初选下发'),
  9346. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  9347. 'company_name' => $companyName,
  9348. 'mail_subject' => $mailSubject,
  9349. 'status' => 1,
  9350. 'fail_reason' => '',
  9351. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  9352. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  9353. ]);
  9354. }
  9355. /**
  9356. * 协助通知抄送:读取 mproc.cc_email(逗号分隔),排除与主收件人相同的地址
  9357. *
  9358. * @return array<int, string>
  9359. */
  9360. protected function resolveMprocNotifyCcEmails(string $toEmail = ''): array
  9361. {
  9362. $raw = trim((string)config('mproc.cc_email'));
  9363. if ($raw === '') {
  9364. return [];
  9365. }
  9366. $toNorm = strtolower(trim($toEmail));
  9367. $out = [];
  9368. $seen = [];
  9369. foreach (preg_split('/[,;,;\s]+/', $raw) ?: [] as $piece) {
  9370. $email = strtolower(trim((string)$piece));
  9371. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9372. continue;
  9373. }
  9374. if ($toNorm !== '' && $email === $toNorm) {
  9375. continue;
  9376. }
  9377. if (isset($seen[$email])) {
  9378. continue;
  9379. }
  9380. $seen[$email] = true;
  9381. $out[] = $email;
  9382. }
  9383. return $out;
  9384. }
  9385. /**
  9386. * 下发通知:解析订单类型名称与评分比例文案
  9387. *
  9388. * @param array<string, mixed> $bundle
  9389. * @return array{order_type:string,score_weights:string}
  9390. */
  9391. protected function resolveIssueNotifyOrderTypeFromBundle(array $bundle): array
  9392. {
  9393. $orderType = '';
  9394. $scoreWeights = '';
  9395. $rule = null;
  9396. if (!empty($bundle['score_rule']) && is_array($bundle['score_rule'])) {
  9397. $rule = $bundle['score_rule'];
  9398. }
  9399. $pos = $bundle['pos'] ?? [];
  9400. $po0 = (is_array($pos) && isset($pos[0]) && is_array($pos[0])) ? $pos[0] : null;
  9401. if ($rule === null && is_array($po0)) {
  9402. $ruleId = (int)($po0['score_rule_id'] ?? 0);
  9403. if ($ruleId > 0) {
  9404. try {
  9405. $rule = ProcuremenSupplierScore::getRuleById($ruleId);
  9406. } catch (\Throwable $e) {
  9407. $rule = null;
  9408. }
  9409. }
  9410. if (!is_array($rule) || (int)($rule['id'] ?? 0) <= 0) {
  9411. $qw = (int)($po0['score_quality_weight'] ?? 0);
  9412. $pw = (int)($po0['score_price_weight'] ?? 0);
  9413. $lw = (int)($po0['score_lead_weight'] ?? 0);
  9414. if ($qw > 0 || $pw > 0 || $lw > 0) {
  9415. $rule = [
  9416. 'name' => trim((string)($po0['score_rule_name'] ?? '')),
  9417. 'quality_weight' => $qw,
  9418. 'price_weight' => $pw,
  9419. 'lead_weight' => $lw,
  9420. ];
  9421. }
  9422. }
  9423. }
  9424. if (is_array($rule)) {
  9425. $orderType = trim((string)($rule['name'] ?? ''));
  9426. $scoreWeights = $this->formatScoreRuleWeightsText($rule);
  9427. }
  9428. if ($orderType === '' && is_array($po0)) {
  9429. $orderType = trim((string)($po0['score_rule_name'] ?? ''));
  9430. }
  9431. return [
  9432. 'order_type' => $orderType,
  9433. 'score_weights' => $scoreWeights,
  9434. ];
  9435. }
  9436. /**
  9437. * 评分比例文案:质量30%、价格50%、交货20%
  9438. *
  9439. * @param array{quality_weight?:mixed,price_weight?:mixed,lead_weight?:mixed} $rule
  9440. */
  9441. protected function formatScoreRuleWeightsText(array $rule): string
  9442. {
  9443. return ProcuremenFormat::scoreRuleWeightsText($rule);
  9444. }
  9445. /**
  9446. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  9447. *
  9448. * @param array<int, array<string, mixed>> $mergeRows
  9449. * @return array<string, mixed>
  9450. */
  9451. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  9452. {
  9453. $head = $mergeRows[0] ?? [];
  9454. $isMerge = count($mergeRows) > 1;
  9455. $orderSet = [];
  9456. foreach ($mergeRows as $r) {
  9457. if (!is_array($r)) {
  9458. continue;
  9459. }
  9460. $dh = trim((string)($r['CCYDH'] ?? ''));
  9461. if ($dh !== '') {
  9462. $orderSet[$dh] = true;
  9463. }
  9464. }
  9465. $multiOrder = count($orderSet) > 1;
  9466. // 多订单:明细块自带各订单头,避免模版里 {ccydh}/{cyjmc} 只显示第一单
  9467. $ccydh = $multiOrder ? '' : (isset($head['CCYDH']) ? (string)$head['CCYDH'] : '');
  9468. $cyjmc = $multiOrder ? '' : (isset($head['CYJMC']) ? (string)$head['CYJMC'] : '');
  9469. return [
  9470. 'ccydh' => $ccydh,
  9471. 'cyjmc' => $cyjmc,
  9472. 'cgymc_single' => $multiOrder ? '' : trim((string)($head['CGYMC'] ?? '')),
  9473. 'is_merge' => $isMerge,
  9474. 'multi_order' => $multiOrder,
  9475. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  9476. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  9477. 'deadline' => $sysRqNotify,
  9478. 'order_type' => '',
  9479. 'score_weights' => '',
  9480. ];
  9481. }
  9482. /**
  9483. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  9484. *
  9485. * @param array<string, mixed> $data
  9486. */
  9487. protected function logIssueNotifyDebug(string $type, array $data): void
  9488. {
  9489. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  9490. return;
  9491. }
  9492. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  9493. }
  9494. protected function ensurePurchaseEmailSendLogTableOnce(): void
  9495. {
  9496. try {
  9497. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  9498. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  9499. return;
  9500. } catch (\Throwable $e) {
  9501. }
  9502. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  9503. if (is_file($sqlFile)) {
  9504. $sql = file_get_contents($sqlFile);
  9505. if (is_string($sql) && $sql !== '') {
  9506. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  9507. $stmt = trim($stmt);
  9508. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  9509. continue;
  9510. }
  9511. try {
  9512. Db::execute($stmt);
  9513. } catch (\Throwable $ignore) {
  9514. }
  9515. }
  9516. }
  9517. }
  9518. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  9519. }
  9520. /**
  9521. * @param array<string, mixed> $row
  9522. */
  9523. protected function persistEmailSendLog(array $row): void
  9524. {
  9525. try {
  9526. $this->ensurePurchaseEmailSendLogTableOnce();
  9527. } catch (\Throwable $e) {
  9528. return;
  9529. }
  9530. list($adminId, $adminName) = $this->GetUseName();
  9531. $cut = function ($s, $max) {
  9532. $s = (string)$s;
  9533. if (function_exists('mb_substr')) {
  9534. return mb_substr($s, 0, $max, 'UTF-8');
  9535. }
  9536. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  9537. };
  9538. $data = [
  9539. 'from_email' => $cut($row['from_email'] ?? '', 128),
  9540. 'to_email' => $cut($row['to_email'] ?? '', 128),
  9541. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  9542. 'scene' => $cut($this->normalizeEmailLogSceneForStore((string)($row['scene'] ?? '')), 64),
  9543. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  9544. 'company_name' => $cut($row['company_name'] ?? '', 128),
  9545. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  9546. 'status' => !empty($row['status']) ? 1 : 0,
  9547. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  9548. 'admin_id' => (int)$adminId,
  9549. 'admin_name' => $cut($adminName, 64),
  9550. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  9551. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  9552. 'createtime' => date('Y-m-d H:i:s'),
  9553. ];
  9554. try {
  9555. Db::table('purchase_email_send_log')->insert($data);
  9556. } catch (\Throwable $e) {
  9557. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  9558. }
  9559. }
  9560. /**
  9561. * 邮件日志场景:库内统一存中文;兼容历史英文码
  9562. *
  9563. * @return array<string, string>
  9564. */
  9565. protected function emailLogSceneLabelMap(): array
  9566. {
  9567. return ProcuremenFormat::emailLogSceneLabelMap();
  9568. }
  9569. /** 写入邮件日志前:英文场景码转中文;已是中文则原样 */
  9570. protected function normalizeEmailLogSceneForStore(string $scene): string
  9571. {
  9572. return ProcuremenFormat::normalizeEmailLogSceneForStore($scene);
  9573. }
  9574. protected function formatEmailLogSceneText(string $scene): string
  9575. {
  9576. return ProcuremenFormat::emailLogSceneText($scene);
  9577. }
  9578. /**
  9579. * 邮件发送日志列表
  9580. */
  9581. public function emailLog()
  9582. {
  9583. $this->relationSearch = false;
  9584. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  9585. $this->request->filter(['strip_tags', 'trim']);
  9586. $bakModel = $this->model;
  9587. $this->model = new \app\admin\model\Purchaseemailsendlog;
  9588. if ($this->request->isAjax()) {
  9589. $this->ensurePurchaseEmailSendLogTableOnce();
  9590. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  9591. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  9592. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  9593. $list = $this->model
  9594. ->where($where)
  9595. ->order($sortField, $orderDir)
  9596. ->paginate($limit);
  9597. $rows = [];
  9598. foreach ($list->items() as $item) {
  9599. $row = is_array($item) ? $item : $item->toArray();
  9600. $scene = trim((string)($row['scene'] ?? ''));
  9601. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  9602. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  9603. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  9604. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  9605. $rows[] = $row;
  9606. }
  9607. $this->model = $bakModel;
  9608. return json(['total' => $list->total(), 'rows' => $rows]);
  9609. }
  9610. $this->model = $bakModel;
  9611. return $this->view->fetch('procuremen/emaillog');
  9612. }
  9613. /**
  9614. * 协助下发弹窗(选多家供应商并通知)
  9615. */
  9616. public function pickReview()
  9617. {
  9618. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  9619. $this->error(__('You have no permission'));
  9620. }
  9621. if ($this->request->isPost()) {
  9622. $this->error('请使用弹窗内「确认下发」提交');
  9623. }
  9624. $this->view->assign('pickMode', 1);
  9625. $this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
  9626. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  9627. }
  9628. /**
  9629. * 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
  9630. */
  9631. protected function ensurePurchaseOrderNotifySalesmanColumn(): void
  9632. {
  9633. static $done = false;
  9634. if ($done) {
  9635. return;
  9636. }
  9637. $done = true;
  9638. try {
  9639. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'notify_salesman'");
  9640. if (empty($cols)) {
  9641. Db::execute(
  9642. "ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
  9643. );
  9644. } else {
  9645. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  9646. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
  9647. Db::execute(
  9648. "ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
  9649. );
  9650. }
  9651. }
  9652. } catch (\Throwable $e) {
  9653. // ignore
  9654. }
  9655. }
  9656. /**
  9657. * 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
  9658. */
  9659. protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
  9660. {
  9661. static $done = false;
  9662. if ($done) {
  9663. return;
  9664. }
  9665. $done = true;
  9666. try {
  9667. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
  9668. if (empty($cols)) {
  9669. Db::execute(
  9670. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
  9671. );
  9672. }
  9673. } catch (\Throwable $e) {
  9674. // ignore
  9675. }
  9676. try {
  9677. $cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
  9678. if (empty($cols2)) {
  9679. Db::execute(
  9680. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
  9681. );
  9682. }
  9683. } catch (\Throwable $e) {
  9684. // ignore
  9685. }
  9686. }
  9687. /**
  9688. * 确保「采购确认通过/未通过」邮箱模版存在。
  9689. * title=说明;remark=邮箱通知;邮件主题由 resolveProcuremenEmailSubject 固定,不用 title。
  9690. */
  9691. protected function ensureConfirmResultEmailTemplates(): void
  9692. {
  9693. static $done = false;
  9694. if ($done) {
  9695. return;
  9696. }
  9697. $done = true;
  9698. $now = date('Y-m-d H:i:s');
  9699. $seeds = [
  9700. 'confirm_ok_email' => [
  9701. 'title' => '确认已通过通知',
  9702. 'content' => "您好,{company_name}:\n\n您参与的订单采购确认结果:已通过 已中标。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  9703. 'remark' => '邮箱通知',
  9704. ],
  9705. 'confirm_fail_email' => [
  9706. 'title' => '确认未通过通知',
  9707. 'content' => "您好,{company_name}:\n\n您参与的订单采购确认结果:未通过 未中标。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  9708. 'remark' => '邮箱通知',
  9709. ],
  9710. ];
  9711. try {
  9712. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  9713. } catch (\Throwable $e) {
  9714. return;
  9715. }
  9716. $colNames = [];
  9717. foreach ($cols as $c) {
  9718. if (!is_array($c)) {
  9719. continue;
  9720. }
  9721. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  9722. if ($n !== '') {
  9723. $colNames[$n] = true;
  9724. }
  9725. }
  9726. foreach ($seeds as $scene => $seed) {
  9727. try {
  9728. $row = Db::table('purchase_sms_template')->where('scene', $scene)->find();
  9729. } catch (\Throwable $e) {
  9730. continue;
  9731. }
  9732. if (is_array($row) && $row !== []) {
  9733. continue;
  9734. }
  9735. $data = [
  9736. 'scene' => $scene,
  9737. 'title' => $seed['title'],
  9738. 'content' => $seed['content'],
  9739. 'remark' => $seed['remark'],
  9740. 'status' => 1,
  9741. ];
  9742. if (isset($colNames['updatetime'])) {
  9743. $data['updatetime'] = $now;
  9744. }
  9745. if (isset($colNames['createtime'])) {
  9746. $data['createtime'] = $now;
  9747. }
  9748. try {
  9749. Db::table('purchase_sms_template')->insert($data);
  9750. } catch (\Throwable $e) {
  9751. // ignore
  9752. }
  9753. }
  9754. }
  9755. /**
  9756. * 确保「供应商询价通知」邮箱模版存在(查询询价-询价/发邮件;可在短信模版配置中修改)
  9757. */
  9758. protected function ensureRfqSupplierEmailTemplate(): void
  9759. {
  9760. static $done = false;
  9761. if ($done) {
  9762. return;
  9763. }
  9764. $done = true;
  9765. $content = "您好,{company_name}:\n\n"
  9766. . "您有新的协助采购询价需求,请登录平台查看并处理。\n\n"
  9767. . "需求编号:{ccydh}\n"
  9768. . "印件名称:{cyjmc}\n"
  9769. . "{process_lines}\n\n"
  9770. . "请在 {deadline} 前完成回复。\n\n"
  9771. . "平台链接:{platform_url}\n";
  9772. try {
  9773. $row = Db::table('purchase_sms_template')
  9774. ->where('scene', 'rfq_supplier_email')
  9775. ->find();
  9776. } catch (\Throwable $e) {
  9777. return;
  9778. }
  9779. $now = date('Y-m-d H:i:s');
  9780. if (is_array($row) && $row !== []) {
  9781. return;
  9782. }
  9783. try {
  9784. $data = [
  9785. 'scene' => 'rfq_supplier_email',
  9786. 'title' => '供应商询价通知',
  9787. 'content' => $content,
  9788. 'remark' => '查询询价-询价/发邮件通知供应商;模版名称作邮件主题',
  9789. 'status' => 1,
  9790. ];
  9791. try {
  9792. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  9793. } catch (\Throwable $e) {
  9794. $cols = [];
  9795. }
  9796. $colNames = [];
  9797. foreach ($cols as $c) {
  9798. if (!is_array($c)) {
  9799. continue;
  9800. }
  9801. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  9802. if ($n !== '') {
  9803. $colNames[$n] = true;
  9804. }
  9805. }
  9806. if (isset($colNames['updatetime'])) {
  9807. $data['updatetime'] = $now;
  9808. }
  9809. if (isset($colNames['createtime'])) {
  9810. $data['createtime'] = $now;
  9811. }
  9812. Db::table('purchase_sms_template')->insert($data);
  9813. } catch (\Throwable $e) {
  9814. // ignore
  9815. }
  9816. }
  9817. /**
  9818. * 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
  9819. */
  9820. protected function ensureRfqSalesmanEmailTemplate(): void
  9821. {
  9822. static $done = false;
  9823. if ($done) {
  9824. return;
  9825. }
  9826. $done = true;
  9827. $content = "您好,{contact_name}:\n\n"
  9828. . "有新的协助采购询价需求,请知悉。\n"
  9829. . "印件名称:{cyjmc}\n"
  9830. . "工序名称:{cgymc}\n"
  9831. . "本次数量:{this_quantity}\n"
  9832. . "供应商报价:\n{supplier_quotes}\n"
  9833. . "平台链接:{platform_url}\n"
  9834. . "需求发起人:{cywyxm}\n";
  9835. try {
  9836. $row = Db::table('purchase_sms_template')
  9837. ->where('scene', 'rfq_salesman_email')
  9838. ->find();
  9839. } catch (\Throwable $e) {
  9840. return;
  9841. }
  9842. $now = date('Y-m-d H:i:s');
  9843. if (is_array($row) && $row !== []) {
  9844. $old = (string)($row['content'] ?? '');
  9845. // 无报价表格 / 无平台链接 / 链接不在「需求发起人」上方时,同步默认文案
  9846. $urlPos = strpos($old, '{platform_url}');
  9847. $cywyPos = strpos($old, '需求发起人');
  9848. $linkNotAboveStarter = ($urlPos === false)
  9849. || ($cywyPos !== false && $urlPos > $cywyPos);
  9850. $needMigrate = (strpos($old, '{supplier_quotes}') === false)
  9851. || (strpos($old, '供应商:{supplier_name}') !== false)
  9852. || $linkNotAboveStarter;
  9853. if ($needMigrate) {
  9854. $data = ['content' => $content];
  9855. if (trim((string)($row['title'] ?? '')) === '' || trim((string)($row['title'] ?? '')) === '询价通知') {
  9856. $data['title'] = '业务员询价通知';
  9857. }
  9858. try {
  9859. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
  9860. if (!empty($cols)) {
  9861. $data['updatetime'] = $now;
  9862. }
  9863. } catch (\Throwable $e) {
  9864. }
  9865. try {
  9866. Db::table('purchase_sms_template')
  9867. ->where('id', (int)($row['id'] ?? 0))
  9868. ->update($data);
  9869. } catch (\Throwable $e) {
  9870. }
  9871. }
  9872. return;
  9873. }
  9874. try {
  9875. $data = [
  9876. 'scene' => 'rfq_salesman_email',
  9877. 'title' => '业务员询价通知',
  9878. 'content' => $content,
  9879. 'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
  9880. 'status' => 1,
  9881. ];
  9882. try {
  9883. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  9884. } catch (\Throwable $e) {
  9885. $cols = [];
  9886. }
  9887. $colNames = [];
  9888. foreach ($cols as $c) {
  9889. if (!is_array($c)) {
  9890. continue;
  9891. }
  9892. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  9893. if ($n !== '') {
  9894. $colNames[$n] = true;
  9895. }
  9896. }
  9897. if (isset($colNames['updatetime'])) {
  9898. $data['updatetime'] = $now;
  9899. }
  9900. if (isset($colNames['createtime'])) {
  9901. $data['createtime'] = $now;
  9902. }
  9903. Db::table('purchase_sms_template')->insert($data);
  9904. } catch (\Throwable $e) {
  9905. // ignore
  9906. }
  9907. }
  9908. /**
  9909. * 通知业务员邮件:供应商报价明细行(仅名称+单价)
  9910. *
  9911. * @return array<int, array{name:string,amount:string}>
  9912. */
  9913. protected function loadRfqSalesmanSupplierQuoteRows(int $sid, string $supplierRaw = ''): array
  9914. {
  9915. $list = [];
  9916. $seen = [];
  9917. try {
  9918. $rows = Db::table('purchase_order_detail')
  9919. ->where('scydgy_id', $sid)
  9920. ->field('company_name,amount')
  9921. ->order('id', 'asc')
  9922. ->select();
  9923. if (is_array($rows)) {
  9924. foreach ($rows as $r) {
  9925. if (!is_array($r)) {
  9926. continue;
  9927. }
  9928. $cn = trim((string)($r['company_name'] ?? ''));
  9929. if ($cn === '' || isset($seen[$cn])) {
  9930. continue;
  9931. }
  9932. $seen[$cn] = true;
  9933. $amount = trim((string)($r['amount'] ?? ''));
  9934. $list[] = [
  9935. 'name' => $cn,
  9936. 'amount' => $amount !== '' ? $amount : '未报价',
  9937. ];
  9938. }
  9939. }
  9940. } catch (\Throwable $e) {
  9941. }
  9942. if ($list === [] && $supplierRaw !== '') {
  9943. foreach ($this->splitRfqSalesmanNames($supplierRaw) as $cn) {
  9944. if ($cn === '' || isset($seen[$cn])) {
  9945. continue;
  9946. }
  9947. $seen[$cn] = true;
  9948. $list[] = [
  9949. 'name' => $cn,
  9950. 'amount' => '未报价',
  9951. ];
  9952. }
  9953. }
  9954. return $list;
  9955. }
  9956. /**
  9957. * 通知业务员邮件:供应商报价 HTML 表格(名称+单价,不含时间)
  9958. */
  9959. protected function buildRfqSalesmanSupplierQuotesHtml(int $sid, string $supplierRaw = ''): string
  9960. {
  9961. $rows = $this->loadRfqSalesmanSupplierQuoteRows($sid, $supplierRaw);
  9962. if ($rows === []) {
  9963. return '<p style="margin:8px 0;color:#888;">暂无报价</p>';
  9964. }
  9965. $html = '<table cellpadding="0" cellspacing="0" border="1" '
  9966. . 'style="border-collapse:collapse;border-color:#ddd;width:100%;max-width:560px;font-size:14px;margin:8px 0;">'
  9967. . '<thead><tr style="background:#f5f5f5;">'
  9968. . '<th style="padding:8px 10px;text-align:center;width:56px;">序号</th>'
  9969. . '<th style="padding:8px 10px;text-align:left;">供应商名称</th>'
  9970. . '<th style="padding:8px 10px;text-align:center;width:100px;">单价</th>'
  9971. . '</tr></thead><tbody>';
  9972. foreach ($rows as $i => $row) {
  9973. $html .= '<tr>'
  9974. . '<td style="padding:8px 10px;text-align:center;">' . ($i + 1) . '</td>'
  9975. . '<td style="padding:8px 10px;">' . htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8') . '</td>'
  9976. . '<td style="padding:8px 10px;text-align:center;">' . htmlspecialchars($row['amount'], ENT_QUOTES, 'UTF-8') . '</td>'
  9977. . '</tr>';
  9978. }
  9979. $html .= '</tbody></table>';
  9980. return $html;
  9981. }
  9982. /**
  9983. * 询价多选字段:数组或字符串统一为顿号拼接
  9984. *
  9985. * @param mixed $raw
  9986. */
  9987. protected function joinRfqMultiSelectValues($raw): string
  9988. {
  9989. $parts = [];
  9990. if (is_array($raw)) {
  9991. foreach ($raw as $item) {
  9992. if (is_array($item)) {
  9993. continue;
  9994. }
  9995. $v = trim((string)$item);
  9996. if ($v !== '') {
  9997. $parts[] = $v;
  9998. }
  9999. }
  10000. } else {
  10001. $s = trim((string)$raw);
  10002. if ($s !== '') {
  10003. foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
  10004. $v = trim((string)$piece);
  10005. if ($v !== '') {
  10006. $parts[] = $v;
  10007. }
  10008. }
  10009. }
  10010. }
  10011. $parts = array_values(array_unique($parts));
  10012. return implode('、', $parts);
  10013. }
  10014. /**
  10015. * 新增询价:可选供应商名称(仅落库记录,不发通知)
  10016. *
  10017. * @return string[]
  10018. */
  10019. protected function loadRfqSupplierNameOptions(): array
  10020. {
  10021. $out = [];
  10022. try {
  10023. $rows = Db::table('customer')
  10024. ->where(function ($q) {
  10025. $q->where('status', 1)
  10026. ->whereOr('status', '1')
  10027. ->whereOr('status', '')
  10028. ->whereNull('status');
  10029. })
  10030. ->order('id', 'desc')
  10031. ->column('company_name');
  10032. } catch (\Throwable $e) {
  10033. return [];
  10034. }
  10035. if (!is_array($rows)) {
  10036. return [];
  10037. }
  10038. foreach ($rows as $name) {
  10039. $name = trim((string)$name);
  10040. if ($name === '' || isset($out[$name])) {
  10041. continue;
  10042. }
  10043. $out[$name] = $name;
  10044. }
  10045. return array_values($out);
  10046. }
  10047. /**
  10048. * 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
  10049. */
  10050. protected function rfqNotifySalesmanAuthGroupId(): int
  10051. {
  10052. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  10053. if ($id > 0) {
  10054. return $id;
  10055. }
  10056. try {
  10057. $found = Db::name('auth_group')
  10058. ->where('name', '业务员')
  10059. ->where('status', 'normal')
  10060. ->order('id', 'asc')
  10061. ->value('id');
  10062. $id = (int)$found;
  10063. } catch (\Throwable $e) {
  10064. $id = 0;
  10065. }
  10066. return $id > 0 ? $id : 12;
  10067. }
  10068. /**
  10069. * 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
  10070. *
  10071. * @return string[]
  10072. */
  10073. protected function loadRfqSalesmanNameOptions(): array
  10074. {
  10075. $out = [];
  10076. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  10077. $name = trim((string)($row['name'] ?? ''));
  10078. if ($name !== '') {
  10079. $out[] = $name;
  10080. }
  10081. }
  10082. return $out;
  10083. }
  10084. /**
  10085. * 业务员角色组下管理员:姓名、邮箱、手机
  10086. *
  10087. * @return array<int, array{name:string,email:string,mobile:string}>
  10088. */
  10089. protected function loadRfqSalesmanContactOptions(): array
  10090. {
  10091. $out = [];
  10092. $seen = [];
  10093. $groupId = $this->rfqNotifySalesmanAuthGroupId();
  10094. if ($groupId <= 0) {
  10095. return [];
  10096. }
  10097. try {
  10098. $adminIds = Db::name('auth_group_access')
  10099. ->where('group_id', $groupId)
  10100. ->column('uid');
  10101. } catch (\Throwable $e) {
  10102. return [];
  10103. }
  10104. $adminIds = is_array($adminIds)
  10105. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  10106. : [];
  10107. if ($adminIds === []) {
  10108. return [];
  10109. }
  10110. try {
  10111. $rows = Db::name('admin')
  10112. ->where('status', 'normal')
  10113. ->where('id', 'in', $adminIds)
  10114. ->order('id', 'asc')
  10115. ->field('id,nickname,username,email,mobile')
  10116. ->select();
  10117. } catch (\Throwable $e) {
  10118. return [];
  10119. }
  10120. if (!is_array($rows)) {
  10121. return [];
  10122. }
  10123. foreach ($rows as $row) {
  10124. if (!is_array($row)) {
  10125. continue;
  10126. }
  10127. $name = trim((string)($row['nickname'] ?? ''));
  10128. if ($name === '') {
  10129. $name = trim((string)($row['username'] ?? ''));
  10130. }
  10131. if ($name === '' || isset($seen[$name])) {
  10132. continue;
  10133. }
  10134. $seen[$name] = true;
  10135. $out[] = [
  10136. 'name' => $name,
  10137. 'email' => trim((string)($row['email'] ?? '')),
  10138. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  10139. ];
  10140. }
  10141. return $out;
  10142. }
  10143. /**
  10144. * 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
  10145. *
  10146. * @return string[]
  10147. */
  10148. protected function loadRfqDeptNameOptions(): array
  10149. {
  10150. $out = [];
  10151. // ERP 承揽部门(主来源)
  10152. try {
  10153. $vals = Db::table('mcyd')
  10154. ->where('CCLBMMC', '<>', '')
  10155. ->whereNotNull('CCLBMMC')
  10156. ->distinct(true)
  10157. ->limit(300)
  10158. ->column('CCLBMMC');
  10159. } catch (\Throwable $e) {
  10160. $vals = [];
  10161. }
  10162. if (is_array($vals)) {
  10163. foreach ($vals as $v) {
  10164. $v = trim((string)$v);
  10165. if ($v === '' || isset($out[$v])) {
  10166. continue;
  10167. }
  10168. $out[$v] = $v;
  10169. }
  10170. }
  10171. // 手工询价历史部门补全
  10172. try {
  10173. $poVals = Db::table('purchase_order')
  10174. ->where('CCLBMMC', '<>', '')
  10175. ->whereNotNull('CCLBMMC')
  10176. ->distinct(true)
  10177. ->limit(200)
  10178. ->column('CCLBMMC');
  10179. } catch (\Throwable $e) {
  10180. $poVals = [];
  10181. }
  10182. if (is_array($poVals)) {
  10183. foreach ($poVals as $v) {
  10184. $v = trim((string)$v);
  10185. if ($v === '' || isset($out[$v])) {
  10186. continue;
  10187. }
  10188. $out[$v] = $v;
  10189. }
  10190. }
  10191. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  10192. if (!isset($out[$preset])) {
  10193. $out[$preset] = $preset;
  10194. }
  10195. }
  10196. $list = array_values($out);
  10197. // 常用部门靠前
  10198. usort($list, static function ($a, $b) {
  10199. $weight = [
  10200. '营销中心' => 1,
  10201. '业务部' => 2,
  10202. '市场部' => 3,
  10203. '外贸部' => 4,
  10204. '新华技术业务部' => 5,
  10205. ];
  10206. $wa = $weight[$a] ?? 100;
  10207. $wb = $weight[$b] ?? 100;
  10208. if ($wa !== $wb) {
  10209. return $wa <=> $wb;
  10210. }
  10211. return strcmp((string)$a, (string)$b);
  10212. });
  10213. return $list;
  10214. }
  10215. /**
  10216. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  10217. */
  10218. public function add()
  10219. {
  10220. if ($this->request->isPost()) {
  10221. $params = $this->request->post('row/a');
  10222. if (!is_array($params)) {
  10223. $this->error(__('Parameter %s can not be empty', ''));
  10224. }
  10225. [, $adminName] = $this->GetUseName();
  10226. $params['cywyxm'] = $adminName;
  10227. try {
  10228. $sid = $this->saveManualPickOrder($params);
  10229. } catch (\InvalidArgumentException $e) {
  10230. $this->error($e->getMessage());
  10231. } catch (\Throwable $e) {
  10232. $this->error($e->getMessage());
  10233. }
  10234. $this->success('新增成功', '', [
  10235. 'scydgy_id' => $sid,
  10236. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  10237. ]);
  10238. }
  10239. $this->ensurePurchaseOrderNotifySalesmanColumn();
  10240. [, $adminName] = $this->GetUseName();
  10241. $this->view->assign('adminNickname', $adminName);
  10242. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  10243. $this->view->assign('defaultCclbmmc', '营销中心');
  10244. $this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
  10245. $this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
  10246. $this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
  10247. return $this->view->fetch();
  10248. }
  10249. /**
  10250. * 业务员新增进度查询(手工询价;有查询权限看全部,含手机端新增且未通知业务员的)
  10251. */
  10252. public function rfqlist()
  10253. {
  10254. $this->relationSearch = false;
  10255. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ';
  10256. $this->request->filter(['strip_tags', 'trim']);
  10257. $this->ensurePurchaseOrderNotifySalesmanColumn();
  10258. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  10259. $this->ensureRfqSalesmanEmailTemplate();
  10260. $this->ensureRfqSupplierEmailTemplate();
  10261. if ($this->request->isAjax()) {
  10262. try {
  10263. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  10264. $limit = max(10, min(500, (int)$limit));
  10265. $filterYm = trim((string)$this->request->param('filter_ym', ''));
  10266. if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
  10267. $filterYm = date('Y-m');
  10268. }
  10269. $applyFilters = function ($query) use ($where, $filterYm) {
  10270. $query->where('scydgy_id', '<', 0);
  10271. $this->applyPurchaseOrderNotDeletedWhere($query);
  10272. // 查询询价:有菜单权限即可看全部手工单(含手机端新增、尚未通知业务员的)
  10273. $this->applyRfqListMonthFilter($query, $filterYm);
  10274. if (!empty($where)) {
  10275. // 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
  10276. $safeWhere = [];
  10277. $skipFields = [
  10278. 'supplier_name' => true,
  10279. 'progress_text' => true,
  10280. 'createtime_text' => true,
  10281. 'notify_time_text' => true,
  10282. 'can_notify_salesman' => true,
  10283. 'has_issued' => true,
  10284. 'has_quoted' => true,
  10285. ];
  10286. foreach ((array)$where as $cond) {
  10287. if (!is_array($cond) || !isset($cond[0])) {
  10288. continue;
  10289. }
  10290. $field = (string)$cond[0];
  10291. $fieldBase = (string)preg_replace('/\|.*$/', '', $field);
  10292. $fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
  10293. if (isset($skipFields[$fieldBase])) {
  10294. continue;
  10295. }
  10296. if ($fieldBase === 'supplier_name') {
  10297. continue;
  10298. }
  10299. $safeWhere[] = $cond;
  10300. }
  10301. if ($safeWhere !== []) {
  10302. $query->where($safeWhere);
  10303. }
  10304. }
  10305. };
  10306. $countQuery = Db::table('purchase_order');
  10307. $applyFilters($countQuery);
  10308. $total = (int)$countQuery->count();
  10309. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  10310. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  10311. $listQuery = Db::table('purchase_order');
  10312. $applyFilters($listQuery);
  10313. $rows = $listQuery
  10314. ->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')
  10315. ->order($sortField, $orderDir)
  10316. ->limit($offset, $limit)
  10317. ->select();
  10318. if (!is_array($rows)) {
  10319. $rows = [];
  10320. }
  10321. $sidList = [];
  10322. foreach ($rows as $r) {
  10323. if (!is_array($r)) {
  10324. continue;
  10325. }
  10326. $sid = (int)($r['scydgy_id'] ?? 0);
  10327. if ($sid < 0) {
  10328. $sidList[$sid] = true;
  10329. }
  10330. }
  10331. $issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
  10332. $quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
  10333. $out = [];
  10334. foreach ($rows as $r) {
  10335. if (!is_array($r)) {
  10336. continue;
  10337. }
  10338. $sid = (int)($r['scydgy_id'] ?? 0);
  10339. if ($sid >= 0) {
  10340. continue;
  10341. }
  10342. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  10343. if ($createdText === '') {
  10344. $createdText = trim((string)($r['dStamp'] ?? ''));
  10345. }
  10346. $notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
  10347. $supplier = trim((string)($r['cGzzxMc'] ?? ''));
  10348. if ($supplier === '') {
  10349. $supplier = trim((string)($r['pick_company_name'] ?? ''));
  10350. }
  10351. $hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
  10352. || isset($issuedSidSet[$sid]);
  10353. $hasQuoted = isset($quotedSidSet[$sid]);
  10354. $salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
  10355. $canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
  10356. $out[] = [
  10357. 'id' => (int)($r['id'] ?? 0),
  10358. 'scydgy_id' => $sid,
  10359. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  10360. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  10361. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  10362. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  10363. 'CDW' => trim((string)($r['CDW'] ?? '')),
  10364. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  10365. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  10366. 'CDF' => trim((string)($r['CDF'] ?? '')),
  10367. 'supplier_name' => $supplier,
  10368. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  10369. 'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
  10370. 'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
  10371. 'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
  10372. 'notify_time_text' => $notifyTimeText,
  10373. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  10374. 'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
  10375. 'has_issued' => $hasIssued ? 1 : 0,
  10376. 'has_quoted' => $hasQuoted ? 1 : 0,
  10377. 'can_notify_salesman' => $canNotifySalesman,
  10378. 'createtime' => $r['createtime'] ?? null,
  10379. 'createtime_text' => $createdText,
  10380. ];
  10381. }
  10382. return json(['total' => $total, 'rows' => $out]);
  10383. } catch (\Throwable $e) {
  10384. Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
  10385. return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
  10386. }
  10387. }
  10388. $sidebar = $this->loadRfqSidebarYearMonths();
  10389. $defaultYm = $this->resolveRfqListDefaultYm($sidebar);
  10390. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  10391. [, $adminName] = $this->GetUseName();
  10392. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  10393. $this->view->assign('adminNickname', $adminName);
  10394. $this->view->assign('defaultYm', $defaultYm);
  10395. $this->view->assign('sidebarYearMonths', $sidebar);
  10396. return $this->view->fetch('procuremen/rfqlist');
  10397. }
  10398. /**
  10399. * 列表默认月份:当月有数据用当月,否则取最近有数据的月份
  10400. *
  10401. * @param array<int, array{year:string, months:array}> $sidebar
  10402. */
  10403. protected function resolveRfqListDefaultYm(array $sidebar): string
  10404. {
  10405. $current = date('Y-m');
  10406. $yms = $this->flattenProcuremenSidebarYms($sidebar);
  10407. if (in_array($current, $yms, true)) {
  10408. return $current;
  10409. }
  10410. if ($yms !== []) {
  10411. rsort($yms, SORT_STRING);
  10412. return (string)$yms[0];
  10413. }
  10414. return $current;
  10415. }
  10416. /**
  10417. * 手工询价列表左侧月份(按 createtime / dStamp)
  10418. *
  10419. * @return array<int, array{year:string, months:array}>
  10420. */
  10421. protected function loadRfqSidebarYearMonths(): array
  10422. {
  10423. $ymSet = [];
  10424. try {
  10425. $q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
  10426. $this->applyPurchaseOrderNotDeletedWhere($q);
  10427. $rows = $q->field('createtime,dStamp')->limit(5000)->select();
  10428. } catch (\Throwable $e) {
  10429. $rows = [];
  10430. }
  10431. if (!is_array($rows)) {
  10432. $rows = [];
  10433. }
  10434. foreach ($rows as $r) {
  10435. if (!is_array($r)) {
  10436. continue;
  10437. }
  10438. $t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  10439. if ($t === '') {
  10440. $t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
  10441. }
  10442. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  10443. $ymSet[$m[1] . '-' . $m[2]] = true;
  10444. }
  10445. }
  10446. return $this->buildYearMonthSidebar(array_keys($ymSet));
  10447. }
  10448. /**
  10449. * 手工询价可见范围(用于详情/操作校验):
  10450. * 超管、具备「查询询价」权限、需求发起人、通知业务员 → 可见
  10451. * 列表页本身不再按发起人/通知过滤,避免手机端新增后后台看不到。
  10452. */
  10453. protected function applyManualRfqViewerWhere($query): void
  10454. {
  10455. if ($this->auth->isSuperAdmin() || $this->hasProcuremenPerm(['rfqlist'])) {
  10456. return;
  10457. }
  10458. [, $adminName] = $this->GetUseName();
  10459. $adminName = trim((string)$adminName);
  10460. if ($adminName === '') {
  10461. $query->whereRaw('1 = 0');
  10462. return;
  10463. }
  10464. // 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
  10465. $query->where(function ($q) use ($adminName) {
  10466. $q->where('cywyxm', $adminName)
  10467. ->whereOr('notify_salesman', $adminName)
  10468. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  10469. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  10470. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  10471. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  10472. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  10473. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  10474. });
  10475. }
  10476. /**
  10477. * 当前用户是否可查看/操作该手工询价单
  10478. */
  10479. protected function canViewManualRfqOrder(array $po): bool
  10480. {
  10481. if ($this->auth->isSuperAdmin()) {
  10482. return true;
  10483. }
  10484. // 有查询询价权限则可操作全部手工询价(询价/查看报价/通知业务员等)
  10485. if ($this->hasProcuremenPerm(['rfqlist'])) {
  10486. return true;
  10487. }
  10488. [, $adminName] = $this->GetUseName();
  10489. $adminName = trim((string)$adminName);
  10490. if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
  10491. return true;
  10492. }
  10493. if ($adminName !== '') {
  10494. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  10495. if ($n === $adminName) {
  10496. return true;
  10497. }
  10498. }
  10499. }
  10500. return false;
  10501. }
  10502. /**
  10503. * 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
  10504. */
  10505. protected function applyRfqListMonthFilter($query, string $ym): void
  10506. {
  10507. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  10508. $ym = date('Y-m');
  10509. }
  10510. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  10511. // 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
  10512. $query->whereRaw(
  10513. "("
  10514. . "CASE "
  10515. . "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  10516. . "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
  10517. . "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
  10518. . "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  10519. . "THEN TRIM(CAST(createtime AS CHAR(32))) "
  10520. . "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
  10521. . "END"
  10522. . ") LIKE '{$ymEsc}-%'"
  10523. );
  10524. }
  10525. /**
  10526. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  10527. */
  10528. public function rfqlistDetails()
  10529. {
  10530. return $this->details();
  10531. }
  10532. /**
  10533. * 查询询价 — 弹窗:可选通知业务员名单(勾选后确认通知)
  10534. */
  10535. public function rfqnotifysalesmen()
  10536. {
  10537. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman'])) {
  10538. $this->error(__('You have no permission'));
  10539. }
  10540. $this->ensurePurchaseOrderNotifySalesmanColumn();
  10541. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  10542. $sid = (int)$this->request->param('scydgy_id', 0);
  10543. if ($sid >= 0) {
  10544. $this->error('仅支持手工新增询价单');
  10545. }
  10546. $po = $this->loadManualRfqOrderForNotify($sid);
  10547. $selectedMap = [];
  10548. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  10549. $selectedMap[$n] = true;
  10550. }
  10551. $list = [];
  10552. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  10553. $name = trim((string)($row['name'] ?? ''));
  10554. if ($name === '') {
  10555. continue;
  10556. }
  10557. $email = trim((string)($row['email'] ?? ''));
  10558. $mobile = trim((string)($row['mobile'] ?? ''));
  10559. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  10560. $list[] = [
  10561. 'name' => $name,
  10562. 'email' => $email,
  10563. 'mobile' => $mobile,
  10564. 'can_select' => $hasEmail ? 1 : 0,
  10565. 'checked' => (!empty($selectedMap[$name]) && $hasEmail) ? 1 : 0,
  10566. ];
  10567. }
  10568. $canNotify = $this->canRfqNotifySalesman($po);
  10569. $this->success('', null, [
  10570. 'scydgy_id' => $sid,
  10571. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  10572. 'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
  10573. 'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
  10574. 'can_notify_salesman' => $canNotify ? 1 : 0,
  10575. 'list' => $list,
  10576. ]);
  10577. }
  10578. /**
  10579. * 查询询价 — 补加通知业务员可选名单
  10580. */
  10581. public function rfqsalesmanoptions()
  10582. {
  10583. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen'])) {
  10584. $this->error(__('You have no permission'));
  10585. }
  10586. $out = [];
  10587. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  10588. $email = trim((string)($row['email'] ?? ''));
  10589. $mobile = trim((string)($row['mobile'] ?? ''));
  10590. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  10591. $out[] = [
  10592. 'name' => (string)($row['name'] ?? ''),
  10593. 'email' => $email,
  10594. 'mobile' => $mobile,
  10595. 'can_select' => $hasEmail ? 1 : 0,
  10596. ];
  10597. }
  10598. $this->success('', null, ['list' => $out]);
  10599. }
  10600. /**
  10601. * 查询询价 — 补加通知业务员(合并更新 notify_salesman)
  10602. */
  10603. public function rfqappendsalesmen()
  10604. {
  10605. if (!$this->request->isPost()) {
  10606. $this->error(__('Invalid parameters'));
  10607. }
  10608. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen'])) {
  10609. $this->error(__('You have no permission'));
  10610. }
  10611. $this->ensurePurchaseOrderNotifySalesmanColumn();
  10612. $sid = (int)$this->request->post('scydgy_id', 0);
  10613. if ($sid >= 0) {
  10614. $this->error('仅支持手工新增询价单');
  10615. }
  10616. $po = $this->loadManualRfqOrderForNotify($sid);
  10617. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  10618. $this->error('订单已完结,无法添加业务员');
  10619. }
  10620. $raw = $this->request->post('salesmen/a', []);
  10621. if (!is_array($raw) || $raw === []) {
  10622. $salesmenJson = $this->request->post('salesmen_json', '');
  10623. if (is_string($salesmenJson) && $salesmenJson !== '') {
  10624. $decoded = json_decode($salesmenJson, true);
  10625. $raw = is_array($decoded) ? $decoded : [];
  10626. }
  10627. }
  10628. $addNames = [];
  10629. foreach ((array)$raw as $item) {
  10630. if (is_array($item)) {
  10631. $n = trim((string)($item['name'] ?? ''));
  10632. } else {
  10633. $n = trim((string)$item);
  10634. }
  10635. if ($n !== '') {
  10636. $addNames[] = $n;
  10637. }
  10638. }
  10639. $addNames = array_values(array_unique($addNames));
  10640. if ($addNames === []) {
  10641. $this->error('请选择要添加的业务员');
  10642. }
  10643. $allowedOptions = $this->loadRfqSalesmanContactOptions();
  10644. $allowedMap = [];
  10645. foreach ($allowedOptions as $opt) {
  10646. $n = trim((string)($opt['name'] ?? ''));
  10647. if ($n === '') {
  10648. continue;
  10649. }
  10650. $email = trim((string)($opt['email'] ?? ''));
  10651. $allowedMap[$n] = ($email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL));
  10652. }
  10653. foreach ($addNames as $n) {
  10654. if (!array_key_exists($n, $allowedMap)) {
  10655. $this->error('业务员不在可选名单中:' . $n);
  10656. }
  10657. if (!$allowedMap[$n]) {
  10658. $this->error('业务员未填写有效邮箱,无法添加:' . $n);
  10659. }
  10660. }
  10661. $existingRaw = trim((string)($po['notify_salesman'] ?? ''));
  10662. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  10663. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  10664. try {
  10665. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['notify_salesman' => $mergedStr]);
  10666. } catch (\Throwable $e) {
  10667. $this->error('保存失败:' . $e->getMessage());
  10668. }
  10669. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  10670. $this->addOrderLog($sid, 'rfq_append_salesman', '添加通知业务员:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  10671. $this->success('已添加业务员', null, [
  10672. 'scydgy_id' => $sid,
  10673. 'notify_salesman' => $mergedStr,
  10674. 'added_count' => count($addNames),
  10675. ]);
  10676. }
  10677. /**
  10678. * 查询询价 — 勾选业务员后邮箱通知(salesmen_json)
  10679. */
  10680. public function rfqnotifysalesman()
  10681. {
  10682. if (!$this->request->isPost()) {
  10683. $this->error(__('Invalid parameters'));
  10684. }
  10685. if (!$this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen'])) {
  10686. $this->error(__('You have no permission'));
  10687. }
  10688. $this->ensurePurchaseOrderNotifySalesmanColumn();
  10689. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  10690. $sid = (int)$this->request->post('scydgy_id', 0);
  10691. if ($sid >= 0) {
  10692. $this->error('仅支持手工新增询价单');
  10693. }
  10694. $po = $this->loadManualRfqOrderForNotify($sid);
  10695. $this->assertRfqCanNotifySalesman($po);
  10696. $raw = $this->request->post('salesmen/a', []);
  10697. if (!is_array($raw) || $raw === []) {
  10698. $salesmenJson = $this->request->post('salesmen_json', '');
  10699. if (is_string($salesmenJson) && $salesmenJson !== '') {
  10700. $decoded = json_decode($salesmenJson, true);
  10701. $raw = is_array($decoded) ? $decoded : [];
  10702. }
  10703. }
  10704. // 兼容旧参数:notify_all / 单人 name
  10705. if ((!is_array($raw) || $raw === []) && (int)$this->request->post('notify_all', 0) === 1) {
  10706. $raw = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  10707. }
  10708. if ((!is_array($raw) || $raw === [])) {
  10709. $oneName = trim((string)$this->request->post('name', ''));
  10710. if ($oneName !== '') {
  10711. $raw = [$oneName];
  10712. }
  10713. }
  10714. $selectedNames = [];
  10715. foreach ((array)$raw as $item) {
  10716. if (is_array($item)) {
  10717. $n = trim((string)($item['name'] ?? ''));
  10718. } else {
  10719. $n = trim((string)$item);
  10720. }
  10721. if ($n !== '') {
  10722. $selectedNames[] = $n;
  10723. }
  10724. }
  10725. $selectedNames = array_values(array_unique($selectedNames));
  10726. if ($selectedNames === []) {
  10727. $this->error('请选择要通知的业务员');
  10728. }
  10729. $optionMap = [];
  10730. foreach ($this->loadRfqSalesmanContactOptions() as $opt) {
  10731. $n = trim((string)($opt['name'] ?? ''));
  10732. if ($n === '') {
  10733. continue;
  10734. }
  10735. $optionMap[$n] = $opt;
  10736. }
  10737. $targets = [];
  10738. foreach ($selectedNames as $n) {
  10739. if (!isset($optionMap[$n])) {
  10740. $this->error('业务员不在可选名单中:' . $n);
  10741. }
  10742. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  10743. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  10744. $this->error('业务员未填写有效邮箱,无法通知:' . $n);
  10745. }
  10746. $resolved = $this->resolveRfqSalesmanContactRows([$n]);
  10747. $targets[] = $resolved[0] ?? [
  10748. 'admin_id' => 0,
  10749. 'name' => $n,
  10750. 'email' => $email,
  10751. ];
  10752. }
  10753. $mergedStr = $this->joinRfqMultiSelectValues($selectedNames);
  10754. try {
  10755. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10756. 'notify_salesman' => $mergedStr,
  10757. ]);
  10758. } catch (\Throwable $e) {
  10759. $this->error('保存通知业务员失败:' . $e->getMessage());
  10760. }
  10761. $po['notify_salesman'] = $mergedStr;
  10762. $mailConfig = $this->loadMailerConfig();
  10763. if (empty($mailConfig['host'])) {
  10764. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  10765. }
  10766. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  10767. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  10768. }
  10769. $this->ensureRfqSalesmanEmailTemplate();
  10770. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  10771. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  10772. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  10773. $cdw = trim((string)($po['CDW'] ?? ''));
  10774. $qty = trim((string)$this->resolveProcuremenThisQuantity($po));
  10775. $ceiling = trim((string)$this->resolveProcuremenCeilingPrice($po));
  10776. $mbz = trim((string)($po['MBZ'] ?? ''));
  10777. $cywyxm = trim((string)($po['cywyxm'] ?? ''));
  10778. $supplier = trim((string)($po['cGzzxMc'] ?? ''));
  10779. if ($supplier === '') {
  10780. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  10781. }
  10782. $supplierQuotesHtml = $this->buildRfqSalesmanSupplierQuotesHtml($sid, $supplier);
  10783. try {
  10784. $platformUrl = $this->buildMprocMobileRfqAddUrl($sid, 'pending');
  10785. } catch (\Throwable $e) {
  10786. $platformUrl = '';
  10787. }
  10788. try {
  10789. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
  10790. } catch (\Throwable $e) {
  10791. $this->error($e->getMessage());
  10792. }
  10793. $okNames = [];
  10794. $failMsgs = [];
  10795. foreach ($targets as $contact) {
  10796. $toEmail = trim((string)($contact['email'] ?? ''));
  10797. $toName = trim((string)($contact['name'] ?? ''));
  10798. $notifyVars = [
  10799. 'contact_name' => $toName,
  10800. 'salesman_name' => $toName,
  10801. 'company_name' => $toName,
  10802. 'email' => $toEmail,
  10803. 'ccydh' => $ccydh,
  10804. 'cyjmc' => $cyjmc,
  10805. 'cgymc' => $cgymc,
  10806. 'cdw' => $cdw,
  10807. 'this_quantity' => $qty,
  10808. 'ceilingPrice' => $ceiling,
  10809. 'MBZ' => $mbz,
  10810. 'supplier_name' => $supplier,
  10811. // 占位符,转 HTML 后再替换成表格,避免被 htmlspecialchars 转义
  10812. 'supplier_quotes' => '__RFQ_SUPPLIER_QUOTES_TABLE__',
  10813. 'cywyxm' => $cywyxm,
  10814. 'platform_url' => $platformUrl,
  10815. ];
  10816. try {
  10817. $mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
  10818. $mailSubject = $mailSubjectTpl;
  10819. foreach ($notifyVars as $k => $v) {
  10820. if ($k === 'supplier_quotes') {
  10821. continue;
  10822. }
  10823. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  10824. }
  10825. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  10826. $mailSubject = trim((string)$mailSubject);
  10827. if ($mailSubject === '') {
  10828. $mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  10829. }
  10830. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  10831. $mailBody = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', $supplierQuotesHtml, $mailBody);
  10832. $mailPlainForLog = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', strip_tags(str_replace(['</tr>', '</p>'], "\n", $supplierQuotesHtml)), $mailPlain);
  10833. $bundle = [
  10834. 'company_name' => $toName,
  10835. 'email' => $toEmail,
  10836. 'mail_plain' => $mailPlainForLog,
  10837. 'mail_body' => $mailBody,
  10838. 'ccydh' => $ccydh,
  10839. 'email_log_scene' => 'rfq_salesman',
  10840. 'email_log_scydgy_id' => $sid,
  10841. 'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
  10842. 'notify_vars' => $notifyVars,
  10843. ];
  10844. $this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
  10845. $okNames[] = $toName . '(' . $toEmail . ')';
  10846. } catch (\Throwable $e) {
  10847. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  10848. }
  10849. }
  10850. if ($okNames === []) {
  10851. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  10852. }
  10853. $now = date('Y-m-d H:i:s');
  10854. try {
  10855. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10856. 'rfq_salesman_notified' => 1,
  10857. 'rfq_salesman_notify_time' => $now,
  10858. ]);
  10859. } catch (\Throwable $e) {
  10860. // ignore
  10861. }
  10862. $this->addOrderLog(
  10863. $sid,
  10864. 'rfq_notify_salesman',
  10865. '邮箱通知业务员:' . implode('、', $okNames),
  10866. (int)($po['id'] ?? 0)
  10867. );
  10868. $msg = '已通知 ' . count($okNames) . ' 人';
  10869. if ($failMsgs !== []) {
  10870. $msg .= ';部分失败:' . implode(';', $failMsgs);
  10871. }
  10872. $this->success($msg, null, [
  10873. 'scydgy_id' => $sid,
  10874. 'notify_salesman' => $mergedStr,
  10875. 'rfq_salesman_notified' => 1,
  10876. 'rfq_salesman_notify_time' => $now,
  10877. 'notify_time_text' => $now,
  10878. 'ok_count' => count($okNames),
  10879. 'fail_count' => count($failMsgs),
  10880. ]);
  10881. }
  10882. /**
  10883. * 生产部角色组 id(mproc.mobile_delivery_group_id,缺省按组名「生产部/生产员」查找)
  10884. */
  10885. protected function deliveryNotifyAuthGroupId(): int
  10886. {
  10887. static $mprocCfgLoaded = false;
  10888. if (!$mprocCfgLoaded) {
  10889. $mprocCfgLoaded = true;
  10890. if (is_file(APP_PATH . 'extra/mproc.php')) {
  10891. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  10892. }
  10893. }
  10894. $id = (int)Config::get('mproc.mobile_delivery_group_id');
  10895. if ($id > 0) {
  10896. return $id;
  10897. }
  10898. try {
  10899. foreach (['生产部', '生产员'] as $name) {
  10900. $gid = (int)Db::name('auth_group')->where('name', $name)->value('id');
  10901. if ($gid > 0) {
  10902. return $gid;
  10903. }
  10904. }
  10905. } catch (\Throwable $e) {
  10906. }
  10907. return 0;
  10908. }
  10909. /**
  10910. * 生产部人员:姓名、邮箱、手机
  10911. *
  10912. * @return array<int, array{name:string,email:string,mobile:string,admin_id:int}>
  10913. */
  10914. protected function loadDeliveryStaffContactOptions(): array
  10915. {
  10916. $out = [];
  10917. $seen = [];
  10918. $groupId = $this->deliveryNotifyAuthGroupId();
  10919. if ($groupId <= 0) {
  10920. return [];
  10921. }
  10922. try {
  10923. $adminIds = Db::name('auth_group_access')
  10924. ->where('group_id', $groupId)
  10925. ->column('uid');
  10926. } catch (\Throwable $e) {
  10927. return [];
  10928. }
  10929. $adminIds = is_array($adminIds)
  10930. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  10931. : [];
  10932. if ($adminIds === []) {
  10933. return [];
  10934. }
  10935. try {
  10936. $rows = Db::name('admin')
  10937. ->where('status', 'normal')
  10938. ->where('id', 'in', $adminIds)
  10939. ->order('id', 'asc')
  10940. ->field('id,nickname,username,email,mobile')
  10941. ->select();
  10942. } catch (\Throwable $e) {
  10943. return [];
  10944. }
  10945. if (!is_array($rows)) {
  10946. return [];
  10947. }
  10948. foreach ($rows as $row) {
  10949. if (!is_array($row)) {
  10950. continue;
  10951. }
  10952. $name = trim((string)($row['nickname'] ?? ''));
  10953. if ($name === '') {
  10954. $name = trim((string)($row['username'] ?? ''));
  10955. }
  10956. if ($name === '' || isset($seen[$name])) {
  10957. continue;
  10958. }
  10959. $seen[$name] = true;
  10960. $out[] = [
  10961. 'admin_id' => (int)($row['id'] ?? 0),
  10962. 'name' => $name,
  10963. 'email' => trim((string)($row['email'] ?? '')),
  10964. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  10965. ];
  10966. }
  10967. return $out;
  10968. }
  10969. /**
  10970. * 交货情况页直达链接(邮件用,单参数避免邮箱客户端拆坏)
  10971. */
  10972. protected function buildMprocMobileDeliveryscoreUrl(string $ccydh): string
  10973. {
  10974. static $mprocCfgLoaded = false;
  10975. if (!$mprocCfgLoaded) {
  10976. $mprocCfgLoaded = true;
  10977. if (is_file(APP_PATH . 'extra/mproc.php')) {
  10978. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  10979. }
  10980. }
  10981. $base = $this->resolveMprocMobilePublicBaseUrl();
  10982. if ($base === '') {
  10983. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  10984. }
  10985. $path = '/index.php/index/index/deliveryscore';
  10986. $ccydh = trim($ccydh);
  10987. if ($ccydh === '') {
  10988. return $base . $path;
  10989. }
  10990. return $base . $path . '?ccydh=' . rawurlencode($ccydh);
  10991. }
  10992. /**
  10993. * 按订单号取已审核外发单(合并工序字段)
  10994. *
  10995. * @return array<string, mixed>|null
  10996. */
  10997. protected function loadApprovedOrderForDeliveryNotify(string $ccydh, int $sid = 0): ?array
  10998. {
  10999. $ccydh = trim($ccydh);
  11000. if ($ccydh === '' && $sid > 0) {
  11001. try {
  11002. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
  11003. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  11004. } catch (\Throwable $e) {
  11005. $ccydh = '';
  11006. }
  11007. }
  11008. if ($ccydh === '') {
  11009. return null;
  11010. }
  11011. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  11012. $approvedIn = implode(',', array_map(static function ($v) {
  11013. return "'" . str_replace("'", "''", (string)$v) . "'";
  11014. }, $approvedVals));
  11015. try {
  11016. $rows = Db::table('purchase_order')
  11017. ->where('CCYDH', $ccydh)
  11018. ->where('scydgy_id', '>', 0)
  11019. ->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%\')')
  11020. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  11021. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  11022. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,CDW,This_quantity,NGZL,pick_company_name,delivery_deadline,MBZ,cywyxm,wflow_status,status')
  11023. ->order('id', 'asc')
  11024. ->select();
  11025. } catch (\Throwable $e) {
  11026. $rows = [];
  11027. }
  11028. if (!is_array($rows) || $rows === []) {
  11029. return null;
  11030. }
  11031. $gymc = [];
  11032. $qty = [];
  11033. $first = null;
  11034. foreach ($rows as $r) {
  11035. if (!is_array($r)) {
  11036. continue;
  11037. }
  11038. if ($first === null) {
  11039. $first = $r;
  11040. }
  11041. $g = trim((string)($r['CGYMC'] ?? ''));
  11042. if ($g !== '' && !in_array($g, $gymc, true)) {
  11043. $gymc[] = $g;
  11044. }
  11045. $q = trim((string)$this->resolveProcuremenThisQuantity($r));
  11046. if ($q !== '' && !in_array($q, $qty, true)) {
  11047. $qty[] = $q;
  11048. }
  11049. }
  11050. if (!is_array($first)) {
  11051. return null;
  11052. }
  11053. $first['CGYMC'] = $gymc !== [] ? implode('、', $gymc) : '';
  11054. $first['This_quantity'] = $qty !== [] ? implode('、', $qty) : '';
  11055. $first['delivery_deadline'] = $this->mprocFormatYmdForNotify($first['delivery_deadline'] ?? '');
  11056. return $first;
  11057. }
  11058. protected function mprocFormatYmdForNotify($raw): string
  11059. {
  11060. return ProcuremenFormat::mprocYmdForNotify($raw);
  11061. }
  11062. /**
  11063. * 确保「交货情况通知生产部-邮箱」模版存在
  11064. */
  11065. protected function ensureDeliveryNotifyEmailTemplate(): void
  11066. {
  11067. static $done = false;
  11068. if ($done) {
  11069. return;
  11070. }
  11071. $done = true;
  11072. $content = "您好,{contact_name}:\n\n"
  11073. . "有订单已中标外发,需要您在手机端确认交货情况(填写库位、交货情况、交货日期等)。\n\n"
  11074. . "订单号:{ccydh}\n"
  11075. . "印件名称:{cyjmc}\n"
  11076. . "工序名称:{cgymc}\n"
  11077. . "订单数量:{this_quantity}\n"
  11078. . "中标供应商:{supplier_name}\n"
  11079. . "交货截止日期:{delivery_deadline}\n\n"
  11080. . "请点击下方链接登录后,找到该订单进行填写:\n"
  11081. . "{platform_url}\n";
  11082. try {
  11083. $row = Db::table('purchase_sms_template')
  11084. ->where('scene', 'delivery_notify_email')
  11085. ->find();
  11086. } catch (\Throwable $e) {
  11087. return;
  11088. }
  11089. $now = date('Y-m-d H:i:s');
  11090. if (is_array($row) && $row !== []) {
  11091. return;
  11092. }
  11093. try {
  11094. $data = [
  11095. 'scene' => 'delivery_notify_email',
  11096. 'title' => '交货情况确认通知 - {ccydh}',
  11097. 'content' => $content,
  11098. 'remark' => '审批通过后通知生产部填写交货情况;模版名称作邮件主题,支持变量',
  11099. 'status' => 1,
  11100. ];
  11101. try {
  11102. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  11103. } catch (\Throwable $e) {
  11104. $cols = [];
  11105. }
  11106. $colNames = [];
  11107. foreach ($cols as $c) {
  11108. if (!is_array($c)) {
  11109. continue;
  11110. }
  11111. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  11112. if ($n !== '') {
  11113. $colNames[$n] = true;
  11114. }
  11115. }
  11116. if (isset($colNames['updatetime'])) {
  11117. $data['updatetime'] = $now;
  11118. }
  11119. if (isset($colNames['createtime'])) {
  11120. $data['createtime'] = $now;
  11121. }
  11122. Db::table('purchase_sms_template')->insert($data);
  11123. } catch (\Throwable $e) {
  11124. // ignore
  11125. }
  11126. }
  11127. /**
  11128. * 通知生产部 — 可选人员名单
  11129. */
  11130. public function deliverynotifymen()
  11131. {
  11132. if (!$this->hasProcuremenPerm(['deliverynotifymen', 'deliverynotify', 'outward_detail', 'outwarddetail', 'purchaseconfirmpick', 'details'])) {
  11133. $this->error(__('You have no permission'));
  11134. }
  11135. $this->ensureDeliveryNotifyEmailTemplate();
  11136. $sid = (int)$this->request->request('scydgy_id', 0);
  11137. $ccydh = trim((string)$this->request->request('ccydh', ''));
  11138. $po = $this->loadApprovedOrderForDeliveryNotify($ccydh, $sid);
  11139. if ($po === null) {
  11140. $this->error('未找到已审核且已中标的订单,无法通知生产部');
  11141. }
  11142. $list = [];
  11143. foreach ($this->loadDeliveryStaffContactOptions() as $opt) {
  11144. $email = trim((string)($opt['email'] ?? ''));
  11145. $list[] = [
  11146. 'name' => (string)($opt['name'] ?? ''),
  11147. 'email' => $email,
  11148. 'mobile' => (string)($opt['mobile'] ?? ''),
  11149. 'can_select' => ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) ? 1 : 0,
  11150. 'checked' => 0,
  11151. ];
  11152. }
  11153. $this->success('', null, [
  11154. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  11155. 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
  11156. 'cgymc' => trim((string)($po['CGYMC'] ?? '')),
  11157. 'this_quantity' => trim((string)($po['This_quantity'] ?? '')),
  11158. 'supplier_name' => trim((string)($po['pick_company_name'] ?? '')),
  11159. 'delivery_deadline' => trim((string)($po['delivery_deadline'] ?? '')),
  11160. 'list' => $list,
  11161. ]);
  11162. }
  11163. /**
  11164. * 通知生产部 — 勾选后发邮件(staff_json / names)
  11165. */
  11166. public function deliverynotify()
  11167. {
  11168. if (!$this->request->isPost()) {
  11169. $this->error(__('Invalid parameters'));
  11170. }
  11171. if (!$this->hasProcuremenPerm(['deliverynotify', 'deliverynotifymen', 'outward_detail', 'outwarddetail', 'purchaseconfirmpick', 'details'])) {
  11172. $this->error(__('You have no permission'));
  11173. }
  11174. $this->ensureDeliveryNotifyEmailTemplate();
  11175. $sid = (int)$this->request->post('scydgy_id', 0);
  11176. $ccydh = trim((string)$this->request->post('ccydh', ''));
  11177. $po = $this->loadApprovedOrderForDeliveryNotify($ccydh, $sid);
  11178. if ($po === null) {
  11179. $this->error('未找到已审核且已中标的订单,无法通知生产部');
  11180. }
  11181. $ccydh = trim((string)($po['CCYDH'] ?? $ccydh));
  11182. $raw = $this->request->post('staff/a', []);
  11183. if (!is_array($raw) || $raw === []) {
  11184. $staffJson = $this->request->post('staff_json', '');
  11185. if (is_string($staffJson) && $staffJson !== '') {
  11186. $decoded = json_decode($staffJson, true);
  11187. $raw = is_array($decoded) ? $decoded : [];
  11188. }
  11189. }
  11190. $selectedNames = [];
  11191. foreach ((array)$raw as $item) {
  11192. if (is_array($item)) {
  11193. $n = trim((string)($item['name'] ?? ''));
  11194. } else {
  11195. $n = trim((string)$item);
  11196. }
  11197. if ($n !== '') {
  11198. $selectedNames[] = $n;
  11199. }
  11200. }
  11201. $selectedNames = array_values(array_unique($selectedNames));
  11202. if ($selectedNames === []) {
  11203. $this->error('请选择要通知的生产部人员');
  11204. }
  11205. $optionMap = [];
  11206. foreach ($this->loadDeliveryStaffContactOptions() as $opt) {
  11207. $n = trim((string)($opt['name'] ?? ''));
  11208. if ($n === '') {
  11209. continue;
  11210. }
  11211. $optionMap[$n] = $opt;
  11212. }
  11213. $targets = [];
  11214. foreach ($selectedNames as $n) {
  11215. if (!isset($optionMap[$n])) {
  11216. $this->error('人员不在生产部可选名单中:' . $n);
  11217. }
  11218. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  11219. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  11220. $this->error('未填写有效邮箱,无法通知:' . $n);
  11221. }
  11222. $targets[] = $optionMap[$n];
  11223. }
  11224. $mailConfig = $this->loadMailerConfig();
  11225. if (empty($mailConfig['host'])) {
  11226. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  11227. }
  11228. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  11229. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  11230. }
  11231. try {
  11232. $platformUrl = $this->buildMprocMobileDeliveryscoreUrl($ccydh);
  11233. } catch (\Throwable $e) {
  11234. $this->error($e->getMessage());
  11235. }
  11236. try {
  11237. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('delivery_notify_email');
  11238. } catch (\Throwable $e) {
  11239. $this->error($e->getMessage());
  11240. }
  11241. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  11242. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  11243. $qty = trim((string)($po['This_quantity'] ?? ''));
  11244. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  11245. $deadline = trim((string)($po['delivery_deadline'] ?? ''));
  11246. $firstSid = (int)($po['scydgy_id'] ?? 0);
  11247. $firstPoId = (int)($po['id'] ?? 0);
  11248. $okNames = [];
  11249. $failMsgs = [];
  11250. foreach ($targets as $contact) {
  11251. $toEmail = trim((string)($contact['email'] ?? ''));
  11252. $toName = trim((string)($contact['name'] ?? ''));
  11253. $notifyVars = [
  11254. 'contact_name' => $toName,
  11255. 'company_name' => $toName,
  11256. 'email' => $toEmail,
  11257. 'ccydh' => $ccydh,
  11258. 'cyjmc' => $cyjmc,
  11259. 'cgymc' => $cgymc,
  11260. 'this_quantity' => $qty,
  11261. 'supplier_name' => $supplier,
  11262. 'delivery_deadline' => $deadline,
  11263. 'platform_url' => $platformUrl,
  11264. ];
  11265. try {
  11266. $mailPlain = $this->renderNotifyTemplate('delivery_notify_email', $notifyVars);
  11267. $mailSubject = $mailSubjectTpl;
  11268. foreach ($notifyVars as $k => $v) {
  11269. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  11270. }
  11271. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  11272. $mailSubject = trim((string)$mailSubject);
  11273. if ($mailSubject === '') {
  11274. $mailSubject = '交货情况确认通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  11275. }
  11276. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  11277. $this->issueSendSupplierEmail([
  11278. 'company_name' => $toName,
  11279. 'email' => $toEmail,
  11280. 'mail_plain' => $mailPlain,
  11281. 'mail_body' => $mailBody,
  11282. 'ccydh' => $ccydh,
  11283. 'email_log_scene' => 'delivery_notify',
  11284. 'email_log_scydgy_id' => $firstSid,
  11285. 'email_log_purchase_order_id' => $firstPoId,
  11286. 'notify_vars' => $notifyVars,
  11287. ], $mailConfig, $mailSubject);
  11288. $okNames[] = $toName . '(' . $toEmail . ')';
  11289. } catch (\Throwable $e) {
  11290. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  11291. }
  11292. }
  11293. if ($okNames === []) {
  11294. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  11295. }
  11296. if ($firstSid > 0) {
  11297. $this->addOrderLog(
  11298. $firstSid,
  11299. 'delivery_notify',
  11300. '邮箱通知生产部:' . implode('、', $okNames),
  11301. $firstPoId > 0 ? $firstPoId : null
  11302. );
  11303. }
  11304. $msg = '已通知 ' . count($okNames) . ' 人';
  11305. if ($failMsgs !== []) {
  11306. $msg .= ';部分失败:' . implode(';', $failMsgs);
  11307. }
  11308. $this->success($msg, null, [
  11309. 'ccydh' => $ccydh,
  11310. 'ok_count' => count($okNames),
  11311. 'fail_count'=> count($failMsgs),
  11312. 'platform_url' => $platformUrl,
  11313. ]);
  11314. }
  11315. /**
  11316. * 查询询价 — 下发前:返回将通知的供应商表格数据
  11317. */
  11318. public function rfqissuesuppliers()
  11319. {
  11320. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers'])) {
  11321. $this->error(__('You have no permission'));
  11322. }
  11323. $sid = (int)$this->request->param('scydgy_id', 0);
  11324. if ($sid >= 0) {
  11325. $this->error('仅支持手工新增询价单');
  11326. }
  11327. $po = $this->loadManualRfqOrderForNotify($sid);
  11328. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  11329. if ($supplierRaw === '') {
  11330. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  11331. }
  11332. $names = $this->splitRfqSalesmanNames($supplierRaw);
  11333. // 已成功发过询价邮件的供应商(含历史 pick_issue 场景)
  11334. $notifiedMap = [];
  11335. try {
  11336. $this->ensurePurchaseEmailSendLogTableOnce();
  11337. $logRows = Db::table('purchase_email_send_log')
  11338. ->where('scydgy_id', $sid)
  11339. ->where('status', 1)
  11340. ->where('scene', 'in', [
  11341. 'rfq_supplier', 'pick_issue',
  11342. '供应商询价通知', '初选下发',
  11343. ])
  11344. ->field('company_name')
  11345. ->select();
  11346. if (is_array($logRows)) {
  11347. foreach ($logRows as $lr) {
  11348. if (!is_array($lr)) {
  11349. continue;
  11350. }
  11351. $cn = trim((string)($lr['company_name'] ?? ''));
  11352. if ($cn !== '') {
  11353. $notifiedMap[$cn] = true;
  11354. }
  11355. }
  11356. }
  11357. } catch (\Throwable $e) {
  11358. }
  11359. // 兼容:明细已生成(曾下发)也视为已通知
  11360. try {
  11361. $detRows = Db::table('purchase_order_detail')
  11362. ->where('scydgy_id', $sid)
  11363. ->field('company_name')
  11364. ->select();
  11365. if (is_array($detRows)) {
  11366. foreach ($detRows as $dr) {
  11367. if (!is_array($dr)) {
  11368. continue;
  11369. }
  11370. $cn = trim((string)($dr['company_name'] ?? ''));
  11371. if ($cn !== '') {
  11372. $notifiedMap[$cn] = true;
  11373. }
  11374. }
  11375. }
  11376. } catch (\Throwable $e) {
  11377. }
  11378. $list = [];
  11379. foreach ($names as $name) {
  11380. // 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
  11381. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  11382. $email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
  11383. $phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
  11384. $username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
  11385. $okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
  11386. $notified = !empty($notifiedMap[$name]) ? 1 : 0;
  11387. $list[] = [
  11388. 'name' => $name,
  11389. 'username' => $username,
  11390. 'email' => $email,
  11391. 'phone' => $phone,
  11392. 'can_notify' => $okEmail ? 1 : 0,
  11393. 'found' => is_array($contact) ? 1 : 0,
  11394. 'notified' => $notified,
  11395. 'notify_status_text' => $notified ? '已通知' : '未通知',
  11396. ];
  11397. }
  11398. $this->success('', null, [
  11399. 'scydgy_id' => $sid,
  11400. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  11401. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  11402. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  11403. 'CDW' => trim((string)($po['CDW'] ?? '')),
  11404. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  11405. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  11406. 'CDF' => trim((string)($po['CDF'] ?? '')),
  11407. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  11408. 'list' => $list,
  11409. ]);
  11410. }
  11411. /**
  11412. * 查询询价 — 补加供应商可选名单
  11413. */
  11414. public function rfqsupplieroptions()
  11415. {
  11416. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
  11417. $this->error(__('You have no permission'));
  11418. }
  11419. $names = array_values($this->loadRfqSupplierNameOptions());
  11420. $out = [];
  11421. foreach ($names as $name) {
  11422. $out[] = ['name' => $name];
  11423. }
  11424. $this->success('', null, ['list' => $out]);
  11425. }
  11426. /**
  11427. * 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
  11428. */
  11429. public function rfqappendsuppliers()
  11430. {
  11431. if (!$this->request->isPost()) {
  11432. $this->error(__('Invalid parameters'));
  11433. }
  11434. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers'])) {
  11435. $this->error(__('You have no permission'));
  11436. }
  11437. $sid = (int)$this->request->post('scydgy_id', 0);
  11438. if ($sid >= 0) {
  11439. $this->error('仅支持手工新增询价单');
  11440. }
  11441. $po = $this->loadManualRfqOrderForNotify($sid);
  11442. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  11443. $this->error('订单已完结,无法补加供应商');
  11444. }
  11445. $raw = $this->request->post('suppliers/a', []);
  11446. if (!is_array($raw) || $raw === []) {
  11447. $suppliersJson = $this->request->post('suppliers_json', '');
  11448. if (is_string($suppliersJson) && $suppliersJson !== '') {
  11449. $decoded = json_decode($suppliersJson, true);
  11450. $raw = is_array($decoded) ? $decoded : [];
  11451. }
  11452. }
  11453. $addNames = [];
  11454. foreach ((array)$raw as $item) {
  11455. if (is_array($item)) {
  11456. $n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
  11457. } else {
  11458. $n = trim((string)$item);
  11459. }
  11460. if ($n !== '') {
  11461. $addNames[] = $n;
  11462. }
  11463. }
  11464. $addNames = array_values(array_unique($addNames));
  11465. if ($addNames === []) {
  11466. $this->error('请选择要补加的供应商');
  11467. }
  11468. $existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
  11469. if ($existingRaw === '') {
  11470. $existingRaw = trim((string)($po['pick_company_name'] ?? ''));
  11471. }
  11472. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  11473. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  11474. try {
  11475. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
  11476. } catch (\Throwable $e) {
  11477. $this->error('保存失败:' . $e->getMessage());
  11478. }
  11479. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11480. $this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  11481. $this->success('已补加供应商', null, [
  11482. 'scydgy_id' => $sid,
  11483. 'cGzzxMc' => $mergedStr,
  11484. 'added_count' => count($addNames),
  11485. ]);
  11486. }
  11487. /**
  11488. * 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
  11489. */
  11490. public function rfqissue()
  11491. {
  11492. if (!$this->request->isPost()) {
  11493. $this->error(__('Invalid parameters'));
  11494. }
  11495. if (!$this->hasProcuremenPerm(['rfqissue'])) {
  11496. $this->error(__('You have no permission'));
  11497. }
  11498. $this->ensureRfqSupplierEmailTemplate();
  11499. $sid = (int)$this->request->post('scydgy_id', 0);
  11500. if ($sid >= 0) {
  11501. $this->error('仅支持手工新增询价单');
  11502. }
  11503. $po = $this->loadManualRfqOrderForNotify($sid);
  11504. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  11505. $this->error('订单已完结,无法下发');
  11506. }
  11507. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  11508. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  11509. $this->error('订单已进入后续流程,无法再下发');
  11510. }
  11511. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  11512. if ($supplierRaw === '') {
  11513. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  11514. }
  11515. $supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
  11516. if ($supplierNames === []) {
  11517. $this->error('请先在新增询价时选择供应商');
  11518. }
  11519. $companies = [];
  11520. $missing = [];
  11521. $noEmail = [];
  11522. foreach ($supplierNames as $name) {
  11523. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  11524. if ($contact === null) {
  11525. $missing[] = $name;
  11526. continue;
  11527. }
  11528. $em = trim((string)($contact['email'] ?? ''));
  11529. if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
  11530. $noEmail[] = $name;
  11531. continue;
  11532. }
  11533. $companies[] = $contact;
  11534. }
  11535. if ($missing !== []) {
  11536. $this->error('未找到供应商档案:' . implode('、', $missing));
  11537. }
  11538. if ($noEmail !== []) {
  11539. $this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
  11540. }
  11541. if ($companies === []) {
  11542. $this->error('没有可通知的供应商');
  11543. }
  11544. $mailConfig = $this->loadMailerConfig();
  11545. if (empty($mailConfig['host'])) {
  11546. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  11547. }
  11548. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  11549. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  11550. }
  11551. $mergeRow = $po;
  11552. $mergeRow['ID'] = $sid;
  11553. $mergeRow['id'] = $sid;
  11554. $mergeRows = [$mergeRow];
  11555. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  11556. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  11557. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  11558. }
  11559. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  11560. $issueTime = date('Y-m-d H:i:s');
  11561. $nameLabels = [];
  11562. foreach ($companies as $c) {
  11563. $nameLabels[] = trim((string)($c['name'] ?? ''));
  11564. }
  11565. $logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
  11566. Db::startTrans();
  11567. try {
  11568. $this->upsertPurchaseOrderFromRow(
  11569. $mergeRow,
  11570. $sysRqDb,
  11571. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  11572. $issueTime,
  11573. $po,
  11574. null,
  11575. $scoreRule
  11576. );
  11577. foreach ($companies as $c) {
  11578. $this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
  11579. }
  11580. Db::commit();
  11581. } catch (\Throwable $e) {
  11582. Db::rollback();
  11583. $this->error($e->getMessage());
  11584. }
  11585. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11586. if ($poId <= 0) {
  11587. try {
  11588. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  11589. } catch (\Throwable $e) {
  11590. $poId = 0;
  11591. }
  11592. }
  11593. $this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
  11594. $posNotify = [];
  11595. try {
  11596. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  11597. if (is_array($fresh)) {
  11598. $fresh['sys_rq'] = $sysRqDb;
  11599. $posNotify = [$fresh];
  11600. }
  11601. } catch (\Throwable $e) {
  11602. $posNotify = [$po];
  11603. $posNotify[0]['sys_rq'] = $sysRqDb;
  11604. }
  11605. $notifyBundle = [
  11606. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  11607. 'pos' => $posNotify,
  11608. 'merge_rows' => $mergeRows,
  11609. ];
  11610. $notifyErrors = [];
  11611. foreach ($companies as $c) {
  11612. $cname = trim((string)($c['name'] ?? ''));
  11613. try {
  11614. // 询价下发:仅邮箱通知供应商
  11615. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  11616. } catch (\Throwable $e) {
  11617. $notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
  11618. }
  11619. }
  11620. if ($notifyErrors !== []) {
  11621. Log::write('procuremen rfq issue notify fail sid=' . $sid . ': ' . implode(';', $notifyErrors), 'error');
  11622. $this->success('询价下发成功。部分供应商邮件未送达,可稍后重发。', null, [
  11623. 'scydgy_id' => $sid,
  11624. 'progress_text' => '待报价',
  11625. 'supplier_count' => count($companies),
  11626. 'notify_failed' => 1,
  11627. 'notify_fail_detail' => $notifyErrors,
  11628. ]);
  11629. }
  11630. $this->success('已询价并邮件通知供应商', null, [
  11631. 'scydgy_id' => $sid,
  11632. 'progress_text' => '待报价',
  11633. 'supplier_count' => count($companies),
  11634. 'notify_failed' => 0,
  11635. ]);
  11636. }
  11637. /**
  11638. * 查询询价 — 弹窗内向单个供应商发送询价邮件
  11639. */
  11640. public function rfqissuesendmail()
  11641. {
  11642. if (!$this->request->isPost()) {
  11643. $this->error(__('Invalid parameters'));
  11644. }
  11645. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail'])) {
  11646. $this->error(__('You have no permission'));
  11647. }
  11648. $this->ensureRfqSupplierEmailTemplate();
  11649. $sid = (int)$this->request->post('scydgy_id', 0);
  11650. $companyName = trim((string)$this->request->post('company_name', ''));
  11651. if ($sid >= 0) {
  11652. $this->error('仅支持手工新增询价单');
  11653. }
  11654. if ($companyName === '') {
  11655. $this->error('请选择供应商');
  11656. }
  11657. $po = $this->loadManualRfqOrderForNotify($sid);
  11658. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  11659. $this->error('订单已完结,无法发送');
  11660. }
  11661. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  11662. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  11663. $this->error('订单已进入后续流程,无法再发送');
  11664. }
  11665. $contact = $this->resolveCustomerContactByCompanyName($companyName, false);
  11666. if ($contact === null) {
  11667. $this->error('未找到供应商档案:' . $companyName);
  11668. }
  11669. $email = trim((string)($contact['email'] ?? ''));
  11670. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  11671. $this->error('该供应商未填写有效邮箱');
  11672. }
  11673. $mailConfig = $this->loadMailerConfig();
  11674. if (empty($mailConfig['host'])) {
  11675. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  11676. }
  11677. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  11678. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  11679. }
  11680. $mergeRow = $po;
  11681. $mergeRow['ID'] = $sid;
  11682. $mergeRow['id'] = $sid;
  11683. $mergeRows = [$mergeRow];
  11684. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  11685. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  11686. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  11687. }
  11688. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  11689. $issueTime = date('Y-m-d H:i:s');
  11690. Db::startTrans();
  11691. try {
  11692. $this->upsertPurchaseOrderFromRow(
  11693. $mergeRow,
  11694. $sysRqDb,
  11695. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  11696. $issueTime,
  11697. $po,
  11698. null,
  11699. $scoreRule
  11700. );
  11701. $this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
  11702. Db::commit();
  11703. } catch (\Throwable $e) {
  11704. Db::rollback();
  11705. $this->error($e->getMessage());
  11706. }
  11707. $posNotify = [];
  11708. try {
  11709. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  11710. if (is_array($fresh)) {
  11711. $fresh['sys_rq'] = $sysRqDb;
  11712. $posNotify = [$fresh];
  11713. }
  11714. } catch (\Throwable $e) {
  11715. $posNotify = [$po];
  11716. $posNotify[0]['sys_rq'] = $sysRqDb;
  11717. }
  11718. $notifyBundle = [
  11719. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  11720. 'pos' => $posNotify,
  11721. 'merge_rows' => $mergeRows,
  11722. ];
  11723. $mailFail = '';
  11724. try {
  11725. $this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  11726. } catch (\Throwable $e) {
  11727. $mailFail = $e->getMessage();
  11728. Log::write('procuremen rfqissuesendmail fail sid=' . $sid . ' company=' . $companyName . ': ' . $mailFail, 'error');
  11729. }
  11730. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11731. if ($poId <= 0) {
  11732. try {
  11733. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  11734. } catch (\Throwable $e) {
  11735. $poId = 0;
  11736. }
  11737. }
  11738. $this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
  11739. if ($mailFail !== '') {
  11740. $this->success('询价已保存。邮件未送达「' . $companyName . '」:' . $mailFail . '。可稍后重发。', null, [
  11741. 'scydgy_id' => $sid,
  11742. 'notify_failed' => 1,
  11743. ]);
  11744. }
  11745. $this->success('已向「' . $companyName . '」发送询价邮件', null, [
  11746. 'scydgy_id' => $sid,
  11747. 'company_name' => $companyName,
  11748. ]);
  11749. }
  11750. /**
  11751. * 查询询价 — 查看各供应商报价(单价)
  11752. */
  11753. public function rfqquotes()
  11754. {
  11755. if (!$this->hasProcuremenPerm(['rfqquotes', 'rfqissue'])) {
  11756. $this->error(__('You have no permission'));
  11757. }
  11758. $sid = (int)$this->request->param('scydgy_id', 0);
  11759. if ($sid >= 0) {
  11760. $this->error('仅支持手工新增询价单');
  11761. }
  11762. $po = $this->loadManualRfqOrderForNotify($sid);
  11763. $rows = [];
  11764. try {
  11765. // 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
  11766. $q = Db::table('purchase_order_detail')
  11767. ->where('scydgy_id', $sid)
  11768. ->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
  11769. ->order('id', 'asc');
  11770. $this->applyActivePurchaseOrderDetailWhere($q);
  11771. $rows = $q->select();
  11772. } catch (\Throwable $e) {
  11773. try {
  11774. $q = Db::table('purchase_order_detail')
  11775. ->where('scydgy_id', $sid)
  11776. ->order('id', 'asc');
  11777. $this->applyActivePurchaseOrderDetailWhere($q);
  11778. $rows = $q->select();
  11779. } catch (\Throwable $e2) {
  11780. $rows = [];
  11781. }
  11782. }
  11783. if (!is_array($rows)) {
  11784. $rows = [];
  11785. }
  11786. $list = [];
  11787. foreach ($rows as $row) {
  11788. if (!is_array($row)) {
  11789. continue;
  11790. }
  11791. $amount = trim((string)($row['amount'] ?? ''));
  11792. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  11793. // 未报价不显示时间(createtime 是下发时间,不是报价时间)
  11794. $oper = '';
  11795. if ($isQuoted) {
  11796. $oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
  11797. if ($oper === '') {
  11798. $oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  11799. }
  11800. }
  11801. $list[] = [
  11802. 'id' => (int)($row['id'] ?? 0),
  11803. 'company_name' => trim((string)($row['company_name'] ?? '')),
  11804. 'amount' => $amount,
  11805. 'amount_text' => $isQuoted ? $amount : '',
  11806. 'is_quoted' => $isQuoted,
  11807. 'quote_label' => $isQuoted ? '已报价' : '未报价',
  11808. 'status_name' => trim((string)($row['status_name'] ?? '')),
  11809. 'oper_time' => $oper,
  11810. ];
  11811. }
  11812. $this->success('', null, [
  11813. 'scydgy_id' => $sid,
  11814. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  11815. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  11816. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  11817. 'CDW' => trim((string)($po['CDW'] ?? '')),
  11818. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  11819. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  11820. 'CDF' => trim((string)($po['CDF'] ?? '')),
  11821. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  11822. 'list' => $list,
  11823. ]);
  11824. }
  11825. /**
  11826. * 手工询价是否已下发(有下发明细或已进入待确认及之后)
  11827. */
  11828. protected function isRfqOrderIssued(array $po): bool
  11829. {
  11830. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  11831. return true;
  11832. }
  11833. $sid = (int)($po['scydgy_id'] ?? 0);
  11834. if ($sid >= 0) {
  11835. return false;
  11836. }
  11837. try {
  11838. $q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  11839. $this->applyActivePurchaseOrderDetailWhere($q);
  11840. return (int)$q->count() > 0;
  11841. } catch (\Throwable $e) {
  11842. return false;
  11843. }
  11844. }
  11845. /**
  11846. * 批量:已有下发明细的手工询价 scydgy_id
  11847. *
  11848. * @param int[] $scydgyIds
  11849. * @return array<int, bool>
  11850. */
  11851. protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
  11852. {
  11853. $set = [];
  11854. $ids = [];
  11855. foreach ($scydgyIds as $sid) {
  11856. $sid = (int)$sid;
  11857. if ($sid < 0) {
  11858. $ids[$sid] = true;
  11859. }
  11860. }
  11861. if ($ids === []) {
  11862. return $set;
  11863. }
  11864. try {
  11865. $q = Db::table('purchase_order_detail')
  11866. ->where('scydgy_id', 'in', array_keys($ids))
  11867. ->field('scydgy_id');
  11868. $this->applyActivePurchaseOrderDetailWhere($q);
  11869. $rows = $q->select();
  11870. } catch (\Throwable $e) {
  11871. return $set;
  11872. }
  11873. if (!is_array($rows)) {
  11874. return $set;
  11875. }
  11876. foreach ($rows as $row) {
  11877. if (!is_array($row)) {
  11878. continue;
  11879. }
  11880. $sid = (int)($row['scydgy_id'] ?? 0);
  11881. if ($sid < 0) {
  11882. $set[$sid] = true;
  11883. }
  11884. }
  11885. return $set;
  11886. }
  11887. /**
  11888. * 批量:已填单价(已报价)的手工询价 scydgy_id
  11889. *
  11890. * @param int[] $scydgyIds
  11891. * @return array<int, bool>
  11892. */
  11893. protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
  11894. {
  11895. $set = [];
  11896. $ids = [];
  11897. foreach ($scydgyIds as $sid) {
  11898. $sid = (int)$sid;
  11899. if ($sid < 0) {
  11900. $ids[$sid] = true;
  11901. }
  11902. }
  11903. if ($ids === []) {
  11904. return $set;
  11905. }
  11906. try {
  11907. $q = Db::table('purchase_order_detail')
  11908. ->where('scydgy_id', 'in', array_keys($ids))
  11909. ->field('scydgy_id,amount');
  11910. $this->applyActivePurchaseOrderDetailWhere($q);
  11911. $rows = $q->select();
  11912. } catch (\Throwable $e) {
  11913. return $set;
  11914. }
  11915. if (!is_array($rows)) {
  11916. return $set;
  11917. }
  11918. foreach ($rows as $row) {
  11919. if (!is_array($row)) {
  11920. continue;
  11921. }
  11922. $amount = trim((string)($row['amount'] ?? ''));
  11923. if ($amount === '' || $amount === '0' || $amount === '0.00') {
  11924. continue;
  11925. }
  11926. $sid = (int)($row['scydgy_id'] ?? 0);
  11927. if ($sid < 0) {
  11928. $set[$sid] = true;
  11929. }
  11930. }
  11931. return $set;
  11932. }
  11933. /**
  11934. * 已下发且至少一家供应商已报价,才允许通知业务员
  11935. */
  11936. protected function canRfqNotifySalesman(array $po): bool
  11937. {
  11938. if (!$this->isRfqOrderIssued($po)) {
  11939. return false;
  11940. }
  11941. $sid = (int)($po['scydgy_id'] ?? 0);
  11942. if ($sid >= 0) {
  11943. return false;
  11944. }
  11945. $quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
  11946. return isset($quoted[$sid]);
  11947. }
  11948. protected function assertRfqCanNotifySalesman(array $po): void
  11949. {
  11950. if (!$this->isRfqOrderIssued($po)) {
  11951. $this->error('请先询价并等待供应商报价后再通知业务员');
  11952. }
  11953. if (!$this->canRfqNotifySalesman($po)) {
  11954. $this->error('供应商尚未报价,暂不能通知业务员');
  11955. }
  11956. }
  11957. /**
  11958. * 加载手工询价单(含可见性校验)
  11959. *
  11960. * @return array<string, mixed>
  11961. */
  11962. protected function loadManualRfqOrderForNotify(int $scydgyId): array
  11963. {
  11964. try {
  11965. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  11966. } catch (\Throwable $e) {
  11967. $po = null;
  11968. }
  11969. if (!is_array($po)) {
  11970. $this->error('订单不存在');
  11971. }
  11972. $modRq = trim((string)($po['mod_rq'] ?? ''));
  11973. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  11974. $this->error('订单不存在');
  11975. }
  11976. if ($this->auth->isSuperAdmin()) {
  11977. return $po;
  11978. }
  11979. if ($this->canViewManualRfqOrder($po)) {
  11980. return $po;
  11981. }
  11982. $this->error('无权操作该订单');
  11983. }
  11984. /**
  11985. * @return string[]
  11986. */
  11987. protected function splitRfqSalesmanNames(string $raw): array
  11988. {
  11989. $parts = [];
  11990. $raw = trim($raw);
  11991. if ($raw === '') {
  11992. return [];
  11993. }
  11994. foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
  11995. $v = trim((string)$piece);
  11996. if ($v !== '' && !in_array($v, $parts, true)) {
  11997. $parts[] = $v;
  11998. }
  11999. }
  12000. return $parts;
  12001. }
  12002. /**
  12003. * 按姓名匹配 fa_admin 邮箱
  12004. *
  12005. * @param string[] $names
  12006. * @return array<int, array{admin_id:int,name:string,email:string}>
  12007. */
  12008. protected function resolveRfqSalesmanContactRows(array $names): array
  12009. {
  12010. $out = [];
  12011. foreach ($names as $name) {
  12012. $name = trim((string)$name);
  12013. if ($name === '') {
  12014. continue;
  12015. }
  12016. $adminId = 0;
  12017. $email = '';
  12018. try {
  12019. $row = Db::name('admin')
  12020. ->where(function ($q) use ($name) {
  12021. $q->where('nickname', $name)->whereOr('username', $name);
  12022. })
  12023. ->where('status', 'normal')
  12024. ->order('id', 'asc')
  12025. ->field('id,nickname,username,email')
  12026. ->find();
  12027. } catch (\Throwable $e) {
  12028. $row = null;
  12029. }
  12030. if (is_array($row)) {
  12031. $adminId = (int)($row['id'] ?? 0);
  12032. $email = trim((string)($row['email'] ?? ''));
  12033. $disp = trim((string)($row['nickname'] ?? ''));
  12034. if ($disp === '') {
  12035. $disp = trim((string)($row['username'] ?? ''));
  12036. }
  12037. if ($disp !== '') {
  12038. $name = $disp;
  12039. }
  12040. }
  12041. $out[] = [
  12042. 'admin_id' => $adminId,
  12043. 'name' => $name,
  12044. 'email' => $email,
  12045. ];
  12046. }
  12047. return $out;
  12048. }
  12049. /**
  12050. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  12051. */
  12052. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  12053. {
  12054. if ($scydgyId >= 0) {
  12055. return;
  12056. }
  12057. try {
  12058. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  12059. } catch (\Throwable $e) {
  12060. $po = null;
  12061. }
  12062. if (!is_array($po)) {
  12063. $this->error('订单不存在');
  12064. }
  12065. $modRq = trim((string)($po['mod_rq'] ?? ''));
  12066. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  12067. $this->error('订单不存在');
  12068. }
  12069. if ($this->auth->isSuperAdmin()) {
  12070. return;
  12071. }
  12072. [, $adminName] = $this->GetUseName();
  12073. $cywy = trim((string)($po['cywyxm'] ?? ''));
  12074. if ($cywy !== '' && $cywy === $adminName) {
  12075. return;
  12076. }
  12077. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  12078. try {
  12079. if ($this->auth->check($rule)) {
  12080. return;
  12081. }
  12082. } catch (\Throwable $e) {
  12083. }
  12084. }
  12085. $this->error('无权查看该订单');
  12086. }
  12087. /**
  12088. * 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
  12089. */
  12090. protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
  12091. {
  12092. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  12093. return ProcuremenStatus::PO_COMPLETED;
  12094. }
  12095. $sid = (int)($row['scydgy_id'] ?? 0);
  12096. if ($sid < 0) {
  12097. if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
  12098. return '已通知业务员';
  12099. }
  12100. if ($hasQuoted) {
  12101. return '供应商已报价';
  12102. }
  12103. if ($hasIssued
  12104. || ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
  12105. || ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
  12106. return '待报价';
  12107. }
  12108. try {
  12109. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  12110. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  12111. if ((int)$detCntQuery->count() > 0) {
  12112. return '待报价';
  12113. }
  12114. } catch (\Throwable $e) {
  12115. }
  12116. return '待询价';
  12117. }
  12118. if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
  12119. return '待入库评分';
  12120. }
  12121. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  12122. return '待采购确认';
  12123. }
  12124. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  12125. return '待确认供应商';
  12126. }
  12127. return '待协助下发';
  12128. }
  12129. /**
  12130. * 协助初选列表 — 批量软删除
  12131. */
  12132. public function pickDelete()
  12133. {
  12134. if (!$this->request->isPost() || !$this->request->isAjax()) {
  12135. $this->error(__('Invalid parameters'));
  12136. }
  12137. if (!$this->procuremenCanPickDelete()) {
  12138. $this->error(__('You have no permission'));
  12139. }
  12140. $rowsRaw = $this->request->post('rows_json', '[]');
  12141. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  12142. if (!is_array($rows) || $rows === []) {
  12143. $this->error('请至少勾选一条工序');
  12144. }
  12145. $done = 0;
  12146. Db::startTrans();
  12147. try {
  12148. foreach ($rows as $row) {
  12149. if (!is_array($row)) {
  12150. continue;
  12151. }
  12152. $this->softDeleteProcuremenPickRow($row);
  12153. $done++;
  12154. }
  12155. if ($done < 1) {
  12156. throw new \Exception('没有可删除的工序');
  12157. }
  12158. Db::commit();
  12159. } catch (\InvalidArgumentException $e) {
  12160. Db::rollback();
  12161. $this->error($e->getMessage());
  12162. } catch (\Throwable $e) {
  12163. Db::rollback();
  12164. $this->error($e->getMessage());
  12165. }
  12166. $this->pickHiddenScydgySetCache = null;
  12167. $this->success('已删除 ' . $done . ' 条工序');
  12168. }
  12169. /**
  12170. * 下发 — 手工新增工序(弹窗)
  12171. */
  12172. public function pickAdd()
  12173. {
  12174. if ($this->request->isPost()) {
  12175. $params = $this->request->post('row/a');
  12176. if (!is_array($params)) {
  12177. $this->error(__('Parameter %s can not be empty', ''));
  12178. }
  12179. try {
  12180. $sid = $this->saveManualPickOrder($params);
  12181. } catch (\InvalidArgumentException $e) {
  12182. $this->error($e->getMessage());
  12183. } catch (\Throwable $e) {
  12184. $this->error($e->getMessage());
  12185. }
  12186. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  12187. }
  12188. return $this->view->fetch('procuremen/pick_add');
  12189. }
  12190. /**
  12191. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  12192. */
  12193. public function pickSubmit()
  12194. {
  12195. if (!$this->request->isPost()) {
  12196. $this->error(__('Invalid parameters'));
  12197. }
  12198. // ---------- 接口订单数据 ----------
  12199. $rowJson = $this->request->post('row_json', '');
  12200. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  12201. $companiesJson = $this->request->post('companies_json', '[]');
  12202. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  12203. $companies = json_decode($companiesJson, true);
  12204. if (!is_array($companies)) {
  12205. $this->error('供应商数据无效');
  12206. }
  12207. $postedCompanyCount = 0;
  12208. $skippedCompanyCount = 0;
  12209. foreach ($companies as $c) {
  12210. if (is_array($c) && (trim((string)($c['name'] ?? $c['company_name'] ?? '')) !== '' || trim((string)($c['id'] ?? '')) !== '')) {
  12211. $postedCompanyCount++;
  12212. }
  12213. }
  12214. $issueCompanies = $this->normalizePickCompanies($companies);
  12215. if ($issueCompanies === []) {
  12216. $this->error('请至少选择一家合作供应商(须同时具备有效手机号与邮箱)');
  12217. }
  12218. // 不可用供应商静默跳过,不向操作员报错;成功提示中说明实际下发家数
  12219. if ($postedCompanyCount > 0 && count($issueCompanies) < $postedCompanyCount) {
  12220. $skippedCompanyCount = $postedCompanyCount - count($issueCompanies);
  12221. Log::write(
  12222. 'procuremen pickSubmit skip companies: posted=' . $postedCompanyCount
  12223. . ' issued=' . count($issueCompanies),
  12224. 'notice'
  12225. );
  12226. }
  12227. $issueNameLabels = [];
  12228. foreach ($issueCompanies as $pc) {
  12229. $issueNameLabels[] = $pc['name'];
  12230. }
  12231. $issueNamesSummary = implode('、', $issueNameLabels);
  12232. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  12233. if ($sysRq === '') {
  12234. $this->error('请选择招标截止日期');
  12235. }
  12236. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  12237. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  12238. (string)$this->request->post('delivery_deadline', ''),
  12239. true
  12240. );
  12241. $scoreRuleId = (int)$this->request->post('score_rule_id', 0);
  12242. if ($scoreRuleId <= 0) {
  12243. $this->error('请选择订单类型');
  12244. }
  12245. $scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
  12246. if ((int)($scoreRule['id'] ?? 0) <= 0) {
  12247. $this->error('订单类型无效,请刷新后重选');
  12248. }
  12249. $scoreRuleId = (int)$scoreRule['id'];
  12250. $this->ensurePurchaseOrderScoreRuleIdColumn();
  12251. $logMsg = '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  12252. $bidDispForLog = $this->formatProcuremenSysRqForDisplay($sysRqDb);
  12253. $delDispForLog = $this->formatProcuremenDeliveryDeadlineForInput($deliveryDeadlineDb);
  12254. if ($delDispForLog === '') {
  12255. $delDispForLog = $this->formatDeliveryYmd($deliveryDeadlineDb);
  12256. }
  12257. $orderTypeForLog = trim((string)($scoreRule['name'] ?? ''));
  12258. $logExtra = [];
  12259. if ($bidDispForLog !== '' && $bidDispForLog !== '—') {
  12260. $logExtra[] = '招标截止日期:' . $bidDispForLog;
  12261. }
  12262. if ($delDispForLog !== '') {
  12263. $logExtra[] = '交货截止日期:' . $delDispForLog;
  12264. }
  12265. if ($orderTypeForLog !== '') {
  12266. $logExtra[] = '订单类型:' . $orderTypeForLog;
  12267. }
  12268. if ($logExtra !== []) {
  12269. $logMsg .= ';' . implode(';', $logExtra);
  12270. }
  12271. $issueTime = date('Y-m-d H:i:s');
  12272. try {
  12273. $issueBatchNo = $this->allocateProcuremenIssueBatchNo();
  12274. } catch (\Throwable $e) {
  12275. $this->error($e->getMessage() !== '' ? $e->getMessage() : '批次号生成失败,请重试');
  12276. }
  12277. $logSidList = [];
  12278. foreach ($mergeRows as $row) {
  12279. if (!is_array($row)) {
  12280. continue;
  12281. }
  12282. $sid = $this->extractScydgyRowId($row);
  12283. if ($this->isValidScydgyRowId($sid)) {
  12284. $logSidList[$sid] = true;
  12285. }
  12286. }
  12287. if ($logSidList === []) {
  12288. $this->error('未找到有效工序,无法下发');
  12289. }
  12290. // 防连点/并发:同一批工序加命名锁,已下发则直接拒绝(避免重复短信邮件)
  12291. $sidKeys = array_keys($logSidList);
  12292. sort($sidKeys, SORT_NUMERIC);
  12293. $pickLockName = 'procuremen_pick_submit_' . md5(implode(',', $sidKeys));
  12294. if (!$this->acquireProcuremenNamedLock($pickLockName, 15)) {
  12295. $this->error('下发处理中,请勿重复点击');
  12296. }
  12297. $existingBySid = [];
  12298. try {
  12299. try {
  12300. $existingRows = Db::table('purchase_order')
  12301. ->where('scydgy_id', 'in', $sidKeys)
  12302. ->select();
  12303. if (is_array($existingRows)) {
  12304. foreach ($existingRows as $poRow) {
  12305. if (!is_array($poRow)) {
  12306. continue;
  12307. }
  12308. $sid = (int)($poRow['scydgy_id'] ?? 0);
  12309. if ($this->isValidScydgyRowId($sid)) {
  12310. $existingBySid[$sid] = $poRow;
  12311. }
  12312. }
  12313. }
  12314. } catch (\Throwable $e) {
  12315. $existingBySid = [];
  12316. }
  12317. foreach ($sidKeys as $sid) {
  12318. $poRow = $existingBySid[$sid] ?? null;
  12319. if (!is_array($poRow)) {
  12320. continue;
  12321. }
  12322. if ($this->isPurchaseOrderSoftDeleted($poRow['mod_rq'] ?? null)) {
  12323. continue;
  12324. }
  12325. $label = $this->formatProcuremenRowLabel(['CCYDH' => $poRow['CCYDH'] ?? '', 'CGYMC' => $poRow['CGYMC'] ?? '']);
  12326. if (ProcuremenStatus::isPoCompleted($poRow['status'] ?? '')) {
  12327. $this->error(($label !== '' ? $label : ('工序#' . $sid)) . '已完结,无法再次下发');
  12328. }
  12329. if (!ProcuremenStatus::isWflowPendingIssue($poRow['wflow_status'] ?? '')) {
  12330. $this->error(($label !== '' ? $label : ('工序#' . $sid)) . '已下发或进入后续流程,请勿重复提交');
  12331. }
  12332. }
  12333. Db::startTrans();
  12334. try {
  12335. $this->enrichProcuremenRowsMbz($mergeRows);
  12336. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  12337. foreach ($mergeRows as $row) {
  12338. if (!is_array($row)) {
  12339. continue;
  12340. }
  12341. $sid = $this->extractScydgyRowId($row);
  12342. $this->upsertPurchaseOrderFromRow(
  12343. $row,
  12344. $sysRqDb,
  12345. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  12346. $issueTime,
  12347. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  12348. $deliveryDeadlineDb,
  12349. $scoreRule,
  12350. $issueBatchNo
  12351. );
  12352. }
  12353. foreach ($issueCompanies as $c) {
  12354. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  12355. }
  12356. Db::commit();
  12357. } catch (\Throwable $e) {
  12358. Db::rollback();
  12359. $this->error($e->getMessage());
  12360. }
  12361. } finally {
  12362. $this->releaseProcuremenNamedLock($pickLockName);
  12363. }
  12364. $poIdBySid = [];
  12365. if ($logSidList !== []) {
  12366. try {
  12367. $poIdBySid = Db::table('purchase_order')
  12368. ->where('scydgy_id', 'in', array_keys($logSidList))
  12369. ->column('id', 'scydgy_id');
  12370. } catch (\Throwable $e) {
  12371. $poIdBySid = [];
  12372. }
  12373. }
  12374. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  12375. if ($logSidList !== []) {
  12376. list($adminId, $adminName) = $this->GetUseName();
  12377. $logRows = [];
  12378. $seenLogSid = [];
  12379. foreach ($mergeRows as $row) {
  12380. if (!is_array($row)) {
  12381. continue;
  12382. }
  12383. $ids = $this->extractScydgyRowId($row);
  12384. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  12385. continue;
  12386. }
  12387. $seenLogSid[$ids] = true;
  12388. $poIdLog = null;
  12389. if (isset($poIdBySid[$ids])) {
  12390. $tid = (int)$poIdBySid[$ids];
  12391. $poIdLog = $tid > 0 ? $tid : null;
  12392. }
  12393. $logRows[] = ProcuremenOperLog::buildInsertRow(
  12394. $ids,
  12395. 'issue_submit',
  12396. $logMsg,
  12397. $poIdLog,
  12398. (int)$adminId,
  12399. (string)$adminName
  12400. );
  12401. }
  12402. if ($logRows !== []) {
  12403. try {
  12404. Db::table('purchase_order_oper_log')->insertAll($logRows);
  12405. } catch (\Throwable $e) {
  12406. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  12407. }
  12408. }
  12409. }
  12410. $posNotify = [];
  12411. if ($logSidList !== []) {
  12412. try {
  12413. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  12414. } catch (\Throwable $e) {
  12415. $posNotify = [];
  12416. }
  12417. }
  12418. if (!is_array($posNotify)) {
  12419. $posNotify = [];
  12420. }
  12421. foreach ($posNotify as $i => $prow) {
  12422. if (is_array($posNotify[$i])) {
  12423. $posNotify[$i]['sys_rq'] = $sysRqDb;
  12424. }
  12425. }
  12426. $ccydhPick = '';
  12427. foreach ($mergeRows as $row) {
  12428. if (!is_array($row)) {
  12429. continue;
  12430. }
  12431. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  12432. if ($ccydhPick !== '') {
  12433. break;
  12434. }
  12435. }
  12436. $notifyBundleBase = [
  12437. 'ccydh' => $ccydhPick,
  12438. 'pos' => $posNotify,
  12439. 'merge_rows' => $mergeRows,
  12440. 'score_rule' => is_array($scoreRule) ? $scoreRule : null,
  12441. ];
  12442. // 写库已成功:先立刻回成功给前端,再后台发短信/邮件(避免多家串行超时转圈/误报失败)
  12443. $okCount = count($issueCompanies);
  12444. $skipHint = '';
  12445. if (!empty($skippedCompanyCount) && (int)$skippedCompanyCount > 0) {
  12446. $skipHint = '(已自动跳过 ' . (int)$skippedCompanyCount . ' 家资料不完整的供应商)';
  12447. }
  12448. $payload = [
  12449. 'issued' => 1,
  12450. 'supplier_count' => $okCount,
  12451. 'notify_pending' => 1,
  12452. 'notify_failed' => 0,
  12453. ];
  12454. $successMsg = '下发成功' . $skipHint . ',已向 ' . $okCount
  12455. . ' 家供应商发起通知。若个别未收到短信或邮件,请到「协助审批下发」使用重发功能补发。';
  12456. if ($this->isProcuremenNotifyDryRun()) {
  12457. $this->notifyDryRunPreview = [];
  12458. $notifyErrors = [];
  12459. foreach ($issueCompanies as $c) {
  12460. if (!is_array($c)) {
  12461. continue;
  12462. }
  12463. $cname = trim((string)($c['name'] ?? ''));
  12464. if ($cname === '') {
  12465. continue;
  12466. }
  12467. try {
  12468. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  12469. } catch (\Throwable $e) {
  12470. $notifyErrors[] = $cname . ':' . $e->getMessage();
  12471. }
  12472. }
  12473. $this->success('【演练模式】已保存并生成通知预览', '', [
  12474. 'notify_dry_run' => true,
  12475. 'notify_preview' => $this->notifyDryRunPreview,
  12476. 'notify_fail_detail' => $notifyErrors,
  12477. ]);
  12478. }
  12479. $this->respondSuccessThenContinue($successMsg, $payload);
  12480. @set_time_limit(300);
  12481. @ini_set('max_execution_time', '300');
  12482. $notifyOk = 0;
  12483. $notifyErrors = [];
  12484. foreach ($issueCompanies as $c) {
  12485. if (!is_array($c)) {
  12486. continue;
  12487. }
  12488. $cname = trim((string)($c['name'] ?? ''));
  12489. if ($cname === '') {
  12490. continue;
  12491. }
  12492. try {
  12493. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  12494. $notifyOk++;
  12495. } catch (\Throwable $e) {
  12496. $notifyErrors[] = $cname . ':' . $e->getMessage();
  12497. Log::write('procuremen pickSubmit background notify fail ' . $cname . ': ' . $e->getMessage(), 'error');
  12498. }
  12499. }
  12500. if ($notifyErrors !== []) {
  12501. Log::write(
  12502. 'procuremen pickSubmit background notify summary ok=' . $notifyOk
  12503. . ' fail=' . count($notifyErrors) . ' ' . implode(';', $notifyErrors),
  12504. 'error'
  12505. );
  12506. }
  12507. exit;
  12508. }
  12509. /**
  12510. * 确认供应商弹窗
  12511. */
  12512. public function auditIssue()
  12513. {
  12514. $ids = $this->request->param('ids', $this->request->param('id', ''));
  12515. if (is_array($ids)) {
  12516. $ids = isset($ids[0]) ? $ids[0] : '';
  12517. }
  12518. $ids = trim((string)$ids);
  12519. if ($ids === '') {
  12520. $this->error(__('Invalid parameters'));
  12521. }
  12522. if ($this->request->isPost()) {
  12523. $this->error('请使用弹窗内「确认」提交');
  12524. }
  12525. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  12526. $pos = $bundle['pos'];
  12527. if ($pos === []) {
  12528. $this->error('该订单不在待确认供应商状态');
  12529. }
  12530. $po = $pos[0];
  12531. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  12532. if ($quoteGroups === []) {
  12533. $toastMsg = '暂无下发明细,请确认该订单已在「供应商初选」完成下发';
  12534. // 弹层内不要走整页跳转提示,仅 Toastr 后关闭
  12535. $this->view->assign('toastMsg', $toastMsg);
  12536. return $this->view->fetch('procuremen/toast_close');
  12537. }
  12538. $pickedName = '';
  12539. foreach ($pos as $poRow) {
  12540. if (!is_array($poRow)) {
  12541. continue;
  12542. }
  12543. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  12544. if ($pn !== '') {
  12545. $pickedName = $pn;
  12546. break;
  12547. }
  12548. }
  12549. $this->view->assign('po', $po);
  12550. $this->view->assign('scydgyId', $ids);
  12551. $this->view->assign('orderCcydh', $bundle['ccydh']);
  12552. $mergeRows = $bundle['merge_rows'];
  12553. $this->view->assign('processRows', $mergeRows);
  12554. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  12555. $this->view->assign('processCount', count($mergeRows));
  12556. $this->view->assign('orderBatchNo', $this->resolveBundleOrderBatchNo($bundle));
  12557. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  12558. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  12559. $this->view->assign('pickedCompanyName', $pickedName);
  12560. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  12561. if ($sysRqForView === '') {
  12562. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  12563. }
  12564. $this->view->assign('sysRq', $sysRqForView);
  12565. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  12566. if ($deliveryDeadlineForView === '') {
  12567. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  12568. }
  12569. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  12570. $this->ensurePurchaseOrderManualPickColumns();
  12571. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
  12572. $manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
  12573. $manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
  12574. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  12575. if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
  12576. $pickedName = $manualPickInfo['company'];
  12577. $this->view->assign('pickedCompanyName', $pickedName);
  12578. }
  12579. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  12580. $this->view->assign('manualPicked', $manualPicked);
  12581. $this->view->assign('manualPickReason', $manualPickInfo['reason']);
  12582. $this->view->assign('quoteVisible', $quoteVisible);
  12583. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
  12584. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  12585. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
  12586. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
  12587. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  12588. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  12589. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  12590. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  12591. return $this->view->fetch('procuremen/audit_issue');
  12592. }
  12593. /**
  12594. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  12595. *
  12596. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  12597. */
  12598. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  12599. {
  12600. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  12601. return false;
  12602. }
  12603. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  12604. return false;
  12605. }
  12606. return true;
  12607. }
  12608. /**
  12609. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  12610. *
  12611. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  12612. */
  12613. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  12614. {
  12615. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  12616. return false;
  12617. }
  12618. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  12619. return false;
  12620. }
  12621. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  12622. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  12623. return true;
  12624. }
  12625. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  12626. }
  12627. /**
  12628. * 确认页 — 补加供应商弹窗
  12629. */
  12630. public function auditAppend()
  12631. {
  12632. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  12633. $this->error(__('You have no permission'));
  12634. }
  12635. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  12636. if (is_array($ids)) {
  12637. $ids = isset($ids[0]) ? $ids[0] : '';
  12638. }
  12639. $ids = trim((string)$ids);
  12640. if ($ids === '') {
  12641. $this->error(__('Invalid parameters'));
  12642. }
  12643. if ($this->request->isPost()) {
  12644. $this->error('请使用弹窗内「确认」提交');
  12645. }
  12646. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  12647. if (($bundle['pos'] ?? []) === []) {
  12648. $this->error('该订单不在待确认供应商状态');
  12649. }
  12650. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  12651. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  12652. $this->error('已开标验证,不能再补加供应商');
  12653. }
  12654. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  12655. $this->error('已指定供应商,不能再补加供应商');
  12656. }
  12657. $this->error('已经超过了招标截止日期,不可操作');
  12658. }
  12659. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  12660. $existingNames = [];
  12661. foreach ($quoteGroups as $g) {
  12662. if (!is_array($g)) {
  12663. continue;
  12664. }
  12665. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  12666. if ($n !== '') {
  12667. $existingNames[$n] = true;
  12668. }
  12669. }
  12670. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  12671. $mergeRows = $bundle['merge_rows'] ?? [];
  12672. $this->view->assign('scydgyId', $ids);
  12673. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  12674. $this->view->assign('po', $po);
  12675. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  12676. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  12677. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  12678. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  12679. if ($sysRqForView === '') {
  12680. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  12681. }
  12682. $this->view->assign('sysRq', $sysRqForView);
  12683. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  12684. if ($deliveryDeadlineForView === '') {
  12685. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  12686. }
  12687. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  12688. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  12689. }
  12690. /**
  12691. * 确认页 — 补加供应商提交
  12692. */
  12693. public function auditAppendSubmit()
  12694. {
  12695. if (!$this->request->isPost()) {
  12696. $this->error(__('Invalid parameters'));
  12697. }
  12698. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  12699. $this->error(__('You have no permission'));
  12700. }
  12701. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  12702. if ($ids === '') {
  12703. $this->error(__('Invalid parameters'));
  12704. }
  12705. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  12706. if (($bundle['pos'] ?? []) === []) {
  12707. $this->error('该订单不在待确认供应商状态');
  12708. }
  12709. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  12710. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  12711. $this->error('已开标验证,不能再补加供应商');
  12712. }
  12713. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  12714. $this->error('已指定供应商,不能再补加供应商');
  12715. }
  12716. $this->error('已经超过了招标截止日期,不可操作');
  12717. }
  12718. $companiesJson = $this->request->post('companies_json', '[]');
  12719. $companies = json_decode((string)$companiesJson, true);
  12720. if (!is_array($companies)) {
  12721. $this->error('供应商数据无效');
  12722. }
  12723. $issueCompanies = $this->normalizePickCompanies($companies);
  12724. if ($issueCompanies === []) {
  12725. $this->error('请至少选择一家合作供应商');
  12726. }
  12727. $mergeRows = $bundle['merge_rows'] ?? [];
  12728. if (!is_array($mergeRows) || $mergeRows === []) {
  12729. $this->error('未找到工序行,无法补加');
  12730. }
  12731. $existingNames = [];
  12732. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  12733. if (!is_array($g)) {
  12734. continue;
  12735. }
  12736. $n = trim((string)($g['company_name'] ?? ''));
  12737. if ($n !== '') {
  12738. $existingNames[$n] = true;
  12739. }
  12740. }
  12741. $toAdd = [];
  12742. foreach ($issueCompanies as $c) {
  12743. if (!is_array($c)) {
  12744. continue;
  12745. }
  12746. $n = trim((string)($c['name'] ?? ''));
  12747. if ($n === '' || isset($existingNames[$n])) {
  12748. continue;
  12749. }
  12750. $toAdd[] = $c;
  12751. }
  12752. if ($toAdd === []) {
  12753. $this->error('所选供应商均已在本单中,请选择新的供应商');
  12754. }
  12755. $addedNames = [];
  12756. Db::startTrans();
  12757. try {
  12758. foreach ($toAdd as $c) {
  12759. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  12760. $addedNames[] = trim((string)($c['name'] ?? ''));
  12761. }
  12762. Db::commit();
  12763. } catch (\Throwable $e) {
  12764. Db::rollback();
  12765. $this->error($e->getMessage());
  12766. }
  12767. $notifyBundleBase = [
  12768. 'ccydh' => $bundle['ccydh'] ?? '',
  12769. 'pos' => $bundle['pos'] ?? [],
  12770. 'merge_rows' => $mergeRows,
  12771. ];
  12772. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  12773. $seenLogSid = [];
  12774. foreach ($bundle['pos'] ?? [] as $poRow) {
  12775. if (!is_array($poRow)) {
  12776. continue;
  12777. }
  12778. $sid = (int)($poRow['scydgy_id'] ?? 0);
  12779. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  12780. continue;
  12781. }
  12782. $seenLogSid[$sid] = true;
  12783. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  12784. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  12785. }
  12786. if ($seenLogSid === []) {
  12787. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  12788. if ($this->isValidScydgyRowId($logSid)) {
  12789. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  12790. }
  12791. }
  12792. if ($this->isProcuremenNotifyDryRun()) {
  12793. $this->notifyDryRunPreview = [];
  12794. $notifyErrors = [];
  12795. foreach ($toAdd as $c) {
  12796. if (!is_array($c)) {
  12797. continue;
  12798. }
  12799. $cname = trim((string)($c['name'] ?? ''));
  12800. if ($cname === '') {
  12801. continue;
  12802. }
  12803. try {
  12804. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  12805. } catch (\Throwable $e) {
  12806. $notifyErrors[] = $cname . ':' . $e->getMessage();
  12807. }
  12808. }
  12809. $this->success('【演练模式】已补加并生成通知预览', '', [
  12810. 'append_ok' => 1,
  12811. 'notify_dry_run' => true,
  12812. 'notify_preview' => $this->notifyDryRunPreview,
  12813. 'notify_fail_detail' => $notifyErrors,
  12814. ]);
  12815. }
  12816. $this->respondSuccessThenContinue(
  12817. '已补加 ' . count($toAdd) . ' 家供应商并发起通知。若个别未收到,请使用「重发短信 / 重发邮件」补发。',
  12818. ['append_ok' => 1, 'notify_pending' => 1, 'notify_failed' => 0]
  12819. );
  12820. $notifyErrors = [];
  12821. foreach ($toAdd as $c) {
  12822. if (!is_array($c)) {
  12823. continue;
  12824. }
  12825. $cname = trim((string)($c['name'] ?? ''));
  12826. if ($cname === '') {
  12827. continue;
  12828. }
  12829. try {
  12830. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  12831. } catch (\Throwable $e) {
  12832. $notifyErrors[] = $cname . ':' . $e->getMessage();
  12833. Log::write('procuremen auditAppend background notify fail ' . $cname . ': ' . $e->getMessage(), 'error');
  12834. }
  12835. }
  12836. if ($notifyErrors !== []) {
  12837. Log::write('procuremen auditAppend background notify summary: ' . implode(';', $notifyErrors), 'error');
  12838. }
  12839. exit;
  12840. }
  12841. /**
  12842. * 开标双重验证 — 可选验证人列表
  12843. */
  12844. public function bidOpenUsers()
  12845. {
  12846. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  12847. $this->error('无权限');
  12848. }
  12849. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  12850. if ($scydgyId !== '') {
  12851. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  12852. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  12853. $this->success('已完成开标验证', null, [
  12854. 'verified' => 1,
  12855. 'users' => [],
  12856. ]);
  12857. }
  12858. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  12859. $this->error('本单已指定供应商,无需再开标');
  12860. }
  12861. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  12862. }
  12863. $this->success('', null, [
  12864. 'verified' => 0,
  12865. 'users' => $this->listBidOpenVerifierCandidates(),
  12866. ]);
  12867. }
  12868. /**
  12869. * 开标双重验证 — 向指定管理员发送短信验证码
  12870. */
  12871. public function bidOpenSendCode()
  12872. {
  12873. if (!$this->request->isPost()) {
  12874. $this->error(__('Invalid parameters'));
  12875. }
  12876. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  12877. $this->error('无权限');
  12878. }
  12879. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  12880. $adminId = (int)$this->request->post('admin_id', 0);
  12881. if ($scydgyId === '' || $adminId <= 0) {
  12882. $this->error('参数无效');
  12883. }
  12884. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  12885. if ($bundle['pos'] === []) {
  12886. $this->error('该订单不在待确认供应商状态');
  12887. }
  12888. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  12889. $this->success('已完成开标验证,无需重复发送');
  12890. }
  12891. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  12892. $this->error('本单已指定供应商,无需再开标');
  12893. }
  12894. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  12895. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  12896. if ($ccydh === '') {
  12897. $this->error('订单号无效');
  12898. }
  12899. $admin = $this->loadBidOpenAdminUser($adminId);
  12900. if ($admin === null) {
  12901. $this->error('验证人无效或未绑定手机号');
  12902. }
  12903. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  12904. $cd = max(30, min(120, $cd));
  12905. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  12906. $this->error('发送过于频繁,请稍后再试');
  12907. }
  12908. $code = (string)random_int(100000, 999999);
  12909. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  12910. $ttl = max(60, min(600, $ttl));
  12911. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  12912. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  12913. try {
  12914. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  12915. } catch (\Throwable $e) {
  12916. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  12917. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  12918. $this->error($e->getMessage());
  12919. }
  12920. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  12921. }
  12922. /**
  12923. * 开标双重验证 — 两人验证码校验并记录
  12924. */
  12925. public function bidOpenVerify()
  12926. {
  12927. if (!$this->request->isPost()) {
  12928. $this->error(__('Invalid parameters'));
  12929. }
  12930. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  12931. $this->error('无权限');
  12932. }
  12933. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  12934. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  12935. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  12936. $code1 = trim((string)$this->request->post('code1', ''));
  12937. $code2 = trim((string)$this->request->post('code2', ''));
  12938. if ($scydgyId === '') {
  12939. $this->error('参数无效');
  12940. }
  12941. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  12942. $this->error('请选择两位验证人');
  12943. }
  12944. if ($verifier1Id === $verifier2Id) {
  12945. $this->error('两位验证人不能相同');
  12946. }
  12947. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  12948. $this->error('请输入6位短信验证码');
  12949. }
  12950. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  12951. if ($bundle['pos'] === []) {
  12952. $this->error('该订单不在待确认供应商状态');
  12953. }
  12954. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  12955. if ($ccydh === '') {
  12956. $this->error('订单号无效');
  12957. }
  12958. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  12959. $this->success('已完成开标验证');
  12960. }
  12961. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  12962. $this->error('本单已指定供应商,无需再开标');
  12963. }
  12964. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  12965. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  12966. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  12967. if ($verifier1 === null || $verifier2 === null) {
  12968. $this->error('验证人无效或未绑定手机号');
  12969. }
  12970. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  12971. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  12972. }
  12973. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  12974. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  12975. }
  12976. try {
  12977. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  12978. } catch (\Throwable $e) {
  12979. $this->error($e->getMessage());
  12980. }
  12981. $this->success('开标验证成功,可查看供应商报价与交货日期');
  12982. }
  12983. /**
  12984. * 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
  12985. */
  12986. public function auditManualPick()
  12987. {
  12988. if (!$this->request->isPost()) {
  12989. $this->error(__('Invalid parameters'));
  12990. }
  12991. if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
  12992. $this->error('无权限');
  12993. }
  12994. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  12995. if ($scydgyId === '') {
  12996. $this->error('参数无效');
  12997. }
  12998. $companyName = trim((string)$this->request->post('selected_company', ''));
  12999. $reason = trim((string)$this->request->post('pick_reason', ''));
  13000. if ($companyName === '') {
  13001. $this->error('请选择一家供应商');
  13002. }
  13003. if ($reason === '') {
  13004. $this->error('请填写选择说明');
  13005. }
  13006. if (mb_strlen($reason) > 500) {
  13007. $this->error('选择说明不能超过500字');
  13008. }
  13009. $this->ensurePurchaseOrderManualPickColumns();
  13010. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13011. $pos = $bundle['pos'];
  13012. if ($pos === []) {
  13013. $this->error('该订单不在待确认供应商状态');
  13014. }
  13015. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13016. $this->error('本单已开标验证,请直接在列表中选定供应商后确认');
  13017. }
  13018. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13019. if ($quoteGroups === []) {
  13020. $this->error('暂无供应商,请确认已完成协助初选通知');
  13021. }
  13022. $matched = null;
  13023. foreach ($quoteGroups as $g) {
  13024. if (!is_array($g)) {
  13025. continue;
  13026. }
  13027. if (trim((string)($g['name'] ?? '')) === $companyName) {
  13028. $matched = $g;
  13029. break;
  13030. }
  13031. }
  13032. if ($matched === null) {
  13033. $this->error('所选供应商不在本单报价列表中');
  13034. }
  13035. $logMsg = '指定供应商:' . $companyName . ';说明:' . $reason;
  13036. Db::startTrans();
  13037. try {
  13038. foreach ($pos as $poRow) {
  13039. if (!is_array($poRow)) {
  13040. continue;
  13041. }
  13042. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13043. if (!$this->isValidScydgyRowId($sid)) {
  13044. continue;
  13045. }
  13046. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  13047. 'pick_company_name' => $companyName,
  13048. 'manual_pick' => 1,
  13049. 'manual_pick_reason' => $reason,
  13050. ]);
  13051. }
  13052. Db::commit();
  13053. } catch (\Throwable $e) {
  13054. Db::rollback();
  13055. $this->error($e->getMessage());
  13056. }
  13057. foreach ($pos as $poRow) {
  13058. if (!is_array($poRow)) {
  13059. continue;
  13060. }
  13061. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13062. if (!$this->isValidScydgyRowId($sid)) {
  13063. continue;
  13064. }
  13065. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  13066. $this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  13067. }
  13068. // 自选后可见报价:按本批各订单分别计算评分(与开标后一致)
  13069. try {
  13070. $bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13071. $this->saveProcuremenSupplierScoresForBundle($bundleFresh, date('Y-m'));
  13072. } catch (\Throwable $e) {
  13073. Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
  13074. }
  13075. $this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
  13076. }
  13077. /**
  13078. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  13079. */
  13080. public function auditSubmit()
  13081. {
  13082. if (!$this->request->isPost()) {
  13083. $this->error(__('Invalid parameters'));
  13084. }
  13085. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13086. if ($scydgyId === '') {
  13087. $this->error('参数无效');
  13088. }
  13089. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13090. $pos = $bundle['pos'];
  13091. $mergeRows = $bundle['merge_rows'];
  13092. if ($pos === [] || $mergeRows === []) {
  13093. $this->error('该订单不在待确认供应商状态');
  13094. }
  13095. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13096. if ($quoteGroups === []) {
  13097. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  13098. }
  13099. $companyName = trim((string)$this->request->post('selected_company', ''));
  13100. if ($companyName === '') {
  13101. $this->error('请选择一家供应商');
  13102. }
  13103. $matched = null;
  13104. foreach ($quoteGroups as $g) {
  13105. if (!is_array($g)) {
  13106. continue;
  13107. }
  13108. if (trim((string)($g['name'] ?? '')) === $companyName) {
  13109. $matched = $g;
  13110. break;
  13111. }
  13112. }
  13113. if ($matched === null) {
  13114. $this->error('所选供应商不在本单报价列表中');
  13115. }
  13116. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  13117. if ($sysRqDb === '') {
  13118. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  13119. } else {
  13120. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  13121. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  13122. }
  13123. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  13124. $this->error('未到招标截止日期,暂不可确认');
  13125. }
  13126. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
  13127. && !$this->isProcuremenManualPickedForBundle($bundle)
  13128. ) {
  13129. $this->error('请先完成开标双重验证或指定供应商后再确认');
  13130. }
  13131. $logMsg = '确认供应商:' . $companyName;
  13132. Db::startTrans();
  13133. try {
  13134. foreach ($pos as $poRow) {
  13135. if (!is_array($poRow)) {
  13136. continue;
  13137. }
  13138. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13139. if (!$this->isValidScydgyRowId($sid)) {
  13140. continue;
  13141. }
  13142. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  13143. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  13144. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  13145. 'pick_company_name' => $companyName,
  13146. 'sys_rq' => $sysRqDb,
  13147. ]);
  13148. }
  13149. Db::commit();
  13150. } catch (\Throwable $e) {
  13151. Db::rollback();
  13152. $this->error($e->getMessage());
  13153. }
  13154. foreach ($pos as $poRow) {
  13155. if (!is_array($poRow)) {
  13156. continue;
  13157. }
  13158. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13159. if (!$this->isValidScydgyRowId($sid)) {
  13160. continue;
  13161. }
  13162. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  13163. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  13164. }
  13165. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  13166. }
  13167. /**
  13168. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  13169. */
  13170. public function auditResendSms()
  13171. {
  13172. if (!$this->request->isPost()) {
  13173. $this->error(__('Invalid parameters'));
  13174. }
  13175. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13176. if ($scydgyId === '') {
  13177. $this->error('参数无效');
  13178. }
  13179. $loaded = $this->loadAuditResendBundle($scydgyId);
  13180. $mergeRows = $loaded['merge_rows'];
  13181. $bundle = $loaded['bundle'];
  13182. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  13183. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13184. if ($quoteGroups === []) {
  13185. $this->error('暂无可通知的供应商');
  13186. }
  13187. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  13188. $companiesJson = (string)$this->request->post('companies_json', '');
  13189. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  13190. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  13191. }
  13192. /**
  13193. * 确认供应商 — 二次发送邮件(可选单家/批量)
  13194. */
  13195. public function auditResendEmail()
  13196. {
  13197. if (!$this->request->isPost()) {
  13198. $this->error(__('Invalid parameters'));
  13199. }
  13200. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13201. if ($scydgyId === '') {
  13202. $this->error('参数无效');
  13203. }
  13204. $loaded = $this->loadAuditResendBundle($scydgyId);
  13205. $mergeRows = $loaded['merge_rows'];
  13206. $bundle = $loaded['bundle'];
  13207. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  13208. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13209. if ($quoteGroups === []) {
  13210. $this->error('暂无可通知的供应商');
  13211. }
  13212. $companiesJson = (string)$this->request->post('companies_json', '');
  13213. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  13214. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  13215. if ($companiesJson === '' && $selectedCompany === '') {
  13216. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  13217. }
  13218. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  13219. }
  13220. /**
  13221. * 废弃单个订单 bundle(退回供应商初选,明细归档留痕)
  13222. *
  13223. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  13224. * @return array<int, true> 已处理的 scydgy_id 集合
  13225. */
  13226. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回供应商初选'): array
  13227. {
  13228. $pos = $bundle['pos'] ?? [];
  13229. if (!is_array($pos) || $pos === []) {
  13230. return [];
  13231. }
  13232. $sids = [];
  13233. $poIdBySid = [];
  13234. foreach ($pos as $poRow) {
  13235. if (!is_array($poRow)) {
  13236. continue;
  13237. }
  13238. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13239. if ($this->isValidScydgyRowId($sid)) {
  13240. $sids[$sid] = true;
  13241. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  13242. if ($poId > 0) {
  13243. $poIdBySid[$sid] = $poId;
  13244. }
  13245. }
  13246. }
  13247. if ($sids === []) {
  13248. return [];
  13249. }
  13250. $logMsg = '重新下发';
  13251. $suffix = trim((string)$logSuffix, ',, ');
  13252. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  13253. $logMsg .= ':从历史存证退回供应商初选';
  13254. } else {
  13255. $logMsg .= ':退回供应商初选';
  13256. }
  13257. Db::table('purchase_order')
  13258. ->where('scydgy_id', 'in', array_keys($sids))
  13259. ->update([
  13260. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  13261. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  13262. 'pick_company_name' => '',
  13263. 'pick_time' => null,
  13264. 'sys_rq' => null,
  13265. 'mod_rq' => null,
  13266. 'manual_pick' => 0,
  13267. 'manual_pick_reason' => '',
  13268. ]);
  13269. // 重新下发后需重新开标;清掉本批按订单号/批次号记录的开标验证
  13270. $ccydhSet = [];
  13271. $batchSet = [];
  13272. foreach ($pos as $poRow) {
  13273. if (!is_array($poRow)) {
  13274. continue;
  13275. }
  13276. foreach ($this->expandProcuremenCcydhTokens($poRow['CCYDH'] ?? '') as $dh) {
  13277. $ccydhSet[$dh] = true;
  13278. }
  13279. $bn = $this->resolveProcuremenOrderBatchNo($poRow);
  13280. if ($bn !== '') {
  13281. $batchSet[$bn] = true;
  13282. }
  13283. }
  13284. $this->clearProcuremenBidOpenRecords(array_keys($ccydhSet), array_keys($batchSet));
  13285. $this->clearProcuremenSupplierScoresForCcydhs(array_keys($ccydhSet));
  13286. // 同订单其它旧批次(有明确批次号、未完结)软删除,避免列表/弹窗仍读到旧批「已开标/已指定」
  13287. $keepBatch = '';
  13288. if ($batchSet !== []) {
  13289. $keepBatch = (string)reset(array_keys($batchSet));
  13290. }
  13291. $this->softDeleteOtherBatchPurchaseOrders(array_keys($ccydhSet), array_keys($sids), $keepBatch);
  13292. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  13293. foreach (array_keys($sids) as $sid) {
  13294. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  13295. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  13296. }
  13297. return $sids;
  13298. }
  13299. /**
  13300. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  13301. *
  13302. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  13303. */
  13304. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  13305. {
  13306. $scydgyId = trim($scydgyId);
  13307. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  13308. if ($scydgyId === '') {
  13309. return $empty;
  13310. }
  13311. try {
  13312. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  13313. } catch (\Throwable $e) {
  13314. $anchor = null;
  13315. }
  13316. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  13317. return $empty;
  13318. }
  13319. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  13320. if ($ccydh === '') {
  13321. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  13322. }
  13323. try {
  13324. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  13325. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  13326. $pos = $query->order('scydgy_id', 'asc')->select();
  13327. } catch (\Throwable $e) {
  13328. $pos = [$anchor];
  13329. }
  13330. if (!is_array($pos) || $pos === []) {
  13331. $pos = [$anchor];
  13332. }
  13333. return [
  13334. 'ccydh' => $ccydh,
  13335. 'pos' => $pos,
  13336. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  13337. ];
  13338. }
  13339. protected function purchaseOrderRowIsCompleted(array $po): bool
  13340. {
  13341. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  13342. }
  13343. /**
  13344. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  13345. *
  13346. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  13347. */
  13348. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  13349. {
  13350. $scydgyId = trim($scydgyId);
  13351. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  13352. if ($scydgyId === '') {
  13353. return $empty;
  13354. }
  13355. try {
  13356. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  13357. } catch (\Throwable $e) {
  13358. $anchor = null;
  13359. }
  13360. if (!is_array($anchor)) {
  13361. return $empty;
  13362. }
  13363. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  13364. if ($ccydh === '') {
  13365. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  13366. }
  13367. try {
  13368. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  13369. } catch (\Throwable $e) {
  13370. $pos = [$anchor];
  13371. }
  13372. if (!is_array($pos) || $pos === []) {
  13373. $pos = [$anchor];
  13374. }
  13375. $pos = $this->filterPurchaseOrdersSameIssueBatch($pos, $anchor);
  13376. return [
  13377. 'ccydh' => $ccydh,
  13378. 'pos' => $pos,
  13379. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  13380. ];
  13381. }
  13382. /**
  13383. * 废弃订单 — 退回供应商初选重新询价(支持单条或批量)
  13384. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  13385. */
  13386. public function auditAbandon()
  13387. {
  13388. if (!$this->request->isPost()) {
  13389. $this->error(__('Invalid parameters'));
  13390. }
  13391. $anchorIds = [];
  13392. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  13393. if ($batchRaw !== '') {
  13394. $decoded = json_decode($batchRaw, true);
  13395. if (is_array($decoded)) {
  13396. foreach ($decoded as $id) {
  13397. $s = trim((string)$id);
  13398. if ($s !== '') {
  13399. $anchorIds[] = $s;
  13400. }
  13401. }
  13402. }
  13403. }
  13404. if ($anchorIds === []) {
  13405. $single = trim((string)$this->request->post('scydgy_id', ''));
  13406. if ($single !== '') {
  13407. $anchorIds[] = $single;
  13408. }
  13409. }
  13410. if ($anchorIds === []) {
  13411. $this->error('请至少选择一条订单');
  13412. }
  13413. $processedCcydh = [];
  13414. $doneOrders = 0;
  13415. $allSids = [];
  13416. Db::startTrans();
  13417. try {
  13418. foreach ($anchorIds as $anchorId) {
  13419. $fromArchive = false;
  13420. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  13421. if (($bundle['pos'] ?? []) === []) {
  13422. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  13423. $fromArchive = ($bundle['pos'] ?? []) !== [];
  13424. }
  13425. if (($bundle['pos'] ?? []) === []) {
  13426. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  13427. $fromArchive = ($bundle['pos'] ?? []) !== [];
  13428. }
  13429. if (($bundle['pos'] ?? []) === []) {
  13430. continue;
  13431. }
  13432. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  13433. $batchTime = '';
  13434. if (!empty($bundle['pos'][0]) && is_array($bundle['pos'][0])) {
  13435. $batchTime = $this->procuremenIssueBatchTime($bundle['pos'][0]);
  13436. }
  13437. $dedupeKey = $ccydh !== '' ? ($ccydh . '|' . $batchTime) : ('sid:' . $anchorId);
  13438. if (isset($processedCcydh[$dedupeKey])) {
  13439. continue;
  13440. }
  13441. $processedCcydh[$dedupeKey] = true;
  13442. $sids = $fromArchive
  13443. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回供应商初选')
  13444. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  13445. if ($sids === []) {
  13446. continue;
  13447. }
  13448. $doneOrders++;
  13449. foreach (array_keys($sids) as $sid) {
  13450. $allSids[(int)$sid] = true;
  13451. }
  13452. }
  13453. if ($doneOrders < 1) {
  13454. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  13455. }
  13456. Db::commit();
  13457. } catch (\Throwable $e) {
  13458. Db::rollback();
  13459. $this->error($e->getMessage());
  13460. }
  13461. $this->pickHiddenScydgySetCache = null;
  13462. $msg = $doneOrders > 1
  13463. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回供应商初选,历史下发与操作记录已保留')
  13464. : '已退回供应商初选,请重新选择供应商下发(历史记录已保留)';
  13465. $this->success($msg);
  13466. }
  13467. /**
  13468. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  13469. */
  13470. public function archiveAbandon()
  13471. {
  13472. return $this->auditAbandon();
  13473. }
  13474. /**
  13475. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  13476. */
  13477. public function purchaseApprovalReject()
  13478. {
  13479. if (!$this->request->isPost() || !$this->request->isAjax()) {
  13480. $this->error(__('Invalid parameters'));
  13481. }
  13482. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  13483. $this->error(__('You have no permission'));
  13484. }
  13485. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  13486. $decoded = json_decode($batchRaw, true);
  13487. if (!is_array($decoded) || $decoded === []) {
  13488. $this->error('提交数据无效');
  13489. }
  13490. $done = 0;
  13491. Db::startTrans();
  13492. try {
  13493. foreach ($decoded as $item) {
  13494. if (!is_array($item)) {
  13495. continue;
  13496. }
  13497. $sid = (int)($item['scydgy_id'] ?? 0);
  13498. if (!$this->isValidScydgyRowId($sid)) {
  13499. continue;
  13500. }
  13501. $this->runPurchaseApprovalRejectForSid($sid);
  13502. $done++;
  13503. }
  13504. if ($done < 1) {
  13505. throw new \Exception('所选订单均不在待审批状态');
  13506. }
  13507. Db::commit();
  13508. } catch (\Throwable $e) {
  13509. Db::rollback();
  13510. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  13511. }
  13512. $this->pickHiddenScydgySetCache = null;
  13513. $this->success('已驳回并退回「协助审批下发」');
  13514. }
  13515. /**
  13516. * @throws \Exception
  13517. */
  13518. protected function runPurchaseApprovalRejectForSid(int $sid): void
  13519. {
  13520. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  13521. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  13522. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  13523. $allIds = $this->purchaseOrderDetail($sid);
  13524. if ($allIds === []) {
  13525. throw new \Exception('未找到下发明细');
  13526. }
  13527. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  13528. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  13529. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  13530. 'pick_company_name' => '',
  13531. ]);
  13532. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  13533. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  13534. $poId = 0;
  13535. try {
  13536. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  13537. if (is_array($po)) {
  13538. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  13539. }
  13540. } catch (\Throwable $e) {
  13541. }
  13542. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  13543. }
  13544. /**
  13545. * 审核弹窗(旧入口,POST 已关闭)
  13546. */
  13547. public function review()
  13548. {
  13549. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  13550. $this->error(__('You have no permission'));
  13551. }
  13552. if ($this->request->isPost()) {
  13553. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  13554. }
  13555. $this->view->assign('pickMode', 0);
  13556. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  13557. }
  13558. /**
  13559. * 审核弹窗获取公司列表
  13560. */
  13561. public function reviewCompanies()
  13562. {
  13563. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  13564. $this->error(__('You have no permission'));
  13565. }
  13566. if (!$this->request->isAjax()) {
  13567. $this->error(__('Invalid parameters'));
  13568. }
  13569. $list = [];
  13570. try {
  13571. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  13572. $rows = Db::table('customer')
  13573. ->where(function ($q) {
  13574. $q->where('status', 1)
  13575. ->whereOr('status', '1')
  13576. ->whereOr('status', '')
  13577. ->whereNull('status');
  13578. })
  13579. ->order('id', 'desc')
  13580. ->select();
  13581. } catch (\Throwable $e) {
  13582. $this->success('', '', []);
  13583. return;
  13584. }
  13585. if (!is_array($rows)) {
  13586. $this->success('', '', []);
  13587. return;
  13588. }
  13589. $detailColCandidates = [
  13590. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  13591. 'company_detail', 'company_desc', 'address',
  13592. ];
  13593. foreach ($rows as $row) {
  13594. if (!is_array($row)) {
  13595. continue;
  13596. }
  13597. $norm = [];
  13598. foreach ($row as $k => $v) {
  13599. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  13600. }
  13601. $row = $norm;
  13602. $st = $row['status'] ?? '';
  13603. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  13604. continue;
  13605. }
  13606. $payload = $this->buildCustomerContactPayloadFromRow($row, false);
  13607. if ($payload === null) {
  13608. continue;
  13609. }
  13610. $detail = '';
  13611. foreach ($detailColCandidates as $dk) {
  13612. if (!isset($row[$dk])) {
  13613. continue;
  13614. }
  13615. $dv = trim((string)$row[$dk]);
  13616. if ($dv !== '') {
  13617. $detail = $dv;
  13618. break;
  13619. }
  13620. }
  13621. $payload['detail'] = $detail;
  13622. $list[] = $this->maskSupplierContactFields($payload);
  13623. }
  13624. $this->success('', '', $list);
  13625. }
  13626. /**
  13627. * 采购确认-下发明细弹窗:
  13628. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  13629. */
  13630. public function outward_detail()
  13631. {
  13632. $ids = $this->request->param('ids', $this->request->param('id', ''));
  13633. if (is_array($ids)) {
  13634. $ids = isset($ids[0]) ? $ids[0] : '';
  13635. }
  13636. $ids = trim((string)$ids);
  13637. if ($ids === '') {
  13638. $this->error(__('Invalid parameters'));
  13639. }
  13640. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  13641. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  13642. $wffTab = 'all';
  13643. }
  13644. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  13645. $purchaseOrderId = 0;
  13646. $po = null;
  13647. try {
  13648. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  13649. if (is_array($po)) {
  13650. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  13651. }
  13652. } catch (\Throwable $e) {
  13653. $purchaseOrderId = 0;
  13654. $po = null;
  13655. }
  13656. if (!$isPurchaseConfirm && is_array($po)) {
  13657. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  13658. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  13659. $isPurchaseConfirm = true;
  13660. }
  13661. }
  13662. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  13663. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  13664. $confirmProcessCount = 1;
  13665. $confirmPickGroups = [];
  13666. $processDisplayRows = [];
  13667. $allDetailsBySid = [];
  13668. $requiredSidList = [];
  13669. $sidList = [$ids];
  13670. if ($isPurchaseConfirm) {
  13671. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  13672. if (!$this->canViewProcuremenSupplierQuotesForBundle($confirmBundle)) {
  13673. $this->error('本单尚未开标或指定供应商,不能审批');
  13674. }
  13675. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  13676. if ($mergeRows !== []) {
  13677. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  13678. }
  13679. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  13680. if ($confirmBundle['pos'] !== []) {
  13681. $sidList = [];
  13682. foreach ($confirmBundle['pos'] as $poRow) {
  13683. if (!is_array($poRow)) {
  13684. continue;
  13685. }
  13686. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13687. if (!$this->isValidScydgyRowId($sid)) {
  13688. continue;
  13689. }
  13690. $sidList[] = (string)$sid;
  13691. $requiredSidList[] = $sid;
  13692. }
  13693. }
  13694. if ($sidList === []) {
  13695. $sidList = [$ids];
  13696. $requiredSidList = [(int)$ids];
  13697. }
  13698. $confirmProcessCount = max(1, count($requiredSidList));
  13699. if (is_array($po) && $purchaseOrderId <= 0) {
  13700. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  13701. }
  13702. }
  13703. $rows = [];
  13704. try {
  13705. if (count($sidList) === 1) {
  13706. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  13707. } else {
  13708. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  13709. }
  13710. } catch (\Throwable $e) {
  13711. $rows = [];
  13712. }
  13713. if ($isPurchaseConfirm) {
  13714. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  13715. }
  13716. foreach ($rows as &$r) {
  13717. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  13718. $r['id'] = $r['ID'];
  13719. }
  13720. if (isset($r['createtime'])) {
  13721. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  13722. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  13723. } else {
  13724. $r['createtime_text'] = (string)$r['createtime'];
  13725. }
  13726. } else {
  13727. $r['createtime_text'] = '';
  13728. }
  13729. if (is_array($r)) {
  13730. $r = $this->maskSupplierContactFields($r);
  13731. }
  13732. }
  13733. unset($r);
  13734. $pickedCompanyName = '';
  13735. $manualPicked = 0;
  13736. $manualPickReason = '';
  13737. $quoteVisible = 0;
  13738. $bidOpenVerified = 0;
  13739. if ($isPurchaseConfirm) {
  13740. // 确认包为空时,用当前主单兜底,避免指定说明读不到
  13741. if (($confirmBundle['ccydh'] ?? '') === '' && is_array($po)) {
  13742. $confirmBundle['ccydh'] = trim((string)($po['CCYDH'] ?? ''));
  13743. }
  13744. if (($confirmBundle['pos'] ?? []) === [] && is_array($po)) {
  13745. $confirmBundle['pos'] = [$po];
  13746. }
  13747. $manualPickInfo = $this->resolveProcuremenManualPickInfo($confirmBundle);
  13748. $manualPicked = $this->isProcuremenManualPickedForBundle($confirmBundle) ? 1 : 0;
  13749. $manualPickReason = (string)($manualPickInfo['reason'] ?? '');
  13750. if ($manualPickInfo['company'] !== '') {
  13751. $pickedCompanyName = $manualPickInfo['company'];
  13752. }
  13753. if ($pickedCompanyName === '') {
  13754. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  13755. if (!is_array($poRow)) {
  13756. continue;
  13757. }
  13758. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  13759. if ($pn !== '') {
  13760. $pickedCompanyName = $pn;
  13761. break;
  13762. }
  13763. }
  13764. }
  13765. // 再兜底:直接读当前主单字段
  13766. if (is_array($po) && (int)($po['manual_pick'] ?? 0) === 1) {
  13767. $manualPicked = 1;
  13768. if ($manualPickReason === '') {
  13769. $manualPickReason = trim((string)($po['manual_pick_reason'] ?? ''));
  13770. }
  13771. if ($pickedCompanyName === '') {
  13772. $pickedCompanyName = trim((string)($po['pick_company_name'] ?? ''));
  13773. }
  13774. }
  13775. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle) ? 1 : 0;
  13776. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  13777. }
  13778. $this->view->assign('rows', $rows ?: []);
  13779. $this->view->assign('rowCount', count($rows ?: []));
  13780. $this->view->assign('scydgyId', $ids);
  13781. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  13782. $this->view->assign('headTitle', $headTitle);
  13783. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  13784. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  13785. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  13786. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  13787. $this->view->assign('orderBatchNo', $this->resolveBundleOrderBatchNo($confirmBundle));
  13788. $this->view->assign('processDisplayRows', $processDisplayRows);
  13789. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  13790. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  13791. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  13792. $this->view->assign('manualPicked', $manualPicked);
  13793. $this->view->assign('manualPickReason', $manualPickReason);
  13794. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  13795. $this->view->assign('quoteVisible', $quoteVisible);
  13796. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
  13797. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  13798. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
  13799. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
  13800. $sysRqDisplay = '—';
  13801. if ($isPurchaseConfirm) {
  13802. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  13803. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  13804. );
  13805. }
  13806. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  13807. $this->view->assign('sysRq', $isPurchaseConfirm
  13808. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  13809. : '');
  13810. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  13811. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  13812. : '');
  13813. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  13814. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  13815. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  13816. if ($isPurchaseConfirm) {
  13817. return $this->view->fetch();
  13818. }
  13819. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  13820. $this->view->engine->layout(false);
  13821. try {
  13822. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  13823. $this->view->assign('dialogBody', $bodyHtml);
  13824. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  13825. } finally {
  13826. if ($restoreLayout) {
  13827. $this->view->engine->layout($restoreLayout);
  13828. }
  13829. }
  13830. }
  13831. /**
  13832. * 月度导出记录表(不存在时自动创建)
  13833. */
  13834. protected function ensurePurchaseMonthExportLogTable(): void
  13835. {
  13836. try {
  13837. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  13838. } catch (\Throwable $e) {
  13839. Db::execute(
  13840. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  13841. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  13842. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  13843. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  13844. `admin_name` varchar(64) NOT NULL DEFAULT '',
  13845. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  13846. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  13847. `createtime` int(10) unsigned DEFAULT NULL,
  13848. PRIMARY KEY (`id`),
  13849. KEY `idx_ym` (`ym`),
  13850. KEY `idx_ct` (`createtime`)
  13851. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  13852. );
  13853. }
  13854. }
  13855. /**
  13856. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  13857. *
  13858. * @param array<int, mixed> $dbRows
  13859. * @return array<int, array<string, mixed>>
  13860. */
  13861. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  13862. {
  13863. $keyword = trim((string)$this->request->get('search', ''));
  13864. if ($keyword === '') {
  13865. $keyword = trim((string)$this->request->request('search', ''));
  13866. }
  13867. $filter = $this->request->get('filter', '');
  13868. $op = $this->request->get('op', '');
  13869. if (is_string($filter) && $filter !== '') {
  13870. $filterArr = (array)json_decode($filter, true);
  13871. } else {
  13872. $filterArr = is_array($filter) ? $filter : [];
  13873. }
  13874. if (is_string($op) && $op !== '') {
  13875. $opArr = (array)json_decode($op, true);
  13876. } else {
  13877. $opArr = is_array($op) ? $op : [];
  13878. }
  13879. if ($keyword === '' && $filterArr === []) {
  13880. return array_values(array_filter($dbRows, 'is_array'));
  13881. }
  13882. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  13883. $out = [];
  13884. foreach ($dbRows as $row) {
  13885. if (!is_array($row)) {
  13886. continue;
  13887. }
  13888. if ($keyword !== '') {
  13889. $hit = false;
  13890. foreach ($searchFields as $f) {
  13891. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  13892. $hit = true;
  13893. break;
  13894. }
  13895. }
  13896. if (!$hit) {
  13897. continue;
  13898. }
  13899. }
  13900. $passFilter = true;
  13901. foreach ($filterArr as $field => $val) {
  13902. $field = (string)$field;
  13903. $val = trim((string)$val);
  13904. if ($field === '' || $val === '') {
  13905. continue;
  13906. }
  13907. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  13908. continue;
  13909. }
  13910. $cell = (string)($row[$field] ?? '');
  13911. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  13912. if ($mode === '=' || $mode === 'EQUAL') {
  13913. if (strcasecmp($cell, $val) !== 0) {
  13914. $passFilter = false;
  13915. break;
  13916. }
  13917. } elseif (mb_stripos($cell, $val) === false) {
  13918. $passFilter = false;
  13919. break;
  13920. }
  13921. }
  13922. if (!$passFilter) {
  13923. continue;
  13924. }
  13925. $out[] = $row;
  13926. }
  13927. return $out;
  13928. }
  13929. /**
  13930. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  13931. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  13932. */
  13933. public function export_month_outward()
  13934. {
  13935. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  13936. $this->error(__('You have no permission'));
  13937. }
  13938. $bundle = $this->prepareMonthOutwardExportBundle();
  13939. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  13940. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  13941. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  13942. $spreadsheet = new Spreadsheet();
  13943. $sheet = $spreadsheet->getActiveSheet();
  13944. $sheet->setTitle('外协加工明细');
  13945. $mon = (int)substr($ym, 5, 2);
  13946. $sheet->mergeCells('A1:H1');
  13947. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  13948. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  13949. $sheet->getStyle('A1')->getAlignment()
  13950. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  13951. ->setVertical(Alignment::VERTICAL_CENTER);
  13952. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  13953. $col = 'A';
  13954. foreach ($headers as $h) {
  13955. $sheet->setCellValue($col . '2', $h);
  13956. $col++;
  13957. }
  13958. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  13959. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  13960. $rowNum = 3;
  13961. $sumSubtotalCounts = 0;
  13962. $grandAmount = 0.0;
  13963. $globalSeq = 0;
  13964. if ($groups === []) {
  13965. $sheet->mergeCells('A3:H3');
  13966. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  13967. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  13968. $rowNum = 4;
  13969. } else {
  13970. foreach ($groups as $items) {
  13971. if ($items === []) {
  13972. continue;
  13973. }
  13974. $groupLineCount = count($items);
  13975. $subAmount = 0.0;
  13976. foreach ($items as $line) {
  13977. $globalSeq++;
  13978. $dr = $line['detail'];
  13979. $amt = $this->procuremenExportAmount($dr);
  13980. $subAmount += $amt;
  13981. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  13982. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  13983. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  13984. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  13985. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  13986. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  13987. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  13988. $sheet->setCellValue('H' . $rowNum, $amt);
  13989. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  13990. $rowNum++;
  13991. }
  13992. $sumSubtotalCounts += $groupLineCount;
  13993. $grandAmount += $subAmount;
  13994. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  13995. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  13996. $sheet->getStyle('G' . $rowNum)->getAlignment()
  13997. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  13998. ->setVertical(Alignment::VERTICAL_CENTER);
  13999. $rowNum++;
  14000. }
  14001. }
  14002. $sheet->setCellValue('A' . $rowNum, '总计');
  14003. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  14004. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  14005. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  14006. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  14007. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  14008. $lastRow = $rowNum;
  14009. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  14010. 'borders' => [
  14011. 'allBorders' => [
  14012. 'borderStyle' => Border::BORDER_THIN,
  14013. 'color' => ['rgb' => '000000'],
  14014. ],
  14015. ],
  14016. ]);
  14017. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  14018. if ($lastRow >= 3) {
  14019. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14020. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14021. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14022. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14023. }
  14024. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  14025. $sheet->getColumnDimension('A')->setWidth(7);
  14026. $sheet->getColumnDimension('B')->setWidth(16);
  14027. $sheet->getColumnDimension('C')->setWidth(52);
  14028. $sheet->getColumnDimension('D')->setWidth(32);
  14029. $sheet->getColumnDimension('E')->setWidth(12);
  14030. $sheet->getColumnDimension('F')->setWidth(44);
  14031. $sheet->getColumnDimension('G')->setWidth(26);
  14032. $sheet->getColumnDimension('H')->setWidth(13);
  14033. $sheet->getRowDimension(1)->setRowHeight(28);
  14034. $ymCompact = str_replace('-', '', $ym);
  14035. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  14036. $filename = $fileBase . '.xlsx';
  14037. try {
  14038. $this->ensurePurchaseMonthExportLogTable();
  14039. list($adminId, $adminName) = $this->GetUseName();
  14040. Db::table('purchase_month_export_log')->insert([
  14041. 'ym' => $ym,
  14042. 'admin_id' => (int)$adminId,
  14043. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  14044. 'row_count' => count($exportLines),
  14045. 'total_amount' => round($grandAmount, 2),
  14046. 'createtime' => time(),
  14047. ]);
  14048. } catch (\Throwable $e) {
  14049. Log::write('month export log: ' . $e->getMessage(), 'error');
  14050. }
  14051. if (ob_get_length()) {
  14052. ob_end_clean();
  14053. }
  14054. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  14055. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  14056. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  14057. header('Cache-Control: max-age=0');
  14058. $writer = new Xlsx($spreadsheet);
  14059. $writer->save('php://output');
  14060. $spreadsheet->disconnectWorksheets();
  14061. unset($spreadsheet);
  14062. exit;
  14063. }
  14064. /**
  14065. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  14066. */
  14067. public function export_month_quote()
  14068. {
  14069. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  14070. $this->error(__('You have no permission'));
  14071. }
  14072. $bundle = $this->prepareMonthOutwardExportBundle();
  14073. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  14074. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  14075. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  14076. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  14077. $spreadsheet = new Spreadsheet();
  14078. $sheet = $spreadsheet->getActiveSheet();
  14079. $sheet->setTitle('供应商报价明细');
  14080. $mon = (int)substr($ym, 5, 2);
  14081. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  14082. $sheet->getColumnDimension('A')->setWidth(7);
  14083. $sheet->getColumnDimension('B')->setWidth(16);
  14084. $sheet->getColumnDimension('C')->setWidth(52);
  14085. $sheet->getColumnDimension('D')->setWidth(26);
  14086. $sheet->getColumnDimension('E')->setWidth(32);
  14087. $sheet->getColumnDimension('F')->setWidth(12);
  14088. $sheet->getColumnDimension('G')->setWidth(14);
  14089. $sheet->getColumnDimension('H')->setWidth(12);
  14090. if ($quoteLastRow < 1) {
  14091. $quoteLastRow = 3;
  14092. }
  14093. $ymCompact = str_replace('-', '', $ym);
  14094. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  14095. if (ob_get_length()) {
  14096. ob_end_clean();
  14097. }
  14098. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  14099. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  14100. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  14101. header('Cache-Control: max-age=0');
  14102. $writer = new Xlsx($spreadsheet);
  14103. $writer->save('php://output');
  14104. $spreadsheet->disconnectWorksheets();
  14105. unset($spreadsheet);
  14106. exit;
  14107. }
  14108. /**
  14109. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  14110. *
  14111. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  14112. */
  14113. protected function prepareMonthOutwardExportBundle(): array
  14114. {
  14115. $this->request->filter(['strip_tags', 'trim']);
  14116. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  14117. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  14118. $ym = date('Y-m');
  14119. }
  14120. $dbRows = [];
  14121. try {
  14122. $query = Db::table('purchase_order');
  14123. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  14124. $dbRows = $query->select();
  14125. } catch (\Throwable $e) {
  14126. $dbRows = [];
  14127. }
  14128. if (!is_array($dbRows)) {
  14129. $dbRows = [];
  14130. }
  14131. $completeTsMap = [];
  14132. $sidList = [];
  14133. foreach ($dbRows as $dbRow) {
  14134. if (!is_array($dbRow)) {
  14135. continue;
  14136. }
  14137. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  14138. if ($sid > 0) {
  14139. $sidList[$sid] = true;
  14140. }
  14141. }
  14142. if ($sidList !== []) {
  14143. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  14144. }
  14145. // 导出始终按「查看月份」取当月完结单;搜索只在当月内再缩小(勿跨月,否则会与列表不一致)
  14146. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  14147. if (!is_array($dbRow)) {
  14148. return false;
  14149. }
  14150. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  14151. if ($done['ts'] <= 0) {
  14152. return false;
  14153. }
  14154. return date('Y-m', $done['ts']) === $ym;
  14155. }));
  14156. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  14157. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  14158. $mainBySid = [];
  14159. foreach ($pool as $rw) {
  14160. if (!is_array($rw)) {
  14161. continue;
  14162. }
  14163. $rid = (int)($rw['ID'] ?? 0);
  14164. if ($rid > 0) {
  14165. $mainBySid[$rid] = $rw;
  14166. }
  14167. }
  14168. if ($mainBySid === []) {
  14169. $detailRows = [];
  14170. } else {
  14171. try {
  14172. $detailRows = Db::table('purchase_order_detail')
  14173. ->where('scydgy_id', 'in', array_keys($mainBySid))
  14174. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  14175. ->order('status', 'desc')
  14176. ->order('CCYDH', 'asc')
  14177. ->order('company_name', 'asc')
  14178. ->order('id', 'asc')
  14179. ->select();
  14180. } catch (\Throwable $e) {
  14181. try {
  14182. $detailRows = Db::table('purchase_order_detail')
  14183. ->where('scydgy_id', 'in', array_keys($mainBySid))
  14184. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  14185. ->order('status', 'desc')
  14186. ->order('CCYDH', 'asc')
  14187. ->order('company_name', 'asc')
  14188. ->order('ID', 'asc')
  14189. ->select();
  14190. } catch (\Throwable $e2) {
  14191. $detailRows = [];
  14192. }
  14193. }
  14194. }
  14195. if (!is_array($detailRows)) {
  14196. $detailRows = [];
  14197. }
  14198. $exportLines = [];
  14199. $detailSidSeen = [];
  14200. foreach ($detailRows as $dr) {
  14201. if (!is_array($dr)) {
  14202. continue;
  14203. }
  14204. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  14205. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  14206. continue;
  14207. }
  14208. if (isset($detailSidSeen[$sid])) {
  14209. continue;
  14210. }
  14211. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  14212. continue;
  14213. }
  14214. $detailSidSeen[$sid] = true;
  14215. $m = $mainBySid[$sid];
  14216. $exportLines[] = [
  14217. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  14218. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  14219. 'company_name' => (string)($dr['company_name'] ?? ''),
  14220. 'CDF' => (string)($m['CDF'] ?? ''),
  14221. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  14222. 'gx' => $this->procuremenExportGxText($m),
  14223. 'detail' => $dr,
  14224. ];
  14225. }
  14226. foreach ($detailRows as $dr) {
  14227. if (!is_array($dr)) {
  14228. continue;
  14229. }
  14230. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  14231. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  14232. continue;
  14233. }
  14234. $detailSidSeen[$sid] = true;
  14235. $m = $mainBySid[$sid];
  14236. $exportLines[] = [
  14237. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  14238. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  14239. 'company_name' => (string)($dr['company_name'] ?? ''),
  14240. 'CDF' => (string)($m['CDF'] ?? ''),
  14241. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  14242. 'gx' => $this->procuremenExportGxText($m),
  14243. 'detail' => $dr,
  14244. ];
  14245. }
  14246. foreach ($mainBySid as $sid => $m) {
  14247. if (isset($detailSidSeen[$sid])) {
  14248. continue;
  14249. }
  14250. $company = trim((string)($m['pick_company_name'] ?? ''));
  14251. $exportLines[] = [
  14252. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  14253. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  14254. 'company_name' => $company,
  14255. 'CDF' => (string)($m['CDF'] ?? ''),
  14256. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  14257. 'gx' => $this->procuremenExportGxText($m),
  14258. 'detail' => [],
  14259. ];
  14260. }
  14261. $groups = [];
  14262. foreach ($exportLines as $line) {
  14263. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  14264. if (!isset($groups[$k])) {
  14265. $groups[$k] = [];
  14266. }
  14267. $groups[$k][] = $line;
  14268. }
  14269. ksort($groups, SORT_STRING);
  14270. return [
  14271. 'ym' => $ym,
  14272. 'mainBySid' => $mainBySid,
  14273. 'detailRows' => $detailRows,
  14274. 'exportLines' => $exportLines,
  14275. 'groups' => $groups,
  14276. ];
  14277. }
  14278. /**
  14279. * 导出用:工序列文案
  14280. */
  14281. protected function procuremenExportGxText(array $r)
  14282. {
  14283. return ProcuremenFormat::exportGxText($r);
  14284. }
  14285. /**
  14286. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  14287. */
  14288. protected function procuremenExportAmount(array $r)
  14289. {
  14290. return ProcuremenFormat::exportAmount($r);
  14291. }
  14292. /**
  14293. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  14294. *
  14295. * @param array<int, array<string, mixed>> $detailRows
  14296. * @param array<int, array<string, mixed>> $mainBySid
  14297. * @return array<int, array<string, mixed>>
  14298. */
  14299. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  14300. {
  14301. $lines = [];
  14302. foreach ($detailRows as $dr) {
  14303. if (!is_array($dr)) {
  14304. continue;
  14305. }
  14306. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  14307. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  14308. continue;
  14309. }
  14310. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  14311. continue;
  14312. }
  14313. $cn = trim((string)($dr['company_name'] ?? ''));
  14314. if ($cn === '') {
  14315. continue;
  14316. }
  14317. $m = $mainBySid[$sid];
  14318. $am = trim((string)($dr['amount'] ?? ''));
  14319. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  14320. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  14321. $amountText = $amountFilled
  14322. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  14323. : '未填写';
  14324. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  14325. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  14326. if ($deliveryShow === '' && $deliveryRaw !== '') {
  14327. $deliveryShow = $deliveryRaw;
  14328. }
  14329. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  14330. ? $deliveryShow
  14331. : '未填写';
  14332. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  14333. $lines[] = [
  14334. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  14335. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  14336. 'gx' => $this->procuremenExportGxText($m),
  14337. 'company_name' => $cn,
  14338. 'amount_text' => $amountText,
  14339. 'amount_num' => $amountFilled ? $amountNum : null,
  14340. 'delivery_text' => $deliveryText,
  14341. 'picked_text' => $picked ? '中标' : '未中标',
  14342. 'picked' => $picked,
  14343. ];
  14344. }
  14345. $winnerSupplierByOrder = [];
  14346. foreach ($lines as $line) {
  14347. $dh = trim((string)($line['CCYDH'] ?? ''));
  14348. $cn = trim((string)($line['company_name'] ?? ''));
  14349. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  14350. $winnerSupplierByOrder[$dh][$cn] = true;
  14351. }
  14352. }
  14353. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  14354. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  14355. if ($c !== 0) {
  14356. return $c;
  14357. }
  14358. $dh = trim((string)($a['CCYDH'] ?? ''));
  14359. $aCn = trim((string)($a['company_name'] ?? ''));
  14360. $bCn = trim((string)($b['company_name'] ?? ''));
  14361. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  14362. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  14363. if ($aSupplierWin !== $bSupplierWin) {
  14364. return $aSupplierWin ? -1 : 1;
  14365. }
  14366. $c = strcmp($aCn, $bCn);
  14367. if ($c !== 0) {
  14368. return $c;
  14369. }
  14370. if (!empty($a['picked']) !== !empty($b['picked'])) {
  14371. return !empty($a['picked']) ? -1 : 1;
  14372. }
  14373. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  14374. if ($c !== 0) {
  14375. return $c;
  14376. }
  14377. return 0;
  14378. });
  14379. return $lines;
  14380. }
  14381. /**
  14382. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  14383. *
  14384. * @param array<int, array<string, mixed>> $quoteLines
  14385. */
  14386. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  14387. {
  14388. $mon = (int)substr($ym, 5, 2);
  14389. $titleRow = $startRow;
  14390. $headerRow = $startRow + 1;
  14391. $dataStartRow = $startRow + 2;
  14392. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  14393. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  14394. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  14395. $sheet->getStyle('A' . $titleRow)->getAlignment()
  14396. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  14397. ->setVertical(Alignment::VERTICAL_CENTER);
  14398. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  14399. $col = 'A';
  14400. foreach ($headers as $h) {
  14401. $sheet->setCellValue($col . $headerRow, $h);
  14402. $col++;
  14403. }
  14404. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  14405. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  14406. $rowNum = $dataStartRow;
  14407. if ($quoteLines === []) {
  14408. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  14409. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  14410. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  14411. $rowNum = $dataStartRow + 1;
  14412. } else {
  14413. $i = 0;
  14414. foreach ($quoteLines as $line) {
  14415. $i++;
  14416. $sheet->setCellValue('A' . $rowNum, $i);
  14417. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  14418. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  14419. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  14420. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  14421. if ($line['amount_num'] !== null) {
  14422. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  14423. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  14424. } else {
  14425. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  14426. }
  14427. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  14428. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  14429. if (!empty($line['picked'])) {
  14430. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  14431. }
  14432. $rowNum++;
  14433. }
  14434. }
  14435. $lastRow = $rowNum - 1;
  14436. if ($lastRow >= $headerRow) {
  14437. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  14438. 'borders' => [
  14439. 'allBorders' => [
  14440. 'borderStyle' => Border::BORDER_THIN,
  14441. 'color' => ['rgb' => '000000'],
  14442. ],
  14443. ],
  14444. ]);
  14445. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  14446. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14447. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14448. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14449. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  14450. if ($lastRow >= $dataStartRow) {
  14451. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  14452. }
  14453. }
  14454. return $lastRow;
  14455. }
  14456. /**
  14457. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  14458. */
  14459. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  14460. {
  14461. if ($lastRow < $dataStartRow || $headerRow < 1) {
  14462. return;
  14463. }
  14464. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  14465. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  14466. ->setVertical(Alignment::VERTICAL_CENTER);
  14467. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  14468. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  14469. ->setVertical(Alignment::VERTICAL_CENTER);
  14470. if ($lastCol > 'B') {
  14471. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  14472. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  14473. ->setVertical(Alignment::VERTICAL_CENTER);
  14474. }
  14475. }
  14476. /**
  14477. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  14478. */
  14479. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  14480. {
  14481. return ProcuremenFormat::sanitizePdfOrderKey($ccydh);
  14482. }
  14483. /**
  14484. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  14485. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  14486. *
  14487. * @return array{objectKey: string, webPath: string}
  14488. */
  14489. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  14490. {
  14491. return ProcuremenFormat::buildConfirmPdfPaths($scydgyId, $ccydhRaw);
  14492. }
  14493. /**
  14494. * 采购确认成功后 / 已完结刷新:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  14495. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  14496. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  14497. * 说明:审批通过时会先存一版;质量+交货评分使订单「已完结」后,详情页打开或评分保存完成时会再重存,以含最终步骤与操作记录。
  14498. *
  14499. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  14500. */
  14501. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  14502. {
  14503. if (!$this->isValidScydgyRowId($scydgyId)) {
  14504. return '';
  14505. }
  14506. $ids = trim((string)$scydgyId);
  14507. $prep = $this->prepareProcuremenDetailsView($ids);
  14508. if (!$prep['ok']) {
  14509. return '';
  14510. }
  14511. $ccydh = $prep['ccydh'];
  14512. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  14513. $objectKey = $paths['objectKey'];
  14514. $webPath = $paths['webPath'];
  14515. $cyjmc = '';
  14516. try {
  14517. $poMeta = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->field('CYJMC')->find();
  14518. if (is_array($poMeta)) {
  14519. $cyjmc = trim((string)($poMeta['CYJMC'] ?? ''));
  14520. }
  14521. } catch (\Throwable $e) {
  14522. $cyjmc = '';
  14523. }
  14524. $genTime = date('Y-m-d H:i:s');
  14525. $metaIds = '工序行ID ' . $ids . ' | 主表订单ID ' . (int)$purchaseOrderId;
  14526. $metaLeft = $metaIds . ($cyjmc !== '' ? ' | ' . $cyjmc : '');
  14527. // PDF 进度:去掉「未发」;节点用纯色圆点(不用图片,避免 mPDF 破图)
  14528. $pdfSteps = [];
  14529. $viewSteps = $prep['steps'] ?? [];
  14530. if (is_array($viewSteps)) {
  14531. foreach ($viewSteps as $st) {
  14532. if (!is_array($st)) {
  14533. continue;
  14534. }
  14535. if (trim((string)($st['title'] ?? '')) === '未发') {
  14536. continue;
  14537. }
  14538. $pdfSteps[] = $st;
  14539. }
  14540. }
  14541. $pdfStepW = count($pdfSteps) > 0 ? (round(100 / count($pdfSteps), 2) . '%') : '16.66%';
  14542. $nPdf = count($pdfSteps);
  14543. foreach ($pdfSteps as $idx => &$pst) {
  14544. if ($idx === 0) {
  14545. $pst['pdf_left_bg'] = '';
  14546. } else {
  14547. $pst['pdf_left_bg'] = !empty($pdfSteps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  14548. }
  14549. if ($idx >= $nPdf - 1) {
  14550. $pst['pdf_right_bg'] = '';
  14551. } else {
  14552. $pst['pdf_right_bg'] = !empty($pst['done']) ? '#1890ff' : '#e0e0e0';
  14553. }
  14554. }
  14555. unset($pst);
  14556. $this->view->assign([
  14557. 'pdf_export' => 1,
  14558. 'pdfMetaLine' => $metaLeft,
  14559. 'pdfMetaLeft' => $metaLeft,
  14560. 'pdfMetaIds' => $metaIds,
  14561. 'pdfMetaTitle' => $cyjmc,
  14562. 'pdfMetaTime' => 'PDF生成时间 ' . $genTime,
  14563. 'pdfSteps' => $pdfSteps,
  14564. 'pdfStepWidth' => $pdfStepW,
  14565. ]);
  14566. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  14567. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  14568. $this->view->engine->layout(false);
  14569. try {
  14570. $html = $this->view->fetch('procuremen/details_pdf_shell');
  14571. } catch (\Throwable $e) {
  14572. if ($restoreLayout) {
  14573. $this->view->engine->layout($restoreLayout);
  14574. }
  14575. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  14576. $this->view->assign([
  14577. 'pdf_export' => '', 'pdfMetaLine' => '', 'pdfMetaLeft' => '',
  14578. 'pdfMetaIds' => '', 'pdfMetaTitle' => '', 'pdfMetaTime' => '',
  14579. 'pdfSteps' => [], 'pdfStepWidth' => '',
  14580. ]);
  14581. return '';
  14582. }
  14583. if ($restoreLayout) {
  14584. $this->view->engine->layout($restoreLayout);
  14585. }
  14586. $this->view->assign([
  14587. 'pdf_export' => '', 'pdfMetaLine' => '', 'pdfMetaLeft' => '',
  14588. 'pdfMetaIds' => '', 'pdfMetaTitle' => '', 'pdfMetaTime' => '',
  14589. 'pdfSteps' => [], 'pdfStepWidth' => '',
  14590. ]);
  14591. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  14592. if (!is_dir($tempDir)) {
  14593. @mkdir($tempDir, 0755, true);
  14594. }
  14595. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  14596. try {
  14597. $mpdf = new \Mpdf\Mpdf([
  14598. 'mode' => 'utf-8',
  14599. 'format' => 'A4',
  14600. 'margin_left' => 12,
  14601. 'margin_right' => 12,
  14602. 'margin_top' => 14,
  14603. 'margin_bottom' => 14,
  14604. 'tempDir' => $tempDir,
  14605. 'autoScriptToLang' => true,
  14606. 'autoLangToFont' => true,
  14607. ]);
  14608. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  14609. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  14610. $mpdf->SetBasePath('http://127.0.0.1/');
  14611. $mpdf->WriteHTML($html);
  14612. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  14613. } catch (\Throwable $e) {
  14614. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  14615. if (is_file($tempPdf)) {
  14616. @unlink($tempPdf);
  14617. }
  14618. return '';
  14619. }
  14620. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  14621. if ($ossUrl !== '') {
  14622. @unlink($tempPdf);
  14623. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  14624. return $ossUrl;
  14625. }
  14626. $pi = pathinfo($objectKey);
  14627. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  14628. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  14629. if ($baseFile === '') {
  14630. @unlink($tempPdf);
  14631. return '';
  14632. }
  14633. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  14634. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  14635. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  14636. @unlink($tempPdf);
  14637. return '';
  14638. }
  14639. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  14640. if (!@copy($tempPdf, $fullPath)) {
  14641. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  14642. @unlink($tempPdf);
  14643. return '';
  14644. }
  14645. @unlink($tempPdf);
  14646. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  14647. return $webPath;
  14648. }
  14649. /**
  14650. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  14651. */
  14652. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  14653. {
  14654. if ($scydgyId <= 0 || $webPath === '') {
  14655. return;
  14656. }
  14657. try {
  14658. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  14659. } catch (\Throwable $e) {
  14660. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  14661. }
  14662. }
  14663. /**
  14664. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  14665. *
  14666. * @param array<string, string> $vars
  14667. * @return array<string, string>
  14668. */
  14669. protected function normalizeSmsTemplateVars(array $vars): array
  14670. {
  14671. return ProcuremenFormat::normalizeSmsTemplateVars($vars);
  14672. }
  14673. /**
  14674. * 按手机号或公司名称查 customer 表联系人姓名
  14675. */
  14676. protected function resolveCustomerContactName(string $phone, string $companyName): string
  14677. {
  14678. $phone = trim($phone);
  14679. $companyName = trim($companyName);
  14680. try {
  14681. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  14682. $row = Db::table('customer')
  14683. ->where(function ($q) use ($phone) {
  14684. $q->where('phone', $phone)->whereOr('account', $phone);
  14685. })
  14686. ->order('id', 'asc')
  14687. ->find();
  14688. if (is_array($row)) {
  14689. $nm = trim((string)($row['username'] ?? ''));
  14690. if ($nm !== '') {
  14691. return $nm;
  14692. }
  14693. }
  14694. }
  14695. if ($companyName !== '') {
  14696. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  14697. if (is_array($row)) {
  14698. return trim((string)($row['username'] ?? ''));
  14699. }
  14700. }
  14701. } catch (\Throwable $e) {
  14702. }
  14703. return '';
  14704. }
  14705. /**
  14706. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;;http(s) 链接做成可点的 &lt;a&gt;(微信 QQ 邮箱提醒纯文本 URL 常不可点)
  14707. */
  14708. protected function plainTextToHtmlEmailBody(string $text): string
  14709. {
  14710. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  14711. $parts = explode("\n", $text);
  14712. $out = [];
  14713. foreach ($parts as $line) {
  14714. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  14715. $out[] = $line;
  14716. } else {
  14717. $esc = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  14718. // 保留工序行空格,便于「单位/工作量」列对齐
  14719. $esc = str_replace(' ', '&nbsp;', $esc);
  14720. $esc = preg_replace(
  14721. '#(https?://[^\s<>"\']+)#iu',
  14722. '<a href="$1" style="color:#1565c0;text-decoration:underline;word-break:break-all;">$1</a>',
  14723. $esc
  14724. );
  14725. $out[] = $esc;
  14726. }
  14727. }
  14728. return implode("<br>\n", $out);
  14729. }
  14730. /**
  14731. * 短信场景:去掉链接类变量,避免误填 URL
  14732. *
  14733. * @param array<string, string> $vars
  14734. * @return array<string, string>
  14735. */
  14736. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  14737. {
  14738. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  14739. return $vars;
  14740. }
  14741. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  14742. $vars[$k] = '';
  14743. }
  14744. return $vars;
  14745. }
  14746. /**
  14747. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  14748. *
  14749. * @param array<string, string> $vars
  14750. */
  14751. protected function renderNotifyTemplate(string $scene, array $vars): string
  14752. {
  14753. $vars = $this->normalizeSmsTemplateVars($vars);
  14754. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  14755. $row = $this->loadNotifyTemplateRow($scene);
  14756. if ($row === null) {
  14757. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  14758. }
  14759. $tpl = trim((string)($row['content'] ?? ''));
  14760. if ($tpl === '') {
  14761. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  14762. }
  14763. foreach ($vars as $k => $v) {
  14764. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  14765. }
  14766. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  14767. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  14768. return $tpl;
  14769. }
  14770. protected function resolveProcuremenEmailSubject(string $scene): string
  14771. {
  14772. // 采购确认结果邮箱:title 仅作说明,邮件主题用固定文案(不用 title)
  14773. if (in_array($scene, ['confirm_ok_email', 'confirm_fail_email'], true)) {
  14774. $this->ensureConfirmResultEmailTemplates();
  14775. $fallback = [
  14776. 'confirm_ok_email' => '采购确认结果:已通过',
  14777. 'confirm_fail_email' => '采购确认结果:未通过',
  14778. ];
  14779. return $fallback[$scene] ?? '协助采购通知';
  14780. }
  14781. // 询价 / 交货确认邮箱:沿用模版 title 作邮件主题(与历史配置一致)
  14782. if (in_array($scene, ['rfq_salesman_email', 'rfq_supplier_email', 'delivery_notify_email'], true)) {
  14783. $row = $this->loadNotifyTemplateRow($scene);
  14784. $title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
  14785. if ($title !== '') {
  14786. return $title;
  14787. }
  14788. $fallback = [
  14789. 'rfq_supplier_email' => '供应商询价通知',
  14790. 'rfq_salesman_email' => '协助采购询价通知',
  14791. 'delivery_notify_email' => '交货情况确认通知',
  14792. ];
  14793. return $fallback[$scene] ?? '协助采购通知';
  14794. }
  14795. $map = [
  14796. 'review_email' => '您有新的协助加工订单',
  14797. ];
  14798. $subject = trim((string)($map[$scene] ?? ''));
  14799. if ($subject === '') {
  14800. $this->error('未配置邮件主题:' . $scene);
  14801. }
  14802. return $subject;
  14803. }
  14804. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  14805. {
  14806. $map = [
  14807. 'review_email' => '协助下发-邮箱',
  14808. 'review_sms' => '协助下发-短信',
  14809. 'confirm_ok' => '采购确认-通过',
  14810. 'confirm_fail' => '采购确认-未通过',
  14811. 'confirm_ok_email' => '采购确认通过-邮箱',
  14812. 'confirm_fail_email' => '采购确认未通过-邮箱',
  14813. 'bid_open' => '开标双重验证',
  14814. 'rfq_salesman_email' => '询价通知业务员-邮箱',
  14815. 'rfq_supplier_email' => '供应商询价通知',
  14816. 'delivery_notify_email'=> '交货情况通知生产部-邮箱',
  14817. ];
  14818. $label = $map[$scene] ?? $scene;
  14819. if ($titleRequired) {
  14820. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  14821. }
  14822. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  14823. }
  14824. /**
  14825. * 是否开启协助通知演练(不发真实短信/邮件)
  14826. */
  14827. protected function isProcuremenNotifyDryRun(): bool
  14828. {
  14829. return (bool)Config::get('procuremen_notify_dry_run');
  14830. }
  14831. /**
  14832. * @param array<string, mixed> $payload
  14833. */
  14834. protected function recordNotifyDryRunPreview(array $payload): void
  14835. {
  14836. $this->notifyDryRunPreview[] = $payload;
  14837. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  14838. }
  14839. /**
  14840. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  14841. * @throws \Exception
  14842. */
  14843. protected function smsbao($phone, $content)
  14844. {
  14845. if ($this->isProcuremenNotifyDryRun()) {
  14846. $this->recordNotifyDryRunPreview([
  14847. 'scene' => 'sms_only',
  14848. 'phone' => $phone,
  14849. 'sms_content' => $content,
  14850. ]);
  14851. return;
  14852. }
  14853. $statusStr = [
  14854. '0' => '短信发送成功',
  14855. '-1' => '参数不全',
  14856. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  14857. '30' => '密码错误',
  14858. '40' => '账号不存在',
  14859. '41' => '余额不足',
  14860. '42' => '帐户已过期',
  14861. '43' => 'IP地址限制',
  14862. '50' => '内容含有敏感词',
  14863. ];
  14864. $smsapi = 'http://api.smsbao.com/';
  14865. $user = 'zhuwei123';
  14866. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  14867. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  14868. $result = @file_get_contents($sendurl);
  14869. if ($result === false) {
  14870. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  14871. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  14872. }
  14873. $result = trim((string)$result);
  14874. if ($result !== '0') {
  14875. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  14876. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  14877. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  14878. }
  14879. }
  14880. }