Procuremen.php 623 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenFormat;
  6. use app\common\library\ProcuremenGuard;
  7. use app\common\library\ProcuremenOperLog;
  8. use app\common\library\ProcuremenSchema;
  9. use app\common\library\ProcuremenStatus;
  10. use app\common\library\ProcuremenSupplierScore;
  11. use app\common\library\ProcuremenTime;
  12. use PHPMailer\PHPMailer\PHPMailer;
  13. use think\Config;
  14. use think\Cache;
  15. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  16. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  17. use PhpOffice\PhpSpreadsheet\Style\Border;
  18. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  19. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  20. use think\Db;
  21. use think\Log;
  22. class Procuremen extends Backend
  23. {
  24. /**
  25. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  26. */
  27. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,b.czlyq,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  28. /**
  29. * Procuremen模型对象
  30. * @var \app\admin\model\Procuremen
  31. */
  32. protected $model = null;
  33. /**
  34. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  35. */
  36. protected $notifyDryRunPreview = [];
  37. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  38. protected $procuremenRedisCache = null;
  39. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  40. protected $pickHiddenScydgySetCache = null;
  41. /** 邮件发送日志表结构已就绪缓存键 */
  42. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v2';
  43. /**
  44. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  45. * @var array
  46. */
  47. protected $noNeedRight = [
  48. 'pickreview', 'review', 'reviewcompanies',
  49. // 方法内用 hasProcuremenPerm 校验(兼容 auditsubmit / auditissue)
  50. 'auditmanualpick',
  51. // 与 rfqlist 同权,方法内校验
  52. 'rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqissuesuppliers', 'rfqissue', 'rfqissuesendmail', 'rfqquotes',
  53. 'rfqappendsuppliers', 'rfqsupplieroptions', 'rfqsalesmanoptions', 'rfqappendsalesmen',
  54. 'deliverynotifymen', 'deliverynotify',
  55. ];
  56. public function _initialize()
  57. {
  58. parent::_initialize();
  59. $this->model = new \app\admin\model\Procuremen;
  60. $this->maybeMigrateLegacyWflowStatusText();
  61. $this->assignProcuremenAuthConfig();
  62. try {
  63. ProcuremenSchema::ensureAll();
  64. } catch (\Throwable $e) {
  65. }
  66. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  67. $this->ensurePurchaseEmailSendLogTableOnce();
  68. }
  69. }
  70. /**
  71. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  72. */
  73. protected function maybeMigrateLegacyWflowStatusText(): void
  74. {
  75. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  76. if (is_file($flagFile)) {
  77. return;
  78. }
  79. $map = [
  80. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  81. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  82. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  83. '3' => ProcuremenStatus::WFLOW_APPROVED,
  84. '4' => ProcuremenStatus::WFLOW_REJECTED,
  85. ];
  86. try {
  87. foreach ($map as $num => $text) {
  88. Db::table('purchase_order')
  89. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  90. ->update(['wflow_status' => $text]);
  91. }
  92. @file_put_contents($flagFile, date('c'));
  93. } catch (\Throwable $e) {
  94. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  95. }
  96. }
  97. /**
  98. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  99. *
  100. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  101. */
  102. protected function hasProcuremenPerm(array $actions): bool
  103. {
  104. foreach ($actions as $action) {
  105. $action = strtolower(trim((string)$action));
  106. if ($action === '') {
  107. continue;
  108. }
  109. if (strpos($action, 'procuremen/') !== 0) {
  110. $action = 'procuremen/' . $action;
  111. }
  112. if ($this->auth->check($action)) {
  113. return true;
  114. }
  115. }
  116. $suffixes = [];
  117. foreach ($actions as $action) {
  118. $action = strtolower(trim((string)$action));
  119. $action = preg_replace('#^procuremen/#', '', $action);
  120. if ($action !== '') {
  121. $suffixes[$action] = true;
  122. }
  123. }
  124. if ($suffixes === []) {
  125. return false;
  126. }
  127. try {
  128. foreach ($this->auth->getRuleList() as $rule) {
  129. $rule = strtolower((string)$rule);
  130. if (strpos($rule, 'procuremen/') !== 0) {
  131. continue;
  132. }
  133. foreach (array_keys($suffixes) as $suffix) {
  134. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  135. return true;
  136. }
  137. }
  138. }
  139. } catch (\Throwable $e) {
  140. }
  141. return false;
  142. }
  143. /**
  144. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  145. *
  146. * @param string[] $actions
  147. */
  148. protected function hasProcuremenPermStrict(array $actions): bool
  149. {
  150. foreach ($actions as $action) {
  151. $action = strtolower(trim((string)$action));
  152. if ($action === '') {
  153. continue;
  154. }
  155. if (strpos($action, 'procuremen/') !== 0) {
  156. $action = 'procuremen/' . $action;
  157. }
  158. if ($this->auth->check($action)) {
  159. return true;
  160. }
  161. }
  162. return false;
  163. }
  164. /**
  165. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  166. *
  167. * @param string[] $titles
  168. */
  169. protected function authHasAssignedRuleTitle(array $titles): bool
  170. {
  171. $titles = array_values(array_filter(array_map('trim', $titles)));
  172. if ($titles === []) {
  173. return false;
  174. }
  175. try {
  176. $ids = $this->auth->getRuleIds();
  177. if (in_array('*', $ids, true)) {
  178. return true;
  179. }
  180. if ($ids === []) {
  181. return false;
  182. }
  183. $rows = Db::name('auth_rule')
  184. ->where('status', 'normal')
  185. ->whereIn('id', $ids)
  186. ->column('title');
  187. foreach ($rows as $title) {
  188. $t = trim((string)$title);
  189. if ($t !== '' && in_array($t, $titles, true)) {
  190. return true;
  191. }
  192. }
  193. } catch (\Throwable $e) {
  194. }
  195. return false;
  196. }
  197. protected function procuremenCanPickDelete(): bool
  198. {
  199. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  200. return true;
  201. }
  202. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  203. }
  204. protected function procuremenCanComplete(): bool
  205. {
  206. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  207. return true;
  208. }
  209. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  210. }
  211. protected function procuremenCanDispatch(): bool
  212. {
  213. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  214. }
  215. /**
  216. * 前端按钮显隐(Config.procuremenAuth)
  217. */
  218. protected function assignProcuremenAuthConfig(): void
  219. {
  220. $authMap = [
  221. 'pickreview' => $this->procuremenCanDispatch(),
  222. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  223. 'pickdelete' => $this->procuremenCanPickDelete(),
  224. 'completedirectly' => $this->procuremenCanComplete(),
  225. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  226. 'auditissue' => $this->hasProcuremenPerm(['auditissue', 'audit']),
  227. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  228. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  229. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  230. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  231. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail', 'confirm']),
  232. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  233. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  234. 'details' => $this->hasProcuremenPerm(['details', 'confirm', 'audit', 'index', 'pick']),
  235. 'confirm' => $this->hasProcuremenPerm(['confirm']),
  236. 'audit' => $this->hasProcuremenPerm(['audit']),
  237. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  238. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  239. 'export_month_quote' => $this->hasProcuremenPerm(['export_month_quote', 'exportMonthQuote', 'export_month_outward', 'exportMonthOutward']),
  240. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  241. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  242. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  243. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  244. 'auditmanualpick' => $this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue']),
  245. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  246. 'add' => $this->hasProcuremenPerm(['add']),
  247. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  248. // 查询询价三个操作按钮:各自独立,不再因有 rfqlist 就全部放开
  249. 'rfqissue' => $this->hasProcuremenPerm(['rfqissue']),
  250. 'rfqquotes' => $this->hasProcuremenPerm(['rfqquotes']),
  251. 'rfqnotifysalesman' => $this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen']),
  252. 'rfqnotifysalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman']),
  253. // 询价附属接口:有「询价」按钮权限即可(无需再单独勾选)
  254. 'rfqissuesuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers']),
  255. 'rfqissuesendmail' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail']),
  256. 'rfqappendsuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers']),
  257. 'rfqsupplieroptions' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions']),
  258. 'rfqsalesmanoptions' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen']),
  259. 'rfqappendsalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen']),
  260. 'deliverynotify' => $this->hasProcuremenPerm(['deliverynotify', 'deliverynotifymen', 'outward_detail', 'outwarddetail', 'purchaseconfirmpick', 'details']),
  261. 'deliverynotifymen' => $this->hasProcuremenPerm(['deliverynotifymen', 'deliverynotify', 'outward_detail', 'outwarddetail', 'purchaseconfirmpick', 'details']),
  262. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  263. ];
  264. $this->assignconfig('procuremenAuth', $authMap);
  265. }
  266. /**
  267. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  268. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  269. * 列表 Tab 写入 hash(mproc_tab),避免邮件客户端拆坏多 query 参数;浏览器端再补全 tab=
  270. *
  271. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  272. * @param string $listTab rfq|draft|submitted|done|rfq_submitted,空则仅靠服务端按状态推断
  273. */
  274. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId, $listTab = '')
  275. {
  276. static $mprocCfgLoaded = false;
  277. if (!$mprocCfgLoaded) {
  278. $mprocCfgLoaded = true;
  279. if (is_file(APP_PATH . 'extra/mproc.php')) {
  280. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  281. }
  282. }
  283. $eid = (int)$purchaseOrderDetailId;
  284. $base = $this->resolveMprocMobilePublicBaseUrl();
  285. if ($base === '') {
  286. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  287. }
  288. $path = trim((string)Config::get('mproc.mobile_index_path'));
  289. if ($path === '') {
  290. $path = '/index.php/index/index/index';
  291. } else {
  292. $path = '/' . ltrim($path, '/');
  293. }
  294. $tab = trim((string)$listTab);
  295. if (!in_array($tab, ['rfq', 'rfq_submitted', 'draft', 'submitted', 'done'], true)) {
  296. $tab = '';
  297. }
  298. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份 Tab
  299. if ($eid > 0) {
  300. $hash = 'mproc_fe=' . $eid;
  301. if ($tab !== '') {
  302. $hash .= '&mproc_tab=' . $tab;
  303. }
  304. return $base . $path . '?focus_eid=' . $eid . '#' . $hash;
  305. }
  306. return $base . $path . '?main_tab=orders' . ($tab !== '' ? ('&tab=' . $tab) : '');
  307. }
  308. /**
  309. * 业务员手机端「订单询价」直达链接(默认待询价)
  310. *
  311. * @param int $scydgyId 手工询价 scydgy_id(负数)
  312. * @param string $status pending|quoted
  313. */
  314. protected function buildMprocMobileRfqAddUrl($scydgyId = 0, $status = 'pending')
  315. {
  316. static $mprocCfgLoaded = false;
  317. if (!$mprocCfgLoaded) {
  318. $mprocCfgLoaded = true;
  319. if (is_file(APP_PATH . 'extra/mproc.php')) {
  320. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  321. }
  322. }
  323. $base = $this->resolveMprocMobilePublicBaseUrl();
  324. if ($base === '') {
  325. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  326. }
  327. $indexPath = trim((string)Config::get('mproc.mobile_index_path'));
  328. if ($indexPath === '') {
  329. $indexPath = '/index.php/index/index/index';
  330. } else {
  331. $indexPath = '/' . ltrim($indexPath, '/');
  332. }
  333. $path = preg_replace('#/index$#', '/rfqadd', rtrim($indexPath, '/'));
  334. if ($path === null || $path === '' || substr($path, -6) === '/index') {
  335. $path = '/index.php/index/index/rfqadd';
  336. }
  337. $status = trim((string)$status) === 'quoted' ? 'quoted' : 'pending';
  338. $sid = (int)$scydgyId;
  339. $q = 'status=' . $status;
  340. $hash = '';
  341. if ($sid < 0) {
  342. $q .= '&focus_sid=' . $sid;
  343. $hash = '#mproc_fs=' . $sid;
  344. }
  345. return $base . $path . '?' . $q . $hash;
  346. }
  347. /**
  348. * 邮件/短信外链:须为带点的公网域名
  349. */
  350. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  351. {
  352. $u = trim((string)$baseUrl);
  353. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  354. return false;
  355. }
  356. $host = parse_url($u, PHP_URL_HOST);
  357. if (!is_string($host) || $host === '') {
  358. return false;
  359. }
  360. if (strcasecmp($host, 'localhost') === 0) {
  361. return false;
  362. }
  363. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  364. return false;
  365. }
  366. if (strpos($host, '.') === false) {
  367. return false;
  368. }
  369. return true;
  370. }
  371. /**
  372. * 解析用于协助邮件/短信的手机端站点根
  373. */
  374. protected function resolveMprocMobilePublicBaseUrl()
  375. {
  376. $candidates = [];
  377. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  378. $candidates[] = trim((string)Config::get('site.indexurl'));
  379. $cdn = trim((string)Config::get('site.cdnurl'));
  380. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  381. $candidates[] = rtrim($cdn, '/');
  382. }
  383. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  384. $candidates[] = $reqBase;
  385. foreach ($candidates as $c) {
  386. if ($c === '') {
  387. continue;
  388. }
  389. $c = rtrim($c, '/');
  390. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  391. return $c;
  392. }
  393. }
  394. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  395. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  396. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  397. return $reqBase;
  398. }
  399. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  400. return '';
  401. }
  402. /**
  403. * 获取 Redis 中 procuremen_redis
  404. */
  405. protected function ProcuremenRedis(): array
  406. {
  407. if ($this->procuremenRedisCache !== null) {
  408. return $this->procuremenRedisCache;
  409. }
  410. try {
  411. $redis = redis();
  412. $raw = $redis->get('procuremen_redis');
  413. if ($raw === false || $raw === '') {
  414. $this->procuremenRedisCache = [];
  415. return $this->procuremenRedisCache;
  416. }
  417. $decoded = json_decode($raw, true);
  418. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  419. $this->procuremenRedisCache = [];
  420. return $this->procuremenRedisCache;
  421. }
  422. $this->procuremenRedisCache = $decoded['data'];
  423. // 整包已解码时顺带补齐侧栏小键,避免下次首屏再扫库
  424. if ($this->loadProcuremenSidebarYmList() === []) {
  425. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($this->procuremenRedisCache));
  426. }
  427. return $this->procuremenRedisCache;
  428. } catch (\Throwable $e) {
  429. $this->procuremenRedisCache = [];
  430. return $this->procuremenRedisCache;
  431. }
  432. }
  433. /**
  434. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  435. *
  436. * @return array<int, array<string, mixed>>
  437. */
  438. protected function procuremenFetchErpPoolFromDb(): array
  439. {
  440. try {
  441. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  442. $endTime = date('Y-m-d 23:59:59');
  443. $list = Db::table('scydgy')
  444. ->alias('a')
  445. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  446. ->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, b.czlyq, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  447. ->where([
  448. 'a.bwjg' => 1,
  449. 'a.iEndBz' => 0,
  450. 'a.iType' => 0,
  451. 'a.iStatus' => 10,
  452. ])
  453. ->where('a.dStamp', '>=', $startTime)
  454. ->where('a.dStamp', '<=', $endTime)
  455. ->order('a.dStamp', 'desc')
  456. ->select();
  457. if (!is_array($list)) {
  458. return [];
  459. }
  460. try {
  461. $redis = redis();
  462. $payload = [
  463. 'code' => 200,
  464. 'msg' => 'success',
  465. 'data' => $list,
  466. ];
  467. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  468. $this->procuremenRedisCache = $list;
  469. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($list));
  470. $this->clearPickMonthPoolCaches();
  471. $this->warmPickMonthPoolCachesFromPool($list);
  472. } catch (\Throwable $e) {
  473. }
  474. return $list;
  475. } catch (\Throwable $e) {
  476. Log::write('拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  477. return [];
  478. }
  479. }
  480. /**
  481. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  482. *
  483. * @return array<int, array<string, mixed>>
  484. */
  485. protected function procuremenEnsureRedisPool(): array
  486. {
  487. $pool = $this->ProcuremenRedis();
  488. if (is_array($pool) && $pool !== []) {
  489. return $pool;
  490. }
  491. static $warmed = false;
  492. if ($warmed) {
  493. return is_array($pool) ? $pool : [];
  494. }
  495. $warmed = true;
  496. return $this->procuremenFetchErpPoolFromDb();
  497. }
  498. /**
  499. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  500. *
  501. * @param array<string, mixed> $row
  502. */
  503. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  504. {
  505. $t = $this->procuremenRowListSortTime($row, $primary);
  506. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  507. return null;
  508. }
  509. $mo = (int)$m[2];
  510. if ($mo < 1 || $mo > 12) {
  511. return null;
  512. }
  513. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  514. }
  515. /**
  516. * @param array<int, array{year:string, months:array}> $sidebar
  517. * @return array<int, array{year:string, months:array}>
  518. */
  519. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  520. {
  521. $ym = trim($ym);
  522. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  523. return $sidebar;
  524. }
  525. foreach ($sidebar as $block) {
  526. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  527. continue;
  528. }
  529. foreach ($block['months'] as $item) {
  530. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  531. return $sidebar;
  532. }
  533. }
  534. }
  535. $y = substr($ym, 0, 4);
  536. $mo = (int)substr($ym, 5, 2);
  537. $sidebar[] = [
  538. 'year' => $y,
  539. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  540. ];
  541. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  542. }
  543. /**
  544. * @param array<int, array{year:string, months:array}> $sidebar
  545. * @return string[]
  546. */
  547. protected function flattenProcuremenSidebarYms(array $sidebar): array
  548. {
  549. $yms = [];
  550. foreach ($sidebar as $block) {
  551. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  552. continue;
  553. }
  554. foreach ($block['months'] as $item) {
  555. if (!is_array($item)) {
  556. continue;
  557. }
  558. $ym = trim((string)($item['ym'] ?? ''));
  559. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  560. $yms[$ym] = true;
  561. }
  562. }
  563. }
  564. return array_keys($yms);
  565. }
  566. /**
  567. * 左侧菜单(协助初选)
  568. * 优先 Redis 月份小键;为空时用轻量 DISTINCT 查库补齐(避免只显示空当月、漏掉有数据的月份)。
  569. */
  570. protected function GetIndexYearMonths()
  571. {
  572. $ymList = $this->ensureProcuremenPickSidebarYmList();
  573. if ($ymList === []) {
  574. $def = date('Y-m');
  575. $ymList = [preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m')];
  576. }
  577. return $this->buildYearMonthSidebar($ymList);
  578. }
  579. /**
  580. * 初选侧栏月份:以轻量 DISTINCT 查库为准(有数据才显示),并写回 Redis 小键。
  581. *
  582. * @return string[]
  583. */
  584. protected function ensureProcuremenPickSidebarYmList(bool $forceRefresh = false): array
  585. {
  586. static $memo = null;
  587. if (!$forceRefresh && is_array($memo)) {
  588. return $memo;
  589. }
  590. $fromDb = $this->queryProcuremenPickSidebarYmListLight();
  591. if ($fromDb !== []) {
  592. $this->saveProcuremenSidebarYmList($fromDb);
  593. $memo = $fromDb;
  594. return $memo;
  595. }
  596. // 库侧暂无初选数据时,再回退 Redis / 当月,避免侧栏空白
  597. $cached = $this->loadProcuremenSidebarYmList();
  598. if ($cached !== []) {
  599. $memo = $cached;
  600. return $memo;
  601. }
  602. $memo = [date('Y-m')];
  603. return $memo;
  604. }
  605. /**
  606. * @return string[] 形如 2026-07
  607. */
  608. protected function loadProcuremenSidebarYmList(): array
  609. {
  610. try {
  611. $raw = redis()->get('procuremen_redis_yms');
  612. if ($raw === false || $raw === null || $raw === '') {
  613. return [];
  614. }
  615. $decoded = json_decode((string)$raw, true);
  616. if (!is_array($decoded)) {
  617. return [];
  618. }
  619. $out = [];
  620. foreach ($decoded as $ym) {
  621. $ym = trim((string)$ym);
  622. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  623. $out[$ym] = true;
  624. }
  625. }
  626. return array_keys($out);
  627. } catch (\Throwable $e) {
  628. return [];
  629. }
  630. }
  631. /**
  632. * @param string[] $ymList
  633. */
  634. protected function saveProcuremenSidebarYmList(array $ymList): void
  635. {
  636. $out = [];
  637. foreach ($ymList as $ym) {
  638. $ym = trim((string)$ym);
  639. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  640. $out[$ym] = true;
  641. }
  642. }
  643. if ($out === []) {
  644. return;
  645. }
  646. try {
  647. redis()->set('procuremen_redis_yms', json_encode(array_keys($out), JSON_UNESCAPED_UNICODE));
  648. } catch (\Throwable $e) {
  649. }
  650. }
  651. /**
  652. * @param array<int, array<string, mixed>> $pool
  653. * @return string[]
  654. */
  655. protected function extractYearMonthsFromPoolRows(array $pool): array
  656. {
  657. $ymSet = [];
  658. foreach ($pool as $r) {
  659. if (!is_array($r)) {
  660. continue;
  661. }
  662. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  663. continue;
  664. }
  665. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  666. if ($ym !== null) {
  667. $ymSet[$ym] = true;
  668. }
  669. }
  670. return array_keys($ymSet);
  671. }
  672. /**
  673. * 轻量查询初选侧栏月份(只取 DISTINCT 年月,不拉整包工序)
  674. *
  675. * @return string[]
  676. */
  677. protected function queryProcuremenPickSidebarYmListLight(): array
  678. {
  679. try {
  680. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  681. $endTime = date('Y-m-d 23:59:59');
  682. $sql = 'SELECT DISTINCT DATE_FORMAT('
  683. . 'IF(b.dputrecord IS NOT NULL AND TRIM(CAST(b.dputrecord AS CHAR(32))) <> \'\''
  684. . ' AND TRIM(CAST(b.dputrecord AS CHAR(32))) NOT LIKE \'0000-00-00%\','
  685. . ' b.dputrecord, a.dStamp), \'%Y-%m\') AS ym'
  686. . ' FROM scydgy a'
  687. . ' INNER JOIN mcyd b ON b.ICYDID = a.ICYDID AND b.iStatus >= 10'
  688. . ' WHERE a.bwjg = 1 AND a.iEndBz = 0 AND a.iType = 0 AND a.iStatus = 10'
  689. . ' AND a.dStamp >= ? AND a.dStamp <= ?';
  690. $rows = Db::query($sql, [$startTime, $endTime]);
  691. if (!is_array($rows)) {
  692. return [];
  693. }
  694. $out = [];
  695. foreach ($rows as $r) {
  696. $ym = trim((string)($r['ym'] ?? ''));
  697. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  698. $out[$ym] = true;
  699. }
  700. }
  701. return array_keys($out);
  702. } catch (\Throwable $e) {
  703. Log::write('初选侧栏月份查询失败:' . $e->getMessage(), 'warning');
  704. return [];
  705. }
  706. }
  707. /**
  708. * @return string[] 含当月在内的近 N 个自然月
  709. */
  710. protected function buildRecentCalendarYmList(int $months = 12): array
  711. {
  712. $months = max(1, min(24, $months));
  713. $out = [];
  714. $base = strtotime(date('Y-m-01'));
  715. for ($i = 0; $i < $months; $i++) {
  716. $out[] = date('Y-m', strtotime('-' . $i . ' month', $base));
  717. }
  718. return $out;
  719. }
  720. /**
  721. * 初选按月工序池:优先月缓存;未命中则直接按月查 ERP。
  722. * 禁止为列表去解近一年整包 Redis(解包/连接异常会造成长时间转圈)。
  723. *
  724. * @return array<int, array<string, mixed>>
  725. */
  726. protected function loadPickPoolForYm(string $ym): array
  727. {
  728. $ym = trim($ym);
  729. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  730. return [];
  731. }
  732. $hit = $this->readPickMonthPoolCache($ym);
  733. if ($hit !== null) {
  734. return $hit;
  735. }
  736. return $this->queryPickPoolForYmFromDb($ym);
  737. }
  738. /**
  739. * @return array<int, array<string, mixed>>|null null=无有效缓存(含旧版空数组误缓存)
  740. */
  741. protected function readPickMonthPoolCache(string $ym): ?array
  742. {
  743. try {
  744. $raw = redis()->get('procuremen_pick_pool:' . $ym);
  745. if ($raw === false || $raw === null || $raw === '') {
  746. return null;
  747. }
  748. $decoded = json_decode((string)$raw, true);
  749. if (!is_array($decoded)) {
  750. return null;
  751. }
  752. // 新格式:{ok:1, rows:[...]},空月也算有效(已从整包确认)
  753. if (isset($decoded['ok']) && (int)$decoded['ok'] === 1 && isset($decoded['rows']) && is_array($decoded['rows'])) {
  754. return $decoded['rows'];
  755. }
  756. // 旧格式:仅非空行列表可命中;[] 多半是错误 SQL 写入,视为未命中
  757. if ($decoded === []) {
  758. try {
  759. redis()->del('procuremen_pick_pool:' . $ym);
  760. } catch (\Throwable $e) {
  761. }
  762. return null;
  763. }
  764. if (isset($decoded[0]) && is_array($decoded[0])) {
  765. return $decoded;
  766. }
  767. return null;
  768. } catch (\Throwable $e) {
  769. return null;
  770. }
  771. }
  772. /**
  773. * @param array<int, array<string, mixed>> $rows
  774. */
  775. protected function writePickMonthPoolCache(string $ym, array $rows): void
  776. {
  777. try {
  778. redis()->setex(
  779. 'procuremen_pick_pool:' . $ym,
  780. 600,
  781. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  782. );
  783. } catch (\Throwable $e) {
  784. }
  785. }
  786. /**
  787. * @param array<int, array<string, mixed>> $pool
  788. * @return array<int, array<string, mixed>>
  789. */
  790. protected function filterPoolRowsByYm(array $pool, string $ym): array
  791. {
  792. $out = [];
  793. foreach ($pool as $r) {
  794. if (!is_array($r)) {
  795. continue;
  796. }
  797. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  798. continue;
  799. }
  800. if ($this->procuremenRowYearMonth($r, 'dputrecord') === $ym) {
  801. $out[] = $r;
  802. }
  803. }
  804. return $out;
  805. }
  806. /**
  807. * 按 dStamp 取当月附近数据,再用列表规则(dputrecord 优先)精确到 ym
  808. *
  809. * @return array<int, array<string, mixed>>
  810. */
  811. protected function queryPickPoolForYmFromDb(string $ym): array
  812. {
  813. $monthStart = $ym . '-01 00:00:00';
  814. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  815. // 略放大窗口,避免 dStamp 与 dputrecord 跨月导致漏数;最终仍按 ym 精确过滤
  816. $queryStart = date('Y-m-d 00:00:00', strtotime($monthStart . ' -7 days'));
  817. $queryEnd = date('Y-m-d 23:59:59', strtotime($monthEnd . ' +7 days'));
  818. try {
  819. $list = Db::table('scydgy')
  820. ->alias('a')
  821. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  822. ->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, b.czlyq, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  823. ->where([
  824. 'a.bwjg' => 1,
  825. 'a.iEndBz' => 0,
  826. 'a.iType' => 0,
  827. 'a.iStatus' => 10,
  828. ])
  829. ->where('a.dStamp', '>=', $queryStart)
  830. ->where('a.dStamp', '<=', $queryEnd)
  831. ->order('a.dStamp', 'desc')
  832. ->select();
  833. } catch (\Throwable $e) {
  834. Log::write('初选按月取数失败 ym=' . $ym . ':' . $e->getMessage(), 'error');
  835. return [];
  836. }
  837. if (!is_array($list)) {
  838. $list = [];
  839. }
  840. $out = $this->filterPoolRowsByYm($list, $ym);
  841. // 新格式缓存(含空月),避免重复打库;读侧只认 ok=1
  842. $this->writePickMonthPoolCache($ym, $out);
  843. try {
  844. $yms = $this->loadProcuremenSidebarYmList();
  845. if ($out !== [] && ($yms === [] || !in_array($ym, $yms, true))) {
  846. $yms[] = $ym;
  847. $this->saveProcuremenSidebarYmList($yms);
  848. }
  849. } catch (\Throwable $e) {
  850. }
  851. return $out;
  852. }
  853. /**
  854. * 整包写入后拆成按月小缓存,供初选列表秒开
  855. *
  856. * @param array<int, array<string, mixed>> $pool
  857. */
  858. protected function warmPickMonthPoolCachesFromPool(array $pool): void
  859. {
  860. if ($pool === []) {
  861. return;
  862. }
  863. $byYm = [];
  864. foreach ($pool as $r) {
  865. if (!is_array($r)) {
  866. continue;
  867. }
  868. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  869. continue;
  870. }
  871. $rowYm = $this->procuremenRowYearMonth($r, 'dputrecord');
  872. if ($rowYm === null) {
  873. continue;
  874. }
  875. $byYm[$rowYm][] = $r;
  876. }
  877. if ($byYm === []) {
  878. return;
  879. }
  880. try {
  881. $redis = redis();
  882. foreach ($byYm as $rowYm => $rows) {
  883. $redis->setex(
  884. 'procuremen_pick_pool:' . $rowYm,
  885. 600,
  886. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  887. );
  888. }
  889. try {
  890. $redis->del('procuremen_pick_hidden_scydgy_v1');
  891. } catch (\Throwable $e) {
  892. }
  893. } catch (\Throwable $e) {
  894. }
  895. }
  896. /**
  897. * 刷新整包后清理近月缓存,避免脏读
  898. */
  899. protected function clearPickMonthPoolCaches(int $months = 24): void
  900. {
  901. try {
  902. $redis = redis();
  903. foreach ($this->buildRecentCalendarYmList($months) as $ym) {
  904. try {
  905. $redis->del('procuremen_pick_pool:' . $ym);
  906. } catch (\Throwable $e) {
  907. }
  908. }
  909. } catch (\Throwable $e) {
  910. }
  911. $this->invalidatePickHiddenScydgyCache();
  912. }
  913. /**
  914. * 下发/完结后清隐藏集缓存,避免初选列表最多 90 秒仍显示已下发行
  915. */
  916. protected function invalidatePickHiddenScydgyCache(): void
  917. {
  918. $this->pickHiddenScydgySetCache = null;
  919. try {
  920. redis()->del('procuremen_pick_hidden_scydgy_v1');
  921. } catch (\Throwable $e) {
  922. }
  923. }
  924. /** 列表/首屏读完鉴权后尽早释放 session,避免多 iframe 串行卡死 */
  925. protected function procuremenReleaseSessionLock(): void
  926. {
  927. if (session_status() === PHP_SESSION_ACTIVE) {
  928. @session_write_close();
  929. }
  930. }
  931. /**
  932. * @param string[] $ymList 形如 2026-06
  933. * @return array<int, array{year:string, months:array}>
  934. */
  935. protected function buildYearMonthSidebar(array $ymList): array
  936. {
  937. rsort($ymList, SORT_STRING);
  938. $byYear = [];
  939. foreach ($ymList as $ym) {
  940. $y = substr($ym, 0, 4);
  941. $mo = (int)substr($ym, 5, 2);
  942. if (!isset($byYear[$y])) {
  943. $byYear[$y] = [];
  944. }
  945. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  946. }
  947. krsort($byYear, SORT_NUMERIC);
  948. foreach ($byYear as $y => $items) {
  949. usort($byYear[$y], function ($a, $b) {
  950. return strcmp($b['ym'], $a['ym']);
  951. });
  952. }
  953. $sidebar = [];
  954. foreach ($byYear as $y => $months) {
  955. $sidebar[] = ['year' => $y, 'months' => $months];
  956. }
  957. return $sidebar;
  958. }
  959. /**
  960. * 已下发/审批/确认列表左侧月份:SQL DISTINCT,禁止把该阶段全部行拉进 PHP
  961. * 注意:MySQL8 严格模式下勿对 datetime 用 <> '',否则报 Incorrect DATETIME value 被吞掉后侧栏只剩默认月
  962. */
  963. protected function GetIssuedOrderYearMonths(string $stage): array
  964. {
  965. if ($stage !== 'audit' && $stage !== 'confirm') {
  966. return $this->GetIndexYearMonths();
  967. }
  968. $ymSet = [];
  969. $addYm = function ($raw) use (&$ymSet): void {
  970. $ym = trim((string)$raw);
  971. if (preg_match('/^([12]\d{3})-(\d{2})/', $ym, $m)) {
  972. $ymSet[$m[1] . '-' . $m[2]] = true;
  973. }
  974. };
  975. try {
  976. $query = Db::table('purchase_order')->field('pick_time,createtime,dStamp');
  977. $this->applyPurchaseOrderNotDeletedWhere($query);
  978. $this->applyPurchaseOrderConfirmAuditListWhere($query);
  979. $rows = $query->select();
  980. if (is_array($rows)) {
  981. foreach ($rows as $r) {
  982. if (!is_array($r)) {
  983. continue;
  984. }
  985. $pick = trim((string)($r['pick_time'] ?? ''));
  986. if ($pick !== '' && stripos($pick, '0000-00-00') !== 0) {
  987. $addYm($pick);
  988. continue;
  989. }
  990. $ct = $r['createtime'] ?? null;
  991. if (is_numeric($ct) && (int)$ct > 946684800) {
  992. $addYm(date('Y-m-d', (int)$ct));
  993. continue;
  994. }
  995. $ctStr = trim((string)$ct);
  996. if ($ctStr !== '' && stripos($ctStr, '0000-00-00') !== 0) {
  997. $addYm($ctStr);
  998. continue;
  999. }
  1000. $ds = trim((string)($r['dStamp'] ?? ''));
  1001. if ($ds !== '' && stripos($ds, '0000-00-00') !== 0) {
  1002. $addYm($ds);
  1003. }
  1004. }
  1005. }
  1006. } catch (\Throwable $e) {
  1007. Log::write('GetIssuedOrderYearMonths: ' . $e->getMessage(), 'error');
  1008. $ymSet = [];
  1009. }
  1010. $ymList = array_keys($ymSet);
  1011. if ($ymList === []) {
  1012. $def = $this->resolveProcuremenDefaultYm($stage);
  1013. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  1014. }
  1015. return $this->buildYearMonthSidebar($ymList);
  1016. }
  1017. /**
  1018. * 列表默认月份:已下发类取最近有数据的月份;初选也取最近有数据月份(避免跨月后落到空当月)
  1019. */
  1020. protected function resolveProcuremenDefaultYm(string $stage): string
  1021. {
  1022. if ($stage === 'pick') {
  1023. $yms = $this->ensureProcuremenPickSidebarYmList();
  1024. if ($yms !== []) {
  1025. rsort($yms, SORT_STRING);
  1026. return $yms[0];
  1027. }
  1028. return date('Y-m');
  1029. }
  1030. try {
  1031. $query = Db::table('purchase_order');
  1032. $this->applyPurchaseOrderNotDeletedWhere($query);
  1033. if ($stage === 'audit') {
  1034. $query->whereIn('wflow_status', ProcuremenStatus::wflowConfirmAndAuditListValues());
  1035. } elseif ($stage === 'confirm') {
  1036. $this->applyPurchaseOrderConfirmStageWhere($query);
  1037. } else {
  1038. return date('Y-m');
  1039. }
  1040. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  1041. if ($latest === null || $latest === '') {
  1042. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  1043. }
  1044. $t = $this->formatProcuremenDetailTime($latest);
  1045. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  1046. return $m[1] . '-' . $m[2];
  1047. }
  1048. } catch (\Throwable $e) {
  1049. }
  1050. return date('Y-m');
  1051. }
  1052. protected function applyPurchaseOrderNotDeletedWhere($query): void
  1053. {
  1054. $query->whereRaw("(mod_rq IS NULL OR mod_rq = '' OR mod_rq LIKE '0000-00-00%')");
  1055. }
  1056. /**
  1057. * 确认/审批列表共用:待确认 + 待审核(待审批) + 已审核
  1058. */
  1059. protected function applyPurchaseOrderConfirmAuditListWhere($query): void
  1060. {
  1061. $vals = ProcuremenStatus::wflowConfirmAndAuditListValues();
  1062. $quoted = [];
  1063. foreach ($vals as $v) {
  1064. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  1065. }
  1066. if ($quoted === []) {
  1067. $query->whereRaw('1 = 0');
  1068. return;
  1069. }
  1070. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  1071. }
  1072. /**
  1073. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  1074. * 完结判断必须走 CAST 文案比较:status 为 0/'0' 时,NOT IN ('已完结','1') 会被 MySQL 把「已完结」转成 0 而整表滤空
  1075. */
  1076. protected function applyPurchaseOrderConfirmStageWhere($query): void
  1077. {
  1078. // 与确认页共用数据范围(待确认/待审核/已审核)
  1079. $this->applyPurchaseOrderConfirmAuditListWhere($query);
  1080. }
  1081. /**
  1082. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  1083. *
  1084. * @param array<string, mixed> $row
  1085. * @return array<string, mixed>
  1086. */
  1087. protected function normalizePurchaseOrderListTimeRow(array $row): array
  1088. {
  1089. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  1090. $pick = trim((string)($row['pick_time'] ?? ''));
  1091. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  1092. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  1093. $t = trim((string)($row[$key] ?? ''));
  1094. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1095. $row['pick_time'] = $t;
  1096. break;
  1097. }
  1098. }
  1099. }
  1100. return $row;
  1101. }
  1102. /**
  1103. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  1104. */
  1105. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  1106. {
  1107. if (!in_array($stage, ['audit', 'confirm'], true)) {
  1108. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1109. }
  1110. if ($pool === []) {
  1111. $def = $this->resolveProcuremenDefaultYm($stage);
  1112. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  1113. }
  1114. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  1115. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1116. return false;
  1117. }
  1118. $monthStart = $ym . '-01 00:00:00';
  1119. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1120. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  1121. return $probe !== [];
  1122. };
  1123. if ($tryYm($requestedYm)) {
  1124. return $requestedYm;
  1125. }
  1126. $fallback = $this->resolveProcuremenDefaultYm($stage);
  1127. if ($tryYm($fallback)) {
  1128. return $fallback;
  1129. }
  1130. $bestYm = '';
  1131. $bestTime = '';
  1132. foreach ($pool as $row) {
  1133. if (!is_array($row)) {
  1134. continue;
  1135. }
  1136. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  1137. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  1138. continue;
  1139. }
  1140. $ymRow = $m[1];
  1141. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  1142. $bestTime = $t;
  1143. $bestYm = $ymRow;
  1144. }
  1145. }
  1146. if ($bestYm !== '') {
  1147. return $bestYm;
  1148. }
  1149. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1150. }
  1151. protected function isPurchaseOrderDetailVoid(array $row): bool
  1152. {
  1153. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  1154. return true;
  1155. }
  1156. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  1157. }
  1158. /**
  1159. * 仅当前有效下发明细(排除废弃归档)
  1160. */
  1161. protected function applyActivePurchaseOrderDetailWhere($query): void
  1162. {
  1163. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1164. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  1165. }
  1166. /**
  1167. * @param array<string, mixed> $detailRow
  1168. */
  1169. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  1170. {
  1171. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  1172. return false;
  1173. }
  1174. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  1175. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  1176. }
  1177. /**
  1178. * 废弃退回初选:下发明细标记归档,不物理删除
  1179. *
  1180. * @param array<int, int|string> $scydgyIds
  1181. */
  1182. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  1183. {
  1184. $ids = [];
  1185. foreach ($scydgyIds as $sid) {
  1186. $n = (int)$sid;
  1187. if ($this->isValidScydgyRowId($n) || $n < 0) {
  1188. $ids[$n] = true;
  1189. }
  1190. }
  1191. if ($ids === []) {
  1192. return;
  1193. }
  1194. $void = ProcuremenStatus::POD_VOID;
  1195. Db::table('purchase_order_detail')
  1196. ->where('scydgy_id', 'in', array_keys($ids))
  1197. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1198. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  1199. ->update([
  1200. 'status' => $void,
  1201. 'status_name' => $void,
  1202. ]);
  1203. }
  1204. /**
  1205. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  1206. */
  1207. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  1208. {
  1209. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  1210. $norm = function (string $col) use ($p): string {
  1211. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  1212. };
  1213. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  1214. $parts = [];
  1215. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  1216. if ($key === 'createtime') {
  1217. $parts[] = $createtime;
  1218. } else {
  1219. $parts[] = $norm($key);
  1220. }
  1221. }
  1222. return 'COALESCE(' . implode(', ', $parts) . ')';
  1223. }
  1224. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  1225. {
  1226. if (!preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $monthStart)
  1227. || !preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $monthEnd)) {
  1228. return;
  1229. }
  1230. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  1231. // 禁止 whereRaw 用 ? :与 whereIn 命名绑定混用时 PDO 会失败,列表被 catch 成空
  1232. $query->whereRaw("({$expr}) >= '{$monthStart}' AND ({$expr}) <= '{$monthEnd}'");
  1233. }
  1234. /**
  1235. * @return array<int, array<string, mixed>>
  1236. */
  1237. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  1238. {
  1239. $this->ensurePurchaseOrderCzlyqColumn();
  1240. $this->ensurePurchaseOrderManualPickColumns();
  1241. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1242. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name,manual_pick,order_batch_no';
  1243. try {
  1244. $this->ensurePurchaseOrderOrderBatchNoColumn();
  1245. $query = Db::table('purchase_order')->field($fields);
  1246. $this->applyPurchaseOrderNotDeletedWhere($query);
  1247. if ($stage === 'audit') {
  1248. $query->whereIn('wflow_status', ProcuremenStatus::wflowConfirmAndAuditListValues());
  1249. } elseif ($stage === 'confirm') {
  1250. $this->applyPurchaseOrderConfirmStageWhere($query);
  1251. } else {
  1252. return [];
  1253. }
  1254. $query->order('pick_time', 'desc')->order('id', 'desc');
  1255. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1256. $monthStart = $ym . '-01 00:00:00';
  1257. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1258. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  1259. }
  1260. $rows = $query->select();
  1261. } catch (\Throwable $e) {
  1262. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  1263. $rows = [];
  1264. }
  1265. return is_array($rows) ? $rows : [];
  1266. }
  1267. /**
  1268. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  1269. */
  1270. protected function resolveProcuremenListStage(): string
  1271. {
  1272. $tab = trim((string)$this->request->request('wff_tab', ''));
  1273. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  1274. return $tab;
  1275. }
  1276. $action = strtolower((string)$this->request->action());
  1277. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  1278. return $action;
  1279. }
  1280. return 'pick';
  1281. }
  1282. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  1283. {
  1284. $this->procuremenReleaseSessionLock();
  1285. $rootTrue = rtrim((string)$this->request->root(true), '/');
  1286. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  1287. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  1288. $indexPhpRoot = $rootTrue . '/index.php';
  1289. }
  1290. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  1291. if ($stage === 'pick') {
  1292. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  1293. $sidebar = $this->GetIndexYearMonths();
  1294. } else {
  1295. $sidebar = $this->GetIssuedOrderYearMonths($stage);
  1296. $defaultYm = $this->latestYmFromSidebar($sidebar);
  1297. }
  1298. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  1299. $this->view->assign('defaultYm', $defaultYm);
  1300. $this->view->assign('sidebarYearMonths', $sidebar);
  1301. $this->view->assign('procuremenStage', $stage);
  1302. $this->view->assign('procuremenPageTitle', $pageTitle);
  1303. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  1304. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  1305. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  1306. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  1307. // 筛选项由列表 AJAX 带回,避免进页再扫 4 次 DISTINCT 白屏
  1308. $this->assignconfig('procuremenFilterOptions', [
  1309. 'czlyq' => [],
  1310. 'CCLBMMC' => [],
  1311. 'cywyxm' => [],
  1312. 'CGYMC' => [],
  1313. ]);
  1314. }
  1315. /**
  1316. * @param array<int, array{year?:string, months?:array}> $sidebar
  1317. */
  1318. protected function latestYmFromSidebar(array $sidebar): string
  1319. {
  1320. $best = '';
  1321. foreach ($sidebar as $block) {
  1322. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  1323. continue;
  1324. }
  1325. foreach ($block['months'] as $item) {
  1326. $ym = is_array($item) ? trim((string)($item['ym'] ?? '')) : '';
  1327. if (preg_match('/^\d{4}-\d{2}$/', $ym) && ($best === '' || strcmp($ym, $best) > 0)) {
  1328. $best = $ym;
  1329. }
  1330. }
  1331. }
  1332. return $best !== '' ? $best : date('Y-m');
  1333. }
  1334. /**
  1335. * 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
  1336. *
  1337. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1338. */
  1339. protected function buildProcuremenFilterOptions(string $stage): array
  1340. {
  1341. $buckets = [
  1342. 'czlyq' => [],
  1343. 'CCLBMMC' => [],
  1344. 'cywyxm' => [],
  1345. 'CGYMC' => [],
  1346. ];
  1347. $maxPerField = 300;
  1348. try {
  1349. if ($stage === 'pick') {
  1350. // 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
  1351. return $buckets;
  1352. }
  1353. if (in_array($stage, ['audit', 'confirm'], true)) {
  1354. $this->ensurePurchaseOrderCzlyqColumn();
  1355. foreach (array_keys($buckets) as $field) {
  1356. try {
  1357. $query = Db::table('purchase_order')->field($field);
  1358. $this->applyPurchaseOrderNotDeletedWhere($query);
  1359. if ($stage === 'audit') {
  1360. $query->whereIn('wflow_status', ProcuremenStatus::wflowConfirmAndAuditListValues());
  1361. } else {
  1362. $this->applyPurchaseOrderConfirmStageWhere($query);
  1363. }
  1364. $query->where($field, '<>', '')->whereNotNull($field);
  1365. $vals = $query->distinct(true)->limit($maxPerField)->column($field);
  1366. if (!is_array($vals)) {
  1367. continue;
  1368. }
  1369. foreach ($vals as $v) {
  1370. $v = trim((string)$v);
  1371. if ($v !== '') {
  1372. $buckets[$field][$v] = $v;
  1373. }
  1374. }
  1375. } catch (\Throwable $e) {
  1376. // 单字段失败不影响其它
  1377. }
  1378. }
  1379. }
  1380. } catch (\Throwable $e) {
  1381. Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
  1382. }
  1383. foreach ($buckets as &$set) {
  1384. if ($set !== []) {
  1385. ksort($set, SORT_STRING);
  1386. }
  1387. }
  1388. unset($set);
  1389. return $buckets;
  1390. }
  1391. /**
  1392. * filter JSON 是否含有效条件
  1393. *
  1394. * @param array<string, mixed> $filterArr
  1395. */
  1396. protected function procuremenFilterArrHasValue(array $filterArr): bool
  1397. {
  1398. foreach ($filterArr as $v) {
  1399. if (is_array($v)) {
  1400. if (array_filter($v, function ($x) {
  1401. return $x !== '' && $x !== null;
  1402. })) {
  1403. return true;
  1404. }
  1405. } elseif ($v !== '' && $v !== null) {
  1406. return true;
  1407. }
  1408. }
  1409. return false;
  1410. }
  1411. /**
  1412. * 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
  1413. *
  1414. * @param array<string, mixed> $filterArr
  1415. * @param array<string, mixed> $opArr
  1416. */
  1417. protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
  1418. {
  1419. if ($search !== '') {
  1420. return false;
  1421. }
  1422. foreach ($filterArr as $fk => $fv) {
  1423. if (is_array($fv)) {
  1424. continue;
  1425. }
  1426. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  1427. continue;
  1428. }
  1429. if ($fv === null) {
  1430. continue;
  1431. }
  1432. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  1433. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  1434. if ($sym === '' || $sym === '=') {
  1435. continue;
  1436. }
  1437. return false;
  1438. }
  1439. return true;
  1440. }
  1441. /**
  1442. * 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
  1443. *
  1444. * @param array<int, mixed> $rows
  1445. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1446. */
  1447. protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
  1448. {
  1449. $buckets = [
  1450. 'czlyq' => [],
  1451. 'CCLBMMC' => [],
  1452. 'cywyxm' => [],
  1453. 'CGYMC' => [],
  1454. ];
  1455. foreach ($rows as $r) {
  1456. if (!is_array($r)) {
  1457. continue;
  1458. }
  1459. foreach ($buckets as $field => &$set) {
  1460. if (count($set) >= $maxPerField) {
  1461. continue;
  1462. }
  1463. $v = trim((string)($r[$field] ?? ''));
  1464. if ($v !== '') {
  1465. $set[$v] = $v;
  1466. }
  1467. }
  1468. unset($set);
  1469. $full = true;
  1470. foreach ($buckets as $set) {
  1471. if (count($set) < $maxPerField) {
  1472. $full = false;
  1473. break;
  1474. }
  1475. }
  1476. if ($full) {
  1477. break;
  1478. }
  1479. }
  1480. foreach ($buckets as &$set) {
  1481. if ($set !== []) {
  1482. // 保证 json 编码为对象(避免 list 下标 0,1,2… 被前端当选项)
  1483. $normalized = [];
  1484. foreach ($set as $k => $v) {
  1485. $s = trim((string)(is_scalar($v) ? $v : $k));
  1486. if ($s === '') {
  1487. continue;
  1488. }
  1489. $normalized[$s] = $s;
  1490. }
  1491. ksort($normalized, SORT_STRING);
  1492. $set = $normalized;
  1493. }
  1494. }
  1495. unset($set);
  1496. return $buckets;
  1497. }
  1498. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  1499. public function pick()
  1500. {
  1501. $this->request->filter(['strip_tags', 'trim']);
  1502. if (!$this->request->isAjax()) {
  1503. $this->assignProcuremenListPage('pick', '协助下发');
  1504. return $this->view->fetch('procuremen/index');
  1505. }
  1506. return $this->index();
  1507. }
  1508. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  1509. public function audit()
  1510. {
  1511. $this->request->filter(['strip_tags', 'trim']);
  1512. if (!$this->request->isAjax()) {
  1513. $this->assignProcuremenListPage('audit', '确认供应商');
  1514. return $this->view->fetch('procuremen/index');
  1515. }
  1516. return $this->index();
  1517. }
  1518. /** 采购确认(定标) */
  1519. public function confirm()
  1520. {
  1521. $this->request->filter(['strip_tags', 'trim']);
  1522. if (!$this->request->isAjax()) {
  1523. $this->assignProcuremenListPage('confirm', '采购确认');
  1524. return $this->view->fetch('procuremen/index');
  1525. }
  1526. return $this->index();
  1527. }
  1528. /**
  1529. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  1530. */
  1531. public function index()
  1532. {
  1533. $this->request->filter(['strip_tags', 'trim']);
  1534. if (!$this->request->isAjax()) {
  1535. $this->assignProcuremenListPage('pick', '协助下发');
  1536. return $this->view->fetch('procuremen/index');
  1537. }
  1538. if ($this->request->request('keyField')) {
  1539. return $this->selectpage();
  1540. }
  1541. $this->procuremenReleaseSessionLock();
  1542. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  1543. $limit = max(10, min(500, (int)$limit));
  1544. $ym = $this->request->request('ym', '');
  1545. $ym = is_string($ym) ? trim($ym) : '';
  1546. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  1547. $wffTab = $this->resolveProcuremenListStage();
  1548. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1549. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  1550. ? $this->resolveProcuremenDefaultYm($wffTab)
  1551. : date('Y-m');
  1552. }
  1553. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1554. $ym = date('Y-m');
  1555. }
  1556. $monthStart = $ym . '-01 00:00:00';
  1557. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1558. $search = trim((string)$this->request->get('search', ''));
  1559. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  1560. $opArr = (array)json_decode($this->request->get('op', ''), true);
  1561. if (!is_array($filterArr)) {
  1562. $filterArr = [];
  1563. }
  1564. if (!is_array($opArr)) {
  1565. $opArr = [];
  1566. }
  1567. // 开标状态 / 订单状态为计算字段,不能进池内等值筛选;单独抽出后在合并后再滤
  1568. $bidOpenStatusFilter = '';
  1569. foreach (['bid_open_status_text', 'a.bid_open_status_text'] as $bidFk) {
  1570. if (!array_key_exists($bidFk, $filterArr)) {
  1571. continue;
  1572. }
  1573. $bidOpenStatusFilter = trim((string)$filterArr[$bidFk]);
  1574. unset($filterArr[$bidFk], $opArr[$bidFk]);
  1575. }
  1576. $orderStatusFilter = '';
  1577. foreach (['order_status_text', 'a.order_status_text'] as $osFk) {
  1578. if (!array_key_exists($osFk, $filterArr)) {
  1579. continue;
  1580. }
  1581. $orderStatusFilter = trim((string)$filterArr[$osFk]);
  1582. unset($filterArr[$osFk], $opArr[$osFk]);
  1583. }
  1584. // 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
  1585. $applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
  1586. $hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
  1587. try {
  1588. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  1589. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1590. $dbRows = $this->loadPurchaseOrderRowsForListStage($wffTab, $ym, $applyMonthRange);
  1591. if ($applyMonthRange && $dbRows === []) {
  1592. $fallbackYm = $this->resolveProcuremenDefaultYm($wffTab);
  1593. if ($fallbackYm !== $ym && preg_match('/^\d{4}-\d{2}$/', $fallbackYm)) {
  1594. $ym = $fallbackYm;
  1595. $monthStart = $ym . '-01 00:00:00';
  1596. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1597. $dbRows = $this->loadPurchaseOrderRowsForListStage($wffTab, $ym, true);
  1598. }
  1599. }
  1600. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(is_array($dbRows) ? $dbRows : []);
  1601. if ($wffTab === 'confirm' && $pool === []) {
  1602. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1603. }
  1604. } else {
  1605. // 初选:按月直查 ERP(不解整包 Redis,避免长时间转圈)
  1606. if ($applyMonthRange) {
  1607. $pool = $this->loadPickPoolForYm($ym);
  1608. } else {
  1609. $pool = $this->procuremenEnsureRedisPool();
  1610. }
  1611. if (!is_array($pool)) {
  1612. $pool = [];
  1613. }
  1614. // 只针对本页候选 ID 查隐藏集,避免全表扫 purchase_order_detail
  1615. $hideSet = $this->loadPickHiddenScydgySetForIds($this->extractScydgyIdsFromPool($pool));
  1616. if ($pool !== [] && $hideSet !== []) {
  1617. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1618. if (!is_array($r)) {
  1619. return false;
  1620. }
  1621. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1622. return $id <= 0 || !isset($hideSet[$id]);
  1623. }));
  1624. }
  1625. // 手工新增(YW / scydgy_id<0)只走「新增询价/查询询价」,不进初选表格
  1626. if ($pool === []) {
  1627. return json([
  1628. 'total' => 0,
  1629. 'rows' => [],
  1630. 'activeYm' => $ym,
  1631. 'filterOptions' => (
  1632. (int)$offset === 0
  1633. && !$hasActiveSearch
  1634. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1635. )
  1636. ? $this->extractProcuremenFilterOptionsFromRows([])
  1637. : new \stdClass(),
  1638. ]);
  1639. }
  1640. }
  1641. $filtered = $this->filterProcuremenIndexPool(
  1642. $pool,
  1643. $monthStart,
  1644. $monthEnd,
  1645. $applyMonthRange,
  1646. $search,
  1647. $filterArr,
  1648. $opArr,
  1649. $listTimePrimary
  1650. );
  1651. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1652. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1653. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1654. }
  1655. if (in_array($wffTab, ['audit', 'confirm'], true) && $bidOpenStatusFilter !== '') {
  1656. $filtered = $this->filterProcuremenPoolByBidOpenStatus($filtered, $bidOpenStatusFilter);
  1657. }
  1658. if (in_array($wffTab, ['audit', 'confirm'], true) && $orderStatusFilter !== '') {
  1659. $filtered = $this->filterProcuremenPoolByOrderStatus($filtered, $orderStatusFilter);
  1660. }
  1661. $sortField = 'ID';
  1662. if (is_string($sort) && $sort !== '') {
  1663. $parts = explode(',', $sort);
  1664. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1665. if ($sortField === '') {
  1666. $sortField = 'ID';
  1667. }
  1668. }
  1669. // 列表「下发时间」列字段为 issue_time,与 pick_time 同义
  1670. if ($sortField === 'issue_time') {
  1671. $sortField = 'pick_time';
  1672. }
  1673. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1674. $nFiltered = count($filtered);
  1675. if (in_array($wffTab, ['audit', 'confirm'], true) && $nFiltered > 1) {
  1676. // 确认/审批:状态分组优先;同状态内固定按下发时间倒序(最新在上,不跟前端 ASC/DESC 翻转)
  1677. // 先补齐下发时间,避免 pick_time 空时回退到提交日导致顺序错乱
  1678. $this->hydrateProcuremenListIssueSortTimes($filtered);
  1679. usort($filtered, function ($a, $b) use ($wffTab) {
  1680. if (!is_array($a)) {
  1681. return 1;
  1682. }
  1683. if (!is_array($b)) {
  1684. return -1;
  1685. }
  1686. $statusKeyA = $a['order_status_text'] ?? $a['wflow_status'] ?? '';
  1687. if (trim((string)$statusKeyA) === '') {
  1688. $statusKeyA = $a['wflow_status'] ?? '';
  1689. }
  1690. $statusKeyB = $b['order_status_text'] ?? $b['wflow_status'] ?? '';
  1691. if (trim((string)$statusKeyB) === '') {
  1692. $statusKeyB = $b['wflow_status'] ?? '';
  1693. }
  1694. $wa = ProcuremenStatus::orderStatusSortWeight($wffTab, $statusKeyA);
  1695. $wb = ProcuremenStatus::orderStatusSortWeight($wffTab, $statusKeyB);
  1696. if ($wa !== $wb) {
  1697. return $wa <=> $wb;
  1698. }
  1699. $ta = trim((string)($a['_issue_sort_time'] ?? ''));
  1700. if ($ta === '') {
  1701. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  1702. }
  1703. $tb = trim((string)($b['_issue_sort_time'] ?? ''));
  1704. if ($tb === '') {
  1705. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  1706. }
  1707. if ($ta !== $tb) {
  1708. if ($ta === '') {
  1709. return 1;
  1710. }
  1711. if ($tb === '') {
  1712. return -1;
  1713. }
  1714. // 倒序:新的在前
  1715. return strcmp($tb, $ta);
  1716. }
  1717. return ((int)($b['ID'] ?? 0) <=> (int)($a['ID'] ?? 0));
  1718. });
  1719. } elseif ($nFiltered > 1) {
  1720. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1721. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1722. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1723. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1724. if ($ta === $tb) {
  1725. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1726. }
  1727. if ($ta === '') {
  1728. return 1;
  1729. }
  1730. if ($tb === '') {
  1731. return -1;
  1732. }
  1733. return strcmp($ta, $tb) * $ord;
  1734. });
  1735. } elseif ($sortField === 'ID') {
  1736. $sortKeys = [];
  1737. foreach ($filtered as $i => $row) {
  1738. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1739. }
  1740. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1741. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1742. } elseif ($sortField === 'CCYDH') {
  1743. usort($filtered, function ($a, $b) use ($ord) {
  1744. $sa = trim((string)($a['CCYDH'] ?? ''));
  1745. $sb = trim((string)($b['CCYDH'] ?? ''));
  1746. if ($sa === $sb) {
  1747. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1748. }
  1749. if ($sa === '') {
  1750. return 1;
  1751. }
  1752. if ($sb === '') {
  1753. return -1;
  1754. }
  1755. return strcmp($sa, $sb) * $ord;
  1756. });
  1757. } else {
  1758. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1759. $va = $a[$sortField] ?? null;
  1760. $vb = $b[$sortField] ?? null;
  1761. $sa = (string)$va;
  1762. $sb = (string)$vb;
  1763. if ($sa === $sb) {
  1764. return 0;
  1765. }
  1766. return strcmp($sa, $sb) * $ord;
  1767. });
  1768. }
  1769. }
  1770. $offset = max(0, (int)$offset);
  1771. $limit = max(1, (int)$limit);
  1772. $rows = array_slice($filtered, $offset, $limit);
  1773. foreach ($rows as &$rw) {
  1774. if (!is_array($rw)) {
  1775. continue;
  1776. }
  1777. $rid = (int)($rw['ID'] ?? 0);
  1778. $rw['_iss_out'] = ($wffTab !== 'pick');
  1779. }
  1780. unset($rw);
  1781. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1782. $idList = [];
  1783. foreach ($rows as $rw) {
  1784. if (!is_array($rw)) {
  1785. continue;
  1786. }
  1787. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1788. foreach ($rw['_order_merge_rows'] as $mr) {
  1789. $mid = (int)($mr['ID'] ?? 0);
  1790. if ($this->isValidScydgyRowId($mid)) {
  1791. $idList[$mid] = true;
  1792. }
  1793. }
  1794. }
  1795. $id = (int)($rw['ID'] ?? 0);
  1796. if ($this->isValidScydgyRowId($id)) {
  1797. $idList[$id] = true;
  1798. }
  1799. }
  1800. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1801. foreach ($rows as &$rw) {
  1802. if (!is_array($rw)) {
  1803. continue;
  1804. }
  1805. $mergeIds = [];
  1806. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1807. foreach ($rw['_order_merge_rows'] as $mr) {
  1808. $mid = (int)($mr['ID'] ?? 0);
  1809. if ($this->isValidScydgyRowId($mid)) {
  1810. $mergeIds[$mid] = true;
  1811. }
  1812. }
  1813. }
  1814. $rid = (int)($rw['ID'] ?? 0);
  1815. if ($this->isValidScydgyRowId($rid)) {
  1816. $mergeIds[$rid] = true;
  1817. }
  1818. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1819. $rw['po_detail_count'] = $s['cnt'];
  1820. $rw['po_amount_fill_cnt'] = $s['amt'];
  1821. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1822. }
  1823. unset($rw);
  1824. }
  1825. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1826. $idList = [];
  1827. foreach ($rows as $rw) {
  1828. if (!is_array($rw)) {
  1829. continue;
  1830. }
  1831. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1832. foreach ($rw['_order_merge_rows'] as $mr) {
  1833. $mid = (int)($mr['ID'] ?? 0);
  1834. if ($this->isValidScydgyRowId($mid)) {
  1835. $idList[$mid] = true;
  1836. }
  1837. }
  1838. }
  1839. $id = (int)($rw['ID'] ?? 0);
  1840. if ($this->isValidScydgyRowId($id)) {
  1841. $idList[$id] = true;
  1842. }
  1843. }
  1844. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1845. $bidOpenSet = [];
  1846. $manualPickSet = [];
  1847. $bidOpenBatchSet = [];
  1848. $ccydhList = [];
  1849. $batchList = [];
  1850. foreach ($rows as $rw0) {
  1851. if (!is_array($rw0)) {
  1852. continue;
  1853. }
  1854. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1855. if ($c0 !== '') {
  1856. $ccydhList[] = $c0;
  1857. }
  1858. $b0 = $this->resolveProcuremenOrderBatchNo($rw0);
  1859. if ($b0 !== '') {
  1860. $batchList[] = $b0;
  1861. }
  1862. if (!empty($rw0['_order_merge_rows']) && is_array($rw0['_order_merge_rows'])) {
  1863. foreach ($rw0['_order_merge_rows'] as $mr0) {
  1864. if (!is_array($mr0)) {
  1865. continue;
  1866. }
  1867. $cm = trim((string)($mr0['CCYDH'] ?? ''));
  1868. if ($cm !== '') {
  1869. $ccydhList[] = $cm;
  1870. }
  1871. $bm = $this->resolveProcuremenOrderBatchNo($mr0);
  1872. if ($bm !== '') {
  1873. $batchList[] = $bm;
  1874. }
  1875. }
  1876. }
  1877. }
  1878. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1879. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  1880. $bidOpenBatchSet = $this->loadProcuremenBidOpenVerifiedBatchSet($batchList);
  1881. foreach ($rows as &$rw) {
  1882. if (!is_array($rw)) {
  1883. continue;
  1884. }
  1885. $mergeIds = [];
  1886. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1887. foreach ($rw['_order_merge_rows'] as $mr) {
  1888. $mid = (int)($mr['ID'] ?? 0);
  1889. if ($this->isValidScydgyRowId($mid)) {
  1890. $mergeIds[$mid] = true;
  1891. }
  1892. }
  1893. }
  1894. $rid = (int)($rw['ID'] ?? 0);
  1895. if ($this->isValidScydgyRowId($rid)) {
  1896. $mergeIds[$rid] = true;
  1897. }
  1898. $buckets = [];
  1899. foreach (array_keys($mergeIds) as $mid) {
  1900. if (isset($quoteBucket[$mid])) {
  1901. $buckets[] = $quoteBucket[$mid];
  1902. }
  1903. }
  1904. $supplierText = $buckets !== []
  1905. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1906. : '';
  1907. $picked = trim((string)($rw['pick_company_name'] ?? $rw['picked_supplier_name'] ?? ''));
  1908. if ($picked === '') {
  1909. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1910. foreach ($rw['_order_merge_rows'] as $mr) {
  1911. if (!is_array($mr)) {
  1912. continue;
  1913. }
  1914. $pn = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  1915. if ($pn !== '') {
  1916. $picked = $pn;
  1917. break;
  1918. }
  1919. }
  1920. }
  1921. }
  1922. $rw['picked_supplier_name'] = $picked;
  1923. $rw['notify_supplier_text'] = $supplierText;
  1924. $wflowRaw = trim((string)($rw['wflow_status'] ?? ''));
  1925. if ($wflowRaw === '' && !empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1926. foreach ($rw['_order_merge_rows'] as $mr) {
  1927. if (!is_array($mr)) {
  1928. continue;
  1929. }
  1930. $wf = trim((string)($mr['wflow_status'] ?? ''));
  1931. if ($wf !== '') {
  1932. $wflowRaw = $wf;
  1933. break;
  1934. }
  1935. }
  1936. }
  1937. $rw['wflow_status'] = $wflowRaw;
  1938. $rw['order_status_text'] = ProcuremenStatus::orderStatusLabelForList($wflowRaw);
  1939. $bidState = $this->resolveProcuremenListBidOpenState($rw, $bidOpenSet, $manualPickSet, $bidOpenBatchSet);
  1940. $rw['bid_open_verified'] = !empty($bidState['verified']) ? 1 : 0;
  1941. $rw['manual_picked'] = !empty($bidState['manual']) ? 1 : 0;
  1942. $rw['bid_open_status_text'] = (string)($bidState['text'] ?? '待开标');
  1943. }
  1944. unset($rw);
  1945. }
  1946. if (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
  1947. $this->enrichProcuremenListMilestoneTimes($rows);
  1948. $this->syncCollapsedOrderQtyPriceForList($rows);
  1949. }
  1950. if ($wffTab === 'all' && count($rows) > 0) {
  1951. $this->mergePurchaseOrder($rows);
  1952. }
  1953. if ($wffTab === 'pick' && count($rows) > 0) {
  1954. $this->mergePurchaseOrder($rows);
  1955. }
  1956. foreach ($rows as &$rwClean) {
  1957. if (is_array($rwClean)) {
  1958. unset($rwClean['_order_merge_rows']);
  1959. if (array_key_exists('NGZL', $rwClean)) {
  1960. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1961. }
  1962. }
  1963. }
  1964. unset($rwClean);
  1965. return json([
  1966. 'total' => count($filtered),
  1967. 'rows' => $rows,
  1968. 'activeYm' => $ym,
  1969. // 初选:把有数据的月份带回,替换「空月份日历」侧栏
  1970. 'sidebarYms' => (in_array($wffTab, ['pick', 'audit', 'confirm'], true) && (int)$offset === 0)
  1971. ? (
  1972. $wffTab === 'pick'
  1973. ? $this->ensureProcuremenPickSidebarYmList()
  1974. : $this->flattenProcuremenSidebarYms($this->GetIssuedOrderYearMonths($wffTab))
  1975. )
  1976. : [],
  1977. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1978. 'filterOptions' => (
  1979. (int)$offset === 0
  1980. && !$hasActiveSearch
  1981. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1982. )
  1983. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1984. : new \stdClass(),
  1985. ]);
  1986. } catch (\Throwable $e) {
  1987. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1988. return json([
  1989. 'total' => 0,
  1990. 'rows' => [],
  1991. ]);
  1992. }
  1993. }
  1994. /**
  1995. * @param array<int, array<string, mixed>> $pool
  1996. * @return int[]
  1997. */
  1998. protected function extractScydgyIdsFromPool(array $pool): array
  1999. {
  2000. $ids = [];
  2001. foreach ($pool as $r) {
  2002. if (!is_array($r)) {
  2003. continue;
  2004. }
  2005. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  2006. if ($id > 0) {
  2007. $ids[$id] = $id;
  2008. }
  2009. }
  2010. return array_values($ids);
  2011. }
  2012. /**
  2013. * 仅查询指定工序 ID 是否已下发/进入后续流程(初选列表加速)
  2014. *
  2015. * @param int[] $scydgyIds
  2016. * @return array<int, true>
  2017. */
  2018. protected function loadPickHiddenScydgySetForIds(array $scydgyIds): array
  2019. {
  2020. $hideSet = [];
  2021. $scydgyIds = array_values(array_filter(array_map('intval', $scydgyIds), function ($id) {
  2022. return $id > 0;
  2023. }));
  2024. if ($scydgyIds === []) {
  2025. return $hideSet;
  2026. }
  2027. // 分批,避免 whereIn 过长
  2028. foreach (array_chunk($scydgyIds, 500) as $chunk) {
  2029. try {
  2030. $poIds = Db::table('purchase_order')
  2031. ->where('scydgy_id', 'in', $chunk)
  2032. ->where(function ($q) {
  2033. $q->whereIn('wflow_status', array_merge(
  2034. ProcuremenStatus::wflowPendingConfirmValues(),
  2035. ProcuremenStatus::wflowPendingApprovalValues()
  2036. ))
  2037. ->whereOr(function ($q1) {
  2038. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  2039. })
  2040. ->whereOr(function ($q2) {
  2041. $q2->whereNotNull('pick_time')
  2042. ->where('pick_time', '<>', '')
  2043. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  2044. })
  2045. ->whereOr(function ($q3) {
  2046. $q3->whereNotNull('mod_rq')
  2047. ->where('mod_rq', '<>', '')
  2048. ->where('mod_rq', 'not like', '0000-00-00%');
  2049. });
  2050. })
  2051. ->column('scydgy_id');
  2052. if (is_array($poIds)) {
  2053. foreach ($poIds as $pid) {
  2054. $k = (int)$pid;
  2055. if ($k !== 0) {
  2056. $hideSet[$k] = true;
  2057. }
  2058. }
  2059. }
  2060. } catch (\Throwable $e) {
  2061. }
  2062. try {
  2063. $detIdsQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $chunk);
  2064. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  2065. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  2066. if (is_array($detIds)) {
  2067. foreach ($detIds as $pid) {
  2068. $k = (int)$pid;
  2069. if ($this->isValidScydgyRowId($k)) {
  2070. $hideSet[$k] = true;
  2071. }
  2072. }
  2073. }
  2074. } catch (\Throwable $e) {
  2075. }
  2076. }
  2077. return $hideSet;
  2078. }
  2079. /**
  2080. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  2081. *
  2082. * @return array<int, true>
  2083. */
  2084. protected function loadPickHiddenScydgySet(): array
  2085. {
  2086. if ($this->pickHiddenScydgySetCache !== null) {
  2087. return $this->pickHiddenScydgySetCache;
  2088. }
  2089. $cacheKey = 'procuremen_pick_hidden_scydgy_v1';
  2090. try {
  2091. $raw = redis()->get($cacheKey);
  2092. if ($raw !== false && $raw !== null && $raw !== '') {
  2093. $ids = json_decode((string)$raw, true);
  2094. if (is_array($ids)) {
  2095. $hideSet = [];
  2096. foreach ($ids as $pid) {
  2097. $k = (int)$pid;
  2098. if ($k !== 0) {
  2099. $hideSet[$k] = true;
  2100. }
  2101. }
  2102. $this->pickHiddenScydgySetCache = $hideSet;
  2103. return $hideSet;
  2104. }
  2105. }
  2106. } catch (\Throwable $e) {
  2107. }
  2108. $hideSet = [];
  2109. try {
  2110. $poIds = Db::table('purchase_order')
  2111. ->where(function ($q) {
  2112. $q->whereIn('wflow_status', array_merge(
  2113. ProcuremenStatus::wflowPendingConfirmValues(),
  2114. ProcuremenStatus::wflowPendingApprovalValues()
  2115. ))
  2116. ->whereOr(function ($q1) {
  2117. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  2118. })
  2119. ->whereOr(function ($q2) {
  2120. $q2->whereNotNull('pick_time')
  2121. ->where('pick_time', '<>', '')
  2122. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  2123. })
  2124. ->whereOr(function ($q3) {
  2125. $q3->whereNotNull('mod_rq')
  2126. ->where('mod_rq', '<>', '')
  2127. ->where('mod_rq', 'not like', '0000-00-00%');
  2128. });
  2129. })
  2130. ->column('scydgy_id');
  2131. if (is_array($poIds)) {
  2132. foreach ($poIds as $pid) {
  2133. $k = (int)$pid;
  2134. if ($k !== 0) {
  2135. $hideSet[$k] = true;
  2136. }
  2137. }
  2138. }
  2139. } catch (\Throwable $e) {
  2140. }
  2141. try {
  2142. $detIdsQuery = Db::table('purchase_order_detail');
  2143. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  2144. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  2145. if (is_array($detIds)) {
  2146. foreach ($detIds as $pid) {
  2147. $k = (int)$pid;
  2148. if ($this->isValidScydgyRowId($k)) {
  2149. $hideSet[$k] = true;
  2150. }
  2151. }
  2152. }
  2153. } catch (\Throwable $e) {
  2154. }
  2155. $this->pickHiddenScydgySetCache = $hideSet;
  2156. try {
  2157. redis()->setex($cacheKey, 90, json_encode(array_map('intval', array_keys($hideSet))));
  2158. } catch (\Throwable $e) {
  2159. }
  2160. return $hideSet;
  2161. }
  2162. /**
  2163. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  2164. *
  2165. * @return array<int, array<string, mixed>>
  2166. */
  2167. protected function loadPickManualOrderRows(): array
  2168. {
  2169. try {
  2170. $dbRows = Db::table('purchase_order')
  2171. ->where('scydgy_id', '<', 0)
  2172. ->whereRaw('(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')')
  2173. ->order('scydgy_id', 'asc')
  2174. ->select();
  2175. } catch (\Throwable $e) {
  2176. try {
  2177. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  2178. } catch (\Throwable $e2) {
  2179. return [];
  2180. }
  2181. }
  2182. if (!is_array($dbRows) || $dbRows === []) {
  2183. return [];
  2184. }
  2185. $detailSidSet = [];
  2186. try {
  2187. $negIds = [];
  2188. foreach ($dbRows as $dbRow) {
  2189. if (!is_array($dbRow)) {
  2190. continue;
  2191. }
  2192. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2193. if ($sid < 0) {
  2194. $negIds[$sid] = true;
  2195. }
  2196. }
  2197. if ($negIds !== []) {
  2198. $detQuery = Db::table('purchase_order_detail')
  2199. ->where('scydgy_id', 'in', array_keys($negIds));
  2200. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  2201. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  2202. if (is_array($detRows)) {
  2203. foreach ($detRows as $did) {
  2204. $detailSidSet[(int)$did] = true;
  2205. }
  2206. }
  2207. }
  2208. } catch (\Throwable $e) {
  2209. }
  2210. $pool = [];
  2211. foreach ($dbRows as $dbRow) {
  2212. if (!is_array($dbRow)) {
  2213. continue;
  2214. }
  2215. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2216. if ($sid >= 0) {
  2217. continue;
  2218. }
  2219. // 已进入确认/审批的不进初选;仅废弃明细残留的仍算可下发
  2220. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  2221. continue;
  2222. }
  2223. // 仅排除已完结;空 status / 「进行中」/ 0 均保留(新建手工单)
  2224. if (ProcuremenStatus::isPoCompleted($dbRow['status'] ?? '')) {
  2225. continue;
  2226. }
  2227. if (isset($detailSidSet[$sid])) {
  2228. continue;
  2229. }
  2230. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  2231. $r['_is_manual'] = 1;
  2232. $pool[] = $r;
  2233. }
  2234. return $pool;
  2235. }
  2236. /**
  2237. * 确认/审批列表排序:补齐下发时间(pick_time + 下发操作日志)
  2238. *
  2239. * @param array<int, array<string, mixed>> $rows
  2240. */
  2241. protected function hydrateProcuremenListIssueSortTimes(array &$rows): void
  2242. {
  2243. if ($rows === []) {
  2244. return;
  2245. }
  2246. $sidList = [];
  2247. foreach ($rows as $rw) {
  2248. if (!is_array($rw)) {
  2249. continue;
  2250. }
  2251. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  2252. foreach ($rw['_order_merge_rows'] as $mr) {
  2253. if (!is_array($mr)) {
  2254. continue;
  2255. }
  2256. $mid = (int)($mr['ID'] ?? 0);
  2257. if ($this->isValidScydgyRowId($mid)) {
  2258. $sidList[$mid] = true;
  2259. }
  2260. }
  2261. }
  2262. $id = (int)($rw['ID'] ?? 0);
  2263. if ($this->isValidScydgyRowId($id)) {
  2264. $sidList[$id] = true;
  2265. }
  2266. }
  2267. $issueBySid = [];
  2268. $sids = array_keys($sidList);
  2269. if ($sids !== []) {
  2270. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  2271. if ($issueActs !== []) {
  2272. try {
  2273. $logs = Db::table('purchase_order_oper_log')
  2274. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  2275. ->where(ProcuremenOperLog::COL_ACTION, 'in', $issueActs)
  2276. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_TIME)
  2277. ->order('id', 'asc')
  2278. ->select();
  2279. } catch (\Throwable $e) {
  2280. $logs = [];
  2281. }
  2282. if (is_array($logs)) {
  2283. foreach ($logs as $lg) {
  2284. if (!is_array($lg)) {
  2285. continue;
  2286. }
  2287. $lg = ProcuremenOperLog::normalizeRow($lg);
  2288. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  2289. if ($sid === 0) {
  2290. continue;
  2291. }
  2292. $tm = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  2293. if ($tm === '') {
  2294. continue;
  2295. }
  2296. if (!isset($issueBySid[$sid]) || strcmp($tm, $issueBySid[$sid]) > 0) {
  2297. $issueBySid[$sid] = $tm;
  2298. }
  2299. }
  2300. }
  2301. }
  2302. }
  2303. foreach ($rows as &$rw) {
  2304. if (!is_array($rw)) {
  2305. continue;
  2306. }
  2307. $mergeSids = [];
  2308. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  2309. foreach ($rw['_order_merge_rows'] as $mr) {
  2310. if (!is_array($mr)) {
  2311. continue;
  2312. }
  2313. $mid = (int)($mr['ID'] ?? 0);
  2314. if ($this->isValidScydgyRowId($mid)) {
  2315. $mergeSids[] = $mid;
  2316. }
  2317. }
  2318. }
  2319. $rid = (int)($rw['ID'] ?? 0);
  2320. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  2321. $mergeSids[] = $rid;
  2322. }
  2323. $best = $this->procuremenRowListSortTime($rw, 'pick_time');
  2324. foreach ($mergeSids as $sid) {
  2325. if (isset($issueBySid[$sid]) && ($best === '' || strcmp($issueBySid[$sid], $best) > 0)) {
  2326. $best = $issueBySid[$sid];
  2327. }
  2328. }
  2329. $rw['_issue_sort_time'] = $best;
  2330. if ($best !== '') {
  2331. $pickOut = trim((string)($rw['pick_time'] ?? ''));
  2332. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  2333. $rw['pick_time'] = $best;
  2334. }
  2335. $rw['issue_time'] = $best;
  2336. }
  2337. }
  2338. unset($rw);
  2339. }
  2340. /**
  2341. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  2342. */
  2343. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  2344. {
  2345. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  2346. foreach ($keys as $k) {
  2347. $t = trim((string)($row[$k] ?? ''));
  2348. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2349. return $t;
  2350. }
  2351. }
  2352. return '';
  2353. }
  2354. /**
  2355. * 分配手工新增工序行 ID(负数递减)
  2356. * 调用方须在命名锁内执行,避免并发重复
  2357. */
  2358. protected function allocateManualScydgyId(): int
  2359. {
  2360. try {
  2361. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  2362. $min = (int)$min;
  2363. return $min < 0 ? $min - 1 : -1;
  2364. } catch (\Throwable $e) {
  2365. return -1;
  2366. }
  2367. }
  2368. /**
  2369. * 手工新增订单号:YW + 年月日 + 当日序号(如 YW20260618001)
  2370. * 调用方须在命名锁内执行,避免并发重复
  2371. */
  2372. protected function allocateManualOrderCcydh(): string
  2373. {
  2374. $prefix = 'YW' . date('Ymd');
  2375. $maxSeq = 0;
  2376. try {
  2377. $rows = Db::table('purchase_order')
  2378. ->where('CCYDH', 'like', $prefix . '%')
  2379. ->column('CCYDH');
  2380. if (is_array($rows)) {
  2381. foreach ($rows as $ccydh) {
  2382. $ccydh = trim((string)$ccydh);
  2383. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3,})$/', $ccydh, $m)) {
  2384. $maxSeq = max($maxSeq, (int)$m[1]);
  2385. }
  2386. }
  2387. }
  2388. } catch (\Throwable $e) {
  2389. }
  2390. $next = $maxSeq + 1;
  2391. $width = $next > 999 ? strlen((string)$next) : 3;
  2392. return $prefix . str_pad((string)$next, $width, '0', STR_PAD_LEFT);
  2393. }
  2394. /**
  2395. * MySQL 命名锁(跨连接防并发撞号)
  2396. */
  2397. protected function acquireProcuremenNamedLock(string $name, int $timeoutSec = 10): bool
  2398. {
  2399. $name = trim($name);
  2400. if ($name === '') {
  2401. return false;
  2402. }
  2403. try {
  2404. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2405. $rows = Db::query('SELECT GET_LOCK(\'' . $nameSql . '\', ' . max(1, $timeoutSec) . ') AS locked');
  2406. if (!is_array($rows) || $rows === []) {
  2407. return false;
  2408. }
  2409. $v = $rows[0]['locked'] ?? $rows[0]['LOCKED'] ?? null;
  2410. return (int)$v === 1;
  2411. } catch (\Throwable $e) {
  2412. return false;
  2413. }
  2414. }
  2415. protected function releaseProcuremenNamedLock(string $name): void
  2416. {
  2417. $name = trim($name);
  2418. if ($name === '') {
  2419. return;
  2420. }
  2421. try {
  2422. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2423. Db::query('SELECT RELEASE_LOCK(\'' . $nameSql . '\')');
  2424. } catch (\Throwable $e) {
  2425. }
  2426. }
  2427. /**
  2428. * purchase_order.mod_rq 是否有有效软删除时间
  2429. */
  2430. protected function isPurchaseOrderSoftDeleted($modRq): bool
  2431. {
  2432. $t = trim((string)$modRq);
  2433. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  2434. }
  2435. /**
  2436. * 列表行 → purchase_order 写入字段
  2437. *
  2438. * @return array<string, mixed>
  2439. */
  2440. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  2441. {
  2442. return $this->normalizePurchaseOrderWritePayload([
  2443. 'scydgy_id' => $scydgyId,
  2444. 'CCYDH' => $row['CCYDH'] ?? null,
  2445. 'CYJMC' => $row['CYJMC'] ?? null,
  2446. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2447. 'CDXMC' => $row['CDXMC'] ?? null,
  2448. 'CGYBH' => $row['CGYBH'] ?? null,
  2449. 'CGYMC' => $row['CGYMC'] ?? null,
  2450. 'CDW' => $row['CDW'] ?? null,
  2451. 'czlyq' => $row['czlyq'] ?? null,
  2452. 'NGZL' => $row['NGZL'] ?? null,
  2453. 'CDF' => $row['CDF'] ?? null,
  2454. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2455. 'MBZ' => $row['MBZ'] ?? null,
  2456. 'bwjg' => $row['bwjg'] ?? null,
  2457. 'iStatus' => $row['iStatus'] ?? null,
  2458. 'dStamp' => $row['dStamp'] ?? null,
  2459. 'dputrecord' => $row['dputrecord'] ?? null,
  2460. 'cywyxm' => $row['cywyxm'] ?? null,
  2461. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2462. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2463. ], $row);
  2464. }
  2465. /**
  2466. * purchase_order 写入前规范化:NOT NULL 列勿显式传 null(会绕过 DEFAULT 触发 1048)
  2467. *
  2468. * @param array<string, mixed> $data
  2469. * @param array<string, mixed> $row 原始列表行(可用于补齐 czlyq)
  2470. * @return array<string, mixed>
  2471. */
  2472. protected function normalizePurchaseOrderWritePayload(array $data, array $row = []): array
  2473. {
  2474. $this->ensurePurchaseOrderCzlyqColumn();
  2475. $cz = '';
  2476. foreach (['czlyq', 'CZLYQ'] as $k) {
  2477. if (isset($data[$k]) && trim((string)$data[$k]) !== '') {
  2478. $cz = trim((string)$data[$k]);
  2479. break;
  2480. }
  2481. if (isset($row[$k]) && trim((string)$row[$k]) !== '') {
  2482. $cz = trim((string)$row[$k]);
  2483. break;
  2484. }
  2485. }
  2486. if ($cz === '') {
  2487. $ccydh = trim((string)($data['CCYDH'] ?? $row['CCYDH'] ?? ''));
  2488. if ($ccydh !== '') {
  2489. try {
  2490. $fromMcyd = Db::table('mcyd')->where('CCYDH', $ccydh)->value('czlyq');
  2491. $cz = trim((string)$fromMcyd);
  2492. } catch (\Throwable $e) {
  2493. $cz = '';
  2494. }
  2495. }
  2496. }
  2497. $data['czlyq'] = $cz;
  2498. // 显式 NULL 的字符串 NOT NULL 列改为空串
  2499. foreach (['czlyq', 'notify_salesman', 'manual_pick_reason', 'score_rule_name'] as $col) {
  2500. if (!array_key_exists($col, $data)) {
  2501. continue;
  2502. }
  2503. if ($data[$col] === null || !is_scalar($data[$col])) {
  2504. $data[$col] = '';
  2505. } else {
  2506. $data[$col] = (string)$data[$col];
  2507. }
  2508. }
  2509. foreach (['rfq_salesman_notified', 'manual_pick', 'score_rule_id', 'score_quality_weight', 'score_price_weight', 'score_lead_weight'] as $col) {
  2510. if (array_key_exists($col, $data) && $data[$col] === null) {
  2511. $data[$col] = 0;
  2512. }
  2513. }
  2514. return $data;
  2515. }
  2516. /**
  2517. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  2518. *
  2519. * @return array{po:?array<string,mixed>, hidden:bool}
  2520. */
  2521. protected function resolvePickRowPoContext(int $sid): array
  2522. {
  2523. $po = null;
  2524. try {
  2525. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2526. if (is_array($found)) {
  2527. $po = $found;
  2528. }
  2529. } catch (\Throwable $e) {
  2530. }
  2531. $hideSet = $this->loadPickHiddenScydgySet();
  2532. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  2533. }
  2534. /**
  2535. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  2536. */
  2537. protected function assertPickRowCanDelete(int $sid, array $row): void
  2538. {
  2539. $ctx = $this->resolvePickRowPoContext($sid);
  2540. $po = $ctx['po'];
  2541. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2542. return;
  2543. }
  2544. if (is_array($po)) {
  2545. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2546. throw new \InvalidArgumentException('该工序已完结,无法删除');
  2547. }
  2548. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2549. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  2550. }
  2551. }
  2552. if ($ctx['hidden']) {
  2553. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2554. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  2555. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  2556. }
  2557. }
  2558. /**
  2559. * 初选直接完结前校验
  2560. */
  2561. protected function assertPickRowCanComplete(int $sid, array $row): void
  2562. {
  2563. $ctx = $this->resolvePickRowPoContext($sid);
  2564. $po = $ctx['po'];
  2565. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2566. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  2567. }
  2568. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2569. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  2570. }
  2571. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  2572. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  2573. }
  2574. }
  2575. /**
  2576. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  2577. */
  2578. protected function softDeleteProcuremenPickRow(array $row): void
  2579. {
  2580. $sid = $this->extractScydgyRowId($row);
  2581. if (!$this->isValidScydgyRowId($sid)) {
  2582. throw new \InvalidArgumentException('无效的行主键');
  2583. }
  2584. $this->assertPickRowCanDelete($sid, $row);
  2585. $po = $this->resolvePickRowPoContext($sid)['po'];
  2586. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2587. return;
  2588. }
  2589. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2590. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  2591. }
  2592. $now = date('Y-m-d H:i:s');
  2593. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2594. if (is_array($exists)) {
  2595. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  2596. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  2597. } else {
  2598. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  2599. $data['mod_rq'] = $now;
  2600. $data['createtime'] = $now;
  2601. Db::table('purchase_order')->insert($data);
  2602. $poIdLog = (int)Db::getLastInsID();
  2603. }
  2604. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  2605. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  2606. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  2607. if ($gymcLog !== '') {
  2608. $logTail .= ' / ' . $gymcLog;
  2609. }
  2610. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  2611. }
  2612. /**
  2613. * 手工新增协助工序(写入 purchase_order)
  2614. *
  2615. * @param array<string, mixed> $params
  2616. * @return int scydgy_id
  2617. */
  2618. protected function saveManualPickOrder(array $params): int
  2619. {
  2620. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  2621. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  2622. $ccydhIn = trim((string)($params['CCYDH'] ?? ''));
  2623. $lockName = 'procuremen_manual_order_alloc';
  2624. if (!$this->acquireProcuremenNamedLock($lockName, 10)) {
  2625. throw new \RuntimeException('系统繁忙,请稍后重试');
  2626. }
  2627. try {
  2628. $ccydh = $ccydhIn !== '' ? $ccydhIn : $this->allocateManualOrderCcydh();
  2629. $now = date('Y-m-d H:i:s');
  2630. $sid = $this->allocateManualScydgyId();
  2631. $this->ensurePurchaseOrderNotifySalesmanColumn();
  2632. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  2633. // 选择供应商 / 通知业务员:支持多选,落库用顿号拼接
  2634. $supplierName = $this->joinRfqMultiSelectValues($params['cGzzxMc'] ?? ($params['pick_company_name'] ?? ''));
  2635. $notifySalesman = $this->joinRfqMultiSelectValues($params['notify_salesman'] ?? '');
  2636. $data = [
  2637. 'scydgy_id' => $sid,
  2638. 'CCYDH' => $ccydh,
  2639. 'CYJMC' => $cyjmc,
  2640. 'CGYMC' => $cgymc,
  2641. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  2642. 'CDW' => trim((string)($params['CDW'] ?? '')),
  2643. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  2644. 'CDF' => trim((string)($params['CDF'] ?? '')),
  2645. 'cGzzxMc' => $supplierName,
  2646. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  2647. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  2648. 'notify_salesman' => $notifySalesman,
  2649. 'rfq_salesman_notified' => 0,
  2650. 'rfq_salesman_notify_time' => null,
  2651. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  2652. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  2653. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  2654. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  2655. 'createtime' => $now,
  2656. 'dStamp' => $now,
  2657. 'dputrecord' => $now,
  2658. ];
  2659. Db::table('purchase_order')->insert($data);
  2660. $poId = (int)Db::getLastInsID();
  2661. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  2662. return $sid;
  2663. } finally {
  2664. $this->releaseProcuremenNamedLock($lockName);
  2665. }
  2666. }
  2667. protected function formatProcuremenRowLabel(array $row): string
  2668. {
  2669. return ProcuremenFormat::rowLabel($row);
  2670. }
  2671. /**
  2672. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  2673. */
  2674. protected function extractScydgyRowId(array $row): int
  2675. {
  2676. return ProcuremenFormat::extractScydgyRowId($row);
  2677. }
  2678. protected function isValidScydgyRowId(int $id): bool
  2679. {
  2680. return ProcuremenGuard::isValidScydgyId($id);
  2681. }
  2682. protected function isManualScydgyRowId(int $id): bool
  2683. {
  2684. return $id < 0;
  2685. }
  2686. /**
  2687. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  2688. *
  2689. * @param int[] $scydgyIds
  2690. * @return array<int, string[]>
  2691. */
  2692. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  2693. {
  2694. $out = [];
  2695. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2696. if ($scydgyIds === []) {
  2697. return $out;
  2698. }
  2699. try {
  2700. $rows = Db::table('purchase_order_detail')
  2701. ->where('scydgy_id', 'in', $scydgyIds)
  2702. ->field('scydgy_id,company_name')
  2703. ->order('company_name', 'asc')
  2704. ->select();
  2705. } catch (\Throwable $e) {
  2706. $rows = [];
  2707. }
  2708. if (!is_array($rows)) {
  2709. return $out;
  2710. }
  2711. foreach ($rows as $r) {
  2712. if (!is_array($r)) {
  2713. continue;
  2714. }
  2715. $sid = (int)($r['scydgy_id'] ?? 0);
  2716. $cn = trim((string)($r['company_name'] ?? ''));
  2717. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2718. continue;
  2719. }
  2720. if (!isset($out[$sid])) {
  2721. $out[$sid] = [];
  2722. }
  2723. if (!in_array($cn, $out[$sid], true)) {
  2724. $out[$sid][] = $cn;
  2725. }
  2726. }
  2727. return $out;
  2728. }
  2729. /**
  2730. * 列表展示通知供应商(完整列表,前端单行省略展开)
  2731. *
  2732. * @param string[] $names
  2733. */
  2734. protected function formatNotifySupplierDisplay(array $names): string
  2735. {
  2736. return ProcuremenFormat::notifySupplierDisplay($names);
  2737. }
  2738. /**
  2739. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  2740. *
  2741. * @param int[] $scydgyIds
  2742. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  2743. */
  2744. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  2745. {
  2746. $out = [];
  2747. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2748. if ($scydgyIds === []) {
  2749. return $out;
  2750. }
  2751. try {
  2752. $rows = Db::table('purchase_order_detail')
  2753. ->where('scydgy_id', 'in', $scydgyIds)
  2754. ->field('scydgy_id,company_name,amount')
  2755. ->select();
  2756. } catch (\Throwable $e) {
  2757. $rows = [];
  2758. }
  2759. if (!is_array($rows)) {
  2760. return $out;
  2761. }
  2762. foreach ($rows as $r) {
  2763. if (!is_array($r)) {
  2764. continue;
  2765. }
  2766. $sid = (int)($r['scydgy_id'] ?? 0);
  2767. $cn = trim((string)($r['company_name'] ?? ''));
  2768. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2769. continue;
  2770. }
  2771. if (!isset($out[$sid])) {
  2772. $out[$sid] = ['all' => [], 'quoted' => []];
  2773. }
  2774. $out[$sid]['all'][$cn] = true;
  2775. $am = trim((string)($r['amount'] ?? ''));
  2776. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2777. $out[$sid]['quoted'][$cn] = true;
  2778. }
  2779. }
  2780. return $out;
  2781. }
  2782. /**
  2783. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  2784. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  2785. */
  2786. protected function mergeQuotedSupplierBuckets(array $buckets): array
  2787. {
  2788. $merged = ['all' => [], 'quoted' => []];
  2789. foreach ($buckets as $b) {
  2790. if (!is_array($b)) {
  2791. continue;
  2792. }
  2793. foreach ($b['all'] ?? [] as $cn => $_) {
  2794. $merged['all'][$cn] = true;
  2795. }
  2796. foreach ($b['quoted'] ?? [] as $cn => $_) {
  2797. $merged['quoted'][$cn] = true;
  2798. }
  2799. }
  2800. return $merged;
  2801. }
  2802. /**
  2803. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  2804. */
  2805. protected function formatQuotedSupplierLines(array $bucket): string
  2806. {
  2807. return ProcuremenFormat::quotedSupplierLines($bucket);
  2808. }
  2809. /**
  2810. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  2811. */
  2812. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  2813. {
  2814. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2815. $this->view->engine->layout(false);
  2816. try {
  2817. $bodyHtml = $this->view->fetch($view);
  2818. $this->view->assign('dialogBody', $bodyHtml);
  2819. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  2820. return $this->view->fetch('procuremen/dialog_lite_shell');
  2821. } finally {
  2822. if ($restoreLayout) {
  2823. $this->view->engine->layout($restoreLayout);
  2824. }
  2825. }
  2826. }
  2827. /**
  2828. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  2829. */
  2830. protected function resolveBundleSysRq(array $bundle): string
  2831. {
  2832. foreach ($bundle['pos'] ?? [] as $po) {
  2833. if (!is_array($po)) {
  2834. continue;
  2835. }
  2836. $sr = trim((string)($po['sys_rq'] ?? ''));
  2837. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  2838. return $sr;
  2839. }
  2840. }
  2841. return '';
  2842. }
  2843. /**
  2844. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  2845. */
  2846. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  2847. {
  2848. $raw = trim((string)$sysRq);
  2849. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  2850. return true;
  2851. }
  2852. $ts = strtotime(str_replace('T', ' ', $raw));
  2853. if ($ts === false || $ts <= 0) {
  2854. return true;
  2855. }
  2856. return time() >= $ts;
  2857. }
  2858. /**
  2859. * 开标前校验:必须已过报价截止时间
  2860. *
  2861. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2862. */
  2863. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  2864. {
  2865. $sysRq = $this->resolveBundleSysRq($bundle);
  2866. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  2867. $this->error('未到招标截止日期');
  2868. }
  2869. }
  2870. /**
  2871. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  2872. *
  2873. * @param array<string, mixed> $d
  2874. * @param string $deliveryYmd
  2875. */
  2876. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  2877. {
  2878. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  2879. return max(0, (int)$d['lead_days']);
  2880. }
  2881. if ($deliveryYmd === '') {
  2882. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  2883. }
  2884. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  2885. return null;
  2886. }
  2887. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2888. $t2 = strtotime($m[1] . ' 00:00:00');
  2889. if ($t1 === false || $t2 === false) {
  2890. return null;
  2891. }
  2892. return max(0, (int)round(($t2 - $t1) / 86400));
  2893. }
  2894. /**
  2895. * @param int|null $days
  2896. */
  2897. protected function formatProcuremenLeadDaysText($days): string
  2898. {
  2899. return ProcuremenFormat::leadDaysText($days);
  2900. }
  2901. /**
  2902. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2903. *
  2904. * @param array<string, mixed> $line
  2905. */
  2906. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2907. {
  2908. $amountFilled = !empty($line['amount_filled']);
  2909. $deliveryFilled = !empty($line['delivery_filled']);
  2910. $leadFilled = !empty($line['lead_days_filled']);
  2911. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2912. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2913. $line['amount_show'] = '';
  2914. if (array_key_exists('amount_text', $line)) {
  2915. $line['amount_text'] = $line['unit_price_text'];
  2916. }
  2917. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2918. $line['delivery_show'] = $deliveryText;
  2919. if (array_key_exists('delivery_text', $line)) {
  2920. $line['delivery_text'] = $deliveryText;
  2921. }
  2922. $line['delivery_ymd'] = '';
  2923. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2924. $line['lead_days_show'] = $leadText;
  2925. $line['lead_days_text'] = $leadText;
  2926. $line['lead_days'] = '';
  2927. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2928. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2929. $line['subtotal_num'] = null;
  2930. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2931. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2932. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2933. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2934. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2935. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2936. $line['amount_filled'] = false;
  2937. $line['delivery_filled'] = false;
  2938. $line['lead_days_filled'] = false;
  2939. $line['is_quoted'] = false;
  2940. if (array_key_exists('quote_label', $line)) {
  2941. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2942. }
  2943. }
  2944. protected function ensurePurchaseOrderBidOpenTable(): void
  2945. {
  2946. static $ready = false;
  2947. if ($ready) {
  2948. return;
  2949. }
  2950. $cacheKey = 'procuremen_bid_open_table_ok_v2';
  2951. try {
  2952. if (Cache::get($cacheKey)) {
  2953. $ready = true;
  2954. return;
  2955. }
  2956. } catch (\Throwable $e) {
  2957. }
  2958. try {
  2959. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2960. $ready = true;
  2961. try {
  2962. Cache::set($cacheKey, 1, 86400);
  2963. } catch (\Throwable $e) {
  2964. }
  2965. } catch (\Throwable $e) {
  2966. Db::execute(
  2967. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2968. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2969. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2970. `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号(多订单同批开标)',
  2971. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2972. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2973. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2974. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2975. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2976. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2977. `createtime` datetime DEFAULT NULL,
  2978. PRIMARY KEY (`id`),
  2979. UNIQUE KEY `uk_ccydh` (`ccydh`),
  2980. KEY `idx_order_batch_no` (`order_batch_no`)
  2981. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2982. );
  2983. $ready = true;
  2984. try {
  2985. Cache::set($cacheKey, 1, 86400);
  2986. } catch (\Throwable $e2) {
  2987. }
  2988. }
  2989. // 旧表兼容:补批次号列(不影响已有按订单号的开标记录)
  2990. try {
  2991. $cols = Db::query("SHOW COLUMNS FROM `purchase_order_bid_open` LIKE 'order_batch_no'");
  2992. if (!is_array($cols) || $cols === []) {
  2993. Db::execute(
  2994. "ALTER TABLE `purchase_order_bid_open` ADD COLUMN `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号(多订单同批开标)' AFTER `ccydh`"
  2995. );
  2996. }
  2997. } catch (\Throwable $e) {
  2998. // ignore
  2999. }
  3000. try {
  3001. $idx = Db::query("SHOW INDEX FROM `purchase_order_bid_open` WHERE Key_name = 'idx_order_batch_no'");
  3002. if (!is_array($idx) || $idx === []) {
  3003. Db::execute('ALTER TABLE `purchase_order_bid_open` ADD INDEX `idx_order_batch_no` (`order_batch_no`)');
  3004. }
  3005. } catch (\Throwable $e) {
  3006. // ignore
  3007. }
  3008. }
  3009. /**
  3010. * 列表/合并行订单号可能为「A、B」拼接,拆成单个订单号
  3011. *
  3012. * @param mixed $raw
  3013. * @return array<int, string>
  3014. */
  3015. protected function expandProcuremenCcydhTokens($raw): array
  3016. {
  3017. $s = trim((string)$raw);
  3018. if ($s === '') {
  3019. return [];
  3020. }
  3021. $parts = preg_split('/[、;;,\n\r]+/u', $s);
  3022. if (!is_array($parts)) {
  3023. return [$s];
  3024. }
  3025. $out = [];
  3026. foreach ($parts as $p) {
  3027. $p = trim((string)$p);
  3028. if ($p !== '' && !in_array($p, $out, true)) {
  3029. $out[] = $p;
  3030. }
  3031. }
  3032. return $out;
  3033. }
  3034. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  3035. {
  3036. $ccydh = trim($ccydh);
  3037. if ($ccydh === '') {
  3038. return false;
  3039. }
  3040. $this->ensurePurchaseOrderBidOpenTable();
  3041. try {
  3042. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3043. return is_array($row);
  3044. } catch (\Throwable $e) {
  3045. return false;
  3046. }
  3047. }
  3048. protected function isProcuremenBidOpenVerifiedByBatchNo(string $batchNo): bool
  3049. {
  3050. $batchNo = trim($batchNo);
  3051. if ($batchNo === '') {
  3052. return false;
  3053. }
  3054. $this->ensurePurchaseOrderBidOpenTable();
  3055. try {
  3056. $row = Db::table('purchase_order_bid_open')
  3057. ->where('order_batch_no', $batchNo)
  3058. ->find();
  3059. return is_array($row);
  3060. } catch (\Throwable $e) {
  3061. return false;
  3062. }
  3063. }
  3064. /**
  3065. * 批量查询订单是否已开标验证(入参支持「A、B」拼接)
  3066. *
  3067. * @param array<int, string> $ccydhs
  3068. * @return array<string, bool> ccydh => true
  3069. */
  3070. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  3071. {
  3072. $set = [];
  3073. $list = [];
  3074. foreach ($ccydhs as $c) {
  3075. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  3076. $list[$one] = true;
  3077. }
  3078. }
  3079. if ($list === []) {
  3080. return $set;
  3081. }
  3082. $this->ensurePurchaseOrderBidOpenTable();
  3083. try {
  3084. $rows = Db::table('purchase_order_bid_open')
  3085. ->where('ccydh', 'in', array_keys($list))
  3086. ->field('ccydh')
  3087. ->select();
  3088. foreach ($rows as $row) {
  3089. if (!is_array($row)) {
  3090. continue;
  3091. }
  3092. $c = trim((string)($row['ccydh'] ?? ''));
  3093. if ($c !== '') {
  3094. $set[$c] = true;
  3095. }
  3096. }
  3097. } catch (\Throwable $e) {
  3098. return [];
  3099. }
  3100. return $set;
  3101. }
  3102. /**
  3103. * 批量查询批次是否已开标
  3104. *
  3105. * @param array<int, string> $batchNos
  3106. * @return array<string, bool>
  3107. */
  3108. protected function loadProcuremenBidOpenVerifiedBatchSet(array $batchNos): array
  3109. {
  3110. $set = [];
  3111. $list = [];
  3112. foreach ($batchNos as $b) {
  3113. $b = trim((string)$b);
  3114. if ($b !== '') {
  3115. $list[$b] = true;
  3116. }
  3117. }
  3118. if ($list === []) {
  3119. return $set;
  3120. }
  3121. $this->ensurePurchaseOrderBidOpenTable();
  3122. try {
  3123. $rows = Db::table('purchase_order_bid_open')
  3124. ->where('order_batch_no', 'in', array_keys($list))
  3125. ->field('order_batch_no')
  3126. ->select();
  3127. foreach ($rows as $row) {
  3128. if (!is_array($row)) {
  3129. continue;
  3130. }
  3131. $b = trim((string)($row['order_batch_no'] ?? ''));
  3132. if ($b !== '') {
  3133. $set[$b] = true;
  3134. }
  3135. }
  3136. } catch (\Throwable $e) {
  3137. return [];
  3138. }
  3139. return $set;
  3140. }
  3141. /**
  3142. * 批量查询订单是否已指定供应商(免开标;入参支持「A、B」拼接)
  3143. * 仅统计未软删除行(mod_rq 空)
  3144. *
  3145. * @param array<int, string> $ccydhs
  3146. * @return array<string, bool> ccydh => true
  3147. */
  3148. protected function loadProcuremenManualPickedCcydhSet(array $ccydhs): array
  3149. {
  3150. $set = [];
  3151. $list = [];
  3152. foreach ($ccydhs as $c) {
  3153. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  3154. $list[$one] = true;
  3155. }
  3156. }
  3157. if ($list === []) {
  3158. return $set;
  3159. }
  3160. $this->ensurePurchaseOrderManualPickColumns();
  3161. try {
  3162. $q = Db::table('purchase_order')
  3163. ->where('CCYDH', 'in', array_keys($list))
  3164. ->where('manual_pick', 1)
  3165. ->whereRaw("(mod_rq IS NULL OR mod_rq = '' OR mod_rq LIKE '0000-00-00%')")
  3166. ->field('CCYDH');
  3167. $rows = $q->select();
  3168. foreach ($rows as $row) {
  3169. if (!is_array($row)) {
  3170. continue;
  3171. }
  3172. $c = trim((string)($row['CCYDH'] ?? ''));
  3173. if ($c !== '') {
  3174. $set[$c] = true;
  3175. }
  3176. }
  3177. } catch (\Throwable $e) {
  3178. return [];
  3179. }
  3180. return $set;
  3181. }
  3182. /**
  3183. * 清除开标验证记录(按订单号 + 批次号)
  3184. *
  3185. * @param array<int, string> $ccydhs
  3186. * @param array<int, string> $batchNos
  3187. */
  3188. protected function clearProcuremenBidOpenRecords(array $ccydhs = [], array $batchNos = []): void
  3189. {
  3190. $ccydhList = [];
  3191. foreach ($ccydhs as $c) {
  3192. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  3193. $ccydhList[$one] = true;
  3194. }
  3195. }
  3196. $batchList = [];
  3197. foreach ($batchNos as $b) {
  3198. $b = trim((string)$b);
  3199. if ($b !== '') {
  3200. $batchList[$b] = true;
  3201. }
  3202. }
  3203. if ($ccydhList === [] && $batchList === []) {
  3204. return;
  3205. }
  3206. try {
  3207. $this->ensurePurchaseOrderBidOpenTable();
  3208. if ($ccydhList !== []) {
  3209. Db::table('purchase_order_bid_open')->where('ccydh', 'in', array_keys($ccydhList))->delete();
  3210. }
  3211. if ($batchList !== []) {
  3212. Db::table('purchase_order_bid_open')->where('order_batch_no', 'in', array_keys($batchList))->delete();
  3213. }
  3214. } catch (\Throwable $e) {
  3215. // ignore
  3216. }
  3217. }
  3218. /**
  3219. * 新下发/重新下发:同订单号下「其它有明确批次号」的未完结主单记 mod_rq 软删除。
  3220. * 不处理:本批保留行、无批次号旧数据、已完结单(避免误伤生产并行工序)。
  3221. *
  3222. * @param array<int, string> $ccydhs
  3223. * @param array<int, int|string> $keepScydgyIds 保留的工序 ID(本批)
  3224. * @param string $keepBatchNo 本批批次号(同批其它工序行也保留)
  3225. */
  3226. protected function softDeleteOtherBatchPurchaseOrders(array $ccydhs, array $keepScydgyIds = [], string $keepBatchNo = ''): void
  3227. {
  3228. $ccydhList = [];
  3229. foreach ($ccydhs as $c) {
  3230. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  3231. $ccydhList[$one] = true;
  3232. }
  3233. }
  3234. $keepBatchNo = trim($keepBatchNo);
  3235. // 无本批批次号时不做软删,避免把同订单其它有效工序一并清掉
  3236. if ($ccydhList === [] || $keepBatchNo === '') {
  3237. return;
  3238. }
  3239. $keepSid = [];
  3240. foreach ($keepScydgyIds as $sid) {
  3241. $sid = (int)$sid;
  3242. if ($this->isValidScydgyRowId($sid)) {
  3243. $keepSid[$sid] = true;
  3244. }
  3245. }
  3246. $now = date('Y-m-d H:i:s');
  3247. $bnEsc = str_replace(["\\", "'"], ["\\\\", "''"], $keepBatchNo);
  3248. try {
  3249. $q = Db::table('purchase_order')
  3250. ->where('CCYDH', 'in', array_keys($ccydhList))
  3251. ->whereRaw("(mod_rq IS NULL OR mod_rq = '' OR mod_rq LIKE '0000-00-00%')")
  3252. // 仅软删「其它非空批次」;空批次号旧数据留给展示层按批次隔离
  3253. ->whereRaw("TRIM(CAST(order_batch_no AS CHAR(64))) <> ''")
  3254. ->whereRaw("order_batch_no <> '{$bnEsc}'")
  3255. // 已完结不软删
  3256. ->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  3257. if ($keepSid !== []) {
  3258. $q->where('scydgy_id', 'not in', array_keys($keepSid));
  3259. }
  3260. $q->update([
  3261. 'mod_rq' => $now,
  3262. 'manual_pick' => 0,
  3263. 'manual_pick_reason' => '',
  3264. ]);
  3265. } catch (\Throwable $e) {
  3266. Log::write('softDeleteOtherBatchPurchaseOrders: ' . $e->getMessage(), 'error');
  3267. }
  3268. }
  3269. /**
  3270. * 重新下发/新下发:清掉按订单号落库的供应商评分,避免旧批 0 分/旧排名串到新批
  3271. *
  3272. * @param array<int, string> $ccydhs
  3273. */
  3274. protected function clearProcuremenSupplierScoresForCcydhs(array $ccydhs): void
  3275. {
  3276. $list = [];
  3277. foreach ($ccydhs as $c) {
  3278. foreach ($this->expandProcuremenCcydhTokens($c) as $one) {
  3279. $list[$one] = true;
  3280. }
  3281. }
  3282. if ($list === []) {
  3283. return;
  3284. }
  3285. try {
  3286. Db::table('supplier_service_score')->where('ccydh', 'in', array_keys($list))->delete();
  3287. } catch (\Throwable $e) {
  3288. Log::write('clearProcuremenSupplierScoresForCcydhs: ' . $e->getMessage(), 'error');
  3289. }
  3290. }
  3291. /**
  3292. * 列表行开标状态:有批次号时只认本批次开标/本行指定,避免同订单号旧批串读
  3293. *
  3294. * @param array<string, mixed> $rw
  3295. * @param array<string, bool> $bidOpenSet
  3296. * @param array<string, bool> $manualPickSet
  3297. * @param array<string, bool> $bidOpenBatchSet
  3298. * @return array{verified:bool,manual:bool,text:string}
  3299. */
  3300. protected function resolveProcuremenListBidOpenState(
  3301. array $rw,
  3302. array $bidOpenSet,
  3303. array $manualPickSet,
  3304. array $bidOpenBatchSet = []
  3305. ): array {
  3306. $batchNo = $this->resolveProcuremenOrderBatchNo($rw);
  3307. if ($batchNo === '' && !empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3308. foreach ($rw['_order_merge_rows'] as $mr) {
  3309. if (!is_array($mr)) {
  3310. continue;
  3311. }
  3312. $batchNo = $this->resolveProcuremenOrderBatchNo($mr);
  3313. if ($batchNo !== '') {
  3314. break;
  3315. }
  3316. }
  3317. }
  3318. $manual = ((int)($rw['manual_pick'] ?? 0) === 1);
  3319. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3320. foreach ($rw['_order_merge_rows'] as $mr) {
  3321. if (!is_array($mr)) {
  3322. continue;
  3323. }
  3324. // 合并行仅认同一批次(无批次号时退回同订单兼容)
  3325. if ($batchNo !== '') {
  3326. $mrBatch = $this->resolveProcuremenOrderBatchNo($mr);
  3327. if ($mrBatch !== '' && $mrBatch !== $batchNo) {
  3328. continue;
  3329. }
  3330. }
  3331. if ((int)($mr['manual_pick'] ?? 0) === 1) {
  3332. $manual = true;
  3333. }
  3334. }
  3335. }
  3336. // 收集本行/合并行订单号,供开标记录与自选集合兜底(自选=免开标,等同已开标可继续确认)
  3337. $ccydhTokens = $this->expandProcuremenCcydhTokens($rw['CCYDH'] ?? '');
  3338. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3339. foreach ($rw['_order_merge_rows'] as $mr) {
  3340. if (!is_array($mr)) {
  3341. continue;
  3342. }
  3343. if ($batchNo !== '') {
  3344. $mrBatch = $this->resolveProcuremenOrderBatchNo($mr);
  3345. if ($mrBatch !== '' && $mrBatch !== $batchNo) {
  3346. continue;
  3347. }
  3348. }
  3349. foreach ($this->expandProcuremenCcydhTokens($mr['CCYDH'] ?? '') as $one) {
  3350. if (!in_array($one, $ccydhTokens, true)) {
  3351. $ccydhTokens[] = $one;
  3352. }
  3353. }
  3354. }
  3355. }
  3356. if ($batchNo !== '') {
  3357. // 有正式批次号:开标只看本批
  3358. $verified = isset($bidOpenBatchSet[$batchNo]);
  3359. // 自选兜底:本行字段漏带时,仍可用有效主单上的自选标记(旧批已软删,不会串读)
  3360. if (!$manual) {
  3361. foreach ($ccydhTokens as $c) {
  3362. if (isset($manualPickSet[$c])) {
  3363. $manual = true;
  3364. break;
  3365. }
  3366. }
  3367. }
  3368. } else {
  3369. // 旧数据无批次号:兼容按订单号开标/指定
  3370. $verified = false;
  3371. foreach ($ccydhTokens as $c) {
  3372. if (isset($bidOpenSet[$c])) {
  3373. $verified = true;
  3374. }
  3375. if (isset($manualPickSet[$c])) {
  3376. $manual = true;
  3377. }
  3378. }
  3379. }
  3380. if ($verified) {
  3381. $text = '已开标';
  3382. } elseif ($manual) {
  3383. $text = '已指定供应商';
  3384. } else {
  3385. $text = '待开标';
  3386. }
  3387. return ['verified' => $verified, 'manual' => $manual, 'text' => $text];
  3388. }
  3389. /**
  3390. * 确认供应商列表:按开标状态筛选(已开标 / 已指定供应商 / 待开标)
  3391. *
  3392. * @param array<int, array<string, mixed>> $pool
  3393. * @return array<int, array<string, mixed>>
  3394. */
  3395. protected function filterProcuremenPoolByBidOpenStatus(array $pool, string $status): array
  3396. {
  3397. $status = trim($status);
  3398. if ($status === '' || !in_array($status, ['待开标', '已开标', '已指定供应商'], true)) {
  3399. return $pool;
  3400. }
  3401. $ccydhList = [];
  3402. $batchList = [];
  3403. foreach ($pool as $rw) {
  3404. if (!is_array($rw)) {
  3405. continue;
  3406. }
  3407. $c = trim((string)($rw['CCYDH'] ?? ''));
  3408. if ($c !== '') {
  3409. $ccydhList[] = $c;
  3410. }
  3411. $b = $this->resolveProcuremenOrderBatchNo($rw);
  3412. if ($b !== '') {
  3413. $batchList[] = $b;
  3414. }
  3415. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3416. foreach ($rw['_order_merge_rows'] as $mr) {
  3417. if (!is_array($mr)) {
  3418. continue;
  3419. }
  3420. $cm = trim((string)($mr['CCYDH'] ?? ''));
  3421. if ($cm !== '') {
  3422. $ccydhList[] = $cm;
  3423. }
  3424. $bm = $this->resolveProcuremenOrderBatchNo($mr);
  3425. if ($bm !== '') {
  3426. $batchList[] = $bm;
  3427. }
  3428. }
  3429. }
  3430. }
  3431. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  3432. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  3433. $bidOpenBatchSet = $this->loadProcuremenBidOpenVerifiedBatchSet($batchList);
  3434. $out = [];
  3435. foreach ($pool as $rw) {
  3436. if (!is_array($rw)) {
  3437. continue;
  3438. }
  3439. $state = $this->resolveProcuremenListBidOpenState($rw, $bidOpenSet, $manualPickSet, $bidOpenBatchSet);
  3440. if (($state['text'] ?? '') === $status) {
  3441. $out[] = $rw;
  3442. }
  3443. }
  3444. return $out;
  3445. }
  3446. /**
  3447. * 按订单状态筛选(待确认 / 已驳回 / 待审核 / 已审核)
  3448. *
  3449. * @param array<int, array<string, mixed>> $pool
  3450. * @return array<int, array<string, mixed>>
  3451. */
  3452. protected function filterProcuremenPoolByOrderStatus(array $pool, string $status): array
  3453. {
  3454. $status = trim($status);
  3455. if ($status === '' || !in_array($status, ['待确认', '已驳回', '待审核', '已审核'], true)) {
  3456. return $pool;
  3457. }
  3458. $out = [];
  3459. foreach ($pool as $rw) {
  3460. if (!is_array($rw)) {
  3461. continue;
  3462. }
  3463. $label = trim((string)($rw['order_status_text'] ?? ''));
  3464. if ($label === '') {
  3465. $label = ProcuremenStatus::orderStatusLabelForList($rw['wflow_status'] ?? '');
  3466. }
  3467. if ($label === $status) {
  3468. $out[] = $rw;
  3469. }
  3470. }
  3471. return $out;
  3472. }
  3473. /**
  3474. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  3475. *
  3476. * @param array<string, mixed> $group
  3477. */
  3478. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  3479. {
  3480. if ($quoteVisible) {
  3481. $group['remark_quote_pending'] = 0;
  3482. return;
  3483. }
  3484. $group['remark'] = '';
  3485. $group['remark_quote_pending'] = 0;
  3486. }
  3487. /**
  3488. * 下发订单备注 MBZ(印件规格),不是供应商填写
  3489. *
  3490. * @param array{pos?:array, merge_rows?:array} $bundle
  3491. */
  3492. protected function resolveBundleOrderMbz(array $bundle): string
  3493. {
  3494. foreach (['pos', 'merge_rows'] as $key) {
  3495. foreach ($bundle[$key] ?? [] as $row) {
  3496. if (!is_array($row)) {
  3497. continue;
  3498. }
  3499. $mbz = trim((string)($row['MBZ'] ?? $row['mbz'] ?? ''));
  3500. if ($mbz !== '') {
  3501. return $mbz;
  3502. }
  3503. }
  3504. }
  3505. return '';
  3506. }
  3507. /**
  3508. * 供应商自己填的备注;与订单 MBZ 相同视为未填(历史误把规格写入明细)
  3509. */
  3510. protected function resolveSupplierOwnRemark($detailRemark, $orderMbz = ''): string
  3511. {
  3512. $own = trim((string)$detailRemark);
  3513. $mbz = trim((string)$orderMbz);
  3514. if ($own === '' || ($mbz !== '' && $own === $mbz)) {
  3515. return '';
  3516. }
  3517. return $own;
  3518. }
  3519. /**
  3520. * 供应商备注展示:仅自己填写的;有工序行时始终占一行「投标备注」(空也显示标签)
  3521. *
  3522. * @param array<string, mixed> $group
  3523. */
  3524. protected function finalizeSupplierRemarkDisplay(array &$group, string $orderMbz, bool $quoteVisible): void
  3525. {
  3526. $group['remark'] = $this->resolveSupplierOwnRemark($group['remark'] ?? '', $orderMbz);
  3527. $this->maskSupplierRemarkBeforeBidOpen($group, $quoteVisible);
  3528. $lineCount = (int)($group['line_count'] ?? 0);
  3529. if ($lineCount <= 0) {
  3530. $lines = $group['lines'] ?? $group['pick_lines'] ?? [];
  3531. $lineCount = is_array($lines) ? count($lines) : 0;
  3532. }
  3533. // 与手机端一致:有供应商工序行就显示投标备注行,内容可为空
  3534. $group['has_remark'] = $lineCount > 0;
  3535. $extra = (!empty($group['has_remark']) ? 1 : 0) + (!empty($group['has_total']) ? 1 : 0);
  3536. $group['display_rowspan'] = $lineCount > 0 ? ($lineCount + $extra) : 0;
  3537. }
  3538. /**
  3539. * @param array{ccydh?:string,pos?:array,order_batch_no?:string} $bundle
  3540. */
  3541. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  3542. {
  3543. $batchNo = $this->resolveBundleOrderBatchNo($bundle);
  3544. // 有批次号:只认本批开标,避免同订单号历史开标串到新批
  3545. if ($batchNo !== '') {
  3546. return $this->isProcuremenBidOpenVerifiedByBatchNo($batchNo);
  3547. }
  3548. $list = [];
  3549. foreach ($bundle['pos'] ?? [] as $po) {
  3550. if (!is_array($po)) {
  3551. continue;
  3552. }
  3553. foreach ($this->expandProcuremenCcydhTokens($po['CCYDH'] ?? '') as $dh) {
  3554. $list[$dh] = true;
  3555. }
  3556. }
  3557. $primary = trim((string)($bundle['ccydh'] ?? ''));
  3558. foreach ($this->expandProcuremenCcydhTokens($primary) as $dh) {
  3559. $list[$dh] = true;
  3560. }
  3561. if ($list === []) {
  3562. return false;
  3563. }
  3564. // 旧数据无批次号:全部订单号都有开标记录才算已开标
  3565. foreach (array_keys($list) as $ccydh) {
  3566. if (!$this->isProcuremenBidOpenVerified($ccydh)) {
  3567. return false;
  3568. }
  3569. }
  3570. return true;
  3571. }
  3572. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  3573. {
  3574. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  3575. return true;
  3576. }
  3577. return $this->isProcuremenManualPickedForBundle($bundle);
  3578. }
  3579. /**
  3580. * 确保 purchase_order 自选供应商字段
  3581. */
  3582. protected function ensurePurchaseOrderManualPickColumns(): void
  3583. {
  3584. static $done = false;
  3585. if ($done) {
  3586. return;
  3587. }
  3588. $done = true;
  3589. $adds = [
  3590. 'manual_pick' => "ADD COLUMN `manual_pick` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=自选供应商(免开标)' AFTER `pick_company_name`",
  3591. 'manual_pick_reason' => "ADD COLUMN `manual_pick_reason` varchar(500) NOT NULL DEFAULT '' COMMENT '自选供应商选择说明' AFTER `manual_pick`",
  3592. ];
  3593. foreach ($adds as $col => $ddl) {
  3594. try {
  3595. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  3596. if (!is_array($cols) || $cols === []) {
  3597. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  3598. }
  3599. } catch (\Throwable $e) {
  3600. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  3601. }
  3602. }
  3603. }
  3604. /**
  3605. * 是否已自选供应商(免开标查看报价)——仅看本 bundle 行,不按订单号串旧批
  3606. *
  3607. * @param array{pos?:array} $bundle
  3608. */
  3609. protected function isProcuremenManualPickedForBundle(array $bundle): bool
  3610. {
  3611. $this->ensurePurchaseOrderManualPickColumns();
  3612. foreach ($bundle['pos'] ?? [] as $poRow) {
  3613. if (!is_array($poRow)) {
  3614. continue;
  3615. }
  3616. if ((int)($poRow['manual_pick'] ?? 0) === 1) {
  3617. return true;
  3618. }
  3619. }
  3620. return false;
  3621. }
  3622. /**
  3623. * @param array{pos?:array} $bundle
  3624. * @return array{company:string,reason:string}
  3625. */
  3626. protected function resolveProcuremenManualPickInfo(array $bundle): array
  3627. {
  3628. $this->ensurePurchaseOrderManualPickColumns();
  3629. foreach ($bundle['pos'] ?? [] as $poRow) {
  3630. if (!is_array($poRow)) {
  3631. continue;
  3632. }
  3633. if ((int)($poRow['manual_pick'] ?? 0) !== 1) {
  3634. continue;
  3635. }
  3636. $cn = trim((string)($poRow['pick_company_name'] ?? ''));
  3637. $reason = trim((string)($poRow['manual_pick_reason'] ?? ''));
  3638. return ['company' => $cn, 'reason' => $reason];
  3639. }
  3640. return ['company' => '', 'reason' => ''];
  3641. }
  3642. protected function loadBidOpenAdminUser(int $adminId): ?array
  3643. {
  3644. if ($adminId <= 0) {
  3645. return null;
  3646. }
  3647. try {
  3648. $row = Db::name('admin')->where('id', $adminId)->find();
  3649. } catch (\Throwable $e) {
  3650. return null;
  3651. }
  3652. if (!is_array($row)) {
  3653. return null;
  3654. }
  3655. $status = strtolower(trim((string)($row['status'] ?? '')));
  3656. if ($status !== '' && $status !== 'normal') {
  3657. return null;
  3658. }
  3659. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  3660. return null;
  3661. }
  3662. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  3663. if (!preg_match('/^1\d{10}$/', $phone)) {
  3664. return null;
  3665. }
  3666. $name = trim((string)($row['nickname'] ?? ''));
  3667. if ($name === '') {
  3668. $name = trim((string)($row['username'] ?? ''));
  3669. }
  3670. return [
  3671. 'id' => (int)$row['id'],
  3672. 'username' => trim((string)($row['username'] ?? '')),
  3673. 'nickname' => $name,
  3674. 'mobile' => $phone,
  3675. ];
  3676. }
  3677. /**
  3678. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  3679. */
  3680. protected function bidOpenVerifierAuthGroupRootId(): int
  3681. {
  3682. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  3683. return $id > 0 ? $id : 10;
  3684. }
  3685. /**
  3686. * @return int[]
  3687. */
  3688. protected function loadBidOpenVerifierAuthGroupIds(): array
  3689. {
  3690. static $memo = [];
  3691. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  3692. if (isset($memo[$rootId])) {
  3693. return $memo[$rootId];
  3694. }
  3695. try {
  3696. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  3697. } catch (\Throwable $e) {
  3698. $memo[$rootId] = [$rootId];
  3699. return $memo[$rootId];
  3700. }
  3701. if (!is_array($groups) || $groups === []) {
  3702. $memo[$rootId] = [$rootId];
  3703. return $memo[$rootId];
  3704. }
  3705. $groupList = [];
  3706. foreach ($groups as $g) {
  3707. if (is_array($g)) {
  3708. $groupList[] = $g;
  3709. }
  3710. }
  3711. if ($groupList === []) {
  3712. $memo[$rootId] = [$rootId];
  3713. return $memo[$rootId];
  3714. }
  3715. $tree = \fast\Tree::instance();
  3716. $tree->init($groupList);
  3717. $ids = $tree->getChildrenIds($rootId, true);
  3718. if (!is_array($ids) || $ids === []) {
  3719. $memo[$rootId] = [$rootId];
  3720. return $memo[$rootId];
  3721. }
  3722. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  3723. return $memo[$rootId];
  3724. }
  3725. protected function isBidOpenVerifierAdmin(int $adminId): bool
  3726. {
  3727. if ($adminId <= 0) {
  3728. return false;
  3729. }
  3730. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3731. if ($groupIds === []) {
  3732. return false;
  3733. }
  3734. try {
  3735. return (bool)Db::name('auth_group_access')
  3736. ->where('uid', $adminId)
  3737. ->where('group_id', 'in', $groupIds)
  3738. ->count();
  3739. } catch (\Throwable $e) {
  3740. return false;
  3741. }
  3742. }
  3743. /**
  3744. * @return array<int, array<string, mixed>>
  3745. */
  3746. protected function listBidOpenVerifierCandidates(): array
  3747. {
  3748. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3749. if ($groupIds === []) {
  3750. return [];
  3751. }
  3752. try {
  3753. $adminIds = Db::name('auth_group_access')
  3754. ->where('group_id', 'in', $groupIds)
  3755. ->column('uid');
  3756. } catch (\Throwable $e) {
  3757. $adminIds = [];
  3758. }
  3759. $adminIds = is_array($adminIds)
  3760. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  3761. : [];
  3762. if ($adminIds === []) {
  3763. return [];
  3764. }
  3765. try {
  3766. $rows = Db::name('admin')
  3767. ->where('status', 'normal')
  3768. ->where('id', 'in', $adminIds)
  3769. ->where('mobile', '<>', '')
  3770. ->order('id', 'asc')
  3771. ->select();
  3772. } catch (\Throwable $e) {
  3773. return [];
  3774. }
  3775. if (!is_array($rows)) {
  3776. return [];
  3777. }
  3778. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  3779. $out = [];
  3780. foreach ($rows as $row) {
  3781. if (!is_array($row)) {
  3782. continue;
  3783. }
  3784. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  3785. if ($one === null) {
  3786. continue;
  3787. }
  3788. $out[] = [
  3789. 'id' => $one['id'],
  3790. 'username' => $one['username'],
  3791. 'nickname' => $one['nickname'],
  3792. 'group_name' => $groupNameMap[$one['id']] ?? '',
  3793. 'mobile' => mask_phone($one['mobile']),
  3794. 'mobile_plain' => (string)$one['mobile'],
  3795. ];
  3796. }
  3797. return $out;
  3798. }
  3799. /**
  3800. * @param int[] $adminIds
  3801. * @return array<int, string>
  3802. */
  3803. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  3804. {
  3805. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  3806. if ($adminIds === []) {
  3807. return [];
  3808. }
  3809. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3810. try {
  3811. $rows = Db::name('auth_group_access')
  3812. ->alias('aga')
  3813. ->join('auth_group ag', 'aga.group_id = ag.id')
  3814. ->where('aga.uid', 'in', $adminIds)
  3815. ->where('aga.group_id', 'in', $groupIds)
  3816. ->field('aga.uid,ag.name')
  3817. ->order('aga.uid', 'asc')
  3818. ->order('aga.group_id', 'asc')
  3819. ->select();
  3820. } catch (\Throwable $e) {
  3821. return [];
  3822. }
  3823. if (!is_array($rows)) {
  3824. return [];
  3825. }
  3826. $out = [];
  3827. foreach ($rows as $row) {
  3828. if (!is_array($row)) {
  3829. continue;
  3830. }
  3831. $uid = (int)($row['uid'] ?? 0);
  3832. $name = trim((string)($row['name'] ?? ''));
  3833. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  3834. continue;
  3835. }
  3836. $out[$uid] = $name;
  3837. }
  3838. return $out;
  3839. }
  3840. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  3841. {
  3842. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  3843. }
  3844. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  3845. {
  3846. return 'procuremen_bidopen_wait_' . $adminId;
  3847. }
  3848. protected function renderBidOpenVerifySms(string $code): string
  3849. {
  3850. $tpl = '';
  3851. try {
  3852. $row = $this->loadNotifyTemplateRow('bid_open');
  3853. if (is_array($row)) {
  3854. $tpl = trim((string)($row['content'] ?? ''));
  3855. }
  3856. } catch (\Throwable $e) {
  3857. $tpl = '';
  3858. }
  3859. if ($tpl === '') {
  3860. $tpl = '【可集达】您的短信验证码是{code}';
  3861. }
  3862. return str_replace('{code}', $code, $tpl);
  3863. }
  3864. protected function sendBidOpenVerifySms(string $phone, string $code): void
  3865. {
  3866. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  3867. }
  3868. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  3869. {
  3870. $code = trim($code);
  3871. if (!preg_match('/^\d{6}$/', $code)) {
  3872. return false;
  3873. }
  3874. $mock = Config::get('mproc.mock_sms_code');
  3875. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3876. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3877. return true;
  3878. }
  3879. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3880. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3881. return false;
  3882. }
  3883. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3884. return true;
  3885. }
  3886. /**
  3887. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3888. */
  3889. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  3890. {
  3891. $ccydhList = [];
  3892. $batchNo = $this->resolveBundleOrderBatchNo($bundle);
  3893. foreach ($bundle['pos'] ?? [] as $poRow) {
  3894. if (!is_array($poRow)) {
  3895. continue;
  3896. }
  3897. foreach ($this->expandProcuremenCcydhTokens($poRow['CCYDH'] ?? '') as $dh) {
  3898. $ccydhList[$dh] = true;
  3899. }
  3900. if ($batchNo === '') {
  3901. $batchNo = $this->resolveProcuremenOrderBatchNo($poRow);
  3902. }
  3903. }
  3904. $primaryCcydh = trim((string)($bundle['ccydh'] ?? ''));
  3905. foreach ($this->expandProcuremenCcydhTokens($primaryCcydh) as $dh) {
  3906. $ccydhList[$dh] = true;
  3907. }
  3908. if ($ccydhList === []) {
  3909. throw new \InvalidArgumentException('订单号无效');
  3910. }
  3911. $this->ensurePurchaseOrderBidOpenTable();
  3912. list($operatorId, $operatorName) = $this->GetUseName();
  3913. $now = date('Y-m-d H:i:s');
  3914. $payloadBase = [
  3915. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  3916. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  3917. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  3918. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  3919. 'operator_id' => (int)$operatorId,
  3920. 'operator_name' => trim((string)$operatorName),
  3921. 'createtime' => $now,
  3922. 'order_batch_no' => $batchNo,
  3923. ];
  3924. foreach (array_keys($ccydhList) as $ccydh) {
  3925. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3926. $payload = $payloadBase;
  3927. $payload['ccydh'] = $ccydh;
  3928. if (is_array($exists)) {
  3929. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  3930. } else {
  3931. Db::table('purchase_order_bid_open')->insert($payload);
  3932. }
  3933. }
  3934. $name1 = $payloadBase['verifier1_name'] !== '' ? $payloadBase['verifier1_name'] : ('ID' . $payloadBase['verifier1_id']);
  3935. $name2 = $payloadBase['verifier2_name'] !== '' ? $payloadBase['verifier2_name'] : ('ID' . $payloadBase['verifier2_id']);
  3936. $labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
  3937. (int)$payloadBase['verifier1_id'],
  3938. (int)$payloadBase['verifier2_id'],
  3939. ]);
  3940. if (isset($labelMap[(int)$payloadBase['verifier1_id']]) && (int)$payloadBase['verifier1_id'] > 0) {
  3941. $name1 = $labelMap[(int)$payloadBase['verifier1_id']];
  3942. }
  3943. if (isset($labelMap[(int)$payloadBase['verifier2_id']]) && (int)$payloadBase['verifier2_id'] > 0) {
  3944. $name2 = $labelMap[(int)$payloadBase['verifier2_id']];
  3945. }
  3946. $logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
  3947. $seenSid = [];
  3948. foreach ($bundle['pos'] ?? [] as $poRow) {
  3949. if (!is_array($poRow)) {
  3950. continue;
  3951. }
  3952. $sid = (int)($poRow['scydgy_id'] ?? 0);
  3953. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  3954. continue;
  3955. }
  3956. $seenSid[$sid] = true;
  3957. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  3958. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  3959. }
  3960. if ($seenSid === []) {
  3961. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  3962. if ($this->isValidScydgyRowId($anchor)) {
  3963. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  3964. }
  3965. }
  3966. // 开标通过后:按订单号分别计算并写入供应商服务评分(避免多订单串分)
  3967. try {
  3968. $ym = date('Y-m', strtotime($now) ?: time());
  3969. $this->saveProcuremenSupplierScoresForBundle($bundle, $ym);
  3970. } catch (\Throwable $e) {
  3971. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  3972. }
  3973. }
  3974. /**
  3975. * 按 bundle 内各订单分别计分落库(单订单价格分);一批多单展示时再按数量×限价比例跨单加权
  3976. *
  3977. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3978. */
  3979. protected function saveProcuremenSupplierScoresForBundle(array $bundle, ?string $ym = null): void
  3980. {
  3981. $batchNo = $this->resolveBundleOrderBatchNo($bundle);
  3982. $posByCcydh = [];
  3983. foreach ($bundle['pos'] ?? [] as $po) {
  3984. if (!is_array($po)) {
  3985. continue;
  3986. }
  3987. $dh = trim((string)($po['CCYDH'] ?? ''));
  3988. if ($dh === '') {
  3989. continue;
  3990. }
  3991. if (!isset($posByCcydh[$dh])) {
  3992. $posByCcydh[$dh] = [];
  3993. }
  3994. $posByCcydh[$dh][] = $po;
  3995. }
  3996. if ($posByCcydh === []) {
  3997. $fallback = trim((string)($bundle['ccydh'] ?? ''));
  3998. if ($fallback === '') {
  3999. return;
  4000. }
  4001. $groups = $this->loadAuditSupplierQuoteGroups($bundle);
  4002. ProcuremenSupplierScore::saveForOrder($fallback, $groups, $ym, $batchNo);
  4003. return;
  4004. }
  4005. $mergeAll = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  4006. foreach ($posByCcydh as $ccydh => $posList) {
  4007. $sidSet = [];
  4008. foreach ($posList as $po) {
  4009. $sid = (int)($po['scydgy_id'] ?? 0);
  4010. if ($this->isValidScydgyRowId($sid)) {
  4011. $sidSet[$sid] = true;
  4012. }
  4013. }
  4014. $mergeRows = [];
  4015. foreach ($mergeAll as $mr) {
  4016. if (!is_array($mr)) {
  4017. continue;
  4018. }
  4019. $gid = $this->extractScydgyRowId($mr);
  4020. if ($this->isValidScydgyRowId($gid) && isset($sidSet[$gid])) {
  4021. $mergeRows[] = $mr;
  4022. }
  4023. }
  4024. $subBundle = [
  4025. 'ccydh' => $ccydh,
  4026. 'order_batch_no' => $batchNo,
  4027. 'pos' => $posList,
  4028. 'merge_rows' => $mergeRows !== [] ? $mergeRows : $this->scydgyRowsForPurchaseOrders($posList),
  4029. ];
  4030. $groups = $this->loadAuditSupplierQuoteGroups($subBundle);
  4031. ProcuremenSupplierScore::saveForOrder($ccydh, $groups, $ym, $batchNo);
  4032. }
  4033. }
  4034. /**
  4035. * 报价行展示字段默认值(模板安全访问)
  4036. *
  4037. * @param array<string, mixed> $line
  4038. * @return array<string, mixed>
  4039. */
  4040. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  4041. {
  4042. if (!array_key_exists('amount_quote_pending', $line)) {
  4043. $line['amount_quote_pending'] = 0;
  4044. }
  4045. if (!array_key_exists('delivery_quote_pending', $line)) {
  4046. $line['delivery_quote_pending'] = 0;
  4047. }
  4048. if (!array_key_exists('quote_before_deadline', $line)) {
  4049. $line['quote_before_deadline'] = 0;
  4050. }
  4051. if (!array_key_exists('amount_filled', $line)) {
  4052. $line['amount_filled'] = 0;
  4053. }
  4054. if (!array_key_exists('delivery_filled', $line)) {
  4055. $line['delivery_filled'] = 0;
  4056. }
  4057. if (!array_key_exists('lead_days_filled', $line)) {
  4058. $line['lead_days_filled'] = 0;
  4059. }
  4060. if (!array_key_exists('lead_days_quote_pending', $line)) {
  4061. $line['lead_days_quote_pending'] = 0;
  4062. }
  4063. if (!array_key_exists('lead_days_show', $line)) {
  4064. $line['lead_days_show'] = '未填写';
  4065. }
  4066. if (!array_key_exists('lead_days_text', $line)) {
  4067. $line['lead_days_text'] = $line['lead_days_show'];
  4068. }
  4069. if (!array_key_exists('ccydh', $line)) {
  4070. $line['ccydh'] = '';
  4071. }
  4072. if (!array_key_exists('cgymc', $line)) {
  4073. $line['cgymc'] = '';
  4074. }
  4075. // 工序列展示文案:上行订单号、下行工序(无括号;兼容旧模板)
  4076. if (!array_key_exists('cgymc_display', $line) || trim((string)$line['cgymc_display']) === '') {
  4077. $dh = trim((string)$line['ccydh']);
  4078. $gy = trim((string)$line['cgymc']);
  4079. $line['cgymc_display'] = $dh !== '' ? ($dh . "\n" . $gy) : $gy;
  4080. }
  4081. return $line;
  4082. }
  4083. /**
  4084. * 供应商报价表「工序名称」列:订单号 + 工序名(不加 [])
  4085. *
  4086. * @return array{ccydh:string,cgymc:string,cgymc_display:string}
  4087. */
  4088. protected function buildSupplierProcessNameFields(string $ccydh, string $cgymc): array
  4089. {
  4090. $ccydh = trim($ccydh);
  4091. $cgymc = trim($cgymc);
  4092. if ($cgymc === '') {
  4093. $cgymc = '工序';
  4094. }
  4095. return [
  4096. 'ccydh' => $ccydh,
  4097. 'cgymc' => $cgymc,
  4098. 'cgymc_display' => $ccydh !== '' ? ($ccydh . "\n" . $cgymc) : $cgymc,
  4099. ];
  4100. }
  4101. /**
  4102. * 审核弹窗:按供应商汇总报价明细
  4103. *
  4104. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  4105. * @return array<int, array<string, mixed>>
  4106. */
  4107. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  4108. {
  4109. $sids = [];
  4110. foreach ($bundle['pos'] ?? [] as $po) {
  4111. if (!is_array($po)) {
  4112. continue;
  4113. }
  4114. $sid = (int)($po['scydgy_id'] ?? 0);
  4115. if ($this->isValidScydgyRowId($sid)) {
  4116. $sids[$sid] = true;
  4117. }
  4118. }
  4119. if ($sids === []) {
  4120. return [];
  4121. }
  4122. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  4123. $orderMbz = $this->resolveBundleOrderMbz($bundle);
  4124. $orderDeadlineMap = $this->buildBundleOrderDeliveryDeadlineMap($bundle);
  4125. $gymcMap = [];
  4126. $ccydhBySid = [];
  4127. $qtyBySid = [];
  4128. $ceilingBySid = [];
  4129. $extraSids = [];
  4130. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  4131. if (!is_array($mr)) {
  4132. continue;
  4133. }
  4134. $gid = $this->extractScydgyRowId($mr);
  4135. if ($this->isValidScydgyRowId($gid)) {
  4136. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  4137. $dh = trim((string)($mr['CCYDH'] ?? ''));
  4138. if ($dh !== '') {
  4139. $ccydhBySid[$gid] = $dh;
  4140. }
  4141. $qtyBySid[$gid] = $this->resolveProcuremenThisQuantity($mr);
  4142. $ceilingBySid[$gid] = $this->resolveProcuremenCeilingPrice($mr);
  4143. }
  4144. }
  4145. foreach ($bundle['pos'] ?? [] as $po) {
  4146. if (!is_array($po)) {
  4147. continue;
  4148. }
  4149. $gid = (int)($po['scydgy_id'] ?? 0);
  4150. if ($this->isValidScydgyRowId($gid)) {
  4151. $nm = trim((string)($po['CGYMC'] ?? ''));
  4152. if ($nm !== '') {
  4153. $gymcMap[$gid] = $nm;
  4154. }
  4155. $dh = trim((string)($po['CCYDH'] ?? ''));
  4156. if ($dh !== '' && empty($ccydhBySid[$gid])) {
  4157. $ccydhBySid[$gid] = $dh;
  4158. }
  4159. if (!isset($qtyBySid[$gid]) || trim((string)$qtyBySid[$gid]) === '') {
  4160. $qtyBySid[$gid] = $this->resolveProcuremenThisQuantity($po);
  4161. }
  4162. if (!isset($ceilingBySid[$gid]) || trim((string)$ceilingBySid[$gid]) === '') {
  4163. $ceilingBySid[$gid] = $this->resolveProcuremenCeilingPrice($po);
  4164. }
  4165. $extraSids[] = $gid;
  4166. }
  4167. }
  4168. // 与上方工序表一致:按订单号升序排供应商明细行
  4169. $orderedSids = $this->orderedScydgyIdsLikeProcessDisplay(
  4170. is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [],
  4171. $extraSids
  4172. );
  4173. try {
  4174. $detailsQuery = Db::table('purchase_order_detail')
  4175. ->where('scydgy_id', 'in', array_keys($sids));
  4176. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  4177. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  4178. } catch (\Throwable $e) {
  4179. try {
  4180. $detailsQuery = Db::table('purchase_order_detail')
  4181. ->where('scydgy_id', 'in', array_keys($sids));
  4182. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  4183. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  4184. } catch (\Throwable $e2) {
  4185. $details = [];
  4186. }
  4187. }
  4188. if (!is_array($details)) {
  4189. $details = [];
  4190. }
  4191. $byCompany = [];
  4192. foreach ($details as $d) {
  4193. if (!is_array($d)) {
  4194. continue;
  4195. }
  4196. $cn = trim((string)($d['company_name'] ?? ''));
  4197. if ($cn === '') {
  4198. continue;
  4199. }
  4200. if (!isset($byCompany[$cn])) {
  4201. $ph = trim((string)($d['phone'] ?? ''));
  4202. $username = trim((string)($d['username'] ?? ''));
  4203. if ($username === '') {
  4204. $username = $this->resolveCustomerContactName($ph, $cn);
  4205. }
  4206. $byCompany[$cn] = [
  4207. 'name' => $cn,
  4208. 'email' => trim((string)($d['email'] ?? '')),
  4209. 'phone' => $ph,
  4210. 'username' => $username,
  4211. 'remark' => '',
  4212. 'has_quote' => false,
  4213. 'lines_map' => [],
  4214. ];
  4215. }
  4216. if ($byCompany[$cn]['remark'] === '') {
  4217. $rm = '';
  4218. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  4219. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  4220. $rm = trim((string)$d[$rk]);
  4221. break;
  4222. }
  4223. }
  4224. if ($rm !== '') {
  4225. $byCompany[$cn]['remark'] = $rm;
  4226. }
  4227. }
  4228. $sid = (int)($d['scydgy_id'] ?? 0);
  4229. $am = trim((string)($d['amount'] ?? ''));
  4230. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  4231. $ccydhLine = trim((string)($ccydhBySid[$sid] ?? ''));
  4232. $processName = $this->buildSupplierProcessNameFields($ccydhLine, $gymc);
  4233. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  4234. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  4235. if ($deliveryShow === '' && $deliveryRaw !== '') {
  4236. $deliveryShow = $deliveryRaw;
  4237. }
  4238. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  4239. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  4240. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  4241. $subtotal = null;
  4242. if ($amountNum !== null) {
  4243. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  4244. }
  4245. $unitPriceText = $amountFilled
  4246. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  4247. : '未填写';
  4248. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  4249. $leadFilled = ($leadDays !== null);
  4250. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  4251. $lineRow = array_merge($processName, [
  4252. 'scydgy_id' => $sid,
  4253. 'This_quantity' => (string)($qtyBySid[$sid] ?? ''),
  4254. 'ceilingPrice' => (string)($ceilingBySid[$sid] ?? ''),
  4255. 'amount' => $am,
  4256. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  4257. 'amount_filled' => $amountFilled,
  4258. 'unit_price_text' => $unitPriceText,
  4259. 'delivery' => $deliveryRaw,
  4260. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  4261. 'delivery_filled' => $deliveryFilled,
  4262. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  4263. 'order_delivery_deadline' => $orderDeadlineMap[$ccydhLine] ?? '',
  4264. 'lead_days' => $leadFilled ? $leadDays : '',
  4265. 'lead_days_filled' => $leadFilled,
  4266. 'lead_days_show' => $leadText,
  4267. 'lead_days_text' => $leadText,
  4268. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  4269. 'subtotal_num' => $subtotal,
  4270. 'status_name' => trim((string)($d['status_name'] ?? '')),
  4271. 'is_quoted' => $amountFilled,
  4272. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  4273. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  4274. ]);
  4275. if (!$quoteVisible) {
  4276. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  4277. }
  4278. // 按工序 id 暂存,下面再按上方工序表顺序输出
  4279. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  4280. }
  4281. foreach ($byCompany as $cn => $g) {
  4282. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  4283. $lines = [];
  4284. $usedSids = [];
  4285. foreach ($orderedSids as $sid) {
  4286. if (!isset($linesMap[$sid])) {
  4287. continue;
  4288. }
  4289. $lines[] = $linesMap[$sid];
  4290. $usedSids[$sid] = true;
  4291. }
  4292. foreach ($linesMap as $sid => $ln) {
  4293. if (isset($usedSids[$sid])) {
  4294. continue;
  4295. }
  4296. $lines[] = $ln;
  4297. }
  4298. $total = count($lines);
  4299. $quoted = 0;
  4300. $groupTotal = 0.0;
  4301. $groupHasTotal = false;
  4302. if ($quoteVisible) {
  4303. foreach ($lines as $ln) {
  4304. $am = trim((string)($ln['amount'] ?? ''));
  4305. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  4306. $quoted++;
  4307. }
  4308. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  4309. $groupTotal += (float)$ln['subtotal_num'];
  4310. $groupHasTotal = true;
  4311. }
  4312. }
  4313. }
  4314. unset($byCompany[$cn]['lines_map']);
  4315. $byCompany[$cn]['lines'] = $lines;
  4316. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  4317. $byCompany[$cn]['line_count'] = $total;
  4318. $byCompany[$cn]['has_total'] = $total > 0;
  4319. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  4320. $this->finalizeSupplierRemarkDisplay($byCompany[$cn], $orderMbz, $quoteVisible);
  4321. }
  4322. $groups = array_values($byCompany);
  4323. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  4324. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  4325. }
  4326. /**
  4327. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  4328. *
  4329. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  4330. * @return array<int, array<string, mixed>>
  4331. */
  4332. protected function loadConfirmSupplierPickGroups(array $bundle): array
  4333. {
  4334. $sids = [];
  4335. $poIdMap = [];
  4336. foreach ($bundle['pos'] ?? [] as $po) {
  4337. if (!is_array($po)) {
  4338. continue;
  4339. }
  4340. $sid = (int)($po['scydgy_id'] ?? 0);
  4341. if ($this->isValidScydgyRowId($sid)) {
  4342. $sids[$sid] = true;
  4343. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  4344. }
  4345. }
  4346. if ($sids === []) {
  4347. return [];
  4348. }
  4349. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  4350. $orderMbz = $this->resolveBundleOrderMbz($bundle);
  4351. $orderDeadlineMap = $this->buildBundleOrderDeliveryDeadlineMap($bundle);
  4352. $gymcMap = [];
  4353. $ccydhBySid = [];
  4354. $qtyBySid = [];
  4355. $ceilingBySid = [];
  4356. $extraSids = [];
  4357. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  4358. if (!is_array($mr)) {
  4359. continue;
  4360. }
  4361. $gid = $this->extractScydgyRowId($mr);
  4362. if ($this->isValidScydgyRowId($gid)) {
  4363. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  4364. $dh = trim((string)($mr['CCYDH'] ?? ''));
  4365. if ($dh !== '') {
  4366. $ccydhBySid[$gid] = $dh;
  4367. }
  4368. $qtyBySid[$gid] = $this->resolveProcuremenThisQuantity($mr);
  4369. $ceilingBySid[$gid] = $this->resolveProcuremenCeilingPrice($mr);
  4370. }
  4371. }
  4372. foreach ($bundle['pos'] ?? [] as $po) {
  4373. if (!is_array($po)) {
  4374. continue;
  4375. }
  4376. $gid = (int)($po['scydgy_id'] ?? 0);
  4377. if ($this->isValidScydgyRowId($gid)) {
  4378. $nm = trim((string)($po['CGYMC'] ?? ''));
  4379. if ($nm !== '') {
  4380. $gymcMap[$gid] = $nm;
  4381. }
  4382. $dh = trim((string)($po['CCYDH'] ?? ''));
  4383. if ($dh !== '' && empty($ccydhBySid[$gid])) {
  4384. $ccydhBySid[$gid] = $dh;
  4385. }
  4386. if (!isset($qtyBySid[$gid]) || trim((string)$qtyBySid[$gid]) === '') {
  4387. $qtyBySid[$gid] = $this->resolveProcuremenThisQuantity($po);
  4388. }
  4389. if (!isset($ceilingBySid[$gid]) || trim((string)$ceilingBySid[$gid]) === '') {
  4390. $ceilingBySid[$gid] = $this->resolveProcuremenCeilingPrice($po);
  4391. }
  4392. $extraSids[] = $gid;
  4393. }
  4394. }
  4395. // 与上方工序表一致:按订单号升序排供应商明细行
  4396. $orderedSids = $this->orderedScydgyIdsLikeProcessDisplay(
  4397. is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [],
  4398. $extraSids
  4399. );
  4400. try {
  4401. $details = Db::table('purchase_order_detail')
  4402. ->where('scydgy_id', 'in', array_keys($sids))
  4403. ->order('company_name', 'asc')
  4404. ->order('id', 'asc')
  4405. ->select();
  4406. } catch (\Throwable $e) {
  4407. try {
  4408. $details = Db::table('purchase_order_detail')
  4409. ->where('scydgy_id', 'in', array_keys($sids))
  4410. ->order('company_name', 'asc')
  4411. ->order('ID', 'asc')
  4412. ->select();
  4413. } catch (\Throwable $e2) {
  4414. $details = [];
  4415. }
  4416. }
  4417. if (!is_array($details)) {
  4418. $details = [];
  4419. }
  4420. $byCompany = [];
  4421. foreach ($details as $d) {
  4422. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  4423. continue;
  4424. }
  4425. $cn = trim((string)($d['company_name'] ?? ''));
  4426. if ($cn === '') {
  4427. continue;
  4428. }
  4429. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  4430. $sid = (int)($d['scydgy_id'] ?? 0);
  4431. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  4432. continue;
  4433. }
  4434. if (!isset($byCompany[$cn])) {
  4435. $ph = trim((string)($d['phone'] ?? ''));
  4436. $username = trim((string)($d['username'] ?? ''));
  4437. if ($username === '') {
  4438. $username = $this->resolveCustomerContactName($ph, $cn);
  4439. }
  4440. $byCompany[$cn] = [
  4441. 'name' => $cn,
  4442. 'email' => trim((string)($d['email'] ?? '')),
  4443. 'phone' => $ph,
  4444. 'username' => $username,
  4445. 'remark' => '',
  4446. 'pick_lines' => [],
  4447. 'detail_picks' => [],
  4448. ];
  4449. }
  4450. if ($byCompany[$cn]['remark'] === '') {
  4451. $rm = '';
  4452. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  4453. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  4454. $rm = trim((string)$d[$rk]);
  4455. break;
  4456. }
  4457. }
  4458. if ($rm !== '') {
  4459. $byCompany[$cn]['remark'] = $rm;
  4460. }
  4461. }
  4462. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  4463. $ccydhLine = trim((string)($ccydhBySid[$sid] ?? ''));
  4464. $processName = $this->buildSupplierProcessNameFields($ccydhLine, $gymc);
  4465. $am = trim((string)($d['amount'] ?? ''));
  4466. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  4467. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  4468. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  4469. if ($deliveryShow === '' && $deliveryRaw !== '') {
  4470. $deliveryShow = $deliveryRaw;
  4471. }
  4472. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  4473. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  4474. $subtotal = null;
  4475. if ($amountNum !== null) {
  4476. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  4477. }
  4478. $unitPriceText = $amountFilled
  4479. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  4480. : '未填写';
  4481. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  4482. $leadFilled = ($leadDays !== null);
  4483. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  4484. $pickLine = array_merge($processName, [
  4485. 'scydgy_id' => $sid,
  4486. 'This_quantity' => (string)($qtyBySid[$sid] ?? ''),
  4487. 'ceilingPrice' => (string)($ceilingBySid[$sid] ?? ''),
  4488. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  4489. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  4490. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  4491. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  4492. 'order_delivery_deadline' => $orderDeadlineMap[$ccydhLine] ?? '',
  4493. 'amount_filled' => $amountFilled,
  4494. 'delivery_filled' => $deliveryFilled,
  4495. 'unit_price_text' => $unitPriceText,
  4496. 'lead_days' => $leadFilled ? $leadDays : '',
  4497. 'lead_days_filled' => $leadFilled,
  4498. 'lead_days_show' => $leadText,
  4499. 'lead_days_text' => $leadText,
  4500. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  4501. 'subtotal_num' => $subtotal,
  4502. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  4503. 'is_quoted' => $amountFilled,
  4504. ]);
  4505. if (!$quoteVisible) {
  4506. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  4507. }
  4508. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  4509. $byCompany[$cn]['detail_picks'][$sid] = [
  4510. 'scydgy_id' => $sid,
  4511. 'detail_id' => $detailId,
  4512. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  4513. 'cgymc' => $processName['cgymc'],
  4514. 'ccydh' => $processName['ccydh'],
  4515. ];
  4516. }
  4517. $out = [];
  4518. foreach ($byCompany as $g) {
  4519. $pickLinesMap = $g['pick_lines'] ?? [];
  4520. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  4521. continue;
  4522. }
  4523. $pickLines = [];
  4524. $usedLineSids = [];
  4525. foreach ($orderedSids as $sid) {
  4526. if (!isset($pickLinesMap[$sid])) {
  4527. continue;
  4528. }
  4529. $pickLines[] = $pickLinesMap[$sid];
  4530. $usedLineSids[$sid] = true;
  4531. }
  4532. foreach ($pickLinesMap as $sid => $ln) {
  4533. if (isset($usedLineSids[$sid])) {
  4534. continue;
  4535. }
  4536. $pickLines[] = $ln;
  4537. }
  4538. $groupTotal = 0.0;
  4539. $groupHasTotal = false;
  4540. if ($quoteVisible) {
  4541. foreach ($pickLines as $ln) {
  4542. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  4543. $groupTotal += (float)$ln['subtotal_num'];
  4544. $groupHasTotal = true;
  4545. }
  4546. }
  4547. }
  4548. $lineCount = count($pickLines);
  4549. $g['pick_lines'] = $pickLines;
  4550. $g['line_count'] = $lineCount;
  4551. $g['has_total'] = $lineCount > 0;
  4552. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  4553. $this->finalizeSupplierRemarkDisplay($g, $orderMbz, $quoteVisible);
  4554. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  4555. $detailPicks = [];
  4556. $usedPickSids = [];
  4557. foreach ($orderedSids as $sid) {
  4558. if (!isset($detailPicksMap[$sid])) {
  4559. continue;
  4560. }
  4561. $detailPicks[] = $detailPicksMap[$sid];
  4562. $usedPickSids[$sid] = true;
  4563. }
  4564. foreach ($detailPicksMap as $sid => $dp) {
  4565. if (isset($usedPickSids[$sid])) {
  4566. continue;
  4567. }
  4568. $detailPicks[] = $dp;
  4569. }
  4570. $g['detail_picks'] = $detailPicks;
  4571. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  4572. unset($g['detail_picks']);
  4573. $out[] = $g;
  4574. }
  4575. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  4576. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  4577. }
  4578. /**
  4579. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  4580. * @return array<int, int[]> scydgy_id => detail_id[]
  4581. */
  4582. protected function mapDetailIdsByScydgyId(array $details): array
  4583. {
  4584. $out = [];
  4585. foreach ($details as $d) {
  4586. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  4587. continue;
  4588. }
  4589. $sid = (int)($d['scydgy_id'] ?? 0);
  4590. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  4591. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  4592. continue;
  4593. }
  4594. if (!isset($out[$sid])) {
  4595. $out[$sid] = [];
  4596. }
  4597. $out[$sid][] = $pk;
  4598. }
  4599. foreach ($out as $sid => $ids) {
  4600. $out[$sid] = array_values(array_unique($ids));
  4601. }
  4602. return $out;
  4603. }
  4604. /**
  4605. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  4606. *
  4607. * @param array<string, mixed> $dbRow
  4608. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  4609. */
  4610. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  4611. {
  4612. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  4613. $r = [
  4614. 'ID' => $sid,
  4615. 'scydgy_id' => $sid,
  4616. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  4617. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  4618. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  4619. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  4620. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  4621. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  4622. 'CDW' => $dbRow['CDW'] ?? '',
  4623. 'czlyq' => $dbRow['czlyq'] ?? '',
  4624. 'NGZL' => $dbRow['NGZL'] ?? '',
  4625. 'CDF' => $dbRow['CDF'] ?? '',
  4626. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  4627. 'MBZ' => $dbRow['MBZ'] ?? '',
  4628. 'bwjg' => $dbRow['bwjg'] ?? '',
  4629. 'iStatus' => $dbRow['iStatus'] ?? '',
  4630. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  4631. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  4632. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  4633. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  4634. 'dStamp' => $dbRow['dStamp'] ?? '',
  4635. 'pick_time' => $dbRow['pick_time'] ?? '',
  4636. 'order_batch_no' => $this->resolveProcuremenOrderBatchNo($dbRow),
  4637. ];
  4638. $r['This_quantity'] = $this->resolveProcuremenThisQuantity($r);
  4639. $r['ceilingPrice'] = $this->resolveProcuremenCeilingPrice($r);
  4640. if ($sid > 0 && isset($dStampMap[$sid])) {
  4641. $t = trim((string)$dStampMap[$sid]);
  4642. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  4643. $r['dStamp'] = $dStampMap[$sid];
  4644. }
  4645. }
  4646. $dsOut = trim((string)($r['dStamp'] ?? ''));
  4647. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  4648. $ct = $dbRow['createtime'];
  4649. if (is_numeric($ct) && (int)$ct > 946684800) {
  4650. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  4651. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  4652. $r['dStamp'] = trim($ct);
  4653. }
  4654. }
  4655. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  4656. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  4657. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  4658. $fallback = trim((string)($r['dStamp'] ?? ''));
  4659. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  4660. $r['dputrecord'] = $fallback;
  4661. }
  4662. }
  4663. if (array_key_exists('id', $dbRow)) {
  4664. $r['purchase_order_id'] = (int)$dbRow['id'];
  4665. }
  4666. if ($sid < 0) {
  4667. $r['_is_manual'] = 1;
  4668. }
  4669. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  4670. $pickOut = trim((string)($r['pick_time'] ?? ''));
  4671. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  4672. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  4673. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  4674. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  4675. $r['pick_time'] = $pickFallback;
  4676. break;
  4677. }
  4678. }
  4679. }
  4680. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  4681. if ($pickNm !== '') {
  4682. $r['pick_company_name'] = $pickNm;
  4683. $r['picked_supplier_name'] = $pickNm;
  4684. }
  4685. // 列表开标状态依赖此字段:有批次号时只认本行/合并行,必须从库带出
  4686. $r['manual_pick'] = ((int)($dbRow['manual_pick'] ?? 0) === 1) ? 1 : 0;
  4687. $r['wflow_status'] = trim((string)($dbRow['wflow_status'] ?? ''));
  4688. $r['order_status_text'] = ProcuremenStatus::orderStatusLabelForList($r['wflow_status']);
  4689. if (array_key_exists('status', $dbRow)) {
  4690. $r['status'] = $dbRow['status'];
  4691. }
  4692. return $r;
  4693. }
  4694. /**
  4695. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  4696. *
  4697. * @return array<int, array<string, mixed>>
  4698. */
  4699. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  4700. {
  4701. $pool = [];
  4702. if (!is_array($dbRows) || $dbRows === []) {
  4703. return $pool;
  4704. }
  4705. $dStampMap = [];
  4706. $sidList = [];
  4707. foreach ($dbRows as $tmpRow) {
  4708. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  4709. $sid = (int)$tmpRow['scydgy_id'];
  4710. if ($sid > 0) {
  4711. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  4712. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  4713. $sidList[$sid] = true;
  4714. }
  4715. }
  4716. }
  4717. }
  4718. if ($sidList !== []) {
  4719. try {
  4720. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  4721. } catch (\Throwable $e) {
  4722. $dStampMap = [];
  4723. }
  4724. }
  4725. foreach ($dbRows as $dbRow) {
  4726. if (!is_array($dbRow)) {
  4727. continue;
  4728. }
  4729. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  4730. }
  4731. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  4732. $needCcydh = [];
  4733. foreach ($pool as $row) {
  4734. if (!is_array($row)) {
  4735. continue;
  4736. }
  4737. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  4738. continue;
  4739. }
  4740. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  4741. if ($ccydh !== '') {
  4742. $needCcydh[$ccydh] = true;
  4743. }
  4744. }
  4745. if ($needCcydh !== []) {
  4746. $czMap = [];
  4747. try {
  4748. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  4749. } catch (\Throwable $e) {
  4750. $czMap = [];
  4751. }
  4752. if (is_array($czMap) && $czMap !== []) {
  4753. foreach ($pool as &$row) {
  4754. if (!is_array($row)) {
  4755. continue;
  4756. }
  4757. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  4758. continue;
  4759. }
  4760. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  4761. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  4762. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  4763. }
  4764. }
  4765. unset($row);
  4766. }
  4767. }
  4768. return $pool;
  4769. }
  4770. /**
  4771. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  4772. *
  4773. * @param int[] $scydgyIds
  4774. * @return array<int, array<string, mixed>>
  4775. */
  4776. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  4777. {
  4778. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4779. if ($scydgyIds === []) {
  4780. return [];
  4781. }
  4782. try {
  4783. $list = Db::table('purchase_order_detail')
  4784. ->where('scydgy_id', 'in', $scydgyIds)
  4785. ->field('scydgy_id,company_name,amount,delivery')
  4786. ->select();
  4787. } catch (\Throwable $e) {
  4788. $list = [];
  4789. }
  4790. return is_array($list) ? $list : [];
  4791. }
  4792. /**
  4793. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  4794. *
  4795. * @param int[] $scydgyIds
  4796. * @param array<int, array<string, mixed>> $allRows
  4797. * @return array{cnt:int, amt:int, deliv:int}
  4798. */
  4799. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  4800. {
  4801. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4802. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4803. if ($scydgyIds === [] || $allRows === []) {
  4804. return $out;
  4805. }
  4806. $idSet = array_flip($scydgyIds);
  4807. $all = [];
  4808. $withAmt = [];
  4809. $withDeliv = [];
  4810. foreach ($allRows as $r) {
  4811. if (!is_array($r)) {
  4812. continue;
  4813. }
  4814. $sid = (int)($r['scydgy_id'] ?? 0);
  4815. if (!isset($idSet[$sid])) {
  4816. continue;
  4817. }
  4818. $cn = trim((string)($r['company_name'] ?? ''));
  4819. if ($cn === '') {
  4820. continue;
  4821. }
  4822. $all[$cn] = true;
  4823. $am = $r['amount'] ?? null;
  4824. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  4825. $withAmt[$cn] = true;
  4826. }
  4827. $dv = $r['delivery'] ?? null;
  4828. if ($dv !== null && trim((string)$dv) !== '') {
  4829. $withDeliv[$cn] = true;
  4830. }
  4831. }
  4832. return [
  4833. 'cnt' => count($all),
  4834. 'amt' => count($withAmt),
  4835. 'deliv' => count($withDeliv),
  4836. ];
  4837. }
  4838. /**
  4839. * 本次数量:优先 This_quantity,空则回退工作量 NGZL(与下发/确认/审批弹窗一致)
  4840. *
  4841. * @param array<string, mixed> $row
  4842. */
  4843. protected function resolveProcuremenThisQuantity(array $row): string
  4844. {
  4845. $q = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  4846. if ($q !== '') {
  4847. return $q;
  4848. }
  4849. $ngzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  4850. if (!is_scalar($ngzl)) {
  4851. return '';
  4852. }
  4853. $s = trim((string)$ngzl);
  4854. if ($s === '') {
  4855. return '';
  4856. }
  4857. if (is_numeric($s) && (float)$s === 0.0) {
  4858. return '';
  4859. }
  4860. return $s;
  4861. }
  4862. /**
  4863. * @param array<string, mixed> $row
  4864. */
  4865. protected function resolveProcuremenCeilingPrice(array $row): string
  4866. {
  4867. return trim((string)($row['ceilingPrice'] ?? $row['ceiling_price'] ?? ''));
  4868. }
  4869. /**
  4870. * 多工序数量/限价拼接:跳过空值,避免出现「、10」「304、」
  4871. *
  4872. * @param array<int, mixed> $parts
  4873. */
  4874. protected function joinProcuremenNonEmpty(array $parts, string $sep = '、'): string
  4875. {
  4876. $out = [];
  4877. foreach ($parts as $p) {
  4878. $s = trim((string)$p);
  4879. if ($s !== '') {
  4880. $out[] = $s;
  4881. }
  4882. }
  4883. return $out === [] ? '' : implode($sep, $out);
  4884. }
  4885. /**
  4886. * 确认/审批列表:合并行按各工序同步本次数量、最高限价(顿号间隔)
  4887. *
  4888. * @param array<int, array<string, mixed>> $rows
  4889. */
  4890. protected function syncCollapsedOrderQtyPriceForList(array &$rows): void
  4891. {
  4892. if ($rows === []) {
  4893. return;
  4894. }
  4895. $idList = [];
  4896. foreach ($rows as $rw) {
  4897. if (!is_array($rw)) {
  4898. continue;
  4899. }
  4900. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4901. foreach ($rw['_order_merge_rows'] as $mr) {
  4902. if (!is_array($mr)) {
  4903. continue;
  4904. }
  4905. $mid = (int)($mr['ID'] ?? 0);
  4906. if ($this->isValidScydgyRowId($mid)) {
  4907. $idList[$mid] = true;
  4908. }
  4909. }
  4910. }
  4911. $id = (int)($rw['ID'] ?? 0);
  4912. if ($this->isValidScydgyRowId($id)) {
  4913. $idList[$id] = true;
  4914. }
  4915. }
  4916. if ($idList === []) {
  4917. return;
  4918. }
  4919. try {
  4920. $list = Db::table('purchase_order')
  4921. ->where('scydgy_id', 'in', array_keys($idList))
  4922. ->field('scydgy_id,This_quantity,ceilingPrice,NGZL,pick_company_name')
  4923. ->select();
  4924. } catch (\Throwable $e) {
  4925. return;
  4926. }
  4927. if (!is_array($list)) {
  4928. return;
  4929. }
  4930. $byId = [];
  4931. foreach ($list as $dbRow) {
  4932. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4933. continue;
  4934. }
  4935. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4936. }
  4937. foreach ($rows as &$rw) {
  4938. if (!is_array($rw)) {
  4939. continue;
  4940. }
  4941. $mergeRows = [];
  4942. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4943. $mergeRows = $rw['_order_merge_rows'];
  4944. } else {
  4945. $mergeRows = [$rw];
  4946. }
  4947. $qtyList = [];
  4948. $priceList = [];
  4949. $picked = '';
  4950. foreach ($mergeRows as $mr) {
  4951. if (!is_array($mr)) {
  4952. continue;
  4953. }
  4954. $sid = (int)($mr['ID'] ?? 0);
  4955. $db = ($sid !== 0 && isset($byId[$sid])) ? $byId[$sid] : null;
  4956. $src = $mr;
  4957. if (is_array($db)) {
  4958. $qDb = trim((string)($db['This_quantity'] ?? $db['this_quantity'] ?? ''));
  4959. $pDb = trim((string)($db['ceilingPrice'] ?? $db['ceiling_price'] ?? ''));
  4960. $ngzlDb = $db['NGZL'] ?? $db['ngzl'] ?? null;
  4961. if ($qDb !== '') {
  4962. $src['This_quantity'] = $qDb;
  4963. }
  4964. if ($pDb !== '') {
  4965. $src['ceilingPrice'] = $pDb;
  4966. }
  4967. if ($ngzlDb !== null && trim((string)$ngzlDb) !== '') {
  4968. $src['NGZL'] = $ngzlDb;
  4969. }
  4970. if ($picked === '') {
  4971. $picked = trim((string)($db['pick_company_name'] ?? ''));
  4972. }
  4973. }
  4974. if ($picked === '') {
  4975. $picked = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  4976. }
  4977. $qtyList[] = $this->resolveProcuremenThisQuantity($src);
  4978. $priceList[] = $this->resolveProcuremenCeilingPrice($src);
  4979. }
  4980. $rw['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  4981. $rw['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  4982. if ($picked !== '') {
  4983. $rw['pick_company_name'] = $picked;
  4984. $rw['picked_supplier_name'] = $picked;
  4985. }
  4986. }
  4987. unset($rw);
  4988. }
  4989. /**
  4990. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  4991. *
  4992. * @param int[] $scydgyIds
  4993. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  4994. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  4995. */
  4996. protected function OrderDetailSummary(array $scydgyIds)
  4997. {
  4998. $out = [];
  4999. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  5000. if ($scydgyIds === []) {
  5001. return $out;
  5002. }
  5003. $list = [];
  5004. try {
  5005. $list = Db::table('purchase_order_detail')
  5006. ->where('scydgy_id', 'in', $scydgyIds)
  5007. ->field('id,scydgy_id,amount,delivery')
  5008. ->select();
  5009. } catch (\Throwable $e) {
  5010. $list = [];
  5011. }
  5012. if (!is_array($list)) {
  5013. return $out;
  5014. }
  5015. foreach ($list as $r) {
  5016. if (!is_array($r)) {
  5017. continue;
  5018. }
  5019. $ids = (int)($r['scydgy_id'] ?? 0);
  5020. if (!$this->isValidScydgyRowId($ids)) {
  5021. continue;
  5022. }
  5023. if (!isset($out[$ids])) {
  5024. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  5025. }
  5026. $out[$ids]['cnt']++;
  5027. $am = $r['amount'] ?? null;
  5028. if ($am !== null && $am !== '') {
  5029. if (!(is_string($am) && trim($am) === '')) {
  5030. $out[$ids]['amt']++;
  5031. }
  5032. }
  5033. $dv = $r['delivery'] ?? null;
  5034. if ($dv !== null && trim((string)$dv) !== '') {
  5035. $out[$ids]['deliv']++;
  5036. }
  5037. }
  5038. return $out;
  5039. }
  5040. /**
  5041. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  5042. *
  5043. * @return array
  5044. */
  5045. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  5046. {
  5047. $strContains = function ($haystack, $needle) {
  5048. if ($needle === '') {
  5049. return false;
  5050. }
  5051. $haystack = (string)$haystack;
  5052. if (function_exists('mb_stripos')) {
  5053. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  5054. }
  5055. return stripos($haystack, $needle) !== false;
  5056. };
  5057. $stripAlias = function ($f) {
  5058. return preg_replace('/^[ab]\./i', '', (string)$f);
  5059. };
  5060. $searchColNames = [];
  5061. foreach (explode(',', $this->searchFields) as $colRaw) {
  5062. $c = $stripAlias(trim($colRaw));
  5063. if ($c !== '') {
  5064. $searchColNames[] = $c;
  5065. }
  5066. }
  5067. // 等值条件先行(表头下拉),减少后续日期解析量
  5068. $eqFilters = [];
  5069. $otherFilters = [];
  5070. foreach ($filterArr as $fk => $fv) {
  5071. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  5072. continue;
  5073. }
  5074. if (is_array($fv)) {
  5075. continue;
  5076. }
  5077. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  5078. continue;
  5079. }
  5080. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  5081. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  5082. $field = $stripAlias($fk);
  5083. if ($sym === '=' || $sym === '') {
  5084. $eqFilters[$field] = trim((string)$fv);
  5085. } else {
  5086. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  5087. }
  5088. }
  5089. $ymTarget = '';
  5090. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  5091. $ymTarget = $ymM[1];
  5092. }
  5093. $filtered = [];
  5094. foreach ($pool as $r) {
  5095. if (!is_array($r)) {
  5096. continue;
  5097. }
  5098. foreach ($eqFilters as $field => $fv) {
  5099. if (trim((string)($r[$field] ?? '')) !== $fv) {
  5100. continue 2;
  5101. }
  5102. }
  5103. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  5104. // 初选池不应含手工单;若混入则直接剔除
  5105. if ($isManual) {
  5106. continue;
  5107. }
  5108. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  5109. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  5110. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  5111. continue;
  5112. }
  5113. if ($applyMonthRange) {
  5114. $mo = (int)$m[2];
  5115. if ($mo < 1 || $mo > 12) {
  5116. continue;
  5117. }
  5118. if ($ymTarget !== '') {
  5119. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  5120. if ($ymRow !== $ymTarget) {
  5121. continue;
  5122. }
  5123. } else {
  5124. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  5125. $rowMonthStart = $ymRow . '-01 00:00:00';
  5126. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  5127. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  5128. continue;
  5129. }
  5130. }
  5131. }
  5132. if ($search !== '') {
  5133. $hitSearch = false;
  5134. foreach ($searchColNames as $c) {
  5135. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  5136. if ($cell !== '' && $strContains($cell, $search)) {
  5137. $hitSearch = true;
  5138. break;
  5139. }
  5140. }
  5141. if (!$hitSearch) {
  5142. continue;
  5143. }
  5144. }
  5145. foreach ($otherFilters as $item) {
  5146. $fv = $item['fv'];
  5147. $sym = $item['sym'];
  5148. $field = $item['field'];
  5149. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  5150. $cellStr = trim((string)$cell);
  5151. switch ($sym) {
  5152. case '<>':
  5153. if ((string)$cell === (string)$fv) {
  5154. continue 3;
  5155. }
  5156. break;
  5157. case 'LIKE':
  5158. case 'NOT LIKE':
  5159. $needle = trim((string)$fv);
  5160. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  5161. if ($sym === 'LIKE' && !$hit) {
  5162. continue 3;
  5163. }
  5164. if ($sym === 'NOT LIKE' && $hit) {
  5165. continue 3;
  5166. }
  5167. break;
  5168. case 'BETWEEN':
  5169. case 'RANGE':
  5170. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  5171. if (count($parts) < 2) {
  5172. $parts = is_string($fv) ? explode(',', $fv) : [];
  5173. }
  5174. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  5175. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  5176. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  5177. continue 3;
  5178. }
  5179. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  5180. continue 3;
  5181. }
  5182. break;
  5183. case '>':
  5184. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  5185. continue 3;
  5186. }
  5187. break;
  5188. case '>=':
  5189. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  5190. continue 3;
  5191. }
  5192. break;
  5193. case '<':
  5194. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  5195. continue 3;
  5196. }
  5197. break;
  5198. case '<=':
  5199. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  5200. continue 3;
  5201. }
  5202. break;
  5203. default:
  5204. if ((string)$cell !== (string)$fv) {
  5205. continue 3;
  5206. }
  5207. break;
  5208. }
  5209. }
  5210. $filtered[] = $r;
  5211. }
  5212. return $filtered;
  5213. }
  5214. /**
  5215. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  5216. */
  5217. public function snapshotToProcure()
  5218. {
  5219. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5220. $this->error(__('Invalid parameters'));
  5221. }
  5222. $row = json_decode($this->request->post('row_json', ''), true);
  5223. if (!is_array($row)) {
  5224. $this->error(__('Invalid parameters'));
  5225. }
  5226. try {
  5227. $ids = $this->extractScydgyRowId($row);
  5228. if (!$this->isValidScydgyRowId($ids)) {
  5229. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  5230. }
  5231. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5232. $data = $this->normalizePurchaseOrderWritePayload([
  5233. 'scydgy_id' => $ids,
  5234. 'CCYDH' => $row['CCYDH'] ?? null,
  5235. 'CYJMC' => $row['CYJMC'] ?? null,
  5236. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  5237. 'CDXMC' => $row['CDXMC'] ?? null,
  5238. 'CGYBH' => $row['CGYBH'] ?? null,
  5239. 'CGYMC' => $row['CGYMC'] ?? null,
  5240. 'CDW' => $row['CDW'] ?? null,
  5241. 'czlyq' => $row['czlyq'] ?? null,
  5242. 'NGZL' => $row['NGZL'] ?? null,
  5243. 'CDF' => $row['CDF'] ?? null,
  5244. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  5245. 'MBZ' => $row['MBZ'] ?? null,
  5246. 'bwjg' => $row['bwjg'] ?? null,
  5247. 'iStatus' => $row['iStatus'] ?? null,
  5248. 'dStamp' => $row['dStamp'] ?? null,
  5249. 'dputrecord' => $row['dputrecord'] ?? null,
  5250. 'cywyxm' => $row['cywyxm'] ?? null,
  5251. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  5252. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  5253. ], $row);
  5254. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  5255. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  5256. $mbzSnap = trim((string)($data['MBZ'] ?? ''));
  5257. if (!$exists && $qtySnap === '' && $priceSnap === '' && $mbzSnap === '') {
  5258. $this->success('操作成功');
  5259. return;
  5260. }
  5261. if ($exists) {
  5262. $upd = $data;
  5263. unset($upd['scydgy_id'], $upd['status']);
  5264. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  5265. } else {
  5266. // 新增:不写 status(空/走库默认);仅写创建时间
  5267. $data['createtime'] = date('Y-m-d H:i:s');
  5268. Db::table('purchase_order')->insert($data);
  5269. }
  5270. } catch (\Throwable $e) {
  5271. $this->error($e->getMessage());
  5272. }
  5273. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  5274. $this->success('操作成功');
  5275. }
  5276. /**
  5277. * 未发列表
  5278. * 「完结」或「仅保存本次数量/最高限价/备注」:有则改、无则插
  5279. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  5280. */
  5281. public function completeDirectly()
  5282. {
  5283. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5284. $this->error(__('参数错误'));
  5285. }
  5286. if (!$this->procuremenCanComplete()) {
  5287. $this->error(__('You have no permission'));
  5288. }
  5289. $row = json_decode($this->request->post('row_json', ''), true);
  5290. if (!is_array($row)) {
  5291. $this->error(__('Invalid parameters'));
  5292. }
  5293. $finishRaw = $this->request->post('finish', '1');
  5294. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  5295. $poIdLog = null;
  5296. try {
  5297. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  5298. $ids = $this->extractScydgyRowId($row);
  5299. if (!$this->isValidScydgyRowId($ids)) {
  5300. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  5301. }
  5302. if ($asComplete) {
  5303. $this->assertPickRowCanComplete($ids, $row);
  5304. }
  5305. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5306. $data = $this->normalizePurchaseOrderWritePayload([
  5307. 'scydgy_id' => $ids,
  5308. 'CCYDH' => $row['CCYDH'] ?? null,
  5309. 'CYJMC' => $row['CYJMC'] ?? null,
  5310. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  5311. 'CDXMC' => $row['CDXMC'] ?? null,
  5312. 'CGYBH' => $row['CGYBH'] ?? null,
  5313. 'CGYMC' => $row['CGYMC'] ?? null,
  5314. 'CDW' => $row['CDW'] ?? null,
  5315. 'czlyq' => $row['czlyq'] ?? null,
  5316. 'NGZL' => $row['NGZL'] ?? null,
  5317. 'CDF' => $row['CDF'] ?? null,
  5318. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  5319. 'MBZ' => $row['MBZ'] ?? null,
  5320. 'bwjg' => $row['bwjg'] ?? null,
  5321. 'iStatus' => $row['iStatus'] ?? null,
  5322. 'dStamp' => $row['dStamp'] ?? null,
  5323. 'dputrecord' => $row['dputrecord'] ?? null,
  5324. 'cywyxm' => $row['cywyxm'] ?? null,
  5325. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  5326. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  5327. ], $row);
  5328. if ($asComplete) {
  5329. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  5330. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  5331. }
  5332. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  5333. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  5334. $mbzCd = trim((string)($data['MBZ'] ?? ''));
  5335. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '' && $mbzCd === '') {
  5336. $this->success('操作成功');
  5337. return;
  5338. }
  5339. if ($exists) {
  5340. $upd = $data;
  5341. unset($upd['scydgy_id']);
  5342. if (!$asComplete) {
  5343. unset($upd['status']);
  5344. }
  5345. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  5346. } else {
  5347. // 新增:不写 status;完结时 $data 已含 status=1
  5348. $data['createtime'] = date('Y-m-d H:i:s');
  5349. Db::table('purchase_order')->insert($data);
  5350. }
  5351. } catch (\Throwable $e) {
  5352. $this->error($e->getMessage());
  5353. }
  5354. try {
  5355. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5356. if (is_array($rpo)) {
  5357. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  5358. $poIdLog = $tid > 0 ? $tid : null;
  5359. }
  5360. } catch (\Throwable $e) {
  5361. $poIdLog = null;
  5362. }
  5363. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  5364. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  5365. if ($asComplete) {
  5366. $this->addOrderLog(
  5367. $ids,
  5368. 'mark_complete',
  5369. '点击「完结」,已标记为已完结',
  5370. $poIdLog
  5371. );
  5372. try {
  5373. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  5374. if ($pdfPublicPath === '') {
  5375. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  5376. }
  5377. } catch (\Throwable $e) {
  5378. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  5379. }
  5380. } else {
  5381. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  5382. $mbz = isset($data['MBZ']) ? trim((string)$data['MBZ']) : '';
  5383. $parts = [];
  5384. if ($q !== '') {
  5385. $parts[] = ($gymc !== '' ? ($gymc . '本次数量') : '本次数量') . '「' . $q . '」';
  5386. } elseif ($gymc !== '') {
  5387. // 仅改限价/备注时仍带工序名便于辨认
  5388. $parts[] = $gymc;
  5389. }
  5390. if ($p !== '') {
  5391. $parts[] = '最高限价「' . $p . '」';
  5392. }
  5393. if ($mbz !== '') {
  5394. $parts[] = '招标备注「' . $mbz . '」';
  5395. }
  5396. $detail = $parts !== [] ? implode(',', $parts) : '(未改数量/限价/招标备注)';
  5397. $this->addOrderLog(
  5398. $ids,
  5399. 'save_qty_price',
  5400. '保存本次数量、最高限价、招标备注:' . $detail,
  5401. $poIdLog
  5402. );
  5403. }
  5404. $this->pickHiddenScydgySetCache = null;
  5405. $this->success("操作成功");
  5406. }
  5407. /**
  5408. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价、备注(若表中有对应列)
  5409. *
  5410. * @param array<int, array> $rows 引用传递当前页行
  5411. */
  5412. protected function mergePurchaseOrder(array &$rows)
  5413. {
  5414. if ($rows === []) {
  5415. return;
  5416. }
  5417. $ids = [];
  5418. foreach ($rows as $rw) {
  5419. if (!is_array($rw)) {
  5420. continue;
  5421. }
  5422. $id = (int)($rw['ID'] ?? 0);
  5423. // 含手工新增负数 scydgy_id,避免限价/数量不同步
  5424. if ($this->isValidScydgyRowId($id)) {
  5425. $ids[$id] = true;
  5426. }
  5427. }
  5428. $idList = array_keys($ids);
  5429. if ($idList === []) {
  5430. return;
  5431. }
  5432. try {
  5433. $list = Db::table('purchase_order')
  5434. ->where('scydgy_id', 'in', $idList)
  5435. ->field('scydgy_id,This_quantity,ceilingPrice,MBZ')
  5436. ->select();
  5437. } catch (\Throwable $e) {
  5438. return;
  5439. }
  5440. if (!is_array($list)) {
  5441. return;
  5442. }
  5443. $byId = [];
  5444. foreach ($list as $dbRow) {
  5445. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  5446. continue;
  5447. }
  5448. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  5449. }
  5450. foreach ($rows as &$rw) {
  5451. if (!is_array($rw)) {
  5452. continue;
  5453. }
  5454. $sid = (int)($rw['ID'] ?? 0);
  5455. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  5456. continue;
  5457. }
  5458. $db = $byId[$sid];
  5459. // 有 purchase_order 记录时同步数量/限价/备注(含清空后的空串,避免刷新后又冒出来)
  5460. if (array_key_exists('This_quantity', $db)) {
  5461. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  5462. }
  5463. if (array_key_exists('ceilingPrice', $db)) {
  5464. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  5465. } elseif (array_key_exists('ceiling_price', $db)) {
  5466. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  5467. }
  5468. if (array_key_exists('MBZ', $db)) {
  5469. $poMbz = $db['MBZ'] === null ? '' : trim((string)$db['MBZ']);
  5470. if ($poMbz !== '') {
  5471. $rw['MBZ'] = $poMbz;
  5472. }
  5473. }
  5474. }
  5475. unset($rw);
  5476. }
  5477. /**
  5478. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  5479. */
  5480. public function purchaseConfirmPick()
  5481. {
  5482. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5483. $this->error(__('Invalid parameters'));
  5484. }
  5485. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  5486. $this->error(__('You have no permission'));
  5487. }
  5488. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  5489. if ($batchRaw !== '') {
  5490. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  5491. return;
  5492. }
  5493. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5494. $sid = (int)$scydgyId;
  5495. if (!$this->isValidScydgyRowId($sid)) {
  5496. $this->error('参数无效');
  5497. }
  5498. $parseIdList = function ($raw) {
  5499. if (is_array($raw)) {
  5500. $arr = $raw;
  5501. } else {
  5502. $decoded = json_decode((string)$raw, true);
  5503. $arr = is_array($decoded) ? $decoded : [];
  5504. }
  5505. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  5506. };
  5507. $selectedRaw = $this->request->post('selected_ids', null);
  5508. if ($selectedRaw === null || $selectedRaw === '') {
  5509. $legacy = (int)$this->request->post('selected_id', 0);
  5510. $selectedIds = $legacy > 0 ? [$legacy] : [];
  5511. } else {
  5512. $selectedIds = $parseIdList($selectedRaw);
  5513. }
  5514. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  5515. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  5516. try {
  5517. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  5518. } catch (\InvalidArgumentException $e) {
  5519. $this->error($e->getMessage());
  5520. } catch (\Throwable $e) {
  5521. $this->error($e->getMessage());
  5522. }
  5523. $this->pickHiddenScydgySetCache = null;
  5524. $this->success('操作成功', '', $result);
  5525. }
  5526. /**
  5527. * 整单采购确认(多道工序一次提交)
  5528. */
  5529. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  5530. {
  5531. $decoded = json_decode($batchRaw, true);
  5532. if (!is_array($decoded) || $decoded === []) {
  5533. $this->error('提交数据无效');
  5534. }
  5535. $picks = [];
  5536. foreach ($decoded as $item) {
  5537. if (!is_array($item)) {
  5538. continue;
  5539. }
  5540. $sid = (int)($item['scydgy_id'] ?? 0);
  5541. if (!$this->isValidScydgyRowId($sid)) {
  5542. continue;
  5543. }
  5544. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  5545. if (!is_array($sel)) {
  5546. $sel = [(int)$sel];
  5547. }
  5548. $unsel = $item['unselected_ids'] ?? [];
  5549. if (!is_array($unsel)) {
  5550. $unsel = json_decode((string)$unsel, true);
  5551. $unsel = is_array($unsel) ? $unsel : [];
  5552. }
  5553. $picks[] = [
  5554. 'scydgy_id' => $sid,
  5555. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  5556. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  5557. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  5558. ];
  5559. }
  5560. if ($picks === []) {
  5561. $this->error('提交数据无效');
  5562. }
  5563. Db::startTrans();
  5564. $results = [];
  5565. try {
  5566. foreach ($picks as $pick) {
  5567. $results[] = $this->runPurchaseConfirmPick(
  5568. (int)$pick['scydgy_id'],
  5569. $pick['selected_ids'],
  5570. $pick['unselected_ids'],
  5571. (int)$pick['purchase_order_id'],
  5572. false,
  5573. false
  5574. );
  5575. }
  5576. Db::commit();
  5577. } catch (\Throwable $e) {
  5578. Db::rollback();
  5579. $msg = $e->getMessage();
  5580. $this->error($msg !== '' ? $msg : '提交失败');
  5581. }
  5582. try {
  5583. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  5584. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  5585. } catch (\Throwable $e) {
  5586. Log::write('采购确认通知批量发送异常: ' . $e->getMessage(), 'error');
  5587. }
  5588. $this->pickHiddenScydgySetCache = null;
  5589. $this->success('操作成功', '', ['batch' => $results]);
  5590. }
  5591. /**
  5592. * @return array<string, mixed>
  5593. */
  5594. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  5595. {
  5596. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  5597. ProcuremenGuard::assertWflowPendingApproval($poRow);
  5598. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  5599. $scydgyId = (string)$sid;
  5600. if ($selectedIds === []) {
  5601. throw new \InvalidArgumentException('请至少勾选一条明细');
  5602. }
  5603. $inter = array_intersect($selectedIds, $unselectedIds);
  5604. if ($inter !== []) {
  5605. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  5606. }
  5607. $allIds = $this->purchaseOrderDetail($sid);
  5608. if ($allIds === []) {
  5609. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  5610. }
  5611. foreach ($selectedIds as $id) {
  5612. if (!in_array($id, $allIds, true)) {
  5613. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  5614. }
  5615. }
  5616. foreach ($unselectedIds as $id) {
  5617. if (!in_array($id, $allIds, true)) {
  5618. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  5619. }
  5620. }
  5621. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  5622. sort($union, SORT_NUMERIC);
  5623. $expect = $allIds;
  5624. sort($expect, SORT_NUMERIC);
  5625. if ($union !== $expect) {
  5626. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  5627. }
  5628. if ($manageTransaction) {
  5629. Db::startTrans();
  5630. }
  5631. try {
  5632. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  5633. $aff = 0;
  5634. try {
  5635. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  5636. } catch (\Throwable $e) {
  5637. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  5638. }
  5639. if ($aff < 1) {
  5640. throw new \Exception('更新选中状态失败');
  5641. }
  5642. $poPayload = [
  5643. // 审核通过后进入「待入库评分」;合格/不合格后才置已完结
  5644. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5645. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  5646. ];
  5647. if ($purchaseOrderId > 0) {
  5648. $poAff = (int)Db::table('purchase_order')
  5649. ->where('id', $purchaseOrderId)
  5650. ->where('scydgy_id', $sid)
  5651. ->update($poPayload);
  5652. if ($poAff < 1) {
  5653. throw new \Exception('主表订单不存在或与工序行不匹配');
  5654. }
  5655. } else {
  5656. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  5657. if ($poAff < 1) {
  5658. throw new \Exception('未找到');
  5659. }
  5660. }
  5661. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  5662. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  5663. if ($manageTransaction) {
  5664. Db::commit();
  5665. }
  5666. } catch (\Throwable $e) {
  5667. if ($manageTransaction) {
  5668. Db::rollback();
  5669. }
  5670. throw $e;
  5671. }
  5672. $poIdFinal = $purchaseOrderId;
  5673. if ($poIdFinal <= 0) {
  5674. try {
  5675. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  5676. if (is_array($rpo)) {
  5677. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  5678. }
  5679. } catch (\Throwable $e) {
  5680. $poIdFinal = 0;
  5681. }
  5682. }
  5683. $pickNames = [];
  5684. foreach ($selectedIds as $pid) {
  5685. $dr = $this->purchaseOrderDetai($sid, $pid);
  5686. $nm = trim((string)($dr['company_name'] ?? ''));
  5687. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  5688. }
  5689. $this->addOrderLog(
  5690. $sid,
  5691. 'purchase_confirm',
  5692. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  5693. $poIdFinal > 0 ? $poIdFinal : null
  5694. );
  5695. if ($sendNotifications) {
  5696. try {
  5697. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  5698. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  5699. 'scydgy_id' => $sid,
  5700. 'selected_ids' => $selectedIds,
  5701. 'unselected_ids' => $unselectedIds,
  5702. 'purchase_order_id' => $purchaseOrderId,
  5703. ]]);
  5704. } catch (\Throwable $e) {
  5705. Log::write('采购确认通知发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  5706. }
  5707. }
  5708. Log::write(sprintf(
  5709. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  5710. $scydgyId,
  5711. $purchaseOrderId,
  5712. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  5713. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  5714. ), 'notice');
  5715. $pdfPublicPath = '';
  5716. try {
  5717. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  5718. } catch (\Throwable $e) {
  5719. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  5720. }
  5721. return [
  5722. 'scydgy_id' => $scydgyId,
  5723. 'purchase_order_id' => $purchaseOrderId,
  5724. 'selected_ids' => $selectedIds,
  5725. 'unselected_ids' => $unselectedIds,
  5726. 'purchase_confirm_pdf' => $pdfPublicPath,
  5727. ];
  5728. }
  5729. /**
  5730. * 审批通过短信:按本次涉及的工序汇总 process_lines
  5731. *
  5732. * @param int[]|string[] $scydgyIds
  5733. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  5734. */
  5735. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  5736. {
  5737. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  5738. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  5739. if ($scydgyIds === []) {
  5740. return $empty;
  5741. }
  5742. $pos = [];
  5743. try {
  5744. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  5745. } catch (\Throwable $e) {
  5746. $rows = [];
  5747. }
  5748. if (is_array($rows)) {
  5749. foreach ($rows as $po) {
  5750. if (is_array($po)) {
  5751. $pos[] = $po;
  5752. }
  5753. }
  5754. }
  5755. if ($pos === []) {
  5756. return $empty;
  5757. }
  5758. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  5759. return [
  5760. 'ccydh' => $ccydh,
  5761. 'pos' => $pos,
  5762. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  5763. ];
  5764. }
  5765. /**
  5766. * 审批通过/未通过:短信 + 邮件(同一供应商只发一条;邮件含平台链接)
  5767. *
  5768. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  5769. * @param array<int, array<string, mixed>> $picks
  5770. */
  5771. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  5772. {
  5773. if ($picks === []) {
  5774. return;
  5775. }
  5776. $this->ensureConfirmResultEmailTemplates();
  5777. $fallbackDetailId = 0;
  5778. $winners = [];
  5779. $losers = [];
  5780. foreach ($picks as $pick) {
  5781. if (!is_array($pick)) {
  5782. continue;
  5783. }
  5784. $sid = (int)($pick['scydgy_id'] ?? 0);
  5785. if (!$this->isValidScydgyRowId($sid)) {
  5786. continue;
  5787. }
  5788. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  5789. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  5790. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  5791. $fallbackDetailId = (int)$selectedIds[0];
  5792. }
  5793. foreach ($selectedIds as $pid) {
  5794. $dr = $this->purchaseOrderDetai($sid, $pid);
  5795. if (!is_array($dr)) {
  5796. continue;
  5797. }
  5798. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  5799. }
  5800. foreach ($unselectedIds as $pid) {
  5801. $dr = $this->purchaseOrderDetai($sid, $pid);
  5802. if (!is_array($dr)) {
  5803. continue;
  5804. }
  5805. $key = $this->notifySupplierDedupeKey($dr);
  5806. if (!isset($winners[$key])) {
  5807. $losers[$key] = $dr;
  5808. }
  5809. }
  5810. }
  5811. if ($winners === [] && $losers === []) {
  5812. return;
  5813. }
  5814. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  5815. $poIdLog = 0;
  5816. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5817. if (isset($pos[0]) && is_array($pos[0])) {
  5818. $poIdLog = (int)($pos[0]['id'] ?? 0);
  5819. }
  5820. $mergeRowsLog = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  5821. $emailLogCcydh = $this->collectCcydhListForEmailLog($mergeRowsLog, $pos);
  5822. $emailLogBatchNo = $this->resolveBundleOrderBatchNo($bundle);
  5823. $sendSmsSafe = function ($phone, $content) {
  5824. $phone = trim((string)$phone);
  5825. if ($phone === '') {
  5826. return;
  5827. }
  5828. try {
  5829. $this->smsbao($phone, $content);
  5830. } catch (\Throwable $e) {
  5831. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  5832. }
  5833. };
  5834. $sendConfirmEmailSafe = function (array $dr, string $emailScene) use ($confirmNotifyVars, $poIdLog, $emailLogCcydh, $emailLogBatchNo) {
  5835. $cname = trim((string)($dr['company_name'] ?? ''));
  5836. $ph = trim((string)($dr['phone'] ?? ''));
  5837. $toEmail = trim((string)($dr['email'] ?? ''));
  5838. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5839. Log::write('采购确认邮件跳过:无有效邮箱 company=' . $cname, 'error');
  5840. return;
  5841. }
  5842. $detailId = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5843. if ($detailId <= 0) {
  5844. $detailId = (int)($confirmNotifyVars['_fallback_detail_id'] ?? 0);
  5845. }
  5846. try {
  5847. $platformUrl = $this->buildMprocMobileOrderUrl($detailId);
  5848. } catch (\Throwable $e) {
  5849. Log::write('采购确认邮件链接失败: ' . $e->getMessage(), 'error');
  5850. $platformUrl = '';
  5851. }
  5852. $vars = array_merge($confirmNotifyVars, [
  5853. 'company_name' => $cname,
  5854. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5855. 'phone' => $ph,
  5856. 'email' => $toEmail,
  5857. 'platform_url' => $platformUrl,
  5858. ]);
  5859. unset($vars['_fallback_detail_id']);
  5860. try {
  5861. $mailPlain = $this->renderNotifyTemplate($emailScene, $vars);
  5862. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  5863. $mailSubject = $this->resolveProcuremenEmailSubject($emailScene);
  5864. $mailConfig = $this->loadMailerConfig();
  5865. $this->issueSendSupplierEmail([
  5866. 'company_name' => $cname,
  5867. 'email' => $toEmail,
  5868. 'mail_plain' => $mailPlain,
  5869. 'mail_body' => $mailBody,
  5870. 'notify_vars' => $vars,
  5871. 'sms_content' => '',
  5872. 'detail_links' => $platformUrl !== '' ? [['url' => $platformUrl, 'cgymc' => '']] : [],
  5873. 'email_log_scene' => (strpos((string)$emailScene, 'confirm_ok') !== false) ? 'confirm_ok' : 'confirm_fail',
  5874. 'email_log_scydgy_id' => (int)($dr['scydgy_id'] ?? 0),
  5875. 'email_log_purchase_order_id' => $poIdLog,
  5876. 'email_log_ccydh' => $emailLogCcydh !== '' ? $emailLogCcydh : trim((string)($vars['ccydh'] ?? '')),
  5877. 'email_log_order_batch_no' => $emailLogBatchNo,
  5878. ], $mailConfig, $mailSubject);
  5879. } catch (\Throwable $e) {
  5880. Log::write('采购确认邮件失败 company=' . $cname . ' email=' . $toEmail . ' ' . $e->getMessage(), 'error');
  5881. }
  5882. };
  5883. $confirmNotifyVars['_fallback_detail_id'] = $fallbackDetailId;
  5884. foreach ($winners as $dr) {
  5885. $cname = trim((string)($dr['company_name'] ?? ''));
  5886. $ph = trim((string)($dr['phone'] ?? ''));
  5887. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  5888. 'company_name' => $cname,
  5889. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5890. 'phone' => $ph,
  5891. ]));
  5892. $sendSmsSafe($ph, $sms);
  5893. $sendConfirmEmailSafe($dr, 'confirm_ok_email');
  5894. }
  5895. foreach ($losers as $dr) {
  5896. $cname = trim((string)($dr['company_name'] ?? ''));
  5897. $ph = trim((string)($dr['phone'] ?? ''));
  5898. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  5899. 'company_name' => $cname,
  5900. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5901. 'phone' => $ph,
  5902. ]));
  5903. $sendSmsSafe($ph, $sms);
  5904. $sendConfirmEmailSafe($dr, 'confirm_fail_email');
  5905. }
  5906. }
  5907. /**
  5908. * 短信去重键:优先手机号,否则公司名
  5909. */
  5910. protected function notifySupplierDedupeKey(array $detailRow): string
  5911. {
  5912. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  5913. if ($ph !== '') {
  5914. return 'p:' . $ph;
  5915. }
  5916. $cn = trim((string)($detailRow['company_name'] ?? ''));
  5917. return 'c:' . $cn;
  5918. }
  5919. /**
  5920. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  5921. *
  5922. * @param int[] $detailIds
  5923. */
  5924. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  5925. {
  5926. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  5927. if ($detailIds === []) {
  5928. return;
  5929. }
  5930. $payload = ['status_name' => $statusName];
  5931. try {
  5932. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  5933. } catch (\Throwable $e) {
  5934. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  5935. }
  5936. }
  5937. /**
  5938. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  5939. */
  5940. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  5941. {
  5942. try {
  5943. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  5944. } catch (\Throwable $e) {
  5945. return;
  5946. }
  5947. if (!is_array($rows)) {
  5948. return;
  5949. }
  5950. foreach ($rows as $dr) {
  5951. if (!is_array($dr)) {
  5952. continue;
  5953. }
  5954. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5955. if ($id <= 0) {
  5956. continue;
  5957. }
  5958. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  5959. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  5960. try {
  5961. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  5962. } catch (\Throwable $e) {
  5963. }
  5964. }
  5965. }
  5966. /**
  5967. * @param array<string, mixed> $detailRow
  5968. */
  5969. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  5970. {
  5971. $am = $detailRow['amount'] ?? null;
  5972. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  5973. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  5974. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  5975. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  5976. }
  5977. /**
  5978. * @return int[]
  5979. */
  5980. protected function purchaseOrderDetail(int $scydgyId): array
  5981. {
  5982. if (!$this->isValidScydgyRowId($scydgyId)) {
  5983. return [];
  5984. }
  5985. try {
  5986. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  5987. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  5988. $list = $listQuery->select();
  5989. } catch (\Throwable $e) {
  5990. return [];
  5991. }
  5992. if (!is_array($list)) {
  5993. return [];
  5994. }
  5995. $ids = [];
  5996. foreach ($list as $r) {
  5997. if (!is_array($r)) {
  5998. continue;
  5999. }
  6000. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  6001. if ($pk > 0) {
  6002. $ids[] = $pk;
  6003. }
  6004. }
  6005. return array_values(array_unique($ids));
  6006. }
  6007. /**
  6008. * 获取当前登录用户信息 [id, 展示名]
  6009. * admin_name 一律记「名称」(昵称),无昵称再回退账号
  6010. */
  6011. protected function GetUseName(): array
  6012. {
  6013. $id = 0;
  6014. $name = '';
  6015. try {
  6016. if ($this->auth && $this->auth->isLogin()) {
  6017. $u = $this->auth->getUserInfo();
  6018. if (is_array($u)) {
  6019. $id = (int)($u['id'] ?? 0);
  6020. $name = trim((string)($u['nickname'] ?? ''));
  6021. // 会话昵称缺失或等于登录账号时,再查库取正式昵称
  6022. $sessionUser = trim((string)($u['username'] ?? ''));
  6023. if ($id > 0 && ($name === '' || ($sessionUser !== '' && strcasecmp($name, $sessionUser) === 0))) {
  6024. try {
  6025. $row = Db::name('admin')->where('id', $id)->field('nickname,username')->find();
  6026. if (is_array($row)) {
  6027. $nick = trim((string)($row['nickname'] ?? ''));
  6028. if ($nick !== '') {
  6029. $name = $nick;
  6030. } elseif ($name === '') {
  6031. $name = trim((string)($row['username'] ?? ''));
  6032. }
  6033. }
  6034. } catch (\Throwable $e) {
  6035. }
  6036. }
  6037. if ($name === '') {
  6038. $name = $sessionUser;
  6039. }
  6040. }
  6041. }
  6042. } catch (\Throwable $e) {
  6043. }
  6044. if ($name === '') {
  6045. $name = '未知用户';
  6046. }
  6047. return [$id, $name];
  6048. }
  6049. /**
  6050. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  6051. */
  6052. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  6053. {
  6054. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  6055. }
  6056. /**
  6057. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  6058. *
  6059. * @param array<int, array<string, mixed>> $rows
  6060. */
  6061. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  6062. {
  6063. $sidList = [];
  6064. foreach ($rows as $rw) {
  6065. if (!is_array($rw)) {
  6066. continue;
  6067. }
  6068. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  6069. foreach ($rw['_order_merge_rows'] as $mr) {
  6070. $mid = (int)($mr['ID'] ?? 0);
  6071. if ($this->isValidScydgyRowId($mid)) {
  6072. $sidList[$mid] = true;
  6073. }
  6074. }
  6075. }
  6076. $id = (int)($rw['ID'] ?? 0);
  6077. if ($this->isValidScydgyRowId($id)) {
  6078. $sidList[$id] = true;
  6079. }
  6080. }
  6081. $sids = array_keys($sidList);
  6082. $issueBySid = [];
  6083. $confirmBySid = [];
  6084. $approveBySid = [];
  6085. if ($sids !== []) {
  6086. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  6087. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  6088. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  6089. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  6090. try {
  6091. $logs = Db::table('purchase_order_oper_log')
  6092. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  6093. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  6094. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  6095. ->order('id', 'asc')
  6096. ->select();
  6097. } catch (\Throwable $e) {
  6098. $logs = [];
  6099. }
  6100. if (is_array($logs)) {
  6101. $issueSet = array_fill_keys($issueActs, true);
  6102. $confirmSet = array_fill_keys($confirmActs, true);
  6103. $approveSet = array_fill_keys($approveActs, true);
  6104. foreach ($logs as $lg) {
  6105. if (!is_array($lg)) {
  6106. continue;
  6107. }
  6108. $lg = ProcuremenOperLog::normalizeRow($lg);
  6109. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  6110. if ($sid === 0) {
  6111. continue;
  6112. }
  6113. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  6114. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  6115. if ($t === '') {
  6116. continue;
  6117. }
  6118. if (isset($issueSet[$action])) {
  6119. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  6120. $issueBySid[$sid] = $t;
  6121. }
  6122. }
  6123. if (isset($confirmSet[$action])) {
  6124. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  6125. $confirmBySid[$sid] = $t;
  6126. }
  6127. }
  6128. if (isset($approveSet[$action])) {
  6129. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  6130. $approveBySid[$sid] = $t;
  6131. }
  6132. }
  6133. }
  6134. }
  6135. }
  6136. foreach ($rows as &$rw) {
  6137. if (!is_array($rw)) {
  6138. continue;
  6139. }
  6140. $mergeSids = [];
  6141. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  6142. foreach ($rw['_order_merge_rows'] as $mr) {
  6143. $mid = (int)($mr['ID'] ?? 0);
  6144. if ($this->isValidScydgyRowId($mid)) {
  6145. $mergeSids[] = $mid;
  6146. }
  6147. }
  6148. }
  6149. $rid = (int)($rw['ID'] ?? 0);
  6150. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  6151. $mergeSids[] = $rid;
  6152. }
  6153. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  6154. $issue = $pick;
  6155. $confirm = '';
  6156. $approve = '';
  6157. foreach ($mergeSids as $sid) {
  6158. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  6159. $issue = $issueBySid[$sid];
  6160. }
  6161. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  6162. $confirm = $confirmBySid[$sid];
  6163. }
  6164. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  6165. $approve = $approveBySid[$sid];
  6166. }
  6167. }
  6168. if ($issue === '' && $pick !== '') {
  6169. $issue = $pick;
  6170. }
  6171. $rw['issue_time'] = $issue;
  6172. $rw['confirm_time'] = $confirm;
  6173. $rw['approve_time'] = $approve;
  6174. }
  6175. unset($rw);
  6176. }
  6177. /**
  6178. * 按主键取一条
  6179. */
  6180. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  6181. {
  6182. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  6183. return [];
  6184. }
  6185. try {
  6186. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  6187. if (is_array($one)) {
  6188. return $one;
  6189. }
  6190. } catch (\Throwable $e) {
  6191. }
  6192. try {
  6193. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  6194. if (is_array($one)) {
  6195. return $one;
  6196. }
  6197. } catch (\Throwable $e) {
  6198. }
  6199. return [];
  6200. }
  6201. /**
  6202. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  6203. */
  6204. protected function formatProcuremenDetailTime($v): string
  6205. {
  6206. return ProcuremenFormat::detailTime($v);
  6207. }
  6208. /**
  6209. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  6210. */
  6211. protected function formatDeliveryYmd($v): string
  6212. {
  6213. return ProcuremenFormat::deliveryYmd($v);
  6214. }
  6215. /**
  6216. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  6217. */
  6218. protected function detailRowSupplierOperated(array $r): bool
  6219. {
  6220. $am = $r['amount'] ?? null;
  6221. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  6222. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  6223. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  6224. return $okAmt || $okDel;
  6225. }
  6226. /**
  6227. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  6228. */
  6229. protected function resolveDetailSupplierOperTime(array $r): string
  6230. {
  6231. if (!$this->detailRowSupplierOperated($r)) {
  6232. return '';
  6233. }
  6234. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  6235. if ($t !== '') {
  6236. return $t;
  6237. }
  6238. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  6239. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  6240. continue;
  6241. }
  6242. $t = $this->formatProcuremenDetailTime($r[$col]);
  6243. if ($t !== '') {
  6244. return $t;
  6245. }
  6246. }
  6247. return '';
  6248. }
  6249. /**
  6250. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  6251. */
  6252. protected function detailRowSupplierAccepted(array $r): bool
  6253. {
  6254. $am = $r['amount'] ?? null;
  6255. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  6256. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  6257. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  6258. return $okAmt && $okDel;
  6259. }
  6260. /**
  6261. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  6262. */
  6263. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  6264. {
  6265. if ($detailCount > 0) {
  6266. return true;
  6267. }
  6268. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  6269. return true;
  6270. }
  6271. $pickTime = trim((string)($main['pick_time'] ?? ''));
  6272. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  6273. return true;
  6274. }
  6275. return false;
  6276. }
  6277. /**
  6278. * 下发时间:优先 pick_time,其次首条下发明细时间
  6279. */
  6280. protected function resolveProcuremenIssueTime(array $main, array $details): string
  6281. {
  6282. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  6283. if ($issueTime !== '') {
  6284. return $issueTime;
  6285. }
  6286. foreach ($details as $dr) {
  6287. if (!is_array($dr)) {
  6288. continue;
  6289. }
  6290. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  6291. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  6292. $issueTime = $t;
  6293. }
  6294. }
  6295. if ($issueTime !== '') {
  6296. return $issueTime;
  6297. }
  6298. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  6299. }
  6300. /**
  6301. * 直接点「完结」时间:优先操作记录 mark_complete
  6302. */
  6303. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  6304. {
  6305. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  6306. }
  6307. /**
  6308. * 操作记录时间(取指定 action 最近一条)
  6309. *
  6310. * @param string|array<int, string> $actions
  6311. */
  6312. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  6313. {
  6314. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  6315. }
  6316. /**
  6317. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  6318. *
  6319. * @param array $main purchase_order 一行
  6320. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  6321. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  6322. */
  6323. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  6324. {
  6325. $issueCnt = count($details);
  6326. $acceptCnt = 0;
  6327. $pickedName = '';
  6328. $pickedTime = '';
  6329. foreach ($details as $dr) {
  6330. if (!is_array($dr)) {
  6331. continue;
  6332. }
  6333. if ($this->detailRowSupplierAccepted($dr)) {
  6334. $acceptCnt++;
  6335. }
  6336. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  6337. if ($pickedName === '') {
  6338. $pickedName = trim((string)($dr['company_name'] ?? ''));
  6339. }
  6340. if ($pickedTime === '') {
  6341. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  6342. if ($pickedTime === '') {
  6343. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  6344. }
  6345. }
  6346. }
  6347. }
  6348. $hasMain = $main !== [];
  6349. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  6350. if ($poTime === '') {
  6351. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  6352. }
  6353. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  6354. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  6355. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  6356. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  6357. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  6358. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  6359. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  6360. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  6361. $inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
  6362. $inboundResult = '';
  6363. if ($scydgyId > 0) {
  6364. try {
  6365. $inRow = Db::table('purchase_order_inbound_score')
  6366. ->where('scydgy_id', $scydgyId)
  6367. ->field('result,updatetime,createtime')
  6368. ->find();
  6369. } catch (\Throwable $e) {
  6370. $inRow = null;
  6371. }
  6372. if (is_array($inRow) && $inRow !== []) {
  6373. $inboundResult = trim((string)($inRow['result'] ?? ''));
  6374. if ($inboundScoreTime === '') {
  6375. $inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
  6376. }
  6377. }
  6378. }
  6379. $inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
  6380. $supplierTime = '';
  6381. if ($acceptCnt > 0) {
  6382. foreach ($details as $dr) {
  6383. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  6384. continue;
  6385. }
  6386. $t = $this->resolveDetailSupplierOperTime($dr);
  6387. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  6388. $supplierTime = $t;
  6389. }
  6390. }
  6391. }
  6392. $directComplete = ($mainCompleted && !$issued);
  6393. $doneTime = '';
  6394. if ($mainCompleted) {
  6395. if ($directComplete) {
  6396. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  6397. }
  6398. if ($doneTime === '' && $inboundScoreTime !== '') {
  6399. $doneTime = $inboundScoreTime;
  6400. }
  6401. if ($doneTime === '') {
  6402. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  6403. }
  6404. if ($doneTime === '') {
  6405. foreach ($details as $dr) {
  6406. if (!is_array($dr)) {
  6407. continue;
  6408. }
  6409. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  6410. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  6411. $doneTime = $t;
  6412. }
  6413. }
  6414. }
  6415. if ($doneTime === '') {
  6416. $doneTime = $poTime;
  6417. }
  6418. // 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
  6419. if ($doneTime === '' && $confirmApproveTime !== '') {
  6420. $doneTime = $confirmApproveTime;
  6421. }
  6422. }
  6423. if ($directComplete) {
  6424. // 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
  6425. $step1Done = $hasMain;
  6426. $step2Done = false;
  6427. $step3Done = false;
  6428. $step4Done = false;
  6429. $step5Done = false;
  6430. $stepInboundDone = $inboundScored;
  6431. $step6Done = $mainCompleted && $inboundScored;
  6432. } else {
  6433. $step1Done = $issued;
  6434. $step2Done = $issued;
  6435. $step3Done = $acceptCnt > 0;
  6436. $step4Done = $wflowPendingApproval;
  6437. if (!$step4Done) {
  6438. foreach ($details as $dr) {
  6439. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  6440. $step4Done = true;
  6441. break;
  6442. }
  6443. }
  6444. }
  6445. $step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
  6446. $stepInboundDone = $inboundScored;
  6447. // 未确认合格/不合格时,「已完结」保持未点亮(灰色)
  6448. $step6Done = $mainCompleted && $inboundScored;
  6449. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  6450. if ($mainCompleted && $issued) {
  6451. $step3Done = true;
  6452. $step4Done = true;
  6453. $step5Done = true;
  6454. // 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
  6455. if ($supplierTime === '') {
  6456. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6457. if ($fillT !== '') {
  6458. $supplierTime = $fillT;
  6459. }
  6460. }
  6461. if ($pickedTime === '') {
  6462. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6463. if ($fillT !== '') {
  6464. $pickedTime = $fillT;
  6465. }
  6466. }
  6467. if ($auditSelectTime === '') {
  6468. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6469. if ($fillT !== '') {
  6470. $auditSelectTime = $fillT;
  6471. }
  6472. }
  6473. if ($confirmApproveTime === '') {
  6474. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  6475. if ($fillT !== '') {
  6476. $confirmApproveTime = $fillT;
  6477. }
  6478. }
  6479. }
  6480. }
  6481. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  6482. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  6483. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  6484. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  6485. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  6486. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  6487. $inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
  6488. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  6489. $deadlineLines = [];
  6490. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  6491. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  6492. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  6493. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  6494. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  6495. }
  6496. }
  6497. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  6498. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  6499. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  6500. if ($deliveryDisp === '') {
  6501. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  6502. }
  6503. if ($deliveryDisp !== '') {
  6504. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  6505. }
  6506. }
  6507. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  6508. $deadlineText = implode("\n", $deadlineLines);
  6509. $prefixOperTime = static function (string $t): string {
  6510. $t = trim($t);
  6511. if ($t === '' || $t === '—') {
  6512. return $t;
  6513. }
  6514. if (strpos($t, '操作时间') === 0) {
  6515. return $t;
  6516. }
  6517. return '操作时间:' . $t;
  6518. };
  6519. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  6520. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  6521. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
  6522. $stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  6523. $step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  6524. $steps = [
  6525. [
  6526. 'title' => '未发',
  6527. 'subtitle' => '',
  6528. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  6529. 'done' => $step1Done,
  6530. ],
  6531. [
  6532. 'title' => '下发',
  6533. 'subtitle' => $deadlineText,
  6534. 'time' => $prefixOperTime($step2Time),
  6535. 'done' => $step2Done,
  6536. ],
  6537. [
  6538. 'title' => '供应商接单',
  6539. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  6540. 'time' => '',
  6541. 'done' => $step3Done,
  6542. ],
  6543. [
  6544. 'title' => '待确认',
  6545. 'subtitle' => $step4Done
  6546. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  6547. : ($issued ? '待选供应商' : ''),
  6548. 'time' => $prefixOperTime($step4Time),
  6549. 'done' => $step4Done,
  6550. ],
  6551. [
  6552. 'title' => '待审批',
  6553. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  6554. 'time' => $prefixOperTime($step5Time),
  6555. 'done' => $step5Done,
  6556. ],
  6557. [
  6558. 'title' => '是否合格',
  6559. 'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
  6560. 'time' => $prefixOperTime($stepInboundTime),
  6561. 'done' => $stepInboundDone,
  6562. ],
  6563. [
  6564. 'title' => '已完结',
  6565. 'subtitle' => '',
  6566. 'time' => $prefixOperTime($step6Time),
  6567. 'done' => $step6Done,
  6568. ],
  6569. ];
  6570. $currentIdx = count($steps) - 1;
  6571. if ($directComplete) {
  6572. // 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
  6573. if (!$step6Done) {
  6574. foreach ($steps as $i => $s) {
  6575. if (($s['title'] ?? '') === '是否合格') {
  6576. $currentIdx = $i;
  6577. break;
  6578. }
  6579. }
  6580. }
  6581. } else {
  6582. foreach ($steps as $i => $s) {
  6583. if (!$s['done']) {
  6584. $currentIdx = $i;
  6585. break;
  6586. }
  6587. }
  6588. }
  6589. $nSteps = count($steps);
  6590. foreach ($steps as $idx => &$s) {
  6591. $s['current'] = ($idx === $currentIdx);
  6592. if ($idx === 0) {
  6593. $s['pdf_left_bg'] = '';
  6594. } else {
  6595. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  6596. }
  6597. if ($idx >= $nSteps - 1) {
  6598. $s['pdf_right_bg'] = '';
  6599. } else {
  6600. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  6601. }
  6602. }
  6603. unset($s);
  6604. $labelMap = [
  6605. 'CCYDH' => '订单号',
  6606. 'CYJMC' => '印件名称',
  6607. 'CCLBMMC' => '承揽部门',
  6608. 'CGYMC' => '工序名称',
  6609. 'CDW' => '单位',
  6610. 'czlyq' => '类型',
  6611. 'NGZL' => '工作量',
  6612. 'CDF' => '单价',
  6613. 'cGzzxMc' => '工作中心',
  6614. 'MBZ' => '招标备注',
  6615. 'This_quantity' => '本次数量',
  6616. 'ceilingPrice' => '最高限价',
  6617. ];
  6618. $orderSummary = [];
  6619. foreach ($labelMap as $key => $lab) {
  6620. if (!array_key_exists($key, $main)) {
  6621. continue;
  6622. }
  6623. $val = $main[$key];
  6624. if ($val === null) {
  6625. $val = '';
  6626. } elseif (!is_scalar($val)) {
  6627. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  6628. } else {
  6629. $val = (string)$val;
  6630. }
  6631. $orderSummary[] = ['label' => $lab, 'value' => $val];
  6632. }
  6633. $orderSummary[] = [
  6634. 'label' => '是否合格',
  6635. 'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
  6636. ];
  6637. $orderSummaryGrid = [];
  6638. $n = count($orderSummary);
  6639. for ($i = 0; $i < $n; $i += 2) {
  6640. $left = $orderSummary[$i];
  6641. $hasRight = ($i + 1) < $n;
  6642. $orderSummaryGrid[] = [
  6643. 'l1' => $left['label'],
  6644. 'v1' => $left['value'],
  6645. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  6646. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  6647. ];
  6648. }
  6649. return [
  6650. 'steps' => $steps,
  6651. 'orderSummary' => $orderSummary,
  6652. 'orderSummaryGrid' => $orderSummaryGrid,
  6653. 'inbound_result' => $inboundResult,
  6654. 'inbound_score_time'=> $inboundScoreTime,
  6655. 'detailRows' => $details,
  6656. ];
  6657. }
  6658. /**
  6659. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  6660. *
  6661. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  6662. */
  6663. protected function prepareProcuremenDetailsView(string $ids): array
  6664. {
  6665. $main = [];
  6666. try {
  6667. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  6668. $main = is_array($one) ? $one : [];
  6669. } catch (\Throwable $e) {
  6670. $main = [];
  6671. }
  6672. $details = [];
  6673. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  6674. if ($mergeRows === []) {
  6675. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  6676. if ($mergeRows === [] && $main !== []) {
  6677. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  6678. }
  6679. }
  6680. $detailSidList = [];
  6681. $anchorSid = (int)$ids;
  6682. if ($anchorSid !== 0) {
  6683. $detailSidList[$anchorSid] = true;
  6684. }
  6685. foreach ($mergeRows as $mr) {
  6686. if (!is_array($mr)) {
  6687. continue;
  6688. }
  6689. $sid = $this->extractScydgyRowId($mr);
  6690. if ($sid !== 0) {
  6691. $detailSidList[$sid] = true;
  6692. }
  6693. }
  6694. try {
  6695. if ($detailSidList !== []) {
  6696. $details = Db::table('purchase_order_detail')
  6697. ->where('scydgy_id', 'in', array_keys($detailSidList))
  6698. ->order('id', 'asc')
  6699. ->select();
  6700. }
  6701. } catch (\Throwable $e) {
  6702. $details = [];
  6703. }
  6704. if (!is_array($details)) {
  6705. $details = [];
  6706. }
  6707. foreach ($details as &$r) {
  6708. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  6709. $r['id'] = $r['ID'];
  6710. }
  6711. if (isset($r['createtime'])) {
  6712. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  6713. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  6714. } else {
  6715. $r['createtime_text'] = (string)$r['createtime'];
  6716. }
  6717. } else {
  6718. $r['createtime_text'] = '';
  6719. }
  6720. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  6721. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  6722. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  6723. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  6724. if (is_array($r)) {
  6725. $r = $this->maskSupplierContactFields($r);
  6726. }
  6727. }
  6728. unset($r);
  6729. $activeDetails = [];
  6730. foreach ($details as $r) {
  6731. if (is_array($r) && empty($r['is_void'])) {
  6732. $activeDetails[] = $r;
  6733. }
  6734. }
  6735. $operLogs = [];
  6736. try {
  6737. $operSidList = array_keys($detailSidList);
  6738. if ($operSidList === [] && (int)$ids !== 0) {
  6739. $operSidList = [(int)$ids];
  6740. }
  6741. if ($operSidList !== []) {
  6742. $operLogs = Db::table('purchase_order_oper_log')
  6743. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  6744. ->order('id', 'asc')
  6745. ->select();
  6746. }
  6747. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  6748. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  6749. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  6750. if ($poId > 0) {
  6751. $operLogs = Db::table('purchase_order_oper_log')
  6752. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  6753. ->order('id', 'asc')
  6754. ->select();
  6755. }
  6756. }
  6757. } catch (\Throwable $e) {
  6758. $operLogs = [];
  6759. }
  6760. if (!is_array($operLogs)) {
  6761. $operLogs = [];
  6762. }
  6763. $operLogsRaw = $operLogs;
  6764. $processNameBySid = [];
  6765. foreach ($mergeRows as $mr) {
  6766. if (!is_array($mr)) {
  6767. continue;
  6768. }
  6769. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  6770. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  6771. if ($psid !== 0 && $gymc !== '') {
  6772. $processNameBySid[$psid] = $gymc;
  6773. }
  6774. }
  6775. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  6776. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
  6777. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  6778. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  6779. if ($ccydh === '') {
  6780. foreach ($details as $r) {
  6781. if (!is_array($r)) {
  6782. continue;
  6783. }
  6784. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  6785. if ($ccydh !== '') {
  6786. break;
  6787. }
  6788. }
  6789. }
  6790. $this->view->assign('ccydh', $ccydh);
  6791. $this->view->assign('steps', $bundle['steps']);
  6792. $this->view->assign('orderSummary', $bundle['orderSummary']);
  6793. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  6794. $this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
  6795. $this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
  6796. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  6797. $this->view->assign('processCount', count($mergeRows));
  6798. $orderBatchNo = $this->resolveProcuremenOrderBatchNo($main);
  6799. if ($orderBatchNo === '' && $detailSidList !== []) {
  6800. try {
  6801. $poBn = Db::table('purchase_order')
  6802. ->where('scydgy_id', 'in', array_keys($detailSidList))
  6803. ->whereRaw("TRIM(IFNULL(`order_batch_no`,'')) <> ''")
  6804. ->order('id', 'desc')
  6805. ->find();
  6806. if (is_array($poBn)) {
  6807. $orderBatchNo = $this->resolveProcuremenOrderBatchNo($poBn);
  6808. }
  6809. } catch (\Throwable $e) {
  6810. $orderBatchNo = '';
  6811. }
  6812. }
  6813. $this->view->assign('orderBatchNo', $orderBatchNo);
  6814. $this->view->assign('detailRows', $details);
  6815. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  6816. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  6817. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  6818. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  6819. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  6820. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  6821. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  6822. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  6823. $this->view->assign('operLogs', $operLogs);
  6824. $sg = $quoteView['supplier_groups'] ?? [];
  6825. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
  6826. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  6827. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
  6828. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
  6829. return [
  6830. 'ok' => $main !== [] || $details !== [],
  6831. 'ccydh' => $ccydh,
  6832. 'steps' => $bundle['steps'],
  6833. ];
  6834. }
  6835. /**
  6836. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  6837. */
  6838. public function details()
  6839. {
  6840. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6841. if (is_array($ids)) {
  6842. $ids = isset($ids[0]) ? $ids[0] : '';
  6843. }
  6844. $ids = trim((string)$ids);
  6845. if ($ids === '') {
  6846. $this->error(__('Invalid parameters'));
  6847. }
  6848. $this->assertManualOrderDetailsViewable((int)$ids);
  6849. // 已完结:打开详情时按最新进度/操作记录重存存证 PDF(含质量/交货评分)
  6850. $sid = (int)$ids;
  6851. if ($this->isValidScydgyRowId($sid)) {
  6852. try {
  6853. $poCheck = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  6854. if (is_array($poCheck) && ProcuremenStatus::isPoCompleted($poCheck['status'] ?? '')) {
  6855. $this->refreshCompletedOrderArchivePdf($sid, true);
  6856. }
  6857. } catch (\Throwable $e) {
  6858. Log::write('详情页刷新完结存证PDF失败 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'notice');
  6859. }
  6860. }
  6861. $this->prepareProcuremenDetailsView($ids);
  6862. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  6863. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  6864. $this->view->engine->layout(false);
  6865. try {
  6866. return $this->view->fetch('procuremen/details_dialog_shell');
  6867. } finally {
  6868. if ($restoreLayout) {
  6869. $this->view->engine->layout($restoreLayout);
  6870. }
  6871. }
  6872. }
  6873. /**
  6874. * 已完结订单重生成存证 PDF(与详情页一致,含质量/交货评分与「已完结」节点)
  6875. *
  6876. * @param bool $requireCompleted true 时仅已完结才重生成;false 强制按当前详情重存
  6877. * @return string 本地 web 路径或 OSS URL,失败为空串
  6878. */
  6879. protected function refreshCompletedOrderArchivePdf(int $scydgyId, bool $requireCompleted = true): string
  6880. {
  6881. if (!$this->isValidScydgyRowId($scydgyId)) {
  6882. return '';
  6883. }
  6884. try {
  6885. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6886. } catch (\Throwable $e) {
  6887. $po = null;
  6888. }
  6889. if (!is_array($po) || $po === []) {
  6890. return '';
  6891. }
  6892. if ($requireCompleted && !ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6893. return trim((string)($po['pdf_url'] ?? ''));
  6894. }
  6895. $poId = (int)($po['id'] ?? 0);
  6896. return $this->savePurchaseConfirmDetailPdf($scydgyId, $poId);
  6897. }
  6898. /**
  6899. * CLI / 手机端评分完结后调用:无后台登录态重生成存证 PDF
  6900. */
  6901. public static function regenerateArchivePdfWithoutAuth(int $scydgyId, bool $requireCompleted = true): string
  6902. {
  6903. if ((int)$scydgyId === 0) {
  6904. return '';
  6905. }
  6906. try {
  6907. $ctl = new class extends Procuremen {
  6908. public function _initialize()
  6909. {
  6910. $this->request = \think\Request::instance();
  6911. $tpl = \think\Config::get('template');
  6912. if (!is_array($tpl)) {
  6913. $tpl = [];
  6914. }
  6915. // CLI / 跨模块调用时无 admin 视图目录
  6916. $tpl['view_path'] = APP_PATH . 'admin' . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR;
  6917. $this->view = new \think\View($tpl, \think\Config::get('view_replace_str'));
  6918. $this->model = new \app\admin\model\Procuremen();
  6919. try {
  6920. ProcuremenSchema::ensureAll();
  6921. } catch (\Throwable $e) {
  6922. }
  6923. }
  6924. public function runRegen(int $sid, bool $requireCompleted): string
  6925. {
  6926. return $this->refreshCompletedOrderArchivePdf($sid, $requireCompleted);
  6927. }
  6928. };
  6929. return $ctl->runRegen($scydgyId, $requireCompleted);
  6930. } catch (\Throwable $e) {
  6931. Log::write('regenerateArchivePdfWithoutAuth 失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'error');
  6932. return '';
  6933. }
  6934. }
  6935. /**
  6936. * 解析合并下发工序行(可跨订单,且均未协助)
  6937. *
  6938. * @return array<int, array<string, mixed>>
  6939. */
  6940. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  6941. {
  6942. $primary = json_decode($rowJson, true);
  6943. if (!is_array($primary)) {
  6944. $this->error(__('Invalid parameters'));
  6945. }
  6946. $merge = json_decode($mergeRowsJson, true);
  6947. if (!is_array($merge) || $merge === []) {
  6948. $merge = [$primary];
  6949. }
  6950. $seen = [];
  6951. $out = [];
  6952. foreach ($merge as $r) {
  6953. if (!is_array($r)) {
  6954. continue;
  6955. }
  6956. $id = $this->extractScydgyRowId($r);
  6957. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  6958. continue;
  6959. }
  6960. $seen[$id] = true;
  6961. $out[] = $r;
  6962. }
  6963. if ($out === []) {
  6964. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  6965. }
  6966. // 允许多订单同批下发:不再校验订单号一致
  6967. $ids = [];
  6968. foreach ($out as $r) {
  6969. $id = $this->extractScydgyRowId($r);
  6970. if ($this->isValidScydgyRowId($id)) {
  6971. $ids[$id] = true;
  6972. }
  6973. }
  6974. $poBySid = [];
  6975. $detCntBySid = [];
  6976. if ($ids !== []) {
  6977. $idList = array_keys($ids);
  6978. try {
  6979. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  6980. if (is_array($poList)) {
  6981. foreach ($poList as $po) {
  6982. if (!is_array($po)) {
  6983. continue;
  6984. }
  6985. $sid = (int)($po['scydgy_id'] ?? 0);
  6986. if ($this->isValidScydgyRowId($sid)) {
  6987. $poBySid[$sid] = $po;
  6988. }
  6989. }
  6990. }
  6991. } catch (\Throwable $e) {
  6992. }
  6993. try {
  6994. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  6995. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  6996. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  6997. if (is_array($detRows)) {
  6998. foreach ($detRows as $dr) {
  6999. if (!is_array($dr)) {
  7000. continue;
  7001. }
  7002. $sid = (int)($dr['scydgy_id'] ?? 0);
  7003. if ($this->isValidScydgyRowId($sid)) {
  7004. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  7005. }
  7006. }
  7007. }
  7008. } catch (\Throwable $e) {
  7009. }
  7010. }
  7011. foreach ($out as $r) {
  7012. $id = $this->extractScydgyRowId($r);
  7013. if (!$this->isValidScydgyRowId($id)) {
  7014. continue;
  7015. }
  7016. $po = $poBySid[$id] ?? null;
  7017. if (!is_array($po)) {
  7018. continue;
  7019. }
  7020. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  7021. $gymc = trim((string)($r['CGYMC'] ?? ''));
  7022. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  7023. }
  7024. $detCnt = (int)($detCntBySid[$id] ?? 0);
  7025. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  7026. $gymc = trim((string)($r['CGYMC'] ?? ''));
  7027. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  7028. }
  7029. }
  7030. return $out;
  7031. }
  7032. /**
  7033. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  7034. */
  7035. protected function maskSupplierContactFields(array $item): array
  7036. {
  7037. if (array_key_exists('email', $item)) {
  7038. $item['email'] = mask_email((string)$item['email']);
  7039. }
  7040. if (array_key_exists('phone', $item)) {
  7041. $item['phone'] = mask_phone((string)$item['phone']);
  7042. }
  7043. return $item;
  7044. }
  7045. /**
  7046. * @param array<int, array<string, mixed>> $list
  7047. * @return array<int, array<string, mixed>>
  7048. */
  7049. protected function maskSupplierContactList(array $list): array
  7050. {
  7051. $out = [];
  7052. foreach ($list as $item) {
  7053. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  7054. }
  7055. return $out;
  7056. }
  7057. /**
  7058. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  7059. *
  7060. * @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
  7061. * @return array<string, string>|null
  7062. */
  7063. protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
  7064. {
  7065. if (!is_array($row)) {
  7066. return null;
  7067. }
  7068. $norm = [];
  7069. foreach ($row as $k => $v) {
  7070. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  7071. }
  7072. $row = $norm;
  7073. $st = $row['status'] ?? '';
  7074. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  7075. return null;
  7076. }
  7077. $companyName = '';
  7078. foreach (['company_name', 'name'] as $nk) {
  7079. if (!empty($row[$nk])) {
  7080. $companyName = trim((string)$row[$nk]);
  7081. break;
  7082. }
  7083. }
  7084. if ($companyName === '') {
  7085. return null;
  7086. }
  7087. $username = '';
  7088. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  7089. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  7090. $username = trim((string)$row[$uk]);
  7091. break;
  7092. }
  7093. }
  7094. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  7095. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  7096. if ($phone === '' && isset($row['account'])) {
  7097. $phone = trim((string)$row['account']);
  7098. }
  7099. if ($phone === '' && isset($row['mobile'])) {
  7100. $phone = trim((string)$row['mobile']);
  7101. }
  7102. if ($requireContactChannels && $email === '' && $phone === '') {
  7103. return null;
  7104. }
  7105. $category = '';
  7106. foreach (['company_type', 'category', 'type_name'] as $ck) {
  7107. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  7108. $category = trim((string)$row[$ck]);
  7109. break;
  7110. }
  7111. }
  7112. return [
  7113. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  7114. 'name' => $companyName,
  7115. 'company_name' => $companyName,
  7116. 'username' => $username,
  7117. 'email' => $email,
  7118. 'phone' => $phone,
  7119. 'category' => $category,
  7120. 'company_type' => $category,
  7121. 'can_select' => ($email !== '' && $phone !== '') ? 1 : 0,
  7122. ];
  7123. }
  7124. /**
  7125. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  7126. */
  7127. protected function resolveCustomerContactById(string $id): ?array
  7128. {
  7129. $id = trim($id);
  7130. if ($id === '' || !ctype_digit($id)) {
  7131. return null;
  7132. }
  7133. try {
  7134. $row = Db::table('customer')->where('id', (int)$id)->find();
  7135. } catch (\Throwable $e) {
  7136. return null;
  7137. }
  7138. return $this->buildCustomerContactPayloadFromRow($row);
  7139. }
  7140. /**
  7141. * 按供应商名称解析联系信息(兼容旧提交数据)
  7142. *
  7143. * @param bool $requireContactChannels true 时须有邮箱或手机
  7144. */
  7145. protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
  7146. {
  7147. $name = trim($name);
  7148. if ($name === '') {
  7149. return null;
  7150. }
  7151. try {
  7152. // customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
  7153. $row = Db::table('customer')
  7154. ->where('company_name', $name)
  7155. ->order('id', 'desc')
  7156. ->find();
  7157. } catch (\Throwable $e) {
  7158. return null;
  7159. }
  7160. return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
  7161. }
  7162. /**
  7163. * 规范化下发/确认时勾选的供应商
  7164. *
  7165. * @param array<int, mixed> $companies
  7166. * @return array<int, array<string, string>>
  7167. */
  7168. protected function normalizePickCompanies(array $companies): array
  7169. {
  7170. $out = [];
  7171. foreach ($companies as $c) {
  7172. if (!is_array($c)) {
  7173. continue;
  7174. }
  7175. $resolved = null;
  7176. $cid = trim((string)($c['id'] ?? ''));
  7177. if ($cid !== '') {
  7178. $resolved = $this->resolveCustomerContactById($cid);
  7179. }
  7180. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  7181. if ($resolved === null && $name !== '') {
  7182. $resolved = $this->resolveCustomerContactByCompanyName($name);
  7183. }
  7184. if ($resolved === null) {
  7185. continue;
  7186. }
  7187. $email = trim((string)($resolved['email'] ?? ''));
  7188. $phone = trim((string)($resolved['phone'] ?? ''));
  7189. // 下发须同时有邮箱和手机号(与初选弹窗可选规则一致)
  7190. if ($email === '' || $phone === '') {
  7191. continue;
  7192. }
  7193. $out[] = $resolved;
  7194. }
  7195. return $out;
  7196. }
  7197. /**
  7198. * 同一次下发批次的时间(优先 pick_time,空则 createtime)
  7199. */
  7200. protected function procuremenIssueBatchTime(array $row): string
  7201. {
  7202. $t = $this->procuremenRowListSortTime($row, 'pick_time');
  7203. if ($t !== '') {
  7204. return $t;
  7205. }
  7206. $t = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  7207. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  7208. return $t;
  7209. }
  7210. return '';
  7211. }
  7212. /**
  7213. * 读取下发批次号(兼容旧字段 issue_batch_no)
  7214. *
  7215. * @param array<string, mixed> $row
  7216. */
  7217. protected function resolveProcuremenOrderBatchNo(array $row): string
  7218. {
  7219. foreach (['order_batch_no', 'issue_batch_no'] as $k) {
  7220. $v = trim((string)($row[$k] ?? ''));
  7221. if ($v !== '') {
  7222. return $v;
  7223. }
  7224. }
  7225. return '';
  7226. }
  7227. /**
  7228. * 从订单 bundle 取下发批次号
  7229. *
  7230. * @param array{order_batch_no?:mixed,pos?:array} $bundle
  7231. */
  7232. protected function resolveBundleOrderBatchNo(array $bundle): string
  7233. {
  7234. $direct = trim((string)($bundle['order_batch_no'] ?? ''));
  7235. if ($direct !== '') {
  7236. return $direct;
  7237. }
  7238. foreach ($bundle['pos'] ?? [] as $po) {
  7239. if (!is_array($po)) {
  7240. continue;
  7241. }
  7242. $bn = $this->resolveProcuremenOrderBatchNo($po);
  7243. if ($bn !== '') {
  7244. return $bn;
  7245. }
  7246. }
  7247. return '';
  7248. }
  7249. /**
  7250. * @param int[] $sidList
  7251. * @return array<int, string> scydgy_id => MBZ
  7252. */
  7253. protected function loadScydgyMbzByIds(array $sidList): array
  7254. {
  7255. $ids = [];
  7256. foreach ($sidList as $sid) {
  7257. $sid = (int)$sid;
  7258. if ($this->isValidScydgyRowId($sid)) {
  7259. $ids[$sid] = true;
  7260. }
  7261. }
  7262. if ($ids === []) {
  7263. return [];
  7264. }
  7265. try {
  7266. $map = Db::table('scydgy')->where('ID', 'in', array_keys($ids))->column('MBZ', 'ID');
  7267. } catch (\Throwable $e) {
  7268. return [];
  7269. }
  7270. return is_array($map) ? $map : [];
  7271. }
  7272. /**
  7273. * purchase_order / 列表行 MBZ 为空时,回退 ERP 工序表 scydgy.MBZ
  7274. *
  7275. * @param array<int, array<string, mixed>> $rows
  7276. */
  7277. protected function enrichProcuremenRowsMbz(array &$rows): void
  7278. {
  7279. if ($rows === []) {
  7280. return;
  7281. }
  7282. $need = [];
  7283. foreach ($rows as $r) {
  7284. if (!is_array($r)) {
  7285. continue;
  7286. }
  7287. if (trim((string)($r['MBZ'] ?? $r['mbz'] ?? '')) !== '') {
  7288. continue;
  7289. }
  7290. $sid = $this->extractScydgyRowId($r);
  7291. if ($this->isValidScydgyRowId($sid)) {
  7292. $need[$sid] = true;
  7293. }
  7294. }
  7295. if ($need === []) {
  7296. return;
  7297. }
  7298. $mbzMap = $this->loadScydgyMbzByIds(array_keys($need));
  7299. if ($mbzMap === []) {
  7300. return;
  7301. }
  7302. foreach ($rows as &$r) {
  7303. if (!is_array($r)) {
  7304. continue;
  7305. }
  7306. if (trim((string)($r['MBZ'] ?? $r['mbz'] ?? '')) !== '') {
  7307. continue;
  7308. }
  7309. $sid = $this->extractScydgyRowId($r);
  7310. if (!$this->isValidScydgyRowId($sid) || !isset($mbzMap[$sid])) {
  7311. continue;
  7312. }
  7313. $mbz = trim((string)$mbzMap[$sid]);
  7314. if ($mbz !== '') {
  7315. $r['MBZ'] = $mbz;
  7316. }
  7317. }
  7318. unset($r);
  7319. }
  7320. /**
  7321. * 列表/弹窗合并键:优先正式批次号 order_batch_no;
  7322. * 旧数据无批次号时回退为「同一订单号 + 同一次下发时间」。
  7323. */
  7324. protected function procuremenIssueBatchGroupKey(array $row): string
  7325. {
  7326. $batchNo = $this->resolveProcuremenOrderBatchNo($row);
  7327. if ($batchNo !== '') {
  7328. return 'bn:' . $batchNo;
  7329. }
  7330. $dh = trim((string)($row['CCYDH'] ?? ''));
  7331. $sid = (int)($row['scydgy_id'] ?? $row['ID'] ?? $row['id'] ?? 0);
  7332. if ($dh === '') {
  7333. return '_id_' . $sid;
  7334. }
  7335. $batch = $this->procuremenIssueBatchTime($row);
  7336. return $batch !== '' ? ($dh . '|' . $batch) : ($dh . '|sid:' . $sid);
  7337. }
  7338. /**
  7339. * 是否同一次下发(同批次号,或旧数据同订单号且下发时间一致)
  7340. */
  7341. protected function isSameProcuremenIssueBatch(array $anchor, array $po): bool
  7342. {
  7343. return $this->procuremenIssueBatchGroupKey($anchor) === $this->procuremenIssueBatchGroupKey($po);
  7344. }
  7345. /**
  7346. * @param array<int, mixed> $pos
  7347. * @return array<int, array<string, mixed>>
  7348. */
  7349. protected function filterPurchaseOrdersSameIssueBatch(array $pos, array $anchor): array
  7350. {
  7351. $out = [];
  7352. foreach ($pos as $po) {
  7353. if (is_array($po) && $this->isSameProcuremenIssueBatch($anchor, $po)) {
  7354. $out[] = $po;
  7355. }
  7356. }
  7357. return $out !== [] ? $out : [$anchor];
  7358. }
  7359. /**
  7360. * 确认供应商列表:同一订单号且同一次下发才合并为一行
  7361. *
  7362. * @param array<int, array<string, mixed>> $pool
  7363. * @return array<int, array<string, mixed>>
  7364. */
  7365. protected function collapseProcuremenPoolByOrder(array $pool): array
  7366. {
  7367. if ($pool === []) {
  7368. return [];
  7369. }
  7370. $groups = [];
  7371. foreach ($pool as $row) {
  7372. if (!is_array($row)) {
  7373. continue;
  7374. }
  7375. $key = $this->procuremenIssueBatchGroupKey($row);
  7376. if (!isset($groups[$key])) {
  7377. $groups[$key] = [];
  7378. }
  7379. $groups[$key][] = $row;
  7380. }
  7381. $out = [];
  7382. foreach ($groups as $ccydh => $rows) {
  7383. if ($rows === []) {
  7384. continue;
  7385. }
  7386. // 与确认/审批弹窗「本单工序」一致:按订单号 → 印件名称 → 工序名称 → 工序ID
  7387. usort($rows, function ($a, $b) {
  7388. $oa = trim((string)($a['CCYDH'] ?? ''));
  7389. $ob = trim((string)($b['CCYDH'] ?? ''));
  7390. if ($oa !== $ob) {
  7391. return strcmp($oa, $ob);
  7392. }
  7393. $na = trim((string)($a['CYJMC'] ?? ''));
  7394. $nb = trim((string)($b['CYJMC'] ?? ''));
  7395. if ($na !== $nb) {
  7396. return strcmp($na, $nb);
  7397. }
  7398. $ga = trim((string)($a['CGYMC'] ?? ''));
  7399. $gb = trim((string)($b['CGYMC'] ?? ''));
  7400. if ($ga !== $gb) {
  7401. return strcmp($ga, $gb);
  7402. }
  7403. $ida = (int)($a['ID'] ?? $a['scydgy_id'] ?? 0);
  7404. $idb = (int)($b['ID'] ?? $b['scydgy_id'] ?? 0);
  7405. return $ida <=> $idb;
  7406. });
  7407. $head = $rows[0];
  7408. $gymcList = [];
  7409. foreach ($rows as $r) {
  7410. $g = trim((string)($r['CGYMC'] ?? ''));
  7411. if ($g !== '' && !in_array($g, $gymcList, true)) {
  7412. $gymcList[] = $g;
  7413. }
  7414. }
  7415. $merged = $head;
  7416. $orderDhList = [];
  7417. $nameList = [];
  7418. foreach ($rows as $r) {
  7419. if (!is_array($r)) {
  7420. continue;
  7421. }
  7422. $odh = trim((string)($r['CCYDH'] ?? ''));
  7423. if ($odh !== '' && !in_array($odh, $orderDhList, true)) {
  7424. $orderDhList[] = $odh;
  7425. }
  7426. $onm = trim((string)($r['CYJMC'] ?? ''));
  7427. if ($onm !== '' && !in_array($onm, $nameList, true)) {
  7428. $nameList[] = $onm;
  7429. }
  7430. }
  7431. $orderDh = $orderDhList !== [] ? implode('、', $orderDhList) : trim((string)($head['CCYDH'] ?? ''));
  7432. $merged['CCYDH'] = $orderDh;
  7433. $merged['order_key'] = $orderDh;
  7434. if ($nameList !== []) {
  7435. $merged['CYJMC'] = implode('、', $nameList);
  7436. }
  7437. $merged['order_batch_no'] = $this->resolveProcuremenOrderBatchNo($head);
  7438. $merged['process_count'] = count($rows);
  7439. $merged['_order_merge_rows'] = $rows;
  7440. $qtyList = [];
  7441. $priceList = [];
  7442. foreach ($rows as $r) {
  7443. if (!is_array($r)) {
  7444. continue;
  7445. }
  7446. $qtyList[] = $this->resolveProcuremenThisQuantity($r);
  7447. $priceList[] = $this->resolveProcuremenCeilingPrice($r);
  7448. }
  7449. if (count($rows) > 1) {
  7450. $merged['CGYMC'] = implode('、', $gymcList);
  7451. // 多工序:数量/限价按有值项顿号间隔(空值不占位)
  7452. $merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  7453. $merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  7454. } else {
  7455. $merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
  7456. $merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
  7457. }
  7458. // 已选供应商:取合并行中首个非空 pick_company_name
  7459. $pickedName = '';
  7460. $manualPick = ((int)($head['manual_pick'] ?? 0) === 1) ? 1 : 0;
  7461. foreach ($rows as $r) {
  7462. if (!is_array($r)) {
  7463. continue;
  7464. }
  7465. if ((int)($r['manual_pick'] ?? 0) === 1) {
  7466. $manualPick = 1;
  7467. }
  7468. $pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
  7469. if ($pn !== '' && $pickedName === '') {
  7470. $pickedName = $pn;
  7471. }
  7472. }
  7473. $merged['manual_pick'] = $manualPick;
  7474. if ($pickedName !== '') {
  7475. $merged['pick_company_name'] = $pickedName;
  7476. $merged['picked_supplier_name'] = $pickedName;
  7477. }
  7478. $mergedPickTime = '';
  7479. foreach ($rows as $r) {
  7480. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  7481. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  7482. $mergedPickTime = $t;
  7483. }
  7484. }
  7485. if ($mergedPickTime !== '') {
  7486. $merged['pick_time'] = $mergedPickTime;
  7487. }
  7488. $out[] = $merged;
  7489. }
  7490. usort($out, function ($a, $b) {
  7491. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  7492. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  7493. if ($ta === $tb) {
  7494. $ida = (int)($a['purchase_order_id'] ?? 0);
  7495. $idb = (int)($b['purchase_order_id'] ?? 0);
  7496. if ($ida !== $idb) {
  7497. return $idb <=> $ida;
  7498. }
  7499. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  7500. }
  7501. if ($ta === '') {
  7502. return 1;
  7503. }
  7504. if ($tb === '') {
  7505. return -1;
  7506. }
  7507. return strcmp($tb, $ta);
  7508. });
  7509. return $out;
  7510. }
  7511. /**
  7512. * 待确认供应商:同一次下发批次的工序(优先 order_batch_no;旧数据回退同订单+同下发时间)
  7513. *
  7514. * @return array{ccydh:string, order_batch_no?:string, pos:array<int,array>, merge_rows:array<int,array>}
  7515. */
  7516. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  7517. {
  7518. $scydgyId = trim($scydgyId);
  7519. $empty = ['ccydh' => '', 'order_batch_no' => '', 'pos' => [], 'merge_rows' => []];
  7520. if ($scydgyId === '') {
  7521. return $empty;
  7522. }
  7523. try {
  7524. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7525. } catch (\Throwable $e) {
  7526. $anchor = null;
  7527. }
  7528. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  7529. return $empty;
  7530. }
  7531. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7532. $batchNo = $this->resolveProcuremenOrderBatchNo($anchor);
  7533. try {
  7534. if ($batchNo !== '') {
  7535. $pos = Db::table('purchase_order')
  7536. ->where('order_batch_no', $batchNo)
  7537. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())
  7538. ->order('scydgy_id', 'asc')
  7539. ->select();
  7540. } elseif ($ccydh !== '') {
  7541. $pos = Db::table('purchase_order')
  7542. ->where('CCYDH', $ccydh)
  7543. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())
  7544. ->order('scydgy_id', 'asc')
  7545. ->select();
  7546. } else {
  7547. $pos = [$anchor];
  7548. }
  7549. } catch (\Throwable $e) {
  7550. $pos = [$anchor];
  7551. }
  7552. if (!is_array($pos) || $pos === []) {
  7553. $pos = [$anchor];
  7554. }
  7555. $pos = $this->filterPurchaseOrdersSameIssueBatch($pos, $anchor);
  7556. return [
  7557. 'ccydh' => $ccydh,
  7558. 'order_batch_no' => $batchNo,
  7559. 'pos' => $pos,
  7560. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  7561. ];
  7562. }
  7563. /**
  7564. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  7565. */
  7566. protected function purchaseOrderRowInConfirmStage(array $po): bool
  7567. {
  7568. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  7569. return false;
  7570. }
  7571. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  7572. return false;
  7573. }
  7574. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  7575. return true;
  7576. }
  7577. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  7578. $sid = (int)($po['scydgy_id'] ?? 0);
  7579. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  7580. }
  7581. return false;
  7582. }
  7583. /**
  7584. * 采购确认:同一次下发批次的待审批工序(优先 order_batch_no)
  7585. *
  7586. * @return array{ccydh:string, order_batch_no?:string, pos:array<int,array>, merge_rows:array<int,array>}
  7587. */
  7588. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  7589. {
  7590. $scydgyId = trim($scydgyId);
  7591. $empty = ['ccydh' => '', 'order_batch_no' => '', 'pos' => [], 'merge_rows' => []];
  7592. if ($scydgyId === '') {
  7593. return $empty;
  7594. }
  7595. try {
  7596. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7597. } catch (\Throwable $e) {
  7598. $anchor = null;
  7599. }
  7600. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  7601. return $empty;
  7602. }
  7603. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7604. $batchNo = $this->resolveProcuremenOrderBatchNo($anchor);
  7605. try {
  7606. if ($batchNo !== '') {
  7607. $posQuery = Db::table('purchase_order')->where('order_batch_no', $batchNo);
  7608. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  7609. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  7610. } elseif ($ccydh !== '') {
  7611. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  7612. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  7613. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  7614. } else {
  7615. $pos = [$anchor];
  7616. }
  7617. } catch (\Throwable $e) {
  7618. $pos = [$anchor];
  7619. }
  7620. if (!is_array($pos) || $pos === []) {
  7621. $pos = [$anchor];
  7622. }
  7623. $pos = array_values(array_filter($pos, function ($po) {
  7624. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  7625. }));
  7626. if ($pos === []) {
  7627. $pos = [$anchor];
  7628. }
  7629. $pos = $this->filterPurchaseOrdersSameIssueBatch($pos, $anchor);
  7630. return [
  7631. 'ccydh' => $ccydh,
  7632. 'order_batch_no' => $batchNo,
  7633. 'pos' => $pos,
  7634. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  7635. ];
  7636. }
  7637. /**
  7638. * @param array<int, array<string, mixed>> $purchaseOrders
  7639. * @return array<int, array<string, mixed>>
  7640. */
  7641. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  7642. {
  7643. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  7644. $byId = [];
  7645. foreach ($pool as $r) {
  7646. if (!is_array($r)) {
  7647. continue;
  7648. }
  7649. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  7650. if ($this->isValidScydgyRowId($sid)) {
  7651. $byId[$sid] = $r;
  7652. }
  7653. }
  7654. $out = [];
  7655. foreach ($purchaseOrders as $po) {
  7656. if (!is_array($po)) {
  7657. continue;
  7658. }
  7659. $sid = (int)($po['scydgy_id'] ?? 0);
  7660. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  7661. $out[] = $byId[$sid];
  7662. }
  7663. }
  7664. $this->enrichProcuremenRowsMbz($out);
  7665. return $out;
  7666. }
  7667. /**
  7668. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  7669. *
  7670. * @return array<int, array<string, mixed>>
  7671. */
  7672. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  7673. {
  7674. $scydgyId = trim($scydgyId);
  7675. if ($scydgyId === '') {
  7676. return [];
  7677. }
  7678. try {
  7679. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7680. } catch (\Throwable $e) {
  7681. $anchor = null;
  7682. }
  7683. if (!is_array($anchor)) {
  7684. return [];
  7685. }
  7686. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  7687. return [];
  7688. }
  7689. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7690. $batchNo = $this->resolveProcuremenOrderBatchNo($anchor);
  7691. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  7692. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  7693. try {
  7694. $q = Db::table('purchase_order');
  7695. if ($batchNo !== '') {
  7696. $q->where('order_batch_no', $batchNo);
  7697. } elseif ($ccydh !== '' && $isValidPick) {
  7698. $q->where('CCYDH', $ccydh)->where('pick_time', $pickTime);
  7699. } else {
  7700. $q->where('scydgy_id', $scydgyId);
  7701. }
  7702. $pos = $q->order('scydgy_id', 'asc')->select();
  7703. } catch (\Throwable $e) {
  7704. $pos = [$anchor];
  7705. }
  7706. if (!is_array($pos) || $pos === []) {
  7707. $pos = [$anchor];
  7708. }
  7709. $pos = array_values(array_filter($pos, function ($po) {
  7710. if (!is_array($po)) {
  7711. return false;
  7712. }
  7713. $mr = $po['mod_rq'] ?? null;
  7714. if ($mr === null || $mr === '') {
  7715. return true;
  7716. }
  7717. $mrs = trim((string)$mr);
  7718. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  7719. }));
  7720. if ($pos === []) {
  7721. $pos = [$anchor];
  7722. }
  7723. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  7724. if ($rows === []) {
  7725. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  7726. }
  7727. return $rows;
  7728. }
  7729. /**
  7730. * 工序/报价明细统一排序:订单号升序 → 印件名称 → 工序名称 → 工序行ID
  7731. * (与审核弹窗上方工序表一致)
  7732. *
  7733. * @param array<int, array<string, mixed>> $mergeRows
  7734. * @return array<int, array<string, mixed>>
  7735. */
  7736. protected function sortProcuremenMergeRowsByCcydh(array $mergeRows): array
  7737. {
  7738. $list = [];
  7739. foreach ($mergeRows as $r) {
  7740. if (is_array($r)) {
  7741. $list[] = $r;
  7742. }
  7743. }
  7744. usort($list, function ($a, $b) {
  7745. $oa = trim((string)($a['CCYDH'] ?? ''));
  7746. $ob = trim((string)($b['CCYDH'] ?? ''));
  7747. if ($oa !== $ob) {
  7748. return strcmp($oa, $ob);
  7749. }
  7750. $na = trim((string)($a['CYJMC'] ?? ''));
  7751. $nb = trim((string)($b['CYJMC'] ?? ''));
  7752. if ($na !== $nb) {
  7753. return strcmp($na, $nb);
  7754. }
  7755. $ga = trim((string)($a['CGYMC'] ?? ''));
  7756. $gb = trim((string)($b['CGYMC'] ?? ''));
  7757. if ($ga !== $gb) {
  7758. return strcmp($ga, $gb);
  7759. }
  7760. $ida = $this->extractScydgyRowId($a);
  7761. $idb = $this->extractScydgyRowId($b);
  7762. return $ida <=> $idb;
  7763. });
  7764. return $list;
  7765. }
  7766. /**
  7767. * 按工序表同序得到 scydgy_id 列表(供应商报价明细行顺序用)
  7768. *
  7769. * @param array<int, array<string, mixed>> $mergeRows
  7770. * @param int[] $extraSids 合并行未覆盖时追加
  7771. * @return int[]
  7772. */
  7773. protected function orderedScydgyIdsLikeProcessDisplay(array $mergeRows, array $extraSids = []): array
  7774. {
  7775. $out = [];
  7776. $seen = [];
  7777. foreach ($this->sortProcuremenMergeRowsByCcydh($mergeRows) as $r) {
  7778. $sid = $this->extractScydgyRowId($r);
  7779. if (!$this->isValidScydgyRowId($sid) || isset($seen[$sid])) {
  7780. continue;
  7781. }
  7782. $seen[$sid] = true;
  7783. $out[] = $sid;
  7784. }
  7785. foreach ($extraSids as $sid) {
  7786. $sid = (int)$sid;
  7787. if (!$this->isValidScydgyRowId($sid) || isset($seen[$sid])) {
  7788. continue;
  7789. }
  7790. $seen[$sid] = true;
  7791. $out[] = $sid;
  7792. }
  7793. return $out;
  7794. }
  7795. /**
  7796. * 审核弹窗工序表展示行(与下发弹窗列一致;按订单号排序,同订单合并订单号/印件名称单元格)
  7797. *
  7798. * @param array<int, array<string, mixed>> $mergeRows
  7799. * @return array<int, array<string, mixed>>
  7800. */
  7801. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  7802. {
  7803. $list = $this->sortProcuremenMergeRowsByCcydh($mergeRows);
  7804. $n = count($list);
  7805. // 连续同订单号+印件名称:合并单元格 rowspan
  7806. $groupSpan = array_fill(0, $n, 1);
  7807. $groupStart = array_fill(0, $n, true);
  7808. $i = 0;
  7809. while ($i < $n) {
  7810. $key = trim((string)($list[$i]['CCYDH'] ?? '')) . "\0" . trim((string)($list[$i]['CYJMC'] ?? ''));
  7811. $j = $i + 1;
  7812. while ($j < $n) {
  7813. $key2 = trim((string)($list[$j]['CCYDH'] ?? '')) . "\0" . trim((string)($list[$j]['CYJMC'] ?? ''));
  7814. if ($key === '' || $key2 !== $key) {
  7815. break;
  7816. }
  7817. $j++;
  7818. }
  7819. $span = $j - $i;
  7820. $groupSpan[$i] = $span;
  7821. for ($k = $i + 1; $k < $j; $k++) {
  7822. $groupStart[$k] = false;
  7823. $groupSpan[$k] = 1;
  7824. }
  7825. $i = $j;
  7826. }
  7827. $out = [];
  7828. foreach ($list as $idx => $r) {
  7829. $qty = $this->resolveProcuremenThisQuantity($r);
  7830. $price = $this->resolveProcuremenCeilingPrice($r);
  7831. $sid = $this->extractScydgyRowId($r);
  7832. $out[] = [
  7833. 'seq' => $idx + 1,
  7834. 'scydgy_id' => $sid,
  7835. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  7836. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  7837. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  7838. 'CDW' => trim((string)($r['CDW'] ?? '')),
  7839. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  7840. 'NGZL' => $r['NGZL'] ?? '',
  7841. 'This_quantity' => $qty,
  7842. 'ceilingPrice' => $price,
  7843. 'CDF' => trim((string)($r['CDF'] ?? '')),
  7844. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  7845. 'show_order_cells' => !empty($groupStart[$idx]),
  7846. 'order_rowspan' => (int)($groupSpan[$idx] ?? 1),
  7847. ];
  7848. }
  7849. return $out;
  7850. }
  7851. /**
  7852. * 解析金额/数量(去千分位等非数字字符)
  7853. */
  7854. protected function parseProcuremenMoneyNumber($value): ?float
  7855. {
  7856. return ProcuremenFormat::moneyNumber($value);
  7857. }
  7858. protected function formatProcuremenMoneyDisplay(?float $amount): string
  7859. {
  7860. return ProcuremenFormat::moneyDisplay($amount);
  7861. }
  7862. /**
  7863. * 列表/详情展示:工作量为 0 时显示空
  7864. */
  7865. protected function formatProcuremenWorkloadDisplay($value): string
  7866. {
  7867. return ProcuremenFormat::workloadDisplay($value);
  7868. }
  7869. /**
  7870. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  7871. */
  7872. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  7873. {
  7874. foreach ($details as $d) {
  7875. if (!is_array($d)) {
  7876. continue;
  7877. }
  7878. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  7879. $cn = trim((string)($d['company_name'] ?? ''));
  7880. if ($cn !== '') {
  7881. return $cn;
  7882. }
  7883. }
  7884. }
  7885. return trim((string)($main['pick_company_name'] ?? ''));
  7886. }
  7887. /**
  7888. * 详情报价小计:单价 × 本工序本次数量
  7889. */
  7890. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  7891. {
  7892. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  7893. if ($unit === null) {
  7894. return null;
  7895. }
  7896. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  7897. if ($qty === null || $qty <= 0) {
  7898. return null;
  7899. }
  7900. return $unit * $qty;
  7901. }
  7902. /**
  7903. * 详情页:工序小计 + 供应商分组报价与总计
  7904. *
  7905. * @param array<int, array<string, mixed>> $mergeRows
  7906. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  7907. * @return array{
  7908. * process_rows: array,
  7909. * supplier_groups: array,
  7910. * order_total_text: string,
  7911. * order_total_has: bool,
  7912. * selected_company: string
  7913. * }
  7914. */
  7915. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  7916. {
  7917. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  7918. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  7919. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
  7920. || ((int)($main['manual_pick'] ?? 0) === 1);
  7921. $orderMbz = trim((string)($main['MBZ'] ?? $main['mbz'] ?? ''));
  7922. if ($orderMbz === '') {
  7923. $orderMbz = $this->resolveBundleOrderMbz(['pos' => [$main], 'merge_rows' => $mergeRows]);
  7924. }
  7925. $qtyBySid = [];
  7926. $ceilingBySid = [];
  7927. $gymcBySid = [];
  7928. $ccydhBySid = [];
  7929. foreach ($mergeRows as $mr) {
  7930. if (!is_array($mr)) {
  7931. continue;
  7932. }
  7933. $sid = $this->extractScydgyRowId($mr);
  7934. if (!$this->isValidScydgyRowId($sid)) {
  7935. continue;
  7936. }
  7937. $qtyBySid[$sid] = $this->resolveProcuremenThisQuantity($mr);
  7938. $ceilingBySid[$sid] = $this->resolveProcuremenCeilingPrice($mr);
  7939. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  7940. $dh = trim((string)($mr['CCYDH'] ?? ''));
  7941. if ($dh !== '') {
  7942. $ccydhBySid[$sid] = $dh;
  7943. }
  7944. }
  7945. // 与上方工序表一致:按订单号升序
  7946. $orderedSids = $this->orderedScydgyIdsLikeProcessDisplay($mergeRows);
  7947. $mainCcydh = trim((string)($main['CCYDH'] ?? $ccydh));
  7948. if ($mainCcydh !== '') {
  7949. foreach ($orderedSids as $sid) {
  7950. if (empty($ccydhBySid[$sid])) {
  7951. $ccydhBySid[$sid] = $mainCcydh;
  7952. }
  7953. }
  7954. }
  7955. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  7956. $detailByCompanySid = [];
  7957. foreach ($details as $d) {
  7958. if (!is_array($d)) {
  7959. continue;
  7960. }
  7961. $cn = trim((string)($d['company_name'] ?? ''));
  7962. $sid = (int)($d['scydgy_id'] ?? 0);
  7963. if ($cn === '' || $sid === 0) {
  7964. continue;
  7965. }
  7966. if (!isset($detailByCompanySid[$cn])) {
  7967. $detailByCompanySid[$cn] = [];
  7968. }
  7969. $detailByCompanySid[$cn][$sid] = $d;
  7970. }
  7971. $supplierGroups = [];
  7972. foreach ($detailByCompanySid as $cn => $bySid) {
  7973. $lines = [];
  7974. $groupTotal = 0.0;
  7975. $groupHas = false;
  7976. $groupVoid = true;
  7977. $usedSids = [];
  7978. $appendLine = function (int $sid, array $d) use (
  7979. &$lines,
  7980. &$groupTotal,
  7981. &$groupHas,
  7982. &$groupVoid,
  7983. $qtyBySid,
  7984. $ceilingBySid,
  7985. $gymcBySid,
  7986. $ccydhBySid,
  7987. $quoteVisible
  7988. ) {
  7989. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  7990. if (!$isVoid) {
  7991. $groupVoid = false;
  7992. }
  7993. $qtyStr = $qtyBySid[$sid] ?? '';
  7994. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  7995. $am = trim((string)($d['amount'] ?? ''));
  7996. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  7997. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  7998. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  7999. $sub = null;
  8000. if (!$isVoid && $amountNum !== null) {
  8001. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  8002. }
  8003. $ct = $this->resolveDetailSupplierOperTime($d);
  8004. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  8005. $leadFilled = ($leadDays !== null);
  8006. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  8007. $processName = $this->buildSupplierProcessNameFields(
  8008. (string)($ccydhBySid[$sid] ?? ''),
  8009. (string)($gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')))
  8010. );
  8011. $line = array_merge($processName, [
  8012. 'scydgy_id' => $sid,
  8013. 'This_quantity' => (string)$qtyStr,
  8014. 'ceilingPrice' => (string)($ceilingBySid[$sid] ?? ''),
  8015. 'amount' => $am,
  8016. 'unit_price_text' => $amountFilled
  8017. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  8018. : '未填写',
  8019. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  8020. 'delivery_ymd' => $deliveryYmd,
  8021. 'amount_filled' => $amountFilled,
  8022. 'delivery_filled' => $deliveryFilled,
  8023. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  8024. 'lead_days' => $leadFilled ? $leadDays : '',
  8025. 'lead_days_filled'=> $leadFilled,
  8026. 'lead_days_show' => $leadText,
  8027. 'lead_days_text' => $leadText,
  8028. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  8029. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  8030. 'is_void' => $isVoid,
  8031. 'oper_time_text' => $ct,
  8032. ]);
  8033. if (!$quoteVisible && !$isVoid) {
  8034. $this->maskSupplierQuoteLineBeforeDeadline($line);
  8035. } elseif ($sub !== null) {
  8036. $groupTotal += $sub;
  8037. $groupHas = true;
  8038. }
  8039. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  8040. };
  8041. foreach ($orderedSids as $sid) {
  8042. if (!isset($bySid[$sid])) {
  8043. continue;
  8044. }
  8045. $usedSids[$sid] = true;
  8046. $appendLine($sid, $bySid[$sid]);
  8047. }
  8048. foreach ($bySid as $sid => $d) {
  8049. if (isset($usedSids[$sid])) {
  8050. continue;
  8051. }
  8052. $appendLine((int)$sid, $d);
  8053. }
  8054. $firstDetail = null;
  8055. foreach ($bySid as $d) {
  8056. if (is_array($d)) {
  8057. $firstDetail = $d;
  8058. break;
  8059. }
  8060. }
  8061. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  8062. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  8063. if ($username === '' && $ph !== '') {
  8064. $username = $this->resolveCustomerContactName($ph, $cn);
  8065. }
  8066. $remark = '';
  8067. foreach ($bySid as $d) {
  8068. if (!is_array($d)) {
  8069. continue;
  8070. }
  8071. $rm = '';
  8072. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  8073. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  8074. $rm = trim((string)$d[$rk]);
  8075. break;
  8076. }
  8077. }
  8078. if ($rm !== '') {
  8079. $remark = $rm;
  8080. break;
  8081. }
  8082. }
  8083. $lineCount = count($lines);
  8084. $supplierGroup = [
  8085. 'company_name' => $cn,
  8086. 'username' => $username,
  8087. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  8088. 'phone' => $ph,
  8089. 'remark' => $remark,
  8090. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  8091. 'is_void' => $groupVoid,
  8092. 'lines' => $lines,
  8093. 'line_count' => $lineCount,
  8094. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  8095. 'has_total' => $lineCount > 0,
  8096. ];
  8097. $this->finalizeSupplierRemarkDisplay($supplierGroup, $orderMbz, $quoteVisible);
  8098. $supplierGroups[] = $supplierGroup;
  8099. }
  8100. usort($supplierGroups, function ($a, $b) {
  8101. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  8102. return ($a['is_void'] ?? false) ? 1 : -1;
  8103. }
  8104. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  8105. return ($a['is_selected'] ?? false) ? -1 : 1;
  8106. }
  8107. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  8108. });
  8109. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  8110. return [
  8111. 'process_rows' => $processRows,
  8112. 'supplier_groups' => $supplierGroups,
  8113. 'order_total_text' => '',
  8114. 'order_total_has' => false,
  8115. 'selected_company' => $selectedCompany,
  8116. ];
  8117. }
  8118. /**
  8119. * 短信用工序明细。
  8120. * 单订单:仅工序行(订单号/印件名称由模版 {ccydh}{cyjmc} 排版);
  8121. * 多订单同批:每个订单各自输出「订单号 + 印件名称 + 工序列表」,组间空行。
  8122. */
  8123. protected function buildProcessLinesPlain(array $mergeRows): string
  8124. {
  8125. $groups = [];
  8126. foreach ($mergeRows as $r) {
  8127. if (!is_array($r)) {
  8128. continue;
  8129. }
  8130. $dh = trim((string)($r['CCYDH'] ?? ''));
  8131. $key = $dh !== '' ? $dh : ('__sid_' . (int)($r['ID'] ?? $r['id'] ?? $r['scydgy_id'] ?? 0));
  8132. if (!isset($groups[$key])) {
  8133. $groups[$key] = [
  8134. 'ccydh' => $dh,
  8135. 'cyjmc' => trim((string)($r['CYJMC'] ?? '')),
  8136. 'rows' => [],
  8137. ];
  8138. } elseif ($groups[$key]['cyjmc'] === '') {
  8139. $groups[$key]['cyjmc'] = trim((string)($r['CYJMC'] ?? ''));
  8140. }
  8141. $groups[$key]['rows'][] = $r;
  8142. }
  8143. if ($groups === []) {
  8144. return '';
  8145. }
  8146. $multiOrder = count($groups) > 1;
  8147. $blocks = [];
  8148. foreach ($groups as $g) {
  8149. $lines = [];
  8150. if ($multiOrder) {
  8151. if ($g['ccydh'] !== '') {
  8152. $lines[] = '订单号:' . $g['ccydh'];
  8153. }
  8154. if ($g['cyjmc'] !== '') {
  8155. $lines[] = '印件名称:' . $g['cyjmc'];
  8156. }
  8157. }
  8158. foreach ($g['rows'] as $r) {
  8159. if (!is_array($r)) {
  8160. continue;
  8161. }
  8162. $gymc = trim((string)($r['CGYMC'] ?? ''));
  8163. if ($gymc === '') {
  8164. $gymc = '—';
  8165. }
  8166. $dw = trim((string)($r['CDW'] ?? ''));
  8167. // 下发通知展示「本次数量」(优先 This_quantity,空则回退 NGZL),与确认/审批弹窗一致
  8168. $qty = $this->resolveProcuremenThisQuantity($r);
  8169. $parts = ['工序名称:' . $gymc];
  8170. if ($dw !== '') {
  8171. $parts[] = '单位:' . $dw;
  8172. }
  8173. if ($qty !== '') {
  8174. $parts[] = '本次数量:' . $qty;
  8175. }
  8176. $lines[] = implode(' ', $parts);
  8177. }
  8178. if ($lines !== []) {
  8179. $blocks[] = implode("\n", $lines);
  8180. }
  8181. }
  8182. return implode("\n\n", $blocks);
  8183. }
  8184. /** 中文友好显示宽度(全角约 2,半角 1) */
  8185. protected function mbDisplayWidth(string $s): int
  8186. {
  8187. if ($s === '') {
  8188. return 0;
  8189. }
  8190. if (function_exists('mb_strwidth')) {
  8191. return (int)mb_strwidth($s, 'UTF-8');
  8192. }
  8193. if (function_exists('mb_strlen')) {
  8194. return (int)mb_strlen($s, 'UTF-8');
  8195. }
  8196. return strlen($s);
  8197. }
  8198. /** 按显示宽度右侧补空格,便于短信/邮件工序行对齐 */
  8199. protected function mbPadRight(string $s, int $width): string
  8200. {
  8201. $cur = $this->mbDisplayWidth($s);
  8202. if ($cur >= $width) {
  8203. return $s;
  8204. }
  8205. return $s . str_repeat(' ', $width - $cur);
  8206. }
  8207. /**
  8208. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  8209. *
  8210. * @return array<string, string>
  8211. */
  8212. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  8213. {
  8214. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  8215. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  8216. }
  8217. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  8218. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  8219. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  8220. $cyjmc = '';
  8221. foreach ($mergeRows as $mr) {
  8222. if (!is_array($mr)) {
  8223. continue;
  8224. }
  8225. if ($ccydh === '') {
  8226. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  8227. }
  8228. if ($cyjmc === '') {
  8229. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  8230. }
  8231. }
  8232. if ($pos !== []) {
  8233. $firstPo = $pos[0];
  8234. if (is_array($firstPo)) {
  8235. if ($ccydh === '') {
  8236. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  8237. }
  8238. if ($cyjmc === '') {
  8239. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  8240. }
  8241. }
  8242. }
  8243. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  8244. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  8245. if (is_array($any)) {
  8246. if ($ccydh === '') {
  8247. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  8248. }
  8249. if ($cyjmc === '') {
  8250. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  8251. }
  8252. }
  8253. }
  8254. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  8255. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  8256. $cgymc = '';
  8257. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  8258. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  8259. }
  8260. return [
  8261. 'ccydh' => $ccydh,
  8262. 'cyjmc' => $cyjmc,
  8263. 'cgymc' => $cgymc,
  8264. 'process_lines' => $processLines,
  8265. 'process_lines_html' => '',
  8266. ];
  8267. }
  8268. /**
  8269. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  8270. * 多订单时 processPlain 已含各订单头,不再重复拼订单号/印件名称。
  8271. */
  8272. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  8273. {
  8274. $processPlain = trim($processPlain);
  8275. if ($processPlain !== '' && preg_match('/^订单号:/u', $processPlain)) {
  8276. return $processPlain;
  8277. }
  8278. $lines = [];
  8279. if ($ccydh !== '') {
  8280. $lines[] = '订单号:' . $ccydh;
  8281. }
  8282. if ($cyjmc !== '') {
  8283. $lines[] = '印件名称:' . $cyjmc;
  8284. }
  8285. if ($processPlain !== '') {
  8286. $lines[] = $processPlain;
  8287. }
  8288. return implode("\n", $lines);
  8289. }
  8290. /**
  8291. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  8292. *
  8293. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  8294. */
  8295. protected function buildPlatformLinksPlain(array $detailLinks): string
  8296. {
  8297. $lines = [];
  8298. $i = 1;
  8299. foreach ($detailLinks as $lk) {
  8300. if (!is_array($lk)) {
  8301. continue;
  8302. }
  8303. $url = trim((string)($lk['url'] ?? ''));
  8304. if ($url === '') {
  8305. continue;
  8306. }
  8307. $label = trim((string)($lk['cgymc'] ?? ''));
  8308. if ($label === '') {
  8309. $label = '工序' . $i;
  8310. }
  8311. $lines[] = $label . ':' . $url;
  8312. $i++;
  8313. }
  8314. return implode("\n", $lines);
  8315. }
  8316. /**
  8317. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  8318. *
  8319. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  8320. */
  8321. protected function buildPlatformLinksHtml(array $detailLinks): string
  8322. {
  8323. $parts = [];
  8324. $i = 1;
  8325. foreach ($detailLinks as $lk) {
  8326. if (!is_array($lk)) {
  8327. continue;
  8328. }
  8329. $url = trim((string)($lk['url'] ?? ''));
  8330. if ($url === '') {
  8331. continue;
  8332. }
  8333. $label = trim((string)($lk['cgymc'] ?? ''));
  8334. if ($label === '') {
  8335. $label = '工序' . $i;
  8336. }
  8337. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  8338. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  8339. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  8340. $i++;
  8341. }
  8342. return implode("<br>\n", $parts);
  8343. }
  8344. /**
  8345. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  8346. *
  8347. * @return array<string, mixed>
  8348. */
  8349. protected function loadMailerConfig(): array
  8350. {
  8351. try {
  8352. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  8353. } catch (\Throwable $e) {
  8354. $cfg = [];
  8355. }
  8356. return is_array($cfg) ? $cfg : [];
  8357. }
  8358. protected function loadNotifyTemplateRow(string $scene): ?array
  8359. {
  8360. if (in_array($scene, ['confirm_ok_email', 'confirm_fail_email'], true)) {
  8361. $this->ensureConfirmResultEmailTemplates();
  8362. }
  8363. try {
  8364. $row = Db::table('purchase_sms_template')
  8365. ->where('scene', $scene)
  8366. ->where(function ($q) {
  8367. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  8368. })
  8369. ->order('id', 'asc')
  8370. ->find();
  8371. } catch (\Throwable $e) {
  8372. return null;
  8373. }
  8374. if (!is_array($row) || $row === []) {
  8375. return null;
  8376. }
  8377. return [
  8378. 'title' => trim((string)($row['title'] ?? '')),
  8379. 'content' => trim((string)($row['content'] ?? '')),
  8380. ];
  8381. }
  8382. /**
  8383. * 邮件用工序明细 HTML。
  8384. * 多订单同批时按订单分组;单订单保持原表格/单行样式。
  8385. */
  8386. protected function buildProcessLinesHtml(array $mergeRows): string
  8387. {
  8388. $groups = [];
  8389. foreach ($mergeRows as $r) {
  8390. if (!is_array($r)) {
  8391. continue;
  8392. }
  8393. $dh = trim((string)($r['CCYDH'] ?? ''));
  8394. $key = $dh !== '' ? $dh : ('__sid_' . (int)($r['ID'] ?? $r['id'] ?? $r['scydgy_id'] ?? 0));
  8395. if (!isset($groups[$key])) {
  8396. $groups[$key] = [
  8397. 'ccydh' => $dh,
  8398. 'cyjmc' => trim((string)($r['CYJMC'] ?? '')),
  8399. 'rows' => [],
  8400. ];
  8401. } elseif ($groups[$key]['cyjmc'] === '') {
  8402. $groups[$key]['cyjmc'] = trim((string)($r['CYJMC'] ?? ''));
  8403. }
  8404. $groups[$key]['rows'][] = $r;
  8405. }
  8406. if ($groups === []) {
  8407. return '';
  8408. }
  8409. $multiOrder = count($groups) > 1;
  8410. $flatRows = [];
  8411. foreach ($groups as $g) {
  8412. foreach ($g['rows'] as $r) {
  8413. $flatRows[] = $r;
  8414. }
  8415. }
  8416. if (!$multiOrder && count($flatRows) <= 1) {
  8417. $r = $flatRows[0] ?? [];
  8418. if (!is_array($r)) {
  8419. return '';
  8420. }
  8421. $gymc = trim((string)($r['CGYMC'] ?? ''));
  8422. $dw = trim((string)($r['CDW'] ?? ''));
  8423. $qty = $this->resolveProcuremenThisQuantity($r);
  8424. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  8425. if ($dw !== '') {
  8426. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  8427. }
  8428. if ($qty !== '') {
  8429. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  8430. }
  8431. return $html;
  8432. }
  8433. $blocks = [];
  8434. foreach ($groups as $g) {
  8435. $head = '';
  8436. if ($multiOrder) {
  8437. if ($g['ccydh'] !== '') {
  8438. $head .= '<div style="margin:10px 0 4px;font-weight:700;">订单号:'
  8439. . htmlspecialchars($g['ccydh'], ENT_QUOTES, 'UTF-8') . '</div>';
  8440. }
  8441. if ($g['cyjmc'] !== '') {
  8442. $head .= '<div style="margin:0 0 6px;color:#333;">印件名称:'
  8443. . htmlspecialchars($g['cyjmc'], ENT_QUOTES, 'UTF-8') . '</div>';
  8444. }
  8445. }
  8446. $rows = '';
  8447. $i = 1;
  8448. foreach ($g['rows'] as $r) {
  8449. if (!is_array($r)) {
  8450. continue;
  8451. }
  8452. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  8453. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  8454. $qty = htmlspecialchars($this->resolveProcuremenThisQuantity($r), ENT_QUOTES, 'UTF-8');
  8455. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  8456. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  8457. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  8458. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  8459. $i++;
  8460. }
  8461. if ($rows === '') {
  8462. continue;
  8463. }
  8464. $table = '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:4px 0 12px;font-size:14px;width:100%;max-width:560px;">'
  8465. . '<thead><tr style="background:#f5f5f5;">'
  8466. . '<th style="padding:6px 8px;border:1px solid #ddd;width:48px;">序号</th>'
  8467. . '<th style="padding:6px 8px;border:1px solid #ddd;text-align:left;">工序名称</th>'
  8468. . '<th style="padding:6px 8px;border:1px solid #ddd;width:64px;">单位</th>'
  8469. . '<th style="padding:6px 8px;border:1px solid #ddd;width:88px;">本次数量</th>'
  8470. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  8471. $blocks[] = $head . $table;
  8472. }
  8473. return implode('', $blocks);
  8474. }
  8475. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  8476. {
  8477. $sysRq = trim($sysRq);
  8478. if ($sysRq === '') {
  8479. if ($required) {
  8480. $this->error('请选择招标截止日期');
  8481. }
  8482. return '';
  8483. }
  8484. $ts = strtotime($sysRq);
  8485. if ($ts === false || $ts <= 0) {
  8486. $this->error('招标截止日期格式无效');
  8487. }
  8488. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  8489. if (!$allowPast) {
  8490. $ymd = date('Y-m-d', $ts);
  8491. if ($ymd < date('Y-m-d')) {
  8492. $this->error('招标截止日期不能早于今天');
  8493. }
  8494. if ($ts <= time()) {
  8495. $this->error('招标截止时间不能早于当前时间');
  8496. }
  8497. }
  8498. return date('Y-m-d H:i:s', $ts);
  8499. }
  8500. /**
  8501. * 确保 purchase_order.czlyq(类型)存在
  8502. */
  8503. protected function ensurePurchaseOrderCzlyqColumn(): void
  8504. {
  8505. static $done = false;
  8506. if ($done) {
  8507. return;
  8508. }
  8509. $done = true;
  8510. try {
  8511. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  8512. if (empty($cols)) {
  8513. Db::execute(
  8514. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  8515. );
  8516. }
  8517. } catch (\Throwable $e) {
  8518. // ignore
  8519. }
  8520. }
  8521. /**
  8522. * 确保 purchase_order.delivery_deadline 存在
  8523. */
  8524. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  8525. {
  8526. static $done = false;
  8527. if ($done) {
  8528. return;
  8529. }
  8530. $done = true;
  8531. try {
  8532. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  8533. if (empty($cols)) {
  8534. Db::execute(
  8535. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  8536. );
  8537. }
  8538. } catch (\Throwable $e) {
  8539. // ignore
  8540. }
  8541. }
  8542. /**
  8543. * 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
  8544. */
  8545. protected function ensurePurchaseOrderScoreRuleIdColumn(): void
  8546. {
  8547. static $done = false;
  8548. if ($done) {
  8549. return;
  8550. }
  8551. $done = true;
  8552. // 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
  8553. $adds = [
  8554. 'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
  8555. 'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
  8556. 'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
  8557. 'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
  8558. 'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
  8559. ];
  8560. $changed = false;
  8561. foreach ($adds as $col => $ddl) {
  8562. try {
  8563. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  8564. if (!is_array($cols) || $cols === []) {
  8565. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  8566. $changed = true;
  8567. }
  8568. } catch (\Throwable $e) {
  8569. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  8570. }
  8571. }
  8572. if ($changed) {
  8573. $this->clearPurchaseOrderTableFieldsCache();
  8574. }
  8575. }
  8576. /**
  8577. * 确保 purchase_order.order_batch_no(下发批次号)存在
  8578. */
  8579. protected function ensurePurchaseOrderOrderBatchNoColumn(): void
  8580. {
  8581. static $done = false;
  8582. if ($done) {
  8583. return;
  8584. }
  8585. $done = true;
  8586. try {
  8587. $hasNew = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'order_batch_no'");
  8588. if (is_array($hasNew) && $hasNew !== []) {
  8589. return;
  8590. }
  8591. $hasOld = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'issue_batch_no'");
  8592. if (is_array($hasOld) && $hasOld !== []) {
  8593. Db::execute(
  8594. "ALTER TABLE `purchase_order` CHANGE COLUMN `issue_batch_no` `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号(如XH202608240001)'"
  8595. );
  8596. try {
  8597. Db::execute('ALTER TABLE `purchase_order` DROP INDEX `idx_issue_batch_no`');
  8598. } catch (\Throwable $eDrop) {
  8599. }
  8600. try {
  8601. Db::execute('ALTER TABLE `purchase_order` ADD INDEX `idx_order_batch_no` (`order_batch_no`)');
  8602. } catch (\Throwable $eIdx) {
  8603. }
  8604. } else {
  8605. Db::execute(
  8606. "ALTER TABLE `purchase_order` ADD COLUMN `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号(如XH202608240001)'"
  8607. );
  8608. try {
  8609. Db::execute('ALTER TABLE `purchase_order` ADD INDEX `idx_order_batch_no` (`order_batch_no`)');
  8610. } catch (\Throwable $eIdx) {
  8611. }
  8612. }
  8613. $this->clearPurchaseOrderTableFieldsCache();
  8614. } catch (\Throwable $e) {
  8615. Log::write('purchase_order.order_batch_no: ' . $e->getMessage(), 'error');
  8616. }
  8617. }
  8618. /** @deprecated 兼容旧调用 */
  8619. protected function ensurePurchaseOrderIssueBatchNoColumn(): void
  8620. {
  8621. $this->ensurePurchaseOrderOrderBatchNoColumn();
  8622. }
  8623. /**
  8624. * 批次号日流水表:取号时立刻落库递增,避免并发下发撞号
  8625. */
  8626. protected function ensurePurchaseIssueBatchSeqTable(): void
  8627. {
  8628. static $done = false;
  8629. if ($done) {
  8630. return;
  8631. }
  8632. $done = true;
  8633. try {
  8634. Db::execute(
  8635. "CREATE TABLE IF NOT EXISTS `purchase_issue_batch_seq` (
  8636. `ymd` char(8) NOT NULL COMMENT '日期Ymd',
  8637. `last_no` int unsigned NOT NULL DEFAULT 0 COMMENT '当日已分配最大流水',
  8638. `updatetime` datetime DEFAULT NULL,
  8639. PRIMARY KEY (`ymd`)
  8640. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助下发批次号日流水'"
  8641. );
  8642. } catch (\Throwable $e) {
  8643. Log::write('purchase_issue_batch_seq: ' . $e->getMessage(), 'error');
  8644. }
  8645. }
  8646. /**
  8647. * 生成下发批次号:XH + Ymd + 当日4位流水(如 XH202608240001)
  8648. * 必须拿到日锁后先递增流水表再返回,避免两笔下发同时取到同一号。
  8649. *
  8650. * @throws \RuntimeException
  8651. */
  8652. protected function allocateProcuremenIssueBatchNo(): string
  8653. {
  8654. $this->ensurePurchaseOrderOrderBatchNoColumn();
  8655. $this->ensurePurchaseIssueBatchSeqTable();
  8656. $ymd = date('Ymd');
  8657. $prefix = 'XH' . $ymd;
  8658. $lockName = 'procuremen_issue_batch_' . $ymd;
  8659. if (!$this->acquireProcuremenNamedLock($lockName, 15)) {
  8660. throw new \RuntimeException('批次号生成繁忙,请稍后重试');
  8661. }
  8662. try {
  8663. $last = 0;
  8664. $hasSeqRow = false;
  8665. try {
  8666. $row = Db::table('purchase_issue_batch_seq')->where('ymd', $ymd)->find();
  8667. if (is_array($row) && $row !== []) {
  8668. $hasSeqRow = true;
  8669. $last = (int)($row['last_no'] ?? 0);
  8670. }
  8671. } catch (\Throwable $e) {
  8672. $last = 0;
  8673. }
  8674. // 兼容:流水表为空时,用已有 purchase_order.order_batch_no 最大值对齐
  8675. try {
  8676. $maxPo = Db::table('purchase_order')
  8677. ->where('order_batch_no', 'like', $prefix . '%')
  8678. ->order('order_batch_no', 'desc')
  8679. ->value('order_batch_no');
  8680. if (is_string($maxPo) && preg_match('/^XH\d{8}(\d{4})$/', $maxPo, $m)) {
  8681. $last = max($last, (int)$m[1]);
  8682. }
  8683. } catch (\Throwable $e) {
  8684. }
  8685. $seq = $last + 1;
  8686. if ($seq < 1) {
  8687. $seq = 1;
  8688. }
  8689. if ($seq > 9999) {
  8690. throw new \RuntimeException('当日批次号已用尽,请联系管理员');
  8691. }
  8692. $now = date('Y-m-d H:i:s');
  8693. try {
  8694. if ($hasSeqRow) {
  8695. Db::table('purchase_issue_batch_seq')->where('ymd', $ymd)->update([
  8696. 'last_no' => $seq,
  8697. 'updatetime' => $now,
  8698. ]);
  8699. } else {
  8700. try {
  8701. Db::table('purchase_issue_batch_seq')->insert([
  8702. 'ymd' => $ymd,
  8703. 'last_no' => $seq,
  8704. 'updatetime' => $now,
  8705. ]);
  8706. } catch (\Throwable $eIns) {
  8707. Db::table('purchase_issue_batch_seq')->where('ymd', $ymd)->update([
  8708. 'last_no' => $seq,
  8709. 'updatetime' => $now,
  8710. ]);
  8711. }
  8712. }
  8713. } catch (\Throwable $e) {
  8714. throw new \RuntimeException('批次号写入失败,请重试');
  8715. }
  8716. return $prefix . str_pad((string)$seq, 4, '0', STR_PAD_LEFT);
  8717. } finally {
  8718. $this->releaseProcuremenNamedLock($lockName);
  8719. }
  8720. }
  8721. /**
  8722. * ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
  8723. */
  8724. protected function clearPurchaseOrderTableFieldsCache(): void
  8725. {
  8726. try {
  8727. $db = (string)Config::get('database.database');
  8728. $key = $db . '.purchase_order';
  8729. $ref = new \ReflectionProperty(\think\db\Query::class, 'info');
  8730. $ref->setAccessible(true);
  8731. $info = $ref->getValue();
  8732. if (is_array($info) && isset($info[$key])) {
  8733. unset($info[$key]);
  8734. $ref->setValue(null, $info);
  8735. }
  8736. } catch (\Throwable $e) {
  8737. }
  8738. try {
  8739. $db = (string)Config::get('database.database');
  8740. $schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
  8741. if (is_file($schemaFile)) {
  8742. @unlink($schemaFile);
  8743. }
  8744. } catch (\Throwable $e) {
  8745. }
  8746. }
  8747. /**
  8748. * @return array<string, bool>
  8749. */
  8750. protected function loadPurchaseOrderColumnSet(): array
  8751. {
  8752. static $set = null;
  8753. if (is_array($set)) {
  8754. return $set;
  8755. }
  8756. $set = [];
  8757. try {
  8758. $cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
  8759. } catch (\Throwable $e) {
  8760. return $set;
  8761. }
  8762. if (!is_array($cols)) {
  8763. return $set;
  8764. }
  8765. foreach ($cols as $c) {
  8766. if (!is_array($c)) {
  8767. continue;
  8768. }
  8769. $f = (string)($c['Field'] ?? $c['field'] ?? '');
  8770. if ($f !== '') {
  8771. $set[$f] = true;
  8772. }
  8773. }
  8774. return $set;
  8775. }
  8776. /**
  8777. * 解析交货截止日期(仅年月日)
  8778. */
  8779. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  8780. {
  8781. $raw = trim($raw);
  8782. if ($raw === '') {
  8783. if ($required) {
  8784. $this->error('请选择交货截止日期');
  8785. }
  8786. return '';
  8787. }
  8788. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  8789. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  8790. } else {
  8791. $ts = strtotime(str_replace('/', '-', $raw));
  8792. if ($ts === false || $ts <= 0) {
  8793. $this->error('交货截止日期格式无效');
  8794. }
  8795. $ymd = date('Y-m-d', $ts);
  8796. }
  8797. if ($ymd < date('Y-m-d')) {
  8798. $this->error('交货截止日期不能早于今天');
  8799. }
  8800. return $ymd;
  8801. }
  8802. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  8803. {
  8804. return ProcuremenFormat::deliveryDeadlineForInput($value);
  8805. }
  8806. /**
  8807. * @param array{pos?:array} $bundle
  8808. * @return array<string, string> CCYDH => Y-m-d
  8809. */
  8810. protected function buildBundleOrderDeliveryDeadlineMap(array $bundle): array
  8811. {
  8812. $map = [];
  8813. foreach ($bundle['pos'] ?? [] as $po) {
  8814. if (!is_array($po)) {
  8815. continue;
  8816. }
  8817. $dh = trim((string)($po['CCYDH'] ?? ''));
  8818. if ($dh === '' || isset($map[$dh])) {
  8819. continue;
  8820. }
  8821. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  8822. if ($d !== '') {
  8823. $map[$dh] = $d;
  8824. }
  8825. }
  8826. return $map;
  8827. }
  8828. /**
  8829. * @param array{pos?:array} $bundle
  8830. */
  8831. protected function resolveBundleDeliveryDeadline(array $bundle): string
  8832. {
  8833. $map = $this->buildBundleOrderDeliveryDeadlineMap($bundle);
  8834. if ($map !== []) {
  8835. $firstDeadline = reset($map);
  8836. return (string)$firstDeadline;
  8837. }
  8838. return '';
  8839. }
  8840. protected function formatProcuremenSysRqForInput($sysRq): string
  8841. {
  8842. return ProcuremenFormat::sysRqForInput($sysRq);
  8843. }
  8844. protected function formatProcuremenSysRqForDisplay($sysRq): string
  8845. {
  8846. return ProcuremenFormat::sysRqForDisplay($sysRq);
  8847. }
  8848. /**
  8849. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  8850. *
  8851. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  8852. * @return array{ccydh?:string,pos:array,merge_rows:array}
  8853. */
  8854. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  8855. {
  8856. return $bundle;
  8857. }
  8858. /**
  8859. * 写入/更新 purchase_order(单道工序行)
  8860. *
  8861. * @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
  8862. */
  8863. protected function upsertPurchaseOrderFromRow(
  8864. array $row,
  8865. string $sysRqDb,
  8866. $wflowStatus = null,
  8867. ?string $pickTime = null,
  8868. ?array $exists = null,
  8869. ?string $deliveryDeadline = null,
  8870. $scoreRuleId = null,
  8871. ?string $issueBatchNo = null
  8872. ): void {
  8873. $ids = $this->extractScydgyRowId($row);
  8874. if (!$this->isValidScydgyRowId($ids)) {
  8875. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  8876. }
  8877. if ($exists === null) {
  8878. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  8879. }
  8880. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  8881. $this->ensurePurchaseOrderScoreRuleIdColumn();
  8882. $this->ensurePurchaseOrderOrderBatchNoColumn();
  8883. $this->ensurePurchaseOrderCzlyqColumn();
  8884. $data = $this->normalizePurchaseOrderWritePayload([
  8885. 'scydgy_id' => $ids,
  8886. 'CCYDH' => $row['CCYDH'] ?? null,
  8887. 'CYJMC' => $row['CYJMC'] ?? null,
  8888. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  8889. 'CDXMC' => $row['CDXMC'] ?? null,
  8890. 'CGYBH' => $row['CGYBH'] ?? null,
  8891. 'CGYMC' => $row['CGYMC'] ?? null,
  8892. 'CDW' => $row['CDW'] ?? null,
  8893. 'czlyq' => $row['czlyq'] ?? null,
  8894. 'NGZL' => $row['NGZL'] ?? null,
  8895. 'CDF' => $row['CDF'] ?? null,
  8896. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  8897. 'MBZ' => trim((string)($row['MBZ'] ?? $row['mbz'] ?? '')),
  8898. 'bwjg' => $row['bwjg'] ?? null,
  8899. 'iStatus' => $row['iStatus'] ?? null,
  8900. 'dStamp' => $row['dStamp'] ?? null,
  8901. 'dputrecord' => $row['dputrecord'] ?? null,
  8902. 'cywyxm' => $row['cywyxm'] ?? null,
  8903. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  8904. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  8905. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  8906. 'sys_rq' => $sysRqDb,
  8907. ], $row);
  8908. // 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
  8909. $qtyUp = trim((string)($data['This_quantity'] ?? ''));
  8910. if ($qtyUp === '') {
  8911. $qtyFallback = $this->resolveProcuremenThisQuantity([
  8912. 'This_quantity' => '',
  8913. 'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
  8914. ]);
  8915. if ($qtyFallback !== '') {
  8916. $data['This_quantity'] = $qtyFallback;
  8917. }
  8918. }
  8919. if ($deliveryDeadline !== null) {
  8920. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  8921. }
  8922. // 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
  8923. $scoreRule = null;
  8924. if (is_array($scoreRuleId)) {
  8925. $scoreRule = $scoreRuleId;
  8926. $scoreRuleId = (int)($scoreRule['id'] ?? 0);
  8927. } else {
  8928. $scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
  8929. }
  8930. if ($scoreRuleId !== null && $scoreRuleId > 0) {
  8931. $poCols = $this->loadPurchaseOrderColumnSet();
  8932. if (!empty($poCols['score_rule_id'])) {
  8933. $data['score_rule_id'] = $scoreRuleId;
  8934. if (is_array($scoreRule)) {
  8935. if (!empty($poCols['score_rule_name'])) {
  8936. $data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
  8937. }
  8938. if (!empty($poCols['score_quality_weight'])) {
  8939. $data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
  8940. }
  8941. if (!empty($poCols['score_price_weight'])) {
  8942. $data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
  8943. }
  8944. if (!empty($poCols['score_lead_weight'])) {
  8945. $data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
  8946. }
  8947. }
  8948. }
  8949. }
  8950. if ($wflowStatus !== null && $wflowStatus !== '') {
  8951. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  8952. }
  8953. if ($pickTime !== null && $pickTime !== '') {
  8954. $data['pick_time'] = $pickTime;
  8955. $data['pick_company_name'] = '';
  8956. // 新下发批次:清空「指定供应商」,避免沿用上轮免开标状态导致提前可见报价
  8957. $this->ensurePurchaseOrderManualPickColumns();
  8958. $data['manual_pick'] = 0;
  8959. $data['manual_pick_reason'] = '';
  8960. // 同订单重新下发后需重新开标(按订单号 + 批次号);并软删同订单其它旧批
  8961. $dh = trim((string)($data['CCYDH'] ?? $row['CCYDH'] ?? ''));
  8962. $bn = trim((string)($issueBatchNo ?? ''));
  8963. if ($bn === '') {
  8964. $bn = $this->resolveProcuremenOrderBatchNo(array_merge(is_array($exists) ? $exists : [], $data, $row));
  8965. }
  8966. $this->clearProcuremenBidOpenRecords($dh !== '' ? [$dh] : [], $bn !== '' ? [$bn] : []);
  8967. if ($dh !== '') {
  8968. // 新下发只清开标/评分;软删其它批仅在「重新下发」入口做,避免正常补发工序误伤并行单
  8969. $this->clearProcuremenSupplierScoresForCcydhs([$dh]);
  8970. }
  8971. }
  8972. if ($issueBatchNo !== null) {
  8973. $batchNo = trim($issueBatchNo);
  8974. $poCols = $this->loadPurchaseOrderColumnSet();
  8975. if (!empty($poCols['order_batch_no'])) {
  8976. $data['order_batch_no'] = $batchNo;
  8977. }
  8978. }
  8979. if ($exists) {
  8980. $upd = $data;
  8981. unset($upd['scydgy_id']);
  8982. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  8983. } else {
  8984. $data['createtime'] = date('Y-m-d H:i:s');
  8985. Db::table('purchase_order')->insert($data);
  8986. }
  8987. }
  8988. /**
  8989. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  8990. *
  8991. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  8992. */
  8993. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
  8994. {
  8995. $toDb = function ($value) {
  8996. if ($value === null) {
  8997. return null;
  8998. }
  8999. if (is_scalar($value)) {
  9000. return $value;
  9001. }
  9002. return json_encode($value, JSON_UNESCAPED_UNICODE);
  9003. };
  9004. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  9005. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  9006. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  9007. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  9008. if ($username === '') {
  9009. $username = $this->resolveCustomerContactName($phone, $companyName);
  9010. }
  9011. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  9012. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  9013. }
  9014. if ($requirePhone && $phone === '') {
  9015. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  9016. }
  9017. $detailLinks = [];
  9018. foreach ($mergeRows as $row) {
  9019. if (!is_array($row)) {
  9020. continue;
  9021. }
  9022. $sid = $this->extractScydgyRowId($row);
  9023. $detailId = 0;
  9024. if ($skipExisting) {
  9025. try {
  9026. $existsQuery = Db::table('purchase_order_detail')
  9027. ->where('scydgy_id', $sid)
  9028. ->where('company_name', $companyName);
  9029. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  9030. $exists = $existsQuery->find();
  9031. } catch (\Throwable $e) {
  9032. $exists = null;
  9033. }
  9034. if (is_array($exists)) {
  9035. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  9036. }
  9037. }
  9038. if ($detailId <= 0) {
  9039. $one = [
  9040. 'scydgy_id' => $toDb($sid),
  9041. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  9042. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  9043. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  9044. 'username' => $username !== '' ? $username : null,
  9045. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  9046. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  9047. 'createtime' => date('Y-m-d H:i:s'),
  9048. 'status' => ProcuremenStatus::POD_UNPICKED,
  9049. 'status_name' => '未提交',
  9050. ];
  9051. // 新下发/重新下发均不继承历史报价,供应商需对本批次重新填报
  9052. Db::table('purchase_order_detail')->insert($one);
  9053. $detailId = (int)Db::getLastInsID();
  9054. }
  9055. $mprocUrl = '';
  9056. if ($buildMobileLinks && $detailId > 0) {
  9057. // 手工询价 → 待报价;协助下发 → 未提交
  9058. $listTab = ($sid < 0) ? 'rfq' : 'draft';
  9059. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId, $listTab);
  9060. }
  9061. $detailLinks[] = [
  9062. 'detail_id' => $detailId,
  9063. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  9064. 'url' => $mprocUrl,
  9065. ];
  9066. }
  9067. $this->invalidatePickHiddenScydgyCache();
  9068. return $detailLinks;
  9069. }
  9070. /**
  9071. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  9072. * @return array<string, mixed>
  9073. */
  9074. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks, string $emailTplScene = 'review_email'): array
  9075. {
  9076. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  9077. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  9078. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  9079. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  9080. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  9081. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  9082. $isMerge = !empty($ctx['is_merge']);
  9083. $contactName = trim((string)($c['username'] ?? ''));
  9084. if ($contactName === '') {
  9085. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  9086. }
  9087. $notifyVars = [
  9088. 'company_name' => $companyName,
  9089. 'contact_name' => $contactName,
  9090. 'phone' => $phone,
  9091. 'email' => $toEmail,
  9092. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  9093. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  9094. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  9095. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  9096. 'deadline' => (string)($ctx['deadline'] ?? ''),
  9097. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  9098. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  9099. 'order_type' => (string)($ctx['order_type'] ?? ''),
  9100. 'score_weights' => (string)($ctx['score_weights'] ?? ''),
  9101. 'platform_url' => $platformUrl,
  9102. 'platform_links' => $platformLinksPlain,
  9103. 'platform_links_html' => $platformLinksHtml,
  9104. ];
  9105. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  9106. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  9107. $mailPlain = $this->renderNotifyTemplate($emailTplScene, $notifyVars);
  9108. if (!empty($ctx['multi_order'])) {
  9109. $smsContent = $this->stripEmptyOrderHeaderLines($smsContent);
  9110. $mailPlain = $this->stripEmptyOrderHeaderLines($mailPlain);
  9111. }
  9112. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  9113. // 邮件:用表格替换纯文本工序块,列对齐更整齐
  9114. $processHtml = trim((string)($ctx['process_html'] ?? ''));
  9115. $processPlain = trim((string)($ctx['process_plain'] ?? ''));
  9116. if ($processHtml !== '' && $processPlain !== '') {
  9117. $plainBlockHtml = $this->plainTextToHtmlEmailBody($processPlain);
  9118. if ($plainBlockHtml !== '' && strpos($mailBody, $plainBlockHtml) !== false) {
  9119. $mailBody = str_replace($plainBlockHtml, $processHtml, $mailBody);
  9120. }
  9121. }
  9122. return [
  9123. 'company_name' => $companyName,
  9124. 'phone' => $phone,
  9125. 'email' => $toEmail,
  9126. 'sms_content' => $smsContent,
  9127. 'mail_plain' => $mailPlain,
  9128. 'mail_body' => $mailBody,
  9129. 'notify_vars' => $notifyVars,
  9130. 'detail_links' => $detailLinks,
  9131. ];
  9132. }
  9133. /**
  9134. * 多订单下发时模版里「订单号:{ccydh}」可能变成空行,去掉以免重复
  9135. */
  9136. protected function stripEmptyOrderHeaderLines(string $text): string
  9137. {
  9138. $text = str_replace(["\r\n", "\r"], "\n", $text);
  9139. $text = preg_replace('/^订单号:\s*\n/mu', '', $text);
  9140. $text = preg_replace('/^印件名称:\s*\n/mu', '', $text);
  9141. $text = preg_replace("/\n{3,}/", "\n\n", (string)$text);
  9142. return (string)$text;
  9143. }
  9144. /**
  9145. * @param array<string, mixed> $chosen
  9146. * @param array<int, array<string, mixed>> $mergeRows
  9147. * @param array{ccydh:string, pos:array} $bundle
  9148. */
  9149. /**
  9150. * 先把成功 JSON 回给浏览器,再继续后台任务(发短信/邮件)。
  9151. * 避免多家供应商通知串行导致页面一直转圈、网关超时被当成系统失败。
  9152. *
  9153. * @param array<string, mixed>|string|null $data
  9154. */
  9155. protected function respondSuccessThenContinue(string $msg, $data = null): void
  9156. {
  9157. $result = [
  9158. 'code' => 1,
  9159. 'msg' => $msg,
  9160. 'data' => $data,
  9161. 'url' => '',
  9162. 'wait' => 3,
  9163. ];
  9164. $json = json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  9165. if ($json === false) {
  9166. $json = '{"code":1,"msg":"操作成功","data":null,"url":"","wait":3}';
  9167. }
  9168. while (ob_get_level() > 0) {
  9169. @ob_end_clean();
  9170. }
  9171. if (!headers_sent()) {
  9172. header('Content-Type: application/json; charset=utf-8');
  9173. header('Cache-Control: no-store, no-cache, must-revalidate');
  9174. header('Connection: close');
  9175. header('Content-Length: ' . strlen($json));
  9176. }
  9177. echo $json;
  9178. if (session_status() === PHP_SESSION_ACTIVE) {
  9179. @session_write_close();
  9180. }
  9181. if (function_exists('fastcgi_finish_request')) {
  9182. @fastcgi_finish_request();
  9183. } else {
  9184. @flush();
  9185. }
  9186. @ignore_user_abort(true);
  9187. @set_time_limit(300);
  9188. @ini_set('max_execution_time', '300');
  9189. }
  9190. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue', string $emailTplScene = 'review_email'): void
  9191. {
  9192. if (!$sendSms && !$sendEmail) {
  9193. return;
  9194. }
  9195. $companyName = trim((string)($chosen['name'] ?? ''));
  9196. $phone = trim((string)($chosen['phone'] ?? ''));
  9197. $toEmail = trim((string)($chosen['email'] ?? ''));
  9198. if ($companyName === '') {
  9199. throw new \Exception('供应商名称无效');
  9200. }
  9201. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  9202. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  9203. }
  9204. if ($sendSms && $phone === '') {
  9205. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  9206. }
  9207. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  9208. $linkListTab = (strpos($emailTplScene, 'rfq_') === 0) ? 'rfq' : 'draft';
  9209. $sids = [];
  9210. foreach ($mergeRows as $mr) {
  9211. if (!is_array($mr)) {
  9212. continue;
  9213. }
  9214. $sid = $this->extractScydgyRowId($mr);
  9215. if ($this->isValidScydgyRowId($sid)) {
  9216. $sids[$sid] = true;
  9217. }
  9218. }
  9219. if ($sids === []) {
  9220. throw new \Exception('未找到工序行,无法发送通知');
  9221. }
  9222. $sysRqNotify = '';
  9223. $pos = $bundle['pos'] ?? [];
  9224. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  9225. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  9226. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  9227. $ts = strtotime($sr);
  9228. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  9229. }
  9230. }
  9231. try {
  9232. $detailsQuery = Db::table('purchase_order_detail')
  9233. ->where('scydgy_id', 'in', array_keys($sids))
  9234. ->where('company_name', $companyName);
  9235. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  9236. $details = $detailsQuery->order('id', 'asc')->select();
  9237. } catch (\Throwable $e) {
  9238. $details = [];
  9239. }
  9240. if (!is_array($details) || $details === []) {
  9241. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  9242. try {
  9243. $detailsQuery = Db::table('purchase_order_detail')
  9244. ->where('scydgy_id', 'in', array_keys($sids))
  9245. ->where('company_name', $companyName);
  9246. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  9247. $details = $detailsQuery->order('id', 'asc')->select();
  9248. } catch (\Throwable $e) {
  9249. $details = [];
  9250. }
  9251. }
  9252. if (!is_array($details) || $details === []) {
  9253. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  9254. }
  9255. $detailLinks = [];
  9256. foreach ($details as $d) {
  9257. if (!is_array($d)) {
  9258. continue;
  9259. }
  9260. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  9261. if ($detailId <= 0) {
  9262. continue;
  9263. }
  9264. $sid = (int)($d['scydgy_id'] ?? 0);
  9265. $gymc = '';
  9266. foreach ($mergeRows as $mr) {
  9267. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  9268. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  9269. break;
  9270. }
  9271. }
  9272. $detailLinks[] = [
  9273. 'detail_id' => $detailId,
  9274. 'cgymc' => $gymc,
  9275. // 询价邮件 → 待报价;下发报价 → 未提交
  9276. 'url' => $this->buildMprocMobileOrderUrl(
  9277. $detailId,
  9278. ($linkListTab === 'rfq' || $sid < 0) ? 'rfq' : 'draft'
  9279. ),
  9280. ];
  9281. }
  9282. if ($detailLinks === []) {
  9283. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  9284. }
  9285. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  9286. $orderTypeCtx = $this->resolveIssueNotifyOrderTypeFromBundle($bundle);
  9287. $ctx['order_type'] = (string)($orderTypeCtx['order_type'] ?? '');
  9288. $ctx['score_weights'] = (string)($orderTypeCtx['score_weights'] ?? '');
  9289. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks, $emailTplScene);
  9290. $notifyBundle['email_log_scene'] = $emailLogScene;
  9291. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  9292. $poIdLog = 0;
  9293. $pos = $bundle['pos'] ?? [];
  9294. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  9295. $poIdLog = (int)($pos[0]['id'] ?? 0);
  9296. }
  9297. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  9298. // 日志单独记订单号/批次号:多订单下发时模版变量 ccydh 会刻意留空,不能沿用到日志
  9299. $notifyBundle['email_log_ccydh'] = $this->collectCcydhListForEmailLog($mergeRows, $pos);
  9300. $notifyBundle['email_log_order_batch_no'] = $this->resolveBundleOrderBatchNo($bundle);
  9301. if ($sendEmail) {
  9302. $mailTplRow = $this->loadNotifyTemplateRow($emailTplScene);
  9303. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  9304. throw new \Exception($this->notifyTemplateMissingMessage($emailTplScene));
  9305. }
  9306. $mailSubject = $this->resolveProcuremenEmailSubject($emailTplScene);
  9307. $mailConfig = $this->loadMailerConfig();
  9308. if (!$this->isProcuremenNotifyDryRun()) {
  9309. if (empty($mailConfig['host'])) {
  9310. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9311. }
  9312. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9313. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9314. }
  9315. }
  9316. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  9317. }
  9318. if ($sendSms) {
  9319. $this->issueSendSupplierSms($notifyBundle);
  9320. }
  9321. }
  9322. /**
  9323. * @param array<int, array<string, mixed>> $quoteGroups
  9324. * @return array<int, array<string, mixed>>
  9325. */
  9326. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  9327. {
  9328. $names = [];
  9329. if (is_string($companiesJson) && $companiesJson !== '') {
  9330. $decoded = json_decode($companiesJson, true);
  9331. if (is_array($decoded)) {
  9332. foreach ($decoded as $nm) {
  9333. $nm = trim((string)$nm);
  9334. if ($nm !== '') {
  9335. $names[] = $nm;
  9336. }
  9337. }
  9338. }
  9339. }
  9340. $names = array_values(array_unique($names));
  9341. if ($names === [] && $selectedCompany !== '') {
  9342. $names = [$selectedCompany];
  9343. }
  9344. if ($names === []) {
  9345. return $quoteGroups;
  9346. }
  9347. $targets = [];
  9348. foreach ($quoteGroups as $g) {
  9349. if (!is_array($g)) {
  9350. continue;
  9351. }
  9352. $cn = trim((string)($g['name'] ?? ''));
  9353. if ($cn !== '' && in_array($cn, $names, true)) {
  9354. $targets[] = $g;
  9355. }
  9356. }
  9357. return $targets;
  9358. }
  9359. /**
  9360. * @return array{pos:array, merge_rows:array, bundle:array}
  9361. */
  9362. protected function loadAuditResendBundle(string $scydgyId): array
  9363. {
  9364. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  9365. $pos = $bundle['pos'];
  9366. $mergeRows = $bundle['merge_rows'];
  9367. if ($pos === [] || $mergeRows === []) {
  9368. $this->error('该订单不在待确认供应商状态');
  9369. }
  9370. $sysRqDb = '';
  9371. if (isset($pos[0]) && is_array($pos[0])) {
  9372. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  9373. }
  9374. foreach ($pos as $i => $poRow) {
  9375. if (is_array($pos[$i]) && $sysRqDb !== '') {
  9376. $pos[$i]['sys_rq'] = $sysRqDb;
  9377. }
  9378. }
  9379. $bundle['pos'] = $pos;
  9380. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  9381. }
  9382. /**
  9383. * @param array<int, array<string, mixed>> $targets
  9384. */
  9385. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  9386. {
  9387. if ($targets === []) {
  9388. $this->error('未找到可通知的供应商');
  9389. }
  9390. $notifyErrors = [];
  9391. try {
  9392. $this->notifyDryRunPreview = [];
  9393. foreach ($targets as $g) {
  9394. if (!is_array($g)) {
  9395. continue;
  9396. }
  9397. $cname = trim((string)($g['name'] ?? ''));
  9398. if ($cname === '') {
  9399. continue;
  9400. }
  9401. $chosen = [
  9402. 'name' => $cname,
  9403. 'company_name' => $cname,
  9404. 'email' => trim((string)($g['email'] ?? '')),
  9405. 'phone' => trim((string)($g['phone'] ?? '')),
  9406. 'username' => trim((string)($g['username'] ?? '')),
  9407. ];
  9408. try {
  9409. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  9410. } catch (\Throwable $e) {
  9411. $notifyErrors[] = $cname . ':' . $e->getMessage();
  9412. }
  9413. }
  9414. } catch (\Throwable $e) {
  9415. Log::write('procuremen auditResend notify fatal: ' . $e->getMessage(), 'error');
  9416. $this->success('重发未全部完成,请核对联系方式后稍后再试', '', [
  9417. 'notify_failed' => 1,
  9418. ]);
  9419. }
  9420. if ($notifyErrors !== []) {
  9421. Log::write('procuremen auditResend partial fail: ' . implode(';', $notifyErrors), 'error');
  9422. $ok = max(0, count($targets) - count($notifyErrors));
  9423. $this->success(
  9424. '已向 ' . $ok . ' 家发送成功;',
  9425. '',
  9426. [
  9427. 'notify_failed' => 1,
  9428. 'notify_fail_detail' => $notifyErrors,
  9429. ]
  9430. );
  9431. }
  9432. if ($this->isProcuremenNotifyDryRun()) {
  9433. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  9434. 'notify_dry_run' => true,
  9435. 'notify_preview' => $this->notifyDryRunPreview,
  9436. ]);
  9437. }
  9438. $nameLabels = [];
  9439. foreach ($targets as $g) {
  9440. if (!is_array($g)) {
  9441. continue;
  9442. }
  9443. $n = trim((string)($g['name'] ?? ''));
  9444. if ($n !== '') {
  9445. $nameLabels[] = $n;
  9446. }
  9447. }
  9448. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  9449. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  9450. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  9451. $seenLogSid = [];
  9452. foreach ($bundle['pos'] ?? [] as $poRow) {
  9453. if (!is_array($poRow)) {
  9454. continue;
  9455. }
  9456. $sid = (int)($poRow['scydgy_id'] ?? 0);
  9457. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  9458. continue;
  9459. }
  9460. $seenLogSid[$sid] = true;
  9461. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  9462. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  9463. }
  9464. if ($seenLogSid === []) {
  9465. foreach ($mergeRows as $mr) {
  9466. if (!is_array($mr)) {
  9467. continue;
  9468. }
  9469. $sid = $this->extractScydgyRowId($mr);
  9470. if ($this->isValidScydgyRowId($sid)) {
  9471. $this->addOrderLog($sid, $logAction, $logMsg, null);
  9472. break;
  9473. }
  9474. }
  9475. }
  9476. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  9477. }
  9478. /**
  9479. * 协助下发 — 发送短信(一家供应商)
  9480. *
  9481. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  9482. */
  9483. protected function issueSendSupplierSms(array $bundle): void
  9484. {
  9485. $companyName = (string)($bundle['company_name'] ?? '');
  9486. $phone = (string)($bundle['phone'] ?? '');
  9487. $smsContent = (string)($bundle['sms_content'] ?? '');
  9488. $this->logIssueNotifyDebug('短信', [
  9489. 'company' => $companyName,
  9490. 'phone' => $phone,
  9491. 'sms_content' => $smsContent,
  9492. ]);
  9493. if ($this->isProcuremenNotifyDryRun()) {
  9494. $this->recordNotifyDryRunPreview([
  9495. 'scene' => 'issue_sms',
  9496. 'company_name' => $companyName,
  9497. 'phone' => $phone,
  9498. 'sms_content' => $smsContent,
  9499. ]);
  9500. return;
  9501. }
  9502. $this->smsbao($phone, $smsContent);
  9503. }
  9504. /**
  9505. * 协助下发 — 发送邮件(一家供应商)
  9506. *
  9507. * @param array<string, mixed> $bundle
  9508. * @param array<string, mixed> $mailConfig
  9509. */
  9510. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  9511. {
  9512. $companyName = (string)($bundle['company_name'] ?? '');
  9513. $toEmail = (string)($bundle['email'] ?? '');
  9514. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  9515. $mailBody = (string)($bundle['mail_body'] ?? '');
  9516. $this->logIssueNotifyDebug('邮件', [
  9517. 'company' => $companyName,
  9518. 'email' => $toEmail,
  9519. 'cc_email' => $this->resolveMprocNotifyCcEmails($toEmail),
  9520. 'mail_subject' => $mailSubject,
  9521. 'mail_body' => $mailPlain,
  9522. ]);
  9523. if ($this->isProcuremenNotifyDryRun()) {
  9524. $this->recordNotifyDryRunPreview([
  9525. 'scene' => 'issue_email',
  9526. 'company_name' => $companyName,
  9527. 'email' => $toEmail,
  9528. 'cc_email' => $this->resolveMprocNotifyCcEmails($toEmail),
  9529. 'mail_subject' => $mailSubject,
  9530. 'mail_body' => $mailPlain,
  9531. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  9532. 'notify_vars' => $bundle['notify_vars'] ?? [],
  9533. 'detail_links' => $bundle['detail_links'] ?? [],
  9534. ]);
  9535. return;
  9536. }
  9537. $mail = new PHPMailer(true);
  9538. $mail->isSMTP();
  9539. $mail->Host = $mailConfig['host'];
  9540. $mail->SMTPAuth = true;
  9541. $mail->Username = $mailConfig['addr'];
  9542. $mail->Password = $mailConfig['pass'];
  9543. $mail->SMTPSecure = $mailConfig['security'];
  9544. $mail->Port = $mailConfig['port'];
  9545. $mail->CharSet = $mailConfig['charset'];
  9546. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  9547. $mail->addAddress($toEmail, $companyName);
  9548. $ccList = $this->resolveMprocNotifyCcEmails($toEmail);
  9549. foreach ($ccList as $cc) {
  9550. $mail->addCC($cc);
  9551. }
  9552. $mail->isHTML(true);
  9553. $mail->Subject = $mailSubject;
  9554. $mail->Body = $mailBody;
  9555. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  9556. $sendOk = true;
  9557. $failReason = '';
  9558. $logCcydh = trim((string)($bundle['email_log_ccydh'] ?? ''));
  9559. if ($logCcydh === '') {
  9560. $logCcydh = trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? '')));
  9561. }
  9562. $logBatchNo = trim((string)($bundle['email_log_order_batch_no'] ?? ($bundle['order_batch_no'] ?? '')));
  9563. $logCommon = [
  9564. 'from_email' => $fromEmail,
  9565. 'to_email' => $toEmail,
  9566. 'send_time' => date('Y-m-d H:i:s'),
  9567. 'scene' => (string)($bundle['email_log_scene'] ?? '初选下发'),
  9568. 'order_batch_no' => $logBatchNo,
  9569. 'ccydh' => $logCcydh,
  9570. 'company_name' => $companyName,
  9571. 'mail_subject' => $mailSubject,
  9572. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  9573. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  9574. ];
  9575. try {
  9576. $mail->send();
  9577. } catch (\Throwable $e) {
  9578. $sendOk = false;
  9579. $failReason = $e->getMessage();
  9580. $this->persistEmailSendLog(array_merge($logCommon, [
  9581. 'status' => 0,
  9582. 'fail_reason' => $failReason,
  9583. ]));
  9584. throw $e;
  9585. }
  9586. $this->persistEmailSendLog(array_merge($logCommon, [
  9587. 'status' => 1,
  9588. 'fail_reason' => '',
  9589. ]));
  9590. }
  9591. /**
  9592. * 协助通知抄送:读取 mproc.cc_email(逗号分隔),排除与主收件人相同的地址
  9593. *
  9594. * @return array<int, string>
  9595. */
  9596. protected function resolveMprocNotifyCcEmails(string $toEmail = ''): array
  9597. {
  9598. $raw = trim((string)config('mproc.cc_email'));
  9599. if ($raw === '') {
  9600. return [];
  9601. }
  9602. $toNorm = strtolower(trim($toEmail));
  9603. $out = [];
  9604. $seen = [];
  9605. foreach (preg_split('/[,;,;\s]+/', $raw) ?: [] as $piece) {
  9606. $email = strtolower(trim((string)$piece));
  9607. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9608. continue;
  9609. }
  9610. if ($toNorm !== '' && $email === $toNorm) {
  9611. continue;
  9612. }
  9613. if (isset($seen[$email])) {
  9614. continue;
  9615. }
  9616. $seen[$email] = true;
  9617. $out[] = $email;
  9618. }
  9619. return $out;
  9620. }
  9621. /**
  9622. * 下发通知:解析订单类型名称与评分比例文案
  9623. *
  9624. * @param array<string, mixed> $bundle
  9625. * @return array{order_type:string,score_weights:string}
  9626. */
  9627. protected function resolveIssueNotifyOrderTypeFromBundle(array $bundle): array
  9628. {
  9629. $orderType = '';
  9630. $scoreWeights = '';
  9631. $rule = null;
  9632. if (!empty($bundle['score_rule']) && is_array($bundle['score_rule'])) {
  9633. $rule = $bundle['score_rule'];
  9634. }
  9635. $pos = $bundle['pos'] ?? [];
  9636. $po0 = (is_array($pos) && isset($pos[0]) && is_array($pos[0])) ? $pos[0] : null;
  9637. if ($rule === null && is_array($po0)) {
  9638. $ruleId = (int)($po0['score_rule_id'] ?? 0);
  9639. if ($ruleId > 0) {
  9640. try {
  9641. $rule = ProcuremenSupplierScore::getRuleById($ruleId);
  9642. } catch (\Throwable $e) {
  9643. $rule = null;
  9644. }
  9645. }
  9646. if (!is_array($rule) || (int)($rule['id'] ?? 0) <= 0) {
  9647. $qw = (int)($po0['score_quality_weight'] ?? 0);
  9648. $pw = (int)($po0['score_price_weight'] ?? 0);
  9649. $lw = (int)($po0['score_lead_weight'] ?? 0);
  9650. if ($qw > 0 || $pw > 0 || $lw > 0) {
  9651. $rule = [
  9652. 'name' => trim((string)($po0['score_rule_name'] ?? '')),
  9653. 'quality_weight' => $qw,
  9654. 'price_weight' => $pw,
  9655. 'lead_weight' => $lw,
  9656. ];
  9657. }
  9658. }
  9659. }
  9660. if (is_array($rule)) {
  9661. $orderType = trim((string)($rule['name'] ?? ''));
  9662. $scoreWeights = $this->formatScoreRuleWeightsText($rule);
  9663. }
  9664. if ($orderType === '' && is_array($po0)) {
  9665. $orderType = trim((string)($po0['score_rule_name'] ?? ''));
  9666. }
  9667. return [
  9668. 'order_type' => $orderType,
  9669. 'score_weights' => $scoreWeights,
  9670. ];
  9671. }
  9672. /**
  9673. * 评分比例文案:质量30%、价格50%、交货20%
  9674. *
  9675. * @param array{quality_weight?:mixed,price_weight?:mixed,lead_weight?:mixed} $rule
  9676. */
  9677. protected function formatScoreRuleWeightsText(array $rule): string
  9678. {
  9679. return ProcuremenFormat::scoreRuleWeightsText($rule);
  9680. }
  9681. /**
  9682. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  9683. *
  9684. * @param array<int, array<string, mixed>> $mergeRows
  9685. * @return array<string, mixed>
  9686. */
  9687. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  9688. {
  9689. $head = $mergeRows[0] ?? [];
  9690. $isMerge = count($mergeRows) > 1;
  9691. $orderSet = [];
  9692. foreach ($mergeRows as $r) {
  9693. if (!is_array($r)) {
  9694. continue;
  9695. }
  9696. $dh = trim((string)($r['CCYDH'] ?? ''));
  9697. if ($dh !== '') {
  9698. $orderSet[$dh] = true;
  9699. }
  9700. }
  9701. $multiOrder = count($orderSet) > 1;
  9702. // 多订单:明细块自带各订单头,避免模版里 {ccydh}/{cyjmc} 只显示第一单
  9703. $ccydh = $multiOrder ? '' : (isset($head['CCYDH']) ? (string)$head['CCYDH'] : '');
  9704. $cyjmc = $multiOrder ? '' : (isset($head['CYJMC']) ? (string)$head['CYJMC'] : '');
  9705. return [
  9706. 'ccydh' => $ccydh,
  9707. 'cyjmc' => $cyjmc,
  9708. 'cgymc_single' => $multiOrder ? '' : trim((string)($head['CGYMC'] ?? '')),
  9709. 'is_merge' => $isMerge,
  9710. 'multi_order' => $multiOrder,
  9711. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  9712. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  9713. 'deadline' => $sysRqNotify,
  9714. 'order_type' => '',
  9715. 'score_weights' => '',
  9716. ];
  9717. }
  9718. /**
  9719. * 邮件发送日志用的订单号列表(多单逗号分隔;与模版变量是否留空无关)
  9720. *
  9721. * @param array<int, array<string, mixed>> $mergeRows
  9722. * @param array<int, array<string, mixed>> $pos
  9723. */
  9724. protected function collectCcydhListForEmailLog(array $mergeRows, array $pos = []): string
  9725. {
  9726. $set = [];
  9727. foreach ($mergeRows as $r) {
  9728. if (!is_array($r)) {
  9729. continue;
  9730. }
  9731. foreach (['CCYDH', 'ccydh'] as $k) {
  9732. $dh = trim((string)($r[$k] ?? ''));
  9733. if ($dh !== '') {
  9734. $set[$dh] = true;
  9735. break;
  9736. }
  9737. }
  9738. }
  9739. if ($set === []) {
  9740. foreach ($pos as $po) {
  9741. if (!is_array($po)) {
  9742. continue;
  9743. }
  9744. foreach (['CCYDH', 'ccydh'] as $k) {
  9745. $dh = trim((string)($po[$k] ?? ''));
  9746. if ($dh !== '') {
  9747. $set[$dh] = true;
  9748. break;
  9749. }
  9750. }
  9751. }
  9752. }
  9753. return implode(',', array_keys($set));
  9754. }
  9755. /**
  9756. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  9757. *
  9758. * @param array<string, mixed> $data
  9759. */
  9760. protected function logIssueNotifyDebug(string $type, array $data): void
  9761. {
  9762. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  9763. return;
  9764. }
  9765. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  9766. }
  9767. protected function ensurePurchaseEmailSendLogTableOnce(): void
  9768. {
  9769. try {
  9770. Db::query('SELECT `id`,`order_batch_no`,`ccydh` FROM `purchase_email_send_log` LIMIT 1');
  9771. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  9772. return;
  9773. } catch (\Throwable $e) {
  9774. }
  9775. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  9776. if (is_file($sqlFile)) {
  9777. $sql = file_get_contents($sqlFile);
  9778. if (is_string($sql) && $sql !== '') {
  9779. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  9780. $stmt = trim($stmt);
  9781. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  9782. continue;
  9783. }
  9784. try {
  9785. Db::execute($stmt);
  9786. } catch (\Throwable $ignore) {
  9787. }
  9788. }
  9789. }
  9790. }
  9791. try {
  9792. $cols = Db::query("SHOW COLUMNS FROM `purchase_email_send_log` LIKE 'order_batch_no'");
  9793. if (!is_array($cols) || $cols === []) {
  9794. Db::execute(
  9795. "ALTER TABLE `purchase_email_send_log` ADD COLUMN `order_batch_no` varchar(32) NOT NULL DEFAULT '' COMMENT '下发批次号' AFTER `scene`"
  9796. );
  9797. }
  9798. } catch (\Throwable $ignore) {
  9799. }
  9800. try {
  9801. $cols = Db::query("SHOW COLUMNS FROM `purchase_email_send_log` LIKE 'ccydh'");
  9802. if (is_array($cols) && $cols !== []) {
  9803. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  9804. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 500) {
  9805. Db::execute(
  9806. "ALTER TABLE `purchase_email_send_log` MODIFY COLUMN `ccydh` varchar(500) NOT NULL DEFAULT '' COMMENT '订单号(多单逗号分隔)'"
  9807. );
  9808. }
  9809. }
  9810. } catch (\Throwable $ignore) {
  9811. }
  9812. try {
  9813. $idx = Db::query("SHOW INDEX FROM `purchase_email_send_log` WHERE Key_name = 'idx_order_batch_no'");
  9814. if (!is_array($idx) || $idx === []) {
  9815. Db::execute('ALTER TABLE `purchase_email_send_log` ADD INDEX `idx_order_batch_no` (`order_batch_no`)');
  9816. }
  9817. } catch (\Throwable $ignore) {
  9818. }
  9819. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  9820. }
  9821. /**
  9822. * @param array<string, mixed> $row
  9823. */
  9824. protected function persistEmailSendLog(array $row): void
  9825. {
  9826. try {
  9827. $this->ensurePurchaseEmailSendLogTableOnce();
  9828. } catch (\Throwable $e) {
  9829. return;
  9830. }
  9831. list($adminId, $adminName) = $this->GetUseName();
  9832. $cut = function ($s, $max) {
  9833. $s = (string)$s;
  9834. if (function_exists('mb_substr')) {
  9835. return mb_substr($s, 0, $max, 'UTF-8');
  9836. }
  9837. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  9838. };
  9839. $data = [
  9840. 'from_email' => $cut($row['from_email'] ?? '', 128),
  9841. 'to_email' => $cut($row['to_email'] ?? '', 128),
  9842. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  9843. 'scene' => $cut($this->normalizeEmailLogSceneForStore((string)($row['scene'] ?? '')), 64),
  9844. 'order_batch_no' => $cut($row['order_batch_no'] ?? '', 32),
  9845. 'ccydh' => $cut($row['ccydh'] ?? '', 500),
  9846. 'company_name' => $cut($row['company_name'] ?? '', 128),
  9847. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  9848. 'status' => !empty($row['status']) ? 1 : 0,
  9849. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  9850. 'admin_id' => (int)$adminId,
  9851. 'admin_name' => $cut($adminName, 64),
  9852. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  9853. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  9854. 'createtime' => date('Y-m-d H:i:s'),
  9855. ];
  9856. try {
  9857. Db::table('purchase_email_send_log')->insert($data);
  9858. } catch (\Throwable $e) {
  9859. // 兼容尚未自动补列的旧库:去掉批次号再试一次
  9860. if (stripos($e->getMessage(), 'order_batch_no') !== false) {
  9861. try {
  9862. unset($data['order_batch_no']);
  9863. Db::table('purchase_email_send_log')->insert($data);
  9864. return;
  9865. } catch (\Throwable $e2) {
  9866. Log::write('persistEmailSendLog: ' . $e2->getMessage(), 'error');
  9867. return;
  9868. }
  9869. }
  9870. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  9871. }
  9872. }
  9873. /**
  9874. * 邮件日志场景:库内统一存中文;兼容历史英文码
  9875. *
  9876. * @return array<string, string>
  9877. */
  9878. protected function emailLogSceneLabelMap(): array
  9879. {
  9880. return ProcuremenFormat::emailLogSceneLabelMap();
  9881. }
  9882. /** 写入邮件日志前:英文场景码转中文;已是中文则原样 */
  9883. protected function normalizeEmailLogSceneForStore(string $scene): string
  9884. {
  9885. return ProcuremenFormat::normalizeEmailLogSceneForStore($scene);
  9886. }
  9887. protected function formatEmailLogSceneText(string $scene): string
  9888. {
  9889. return ProcuremenFormat::emailLogSceneText($scene);
  9890. }
  9891. /**
  9892. * 邮件发送日志列表
  9893. */
  9894. public function emailLog()
  9895. {
  9896. $this->relationSearch = false;
  9897. $this->searchFields = 'from_email,to_email,ccydh,order_batch_no,company_name,admin_name,mail_subject';
  9898. $this->request->filter(['strip_tags', 'trim']);
  9899. $bakModel = $this->model;
  9900. $this->model = new \app\admin\model\Purchaseemailsendlog;
  9901. if ($this->request->isAjax()) {
  9902. $this->ensurePurchaseEmailSendLogTableOnce();
  9903. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  9904. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  9905. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  9906. $list = $this->model
  9907. ->where($where)
  9908. ->order($sortField, $orderDir)
  9909. ->paginate($limit);
  9910. $rows = [];
  9911. $needEnrichPoIds = [];
  9912. foreach ($list->items() as $item) {
  9913. $row = is_array($item) ? $item : $item->toArray();
  9914. $scene = trim((string)($row['scene'] ?? ''));
  9915. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  9916. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  9917. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  9918. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  9919. $row['order_batch_no'] = trim((string)($row['order_batch_no'] ?? ''));
  9920. $row['ccydh'] = trim((string)($row['ccydh'] ?? ''));
  9921. $poId = (int)($row['purchase_order_id'] ?? 0);
  9922. if ($poId > 0 && ($row['ccydh'] === '' || $row['order_batch_no'] === '')) {
  9923. $needEnrichPoIds[$poId] = true;
  9924. }
  9925. $rows[] = $row;
  9926. }
  9927. if ($needEnrichPoIds !== []) {
  9928. $poMap = $this->loadEmailLogEnrichPoMap(array_keys($needEnrichPoIds));
  9929. foreach ($rows as &$row) {
  9930. $poId = (int)($row['purchase_order_id'] ?? 0);
  9931. if ($poId <= 0 || !isset($poMap[$poId])) {
  9932. continue;
  9933. }
  9934. $info = $poMap[$poId];
  9935. if ($row['order_batch_no'] === '' && $info['order_batch_no'] !== '') {
  9936. $row['order_batch_no'] = $info['order_batch_no'];
  9937. }
  9938. if ($row['ccydh'] === '') {
  9939. if ($info['order_batch_no'] !== '' && isset($info['batch_ccydhs']) && $info['batch_ccydhs'] !== '') {
  9940. $row['ccydh'] = $info['batch_ccydhs'];
  9941. } elseif ($info['ccydh'] !== '') {
  9942. $row['ccydh'] = $info['ccydh'];
  9943. }
  9944. }
  9945. }
  9946. unset($row);
  9947. }
  9948. $this->model = $bakModel;
  9949. return json(['total' => $list->total(), 'rows' => $rows]);
  9950. }
  9951. $this->model = $bakModel;
  9952. return $this->view->fetch('procuremen/emaillog');
  9953. }
  9954. /**
  9955. * 历史邮件日志缺订单号/批次号时,按 purchase_order_id 回填展示
  9956. *
  9957. * @param array<int, int> $poIds
  9958. * @return array<int, array{ccydh:string,order_batch_no:string,batch_ccydhs:string}>
  9959. */
  9960. protected function loadEmailLogEnrichPoMap(array $poIds): array
  9961. {
  9962. $out = [];
  9963. $poIds = array_values(array_unique(array_filter(array_map('intval', $poIds))));
  9964. if ($poIds === []) {
  9965. return $out;
  9966. }
  9967. try {
  9968. $pos = Db::table('purchase_order')->where('id', 'in', $poIds)->field('id,CCYDH,order_batch_no')->select();
  9969. } catch (\Throwable $e) {
  9970. try {
  9971. $pos = Db::table('purchase_order')->where('id', 'in', $poIds)->field('id,CCYDH')->select();
  9972. } catch (\Throwable $e2) {
  9973. return $out;
  9974. }
  9975. }
  9976. $batchSet = [];
  9977. foreach ($pos as $po) {
  9978. if (!is_array($po)) {
  9979. continue;
  9980. }
  9981. $id = (int)($po['id'] ?? 0);
  9982. if ($id <= 0) {
  9983. continue;
  9984. }
  9985. $bn = $this->resolveProcuremenOrderBatchNo($po);
  9986. $out[$id] = [
  9987. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9988. 'order_batch_no' => $bn,
  9989. 'batch_ccydhs' => '',
  9990. ];
  9991. if ($bn !== '') {
  9992. $batchSet[$bn] = true;
  9993. }
  9994. }
  9995. if ($batchSet === []) {
  9996. return $out;
  9997. }
  9998. try {
  9999. $batchRows = Db::table('purchase_order')
  10000. ->where('order_batch_no', 'in', array_keys($batchSet))
  10001. ->field('CCYDH,order_batch_no')
  10002. ->select();
  10003. } catch (\Throwable $e) {
  10004. return $out;
  10005. }
  10006. $byBatch = [];
  10007. foreach ($batchRows as $br) {
  10008. if (!is_array($br)) {
  10009. continue;
  10010. }
  10011. $bn = trim((string)($br['order_batch_no'] ?? ''));
  10012. $dh = trim((string)($br['CCYDH'] ?? ''));
  10013. if ($bn === '' || $dh === '') {
  10014. continue;
  10015. }
  10016. $byBatch[$bn][$dh] = true;
  10017. }
  10018. foreach ($out as $id => $info) {
  10019. $bn = $info['order_batch_no'];
  10020. if ($bn !== '' && isset($byBatch[$bn])) {
  10021. $out[$id]['batch_ccydhs'] = implode(',', array_keys($byBatch[$bn]));
  10022. }
  10023. }
  10024. return $out;
  10025. }
  10026. /**
  10027. * 协助下发弹窗(选多家供应商并通知)
  10028. */
  10029. public function pickReview()
  10030. {
  10031. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  10032. $this->error(__('You have no permission'));
  10033. }
  10034. if ($this->request->isPost()) {
  10035. $this->error('请使用弹窗内「确认下发」提交');
  10036. }
  10037. $this->view->assign('pickMode', 1);
  10038. $this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
  10039. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  10040. }
  10041. /**
  10042. * 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
  10043. */
  10044. protected function ensurePurchaseOrderNotifySalesmanColumn(): void
  10045. {
  10046. static $done = false;
  10047. if ($done) {
  10048. return;
  10049. }
  10050. $done = true;
  10051. try {
  10052. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'notify_salesman'");
  10053. if (empty($cols)) {
  10054. Db::execute(
  10055. "ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
  10056. );
  10057. } else {
  10058. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  10059. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
  10060. Db::execute(
  10061. "ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
  10062. );
  10063. }
  10064. }
  10065. } catch (\Throwable $e) {
  10066. // ignore
  10067. }
  10068. }
  10069. /**
  10070. * 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
  10071. */
  10072. protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
  10073. {
  10074. static $done = false;
  10075. if ($done) {
  10076. return;
  10077. }
  10078. $done = true;
  10079. try {
  10080. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
  10081. if (empty($cols)) {
  10082. Db::execute(
  10083. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
  10084. );
  10085. }
  10086. } catch (\Throwable $e) {
  10087. // ignore
  10088. }
  10089. try {
  10090. $cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
  10091. if (empty($cols2)) {
  10092. Db::execute(
  10093. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
  10094. );
  10095. }
  10096. } catch (\Throwable $e) {
  10097. // ignore
  10098. }
  10099. }
  10100. /**
  10101. * 确保「采购确认通过/未通过」邮箱模版存在。
  10102. * title=说明;remark=邮箱通知;邮件主题由 resolveProcuremenEmailSubject 固定,不用 title。
  10103. */
  10104. protected function ensureConfirmResultEmailTemplates(): void
  10105. {
  10106. static $done = false;
  10107. if ($done) {
  10108. return;
  10109. }
  10110. $done = true;
  10111. $now = date('Y-m-d H:i:s');
  10112. $seeds = [
  10113. 'confirm_ok_email' => [
  10114. 'title' => '确认已通过通知',
  10115. 'content' => "您好,{company_name}:\n\n您参与的订单采购确认结果:已通过 已中标。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  10116. 'remark' => '邮箱通知',
  10117. ],
  10118. 'confirm_fail_email' => [
  10119. 'title' => '确认未通过通知',
  10120. 'content' => "您好,{company_name}:\n\n您参与的订单采购确认结果:未通过 未中标。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  10121. 'remark' => '邮箱通知',
  10122. ],
  10123. ];
  10124. try {
  10125. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  10126. } catch (\Throwable $e) {
  10127. return;
  10128. }
  10129. $colNames = [];
  10130. foreach ($cols as $c) {
  10131. if (!is_array($c)) {
  10132. continue;
  10133. }
  10134. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  10135. if ($n !== '') {
  10136. $colNames[$n] = true;
  10137. }
  10138. }
  10139. foreach ($seeds as $scene => $seed) {
  10140. try {
  10141. $row = Db::table('purchase_sms_template')->where('scene', $scene)->find();
  10142. } catch (\Throwable $e) {
  10143. continue;
  10144. }
  10145. if (is_array($row) && $row !== []) {
  10146. continue;
  10147. }
  10148. $data = [
  10149. 'scene' => $scene,
  10150. 'title' => $seed['title'],
  10151. 'content' => $seed['content'],
  10152. 'remark' => $seed['remark'],
  10153. 'status' => 1,
  10154. ];
  10155. if (isset($colNames['updatetime'])) {
  10156. $data['updatetime'] = $now;
  10157. }
  10158. if (isset($colNames['createtime'])) {
  10159. $data['createtime'] = $now;
  10160. }
  10161. try {
  10162. Db::table('purchase_sms_template')->insert($data);
  10163. } catch (\Throwable $e) {
  10164. // ignore
  10165. }
  10166. }
  10167. }
  10168. /**
  10169. * 确保「供应商询价通知」邮箱模版存在(查询询价-询价/发邮件;可在短信模版配置中修改)
  10170. */
  10171. protected function ensureRfqSupplierEmailTemplate(): void
  10172. {
  10173. static $done = false;
  10174. if ($done) {
  10175. return;
  10176. }
  10177. $done = true;
  10178. $content = "您好,{company_name}:\n\n"
  10179. . "您有新的协助采购询价需求,请登录平台查看并处理。\n\n"
  10180. . "需求编号:{ccydh}\n"
  10181. . "印件名称:{cyjmc}\n"
  10182. . "{process_lines}\n\n"
  10183. . "请在 {deadline} 前完成回复。\n\n"
  10184. . "平台链接:{platform_url}\n";
  10185. try {
  10186. $row = Db::table('purchase_sms_template')
  10187. ->where('scene', 'rfq_supplier_email')
  10188. ->find();
  10189. } catch (\Throwable $e) {
  10190. return;
  10191. }
  10192. $now = date('Y-m-d H:i:s');
  10193. if (is_array($row) && $row !== []) {
  10194. return;
  10195. }
  10196. try {
  10197. $data = [
  10198. 'scene' => 'rfq_supplier_email',
  10199. 'title' => '供应商询价通知',
  10200. 'content' => $content,
  10201. 'remark' => '查询询价-询价/发邮件通知供应商;模版名称作邮件主题',
  10202. 'status' => 1,
  10203. ];
  10204. try {
  10205. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  10206. } catch (\Throwable $e) {
  10207. $cols = [];
  10208. }
  10209. $colNames = [];
  10210. foreach ($cols as $c) {
  10211. if (!is_array($c)) {
  10212. continue;
  10213. }
  10214. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  10215. if ($n !== '') {
  10216. $colNames[$n] = true;
  10217. }
  10218. }
  10219. if (isset($colNames['updatetime'])) {
  10220. $data['updatetime'] = $now;
  10221. }
  10222. if (isset($colNames['createtime'])) {
  10223. $data['createtime'] = $now;
  10224. }
  10225. Db::table('purchase_sms_template')->insert($data);
  10226. } catch (\Throwable $e) {
  10227. // ignore
  10228. }
  10229. }
  10230. /**
  10231. * 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
  10232. */
  10233. protected function ensureRfqSalesmanEmailTemplate(): void
  10234. {
  10235. static $done = false;
  10236. if ($done) {
  10237. return;
  10238. }
  10239. $done = true;
  10240. $content = "您好,{contact_name}:\n\n"
  10241. . "有新的协助采购询价需求,请知悉。\n"
  10242. . "印件名称:{cyjmc}\n"
  10243. . "工序名称:{cgymc}\n"
  10244. . "本次数量:{this_quantity}\n"
  10245. . "供应商报价:\n{supplier_quotes}\n"
  10246. . "平台链接:{platform_url}\n"
  10247. . "需求发起人:{cywyxm}\n";
  10248. try {
  10249. $row = Db::table('purchase_sms_template')
  10250. ->where('scene', 'rfq_salesman_email')
  10251. ->find();
  10252. } catch (\Throwable $e) {
  10253. return;
  10254. }
  10255. $now = date('Y-m-d H:i:s');
  10256. if (is_array($row) && $row !== []) {
  10257. $old = (string)($row['content'] ?? '');
  10258. // 无报价表格 / 无平台链接 / 链接不在「需求发起人」上方时,同步默认文案
  10259. $urlPos = strpos($old, '{platform_url}');
  10260. $cywyPos = strpos($old, '需求发起人');
  10261. $linkNotAboveStarter = ($urlPos === false)
  10262. || ($cywyPos !== false && $urlPos > $cywyPos);
  10263. $needMigrate = (strpos($old, '{supplier_quotes}') === false)
  10264. || (strpos($old, '供应商:{supplier_name}') !== false)
  10265. || $linkNotAboveStarter;
  10266. if ($needMigrate) {
  10267. $data = ['content' => $content];
  10268. if (trim((string)($row['title'] ?? '')) === '' || trim((string)($row['title'] ?? '')) === '询价通知') {
  10269. $data['title'] = '业务员询价通知';
  10270. }
  10271. try {
  10272. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
  10273. if (!empty($cols)) {
  10274. $data['updatetime'] = $now;
  10275. }
  10276. } catch (\Throwable $e) {
  10277. }
  10278. try {
  10279. Db::table('purchase_sms_template')
  10280. ->where('id', (int)($row['id'] ?? 0))
  10281. ->update($data);
  10282. } catch (\Throwable $e) {
  10283. }
  10284. }
  10285. return;
  10286. }
  10287. try {
  10288. $data = [
  10289. 'scene' => 'rfq_salesman_email',
  10290. 'title' => '业务员询价通知',
  10291. 'content' => $content,
  10292. 'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
  10293. 'status' => 1,
  10294. ];
  10295. try {
  10296. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  10297. } catch (\Throwable $e) {
  10298. $cols = [];
  10299. }
  10300. $colNames = [];
  10301. foreach ($cols as $c) {
  10302. if (!is_array($c)) {
  10303. continue;
  10304. }
  10305. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  10306. if ($n !== '') {
  10307. $colNames[$n] = true;
  10308. }
  10309. }
  10310. if (isset($colNames['updatetime'])) {
  10311. $data['updatetime'] = $now;
  10312. }
  10313. if (isset($colNames['createtime'])) {
  10314. $data['createtime'] = $now;
  10315. }
  10316. Db::table('purchase_sms_template')->insert($data);
  10317. } catch (\Throwable $e) {
  10318. // ignore
  10319. }
  10320. }
  10321. /**
  10322. * 通知业务员邮件:供应商报价明细行(仅名称+单价)
  10323. *
  10324. * @return array<int, array{name:string,amount:string}>
  10325. */
  10326. protected function loadRfqSalesmanSupplierQuoteRows(int $sid, string $supplierRaw = ''): array
  10327. {
  10328. $list = [];
  10329. $seen = [];
  10330. try {
  10331. $rows = Db::table('purchase_order_detail')
  10332. ->where('scydgy_id', $sid)
  10333. ->field('company_name,amount')
  10334. ->order('id', 'asc')
  10335. ->select();
  10336. if (is_array($rows)) {
  10337. foreach ($rows as $r) {
  10338. if (!is_array($r)) {
  10339. continue;
  10340. }
  10341. $cn = trim((string)($r['company_name'] ?? ''));
  10342. if ($cn === '' || isset($seen[$cn])) {
  10343. continue;
  10344. }
  10345. $seen[$cn] = true;
  10346. $amount = trim((string)($r['amount'] ?? ''));
  10347. $list[] = [
  10348. 'name' => $cn,
  10349. 'amount' => $amount !== '' ? $amount : '未报价',
  10350. ];
  10351. }
  10352. }
  10353. } catch (\Throwable $e) {
  10354. }
  10355. if ($list === [] && $supplierRaw !== '') {
  10356. foreach ($this->splitRfqSalesmanNames($supplierRaw) as $cn) {
  10357. if ($cn === '' || isset($seen[$cn])) {
  10358. continue;
  10359. }
  10360. $seen[$cn] = true;
  10361. $list[] = [
  10362. 'name' => $cn,
  10363. 'amount' => '未报价',
  10364. ];
  10365. }
  10366. }
  10367. return $list;
  10368. }
  10369. /**
  10370. * 通知业务员邮件:供应商报价 HTML 表格(名称+单价,不含时间)
  10371. */
  10372. protected function buildRfqSalesmanSupplierQuotesHtml(int $sid, string $supplierRaw = ''): string
  10373. {
  10374. $rows = $this->loadRfqSalesmanSupplierQuoteRows($sid, $supplierRaw);
  10375. if ($rows === []) {
  10376. return '<p style="margin:8px 0;color:#888;">暂无报价</p>';
  10377. }
  10378. $html = '<table cellpadding="0" cellspacing="0" border="1" '
  10379. . 'style="border-collapse:collapse;border-color:#ddd;width:100%;max-width:560px;font-size:14px;margin:8px 0;">'
  10380. . '<thead><tr style="background:#f5f5f5;">'
  10381. . '<th style="padding:8px 10px;text-align:center;width:56px;">序号</th>'
  10382. . '<th style="padding:8px 10px;text-align:left;">供应商名称</th>'
  10383. . '<th style="padding:8px 10px;text-align:center;width:100px;">单价</th>'
  10384. . '</tr></thead><tbody>';
  10385. foreach ($rows as $i => $row) {
  10386. $html .= '<tr>'
  10387. . '<td style="padding:8px 10px;text-align:center;">' . ($i + 1) . '</td>'
  10388. . '<td style="padding:8px 10px;">' . htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8') . '</td>'
  10389. . '<td style="padding:8px 10px;text-align:center;">' . htmlspecialchars($row['amount'], ENT_QUOTES, 'UTF-8') . '</td>'
  10390. . '</tr>';
  10391. }
  10392. $html .= '</tbody></table>';
  10393. return $html;
  10394. }
  10395. /**
  10396. * 询价多选字段:数组或字符串统一为顿号拼接
  10397. *
  10398. * @param mixed $raw
  10399. */
  10400. protected function joinRfqMultiSelectValues($raw): string
  10401. {
  10402. $parts = [];
  10403. if (is_array($raw)) {
  10404. foreach ($raw as $item) {
  10405. if (is_array($item)) {
  10406. continue;
  10407. }
  10408. $v = trim((string)$item);
  10409. if ($v !== '') {
  10410. $parts[] = $v;
  10411. }
  10412. }
  10413. } else {
  10414. $s = trim((string)$raw);
  10415. if ($s !== '') {
  10416. foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
  10417. $v = trim((string)$piece);
  10418. if ($v !== '') {
  10419. $parts[] = $v;
  10420. }
  10421. }
  10422. }
  10423. }
  10424. $parts = array_values(array_unique($parts));
  10425. return implode('、', $parts);
  10426. }
  10427. /**
  10428. * 新增询价:可选供应商名称(仅落库记录,不发通知)
  10429. *
  10430. * @return string[]
  10431. */
  10432. protected function loadRfqSupplierNameOptions(): array
  10433. {
  10434. $out = [];
  10435. try {
  10436. $rows = Db::table('customer')
  10437. ->where(function ($q) {
  10438. $q->where('status', 1)
  10439. ->whereOr('status', '1')
  10440. ->whereOr('status', '')
  10441. ->whereNull('status');
  10442. })
  10443. ->order('id', 'desc')
  10444. ->column('company_name');
  10445. } catch (\Throwable $e) {
  10446. return [];
  10447. }
  10448. if (!is_array($rows)) {
  10449. return [];
  10450. }
  10451. foreach ($rows as $name) {
  10452. $name = trim((string)$name);
  10453. if ($name === '' || isset($out[$name])) {
  10454. continue;
  10455. }
  10456. $out[$name] = $name;
  10457. }
  10458. return array_values($out);
  10459. }
  10460. /**
  10461. * 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
  10462. */
  10463. protected function rfqNotifySalesmanAuthGroupId(): int
  10464. {
  10465. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  10466. if ($id > 0) {
  10467. return $id;
  10468. }
  10469. try {
  10470. $found = Db::name('auth_group')
  10471. ->where('name', '业务员')
  10472. ->where('status', 'normal')
  10473. ->order('id', 'asc')
  10474. ->value('id');
  10475. $id = (int)$found;
  10476. } catch (\Throwable $e) {
  10477. $id = 0;
  10478. }
  10479. return $id > 0 ? $id : 12;
  10480. }
  10481. /**
  10482. * 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
  10483. *
  10484. * @return string[]
  10485. */
  10486. protected function loadRfqSalesmanNameOptions(): array
  10487. {
  10488. $out = [];
  10489. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  10490. $name = trim((string)($row['name'] ?? ''));
  10491. if ($name !== '') {
  10492. $out[] = $name;
  10493. }
  10494. }
  10495. return $out;
  10496. }
  10497. /**
  10498. * 业务员角色组下管理员:姓名、邮箱、手机
  10499. *
  10500. * @return array<int, array{name:string,email:string,mobile:string}>
  10501. */
  10502. protected function loadRfqSalesmanContactOptions(): array
  10503. {
  10504. $out = [];
  10505. $seen = [];
  10506. $groupId = $this->rfqNotifySalesmanAuthGroupId();
  10507. if ($groupId <= 0) {
  10508. return [];
  10509. }
  10510. try {
  10511. $adminIds = Db::name('auth_group_access')
  10512. ->where('group_id', $groupId)
  10513. ->column('uid');
  10514. } catch (\Throwable $e) {
  10515. return [];
  10516. }
  10517. $adminIds = is_array($adminIds)
  10518. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  10519. : [];
  10520. if ($adminIds === []) {
  10521. return [];
  10522. }
  10523. try {
  10524. $rows = Db::name('admin')
  10525. ->where('status', 'normal')
  10526. ->where('id', 'in', $adminIds)
  10527. ->order('id', 'asc')
  10528. ->field('id,nickname,username,email,mobile')
  10529. ->select();
  10530. } catch (\Throwable $e) {
  10531. return [];
  10532. }
  10533. if (!is_array($rows)) {
  10534. return [];
  10535. }
  10536. foreach ($rows as $row) {
  10537. if (!is_array($row)) {
  10538. continue;
  10539. }
  10540. $name = trim((string)($row['nickname'] ?? ''));
  10541. if ($name === '') {
  10542. $name = trim((string)($row['username'] ?? ''));
  10543. }
  10544. if ($name === '' || isset($seen[$name])) {
  10545. continue;
  10546. }
  10547. $seen[$name] = true;
  10548. $out[] = [
  10549. 'name' => $name,
  10550. 'email' => trim((string)($row['email'] ?? '')),
  10551. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  10552. ];
  10553. }
  10554. return $out;
  10555. }
  10556. /**
  10557. * 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
  10558. *
  10559. * @return string[]
  10560. */
  10561. protected function loadRfqDeptNameOptions(): array
  10562. {
  10563. $out = [];
  10564. // ERP 承揽部门(主来源)
  10565. try {
  10566. $vals = Db::table('mcyd')
  10567. ->where('CCLBMMC', '<>', '')
  10568. ->whereNotNull('CCLBMMC')
  10569. ->distinct(true)
  10570. ->limit(300)
  10571. ->column('CCLBMMC');
  10572. } catch (\Throwable $e) {
  10573. $vals = [];
  10574. }
  10575. if (is_array($vals)) {
  10576. foreach ($vals as $v) {
  10577. $v = trim((string)$v);
  10578. if ($v === '' || isset($out[$v])) {
  10579. continue;
  10580. }
  10581. $out[$v] = $v;
  10582. }
  10583. }
  10584. // 手工询价历史部门补全
  10585. try {
  10586. $poVals = Db::table('purchase_order')
  10587. ->where('CCLBMMC', '<>', '')
  10588. ->whereNotNull('CCLBMMC')
  10589. ->distinct(true)
  10590. ->limit(200)
  10591. ->column('CCLBMMC');
  10592. } catch (\Throwable $e) {
  10593. $poVals = [];
  10594. }
  10595. if (is_array($poVals)) {
  10596. foreach ($poVals as $v) {
  10597. $v = trim((string)$v);
  10598. if ($v === '' || isset($out[$v])) {
  10599. continue;
  10600. }
  10601. $out[$v] = $v;
  10602. }
  10603. }
  10604. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  10605. if (!isset($out[$preset])) {
  10606. $out[$preset] = $preset;
  10607. }
  10608. }
  10609. $list = array_values($out);
  10610. // 常用部门靠前
  10611. usort($list, static function ($a, $b) {
  10612. $weight = [
  10613. '营销中心' => 1,
  10614. '业务部' => 2,
  10615. '市场部' => 3,
  10616. '外贸部' => 4,
  10617. '新华技术业务部' => 5,
  10618. ];
  10619. $wa = $weight[$a] ?? 100;
  10620. $wb = $weight[$b] ?? 100;
  10621. if ($wa !== $wb) {
  10622. return $wa <=> $wb;
  10623. }
  10624. return strcmp((string)$a, (string)$b);
  10625. });
  10626. return $list;
  10627. }
  10628. /**
  10629. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  10630. */
  10631. public function add()
  10632. {
  10633. if ($this->request->isPost()) {
  10634. $params = $this->request->post('row/a');
  10635. if (!is_array($params)) {
  10636. $this->error(__('Parameter %s can not be empty', ''));
  10637. }
  10638. [, $adminName] = $this->GetUseName();
  10639. $params['cywyxm'] = $adminName;
  10640. try {
  10641. $sid = $this->saveManualPickOrder($params);
  10642. } catch (\InvalidArgumentException $e) {
  10643. $this->error($e->getMessage());
  10644. } catch (\Throwable $e) {
  10645. $this->error($e->getMessage());
  10646. }
  10647. $this->success('新增成功', '', [
  10648. 'scydgy_id' => $sid,
  10649. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  10650. ]);
  10651. }
  10652. $this->ensurePurchaseOrderNotifySalesmanColumn();
  10653. [, $adminName] = $this->GetUseName();
  10654. $this->view->assign('adminNickname', $adminName);
  10655. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  10656. $this->view->assign('defaultCclbmmc', '营销中心');
  10657. $this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
  10658. $this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
  10659. $this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
  10660. return $this->view->fetch();
  10661. }
  10662. /**
  10663. * 业务员新增进度查询(手工询价;有查询权限看全部,含手机端新增且未通知业务员的)
  10664. */
  10665. public function rfqlist()
  10666. {
  10667. $this->relationSearch = false;
  10668. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ';
  10669. $this->request->filter(['strip_tags', 'trim']);
  10670. $this->ensurePurchaseOrderNotifySalesmanColumn();
  10671. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  10672. $this->ensureRfqSalesmanEmailTemplate();
  10673. $this->ensureRfqSupplierEmailTemplate();
  10674. if ($this->request->isAjax()) {
  10675. try {
  10676. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  10677. $limit = max(10, min(500, (int)$limit));
  10678. $filterYm = trim((string)$this->request->param('filter_ym', ''));
  10679. if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
  10680. $filterYm = date('Y-m');
  10681. }
  10682. $applyFilters = function ($query) use ($where, $filterYm) {
  10683. $query->where('scydgy_id', '<', 0);
  10684. $this->applyPurchaseOrderNotDeletedWhere($query);
  10685. // 查询询价:有菜单权限即可看全部手工单(含手机端新增、尚未通知业务员的)
  10686. $this->applyRfqListMonthFilter($query, $filterYm);
  10687. if (!empty($where)) {
  10688. // 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
  10689. $safeWhere = [];
  10690. $skipFields = [
  10691. 'supplier_name' => true,
  10692. 'progress_text' => true,
  10693. 'createtime_text' => true,
  10694. 'notify_time_text' => true,
  10695. 'can_notify_salesman' => true,
  10696. 'has_issued' => true,
  10697. 'has_quoted' => true,
  10698. ];
  10699. foreach ((array)$where as $cond) {
  10700. if (!is_array($cond) || !isset($cond[0])) {
  10701. continue;
  10702. }
  10703. $field = (string)$cond[0];
  10704. $fieldBase = (string)preg_replace('/\|.*$/', '', $field);
  10705. $fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
  10706. if (isset($skipFields[$fieldBase])) {
  10707. continue;
  10708. }
  10709. if ($fieldBase === 'supplier_name') {
  10710. continue;
  10711. }
  10712. $safeWhere[] = $cond;
  10713. }
  10714. if ($safeWhere !== []) {
  10715. $query->where($safeWhere);
  10716. }
  10717. }
  10718. };
  10719. $countQuery = Db::table('purchase_order');
  10720. $applyFilters($countQuery);
  10721. $total = (int)$countQuery->count();
  10722. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  10723. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  10724. $listQuery = Db::table('purchase_order');
  10725. $applyFilters($listQuery);
  10726. $rows = $listQuery
  10727. ->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')
  10728. ->order($sortField, $orderDir)
  10729. ->limit($offset, $limit)
  10730. ->select();
  10731. if (!is_array($rows)) {
  10732. $rows = [];
  10733. }
  10734. $sidList = [];
  10735. foreach ($rows as $r) {
  10736. if (!is_array($r)) {
  10737. continue;
  10738. }
  10739. $sid = (int)($r['scydgy_id'] ?? 0);
  10740. if ($sid < 0) {
  10741. $sidList[$sid] = true;
  10742. }
  10743. }
  10744. $issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
  10745. $quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
  10746. $out = [];
  10747. foreach ($rows as $r) {
  10748. if (!is_array($r)) {
  10749. continue;
  10750. }
  10751. $sid = (int)($r['scydgy_id'] ?? 0);
  10752. if ($sid >= 0) {
  10753. continue;
  10754. }
  10755. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  10756. if ($createdText === '') {
  10757. $createdText = trim((string)($r['dStamp'] ?? ''));
  10758. }
  10759. $notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
  10760. $supplier = trim((string)($r['cGzzxMc'] ?? ''));
  10761. if ($supplier === '') {
  10762. $supplier = trim((string)($r['pick_company_name'] ?? ''));
  10763. }
  10764. $hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
  10765. || isset($issuedSidSet[$sid]);
  10766. $hasQuoted = isset($quotedSidSet[$sid]);
  10767. $salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
  10768. $canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
  10769. $out[] = [
  10770. 'id' => (int)($r['id'] ?? 0),
  10771. 'scydgy_id' => $sid,
  10772. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  10773. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  10774. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  10775. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  10776. 'CDW' => trim((string)($r['CDW'] ?? '')),
  10777. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  10778. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  10779. 'CDF' => trim((string)($r['CDF'] ?? '')),
  10780. 'supplier_name' => $supplier,
  10781. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  10782. 'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
  10783. 'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
  10784. 'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
  10785. 'notify_time_text' => $notifyTimeText,
  10786. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  10787. 'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
  10788. 'has_issued' => $hasIssued ? 1 : 0,
  10789. 'has_quoted' => $hasQuoted ? 1 : 0,
  10790. 'can_notify_salesman' => $canNotifySalesman,
  10791. 'createtime' => $r['createtime'] ?? null,
  10792. 'createtime_text' => $createdText,
  10793. ];
  10794. }
  10795. return json(['total' => $total, 'rows' => $out]);
  10796. } catch (\Throwable $e) {
  10797. Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
  10798. return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
  10799. }
  10800. }
  10801. $sidebar = $this->loadRfqSidebarYearMonths();
  10802. $defaultYm = $this->resolveRfqListDefaultYm($sidebar);
  10803. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  10804. [, $adminName] = $this->GetUseName();
  10805. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  10806. $this->view->assign('adminNickname', $adminName);
  10807. $this->view->assign('defaultYm', $defaultYm);
  10808. $this->view->assign('sidebarYearMonths', $sidebar);
  10809. return $this->view->fetch('procuremen/rfqlist');
  10810. }
  10811. /**
  10812. * 列表默认月份:当月有数据用当月,否则取最近有数据的月份
  10813. *
  10814. * @param array<int, array{year:string, months:array}> $sidebar
  10815. */
  10816. protected function resolveRfqListDefaultYm(array $sidebar): string
  10817. {
  10818. $current = date('Y-m');
  10819. $yms = $this->flattenProcuremenSidebarYms($sidebar);
  10820. if (in_array($current, $yms, true)) {
  10821. return $current;
  10822. }
  10823. if ($yms !== []) {
  10824. rsort($yms, SORT_STRING);
  10825. return (string)$yms[0];
  10826. }
  10827. return $current;
  10828. }
  10829. /**
  10830. * 手工询价列表左侧月份(按 createtime / dStamp)
  10831. *
  10832. * @return array<int, array{year:string, months:array}>
  10833. */
  10834. protected function loadRfqSidebarYearMonths(): array
  10835. {
  10836. $ymSet = [];
  10837. try {
  10838. $q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
  10839. $this->applyPurchaseOrderNotDeletedWhere($q);
  10840. $rows = $q->field('createtime,dStamp')->limit(5000)->select();
  10841. } catch (\Throwable $e) {
  10842. $rows = [];
  10843. }
  10844. if (!is_array($rows)) {
  10845. $rows = [];
  10846. }
  10847. foreach ($rows as $r) {
  10848. if (!is_array($r)) {
  10849. continue;
  10850. }
  10851. $t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  10852. if ($t === '') {
  10853. $t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
  10854. }
  10855. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  10856. $ymSet[$m[1] . '-' . $m[2]] = true;
  10857. }
  10858. }
  10859. return $this->buildYearMonthSidebar(array_keys($ymSet));
  10860. }
  10861. /**
  10862. * 手工询价可见范围(用于详情/操作校验):
  10863. * 超管、具备「查询询价」权限、需求发起人、通知业务员 → 可见
  10864. * 列表页本身不再按发起人/通知过滤,避免手机端新增后后台看不到。
  10865. */
  10866. protected function applyManualRfqViewerWhere($query): void
  10867. {
  10868. if ($this->auth->isSuperAdmin() || $this->hasProcuremenPerm(['rfqlist'])) {
  10869. return;
  10870. }
  10871. [, $adminName] = $this->GetUseName();
  10872. $adminName = trim((string)$adminName);
  10873. if ($adminName === '') {
  10874. $query->whereRaw('1 = 0');
  10875. return;
  10876. }
  10877. // 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
  10878. $query->where(function ($q) use ($adminName) {
  10879. $q->where('cywyxm', $adminName)
  10880. ->whereOr('notify_salesman', $adminName)
  10881. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  10882. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  10883. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  10884. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  10885. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  10886. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  10887. });
  10888. }
  10889. /**
  10890. * 当前用户是否可查看/操作该手工询价单
  10891. */
  10892. protected function canViewManualRfqOrder(array $po): bool
  10893. {
  10894. if ($this->auth->isSuperAdmin()) {
  10895. return true;
  10896. }
  10897. // 有查询询价权限则可操作全部手工询价(询价/查看报价/通知业务员等)
  10898. if ($this->hasProcuremenPerm(['rfqlist'])) {
  10899. return true;
  10900. }
  10901. [, $adminName] = $this->GetUseName();
  10902. $adminName = trim((string)$adminName);
  10903. if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
  10904. return true;
  10905. }
  10906. if ($adminName !== '') {
  10907. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  10908. if ($n === $adminName) {
  10909. return true;
  10910. }
  10911. }
  10912. }
  10913. return false;
  10914. }
  10915. /**
  10916. * 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
  10917. */
  10918. protected function applyRfqListMonthFilter($query, string $ym): void
  10919. {
  10920. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  10921. $ym = date('Y-m');
  10922. }
  10923. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  10924. // 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
  10925. $query->whereRaw(
  10926. "("
  10927. . "CASE "
  10928. . "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  10929. . "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
  10930. . "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
  10931. . "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  10932. . "THEN TRIM(CAST(createtime AS CHAR(32))) "
  10933. . "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
  10934. . "END"
  10935. . ") LIKE '{$ymEsc}-%'"
  10936. );
  10937. }
  10938. /**
  10939. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  10940. */
  10941. public function rfqlistDetails()
  10942. {
  10943. return $this->details();
  10944. }
  10945. /**
  10946. * 查询询价 — 弹窗:可选通知业务员名单(勾选后确认通知)
  10947. */
  10948. public function rfqnotifysalesmen()
  10949. {
  10950. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman'])) {
  10951. $this->error(__('You have no permission'));
  10952. }
  10953. $this->ensurePurchaseOrderNotifySalesmanColumn();
  10954. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  10955. $sid = (int)$this->request->param('scydgy_id', 0);
  10956. if ($sid >= 0) {
  10957. $this->error('仅支持手工新增询价单');
  10958. }
  10959. $po = $this->loadManualRfqOrderForNotify($sid);
  10960. $selectedMap = [];
  10961. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  10962. $selectedMap[$n] = true;
  10963. }
  10964. $list = [];
  10965. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  10966. $name = trim((string)($row['name'] ?? ''));
  10967. if ($name === '') {
  10968. continue;
  10969. }
  10970. $email = trim((string)($row['email'] ?? ''));
  10971. $mobile = trim((string)($row['mobile'] ?? ''));
  10972. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  10973. $list[] = [
  10974. 'name' => $name,
  10975. 'email' => $email,
  10976. 'mobile' => $mobile,
  10977. 'can_select' => $hasEmail ? 1 : 0,
  10978. 'checked' => (!empty($selectedMap[$name]) && $hasEmail) ? 1 : 0,
  10979. ];
  10980. }
  10981. $canNotify = $this->canRfqNotifySalesman($po);
  10982. $this->success('', null, [
  10983. 'scydgy_id' => $sid,
  10984. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  10985. 'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
  10986. 'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
  10987. 'can_notify_salesman' => $canNotify ? 1 : 0,
  10988. 'list' => $list,
  10989. ]);
  10990. }
  10991. /**
  10992. * 查询询价 — 补加通知业务员可选名单
  10993. */
  10994. public function rfqsalesmanoptions()
  10995. {
  10996. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen'])) {
  10997. $this->error(__('You have no permission'));
  10998. }
  10999. $out = [];
  11000. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  11001. $email = trim((string)($row['email'] ?? ''));
  11002. $mobile = trim((string)($row['mobile'] ?? ''));
  11003. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  11004. $out[] = [
  11005. 'name' => (string)($row['name'] ?? ''),
  11006. 'email' => $email,
  11007. 'mobile' => $mobile,
  11008. 'can_select' => $hasEmail ? 1 : 0,
  11009. ];
  11010. }
  11011. $this->success('', null, ['list' => $out]);
  11012. }
  11013. /**
  11014. * 查询询价 — 补加通知业务员(合并更新 notify_salesman)
  11015. */
  11016. public function rfqappendsalesmen()
  11017. {
  11018. if (!$this->request->isPost()) {
  11019. $this->error(__('Invalid parameters'));
  11020. }
  11021. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen'])) {
  11022. $this->error(__('You have no permission'));
  11023. }
  11024. $this->ensurePurchaseOrderNotifySalesmanColumn();
  11025. $sid = (int)$this->request->post('scydgy_id', 0);
  11026. if ($sid >= 0) {
  11027. $this->error('仅支持手工新增询价单');
  11028. }
  11029. $po = $this->loadManualRfqOrderForNotify($sid);
  11030. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  11031. $this->error('订单已完结,无法添加业务员');
  11032. }
  11033. $raw = $this->request->post('salesmen/a', []);
  11034. if (!is_array($raw) || $raw === []) {
  11035. $salesmenJson = $this->request->post('salesmen_json', '');
  11036. if (is_string($salesmenJson) && $salesmenJson !== '') {
  11037. $decoded = json_decode($salesmenJson, true);
  11038. $raw = is_array($decoded) ? $decoded : [];
  11039. }
  11040. }
  11041. $addNames = [];
  11042. foreach ((array)$raw as $item) {
  11043. if (is_array($item)) {
  11044. $n = trim((string)($item['name'] ?? ''));
  11045. } else {
  11046. $n = trim((string)$item);
  11047. }
  11048. if ($n !== '') {
  11049. $addNames[] = $n;
  11050. }
  11051. }
  11052. $addNames = array_values(array_unique($addNames));
  11053. if ($addNames === []) {
  11054. $this->error('请选择要添加的业务员');
  11055. }
  11056. $allowedOptions = $this->loadRfqSalesmanContactOptions();
  11057. $allowedMap = [];
  11058. foreach ($allowedOptions as $opt) {
  11059. $n = trim((string)($opt['name'] ?? ''));
  11060. if ($n === '') {
  11061. continue;
  11062. }
  11063. $email = trim((string)($opt['email'] ?? ''));
  11064. $allowedMap[$n] = ($email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL));
  11065. }
  11066. foreach ($addNames as $n) {
  11067. if (!array_key_exists($n, $allowedMap)) {
  11068. $this->error('业务员不在可选名单中:' . $n);
  11069. }
  11070. if (!$allowedMap[$n]) {
  11071. $this->error('业务员未填写有效邮箱,无法添加:' . $n);
  11072. }
  11073. }
  11074. $existingRaw = trim((string)($po['notify_salesman'] ?? ''));
  11075. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  11076. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  11077. try {
  11078. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['notify_salesman' => $mergedStr]);
  11079. } catch (\Throwable $e) {
  11080. $this->error('保存失败:' . $e->getMessage());
  11081. }
  11082. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11083. $this->addOrderLog($sid, 'rfq_append_salesman', '添加通知业务员:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  11084. $this->success('已添加业务员', null, [
  11085. 'scydgy_id' => $sid,
  11086. 'notify_salesman' => $mergedStr,
  11087. 'added_count' => count($addNames),
  11088. ]);
  11089. }
  11090. /**
  11091. * 查询询价 — 勾选业务员后邮箱通知(salesmen_json)
  11092. */
  11093. public function rfqnotifysalesman()
  11094. {
  11095. if (!$this->request->isPost()) {
  11096. $this->error(__('Invalid parameters'));
  11097. }
  11098. if (!$this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen'])) {
  11099. $this->error(__('You have no permission'));
  11100. }
  11101. $this->ensurePurchaseOrderNotifySalesmanColumn();
  11102. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  11103. $sid = (int)$this->request->post('scydgy_id', 0);
  11104. if ($sid >= 0) {
  11105. $this->error('仅支持手工新增询价单');
  11106. }
  11107. $po = $this->loadManualRfqOrderForNotify($sid);
  11108. $this->assertRfqCanNotifySalesman($po);
  11109. $raw = $this->request->post('salesmen/a', []);
  11110. if (!is_array($raw) || $raw === []) {
  11111. $salesmenJson = $this->request->post('salesmen_json', '');
  11112. if (is_string($salesmenJson) && $salesmenJson !== '') {
  11113. $decoded = json_decode($salesmenJson, true);
  11114. $raw = is_array($decoded) ? $decoded : [];
  11115. }
  11116. }
  11117. // 兼容旧参数:notify_all / 单人 name
  11118. if ((!is_array($raw) || $raw === []) && (int)$this->request->post('notify_all', 0) === 1) {
  11119. $raw = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  11120. }
  11121. if ((!is_array($raw) || $raw === [])) {
  11122. $oneName = trim((string)$this->request->post('name', ''));
  11123. if ($oneName !== '') {
  11124. $raw = [$oneName];
  11125. }
  11126. }
  11127. $selectedNames = [];
  11128. foreach ((array)$raw as $item) {
  11129. if (is_array($item)) {
  11130. $n = trim((string)($item['name'] ?? ''));
  11131. } else {
  11132. $n = trim((string)$item);
  11133. }
  11134. if ($n !== '') {
  11135. $selectedNames[] = $n;
  11136. }
  11137. }
  11138. $selectedNames = array_values(array_unique($selectedNames));
  11139. if ($selectedNames === []) {
  11140. $this->error('请选择要通知的业务员');
  11141. }
  11142. $optionMap = [];
  11143. foreach ($this->loadRfqSalesmanContactOptions() as $opt) {
  11144. $n = trim((string)($opt['name'] ?? ''));
  11145. if ($n === '') {
  11146. continue;
  11147. }
  11148. $optionMap[$n] = $opt;
  11149. }
  11150. $targets = [];
  11151. foreach ($selectedNames as $n) {
  11152. if (!isset($optionMap[$n])) {
  11153. $this->error('业务员不在可选名单中:' . $n);
  11154. }
  11155. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  11156. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  11157. $this->error('业务员未填写有效邮箱,无法通知:' . $n);
  11158. }
  11159. $resolved = $this->resolveRfqSalesmanContactRows([$n]);
  11160. $targets[] = $resolved[0] ?? [
  11161. 'admin_id' => 0,
  11162. 'name' => $n,
  11163. 'email' => $email,
  11164. ];
  11165. }
  11166. $mergedStr = $this->joinRfqMultiSelectValues($selectedNames);
  11167. try {
  11168. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11169. 'notify_salesman' => $mergedStr,
  11170. ]);
  11171. } catch (\Throwable $e) {
  11172. $this->error('保存通知业务员失败:' . $e->getMessage());
  11173. }
  11174. $po['notify_salesman'] = $mergedStr;
  11175. $mailConfig = $this->loadMailerConfig();
  11176. if (empty($mailConfig['host'])) {
  11177. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  11178. }
  11179. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  11180. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  11181. }
  11182. $this->ensureRfqSalesmanEmailTemplate();
  11183. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  11184. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  11185. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  11186. $cdw = trim((string)($po['CDW'] ?? ''));
  11187. $qty = trim((string)$this->resolveProcuremenThisQuantity($po));
  11188. $ceiling = trim((string)$this->resolveProcuremenCeilingPrice($po));
  11189. $mbz = trim((string)($po['MBZ'] ?? ''));
  11190. $cywyxm = trim((string)($po['cywyxm'] ?? ''));
  11191. $supplier = trim((string)($po['cGzzxMc'] ?? ''));
  11192. if ($supplier === '') {
  11193. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  11194. }
  11195. $supplierQuotesHtml = $this->buildRfqSalesmanSupplierQuotesHtml($sid, $supplier);
  11196. try {
  11197. $platformUrl = $this->buildMprocMobileRfqAddUrl($sid, 'pending');
  11198. } catch (\Throwable $e) {
  11199. $platformUrl = '';
  11200. }
  11201. try {
  11202. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
  11203. } catch (\Throwable $e) {
  11204. $this->error($e->getMessage());
  11205. }
  11206. $okNames = [];
  11207. $failMsgs = [];
  11208. foreach ($targets as $contact) {
  11209. $toEmail = trim((string)($contact['email'] ?? ''));
  11210. $toName = trim((string)($contact['name'] ?? ''));
  11211. $notifyVars = [
  11212. 'contact_name' => $toName,
  11213. 'salesman_name' => $toName,
  11214. 'company_name' => $toName,
  11215. 'email' => $toEmail,
  11216. 'ccydh' => $ccydh,
  11217. 'cyjmc' => $cyjmc,
  11218. 'cgymc' => $cgymc,
  11219. 'cdw' => $cdw,
  11220. 'this_quantity' => $qty,
  11221. 'ceilingPrice' => $ceiling,
  11222. 'MBZ' => $mbz,
  11223. 'supplier_name' => $supplier,
  11224. // 占位符,转 HTML 后再替换成表格,避免被 htmlspecialchars 转义
  11225. 'supplier_quotes' => '__RFQ_SUPPLIER_QUOTES_TABLE__',
  11226. 'cywyxm' => $cywyxm,
  11227. 'platform_url' => $platformUrl,
  11228. ];
  11229. try {
  11230. $mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
  11231. $mailSubject = $mailSubjectTpl;
  11232. foreach ($notifyVars as $k => $v) {
  11233. if ($k === 'supplier_quotes') {
  11234. continue;
  11235. }
  11236. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  11237. }
  11238. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  11239. $mailSubject = trim((string)$mailSubject);
  11240. if ($mailSubject === '') {
  11241. $mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  11242. }
  11243. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  11244. $mailBody = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', $supplierQuotesHtml, $mailBody);
  11245. $mailPlainForLog = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', strip_tags(str_replace(['</tr>', '</p>'], "\n", $supplierQuotesHtml)), $mailPlain);
  11246. $bundle = [
  11247. 'company_name' => $toName,
  11248. 'email' => $toEmail,
  11249. 'mail_plain' => $mailPlainForLog,
  11250. 'mail_body' => $mailBody,
  11251. 'ccydh' => $ccydh,
  11252. 'email_log_scene' => 'rfq_salesman',
  11253. 'email_log_scydgy_id' => $sid,
  11254. 'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
  11255. 'email_log_ccydh' => $ccydh,
  11256. 'email_log_order_batch_no' => $this->resolveProcuremenOrderBatchNo(is_array($po) ? $po : []),
  11257. 'notify_vars' => $notifyVars,
  11258. ];
  11259. $this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
  11260. $okNames[] = $toName . '(' . $toEmail . ')';
  11261. } catch (\Throwable $e) {
  11262. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  11263. }
  11264. }
  11265. if ($okNames === []) {
  11266. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  11267. }
  11268. $now = date('Y-m-d H:i:s');
  11269. try {
  11270. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11271. 'rfq_salesman_notified' => 1,
  11272. 'rfq_salesman_notify_time' => $now,
  11273. ]);
  11274. } catch (\Throwable $e) {
  11275. // ignore
  11276. }
  11277. $this->addOrderLog(
  11278. $sid,
  11279. 'rfq_notify_salesman',
  11280. '邮箱通知业务员:' . implode('、', $okNames),
  11281. (int)($po['id'] ?? 0)
  11282. );
  11283. $msg = '已通知 ' . count($okNames) . ' 人';
  11284. if ($failMsgs !== []) {
  11285. $msg .= ';部分失败:' . implode(';', $failMsgs);
  11286. }
  11287. $this->success($msg, null, [
  11288. 'scydgy_id' => $sid,
  11289. 'notify_salesman' => $mergedStr,
  11290. 'rfq_salesman_notified' => 1,
  11291. 'rfq_salesman_notify_time' => $now,
  11292. 'notify_time_text' => $now,
  11293. 'ok_count' => count($okNames),
  11294. 'fail_count' => count($failMsgs),
  11295. ]);
  11296. }
  11297. /**
  11298. * 生产部角色组 id(mproc.mobile_delivery_group_id,缺省按组名「生产部/生产员」查找)
  11299. */
  11300. protected function deliveryNotifyAuthGroupId(): int
  11301. {
  11302. static $mprocCfgLoaded = false;
  11303. if (!$mprocCfgLoaded) {
  11304. $mprocCfgLoaded = true;
  11305. if (is_file(APP_PATH . 'extra/mproc.php')) {
  11306. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  11307. }
  11308. }
  11309. $id = (int)Config::get('mproc.mobile_delivery_group_id');
  11310. if ($id > 0) {
  11311. return $id;
  11312. }
  11313. try {
  11314. foreach (['生产部', '生产员'] as $name) {
  11315. $gid = (int)Db::name('auth_group')->where('name', $name)->value('id');
  11316. if ($gid > 0) {
  11317. return $gid;
  11318. }
  11319. }
  11320. } catch (\Throwable $e) {
  11321. }
  11322. return 0;
  11323. }
  11324. /**
  11325. * 生产部人员:姓名、邮箱、手机
  11326. *
  11327. * @return array<int, array{name:string,email:string,mobile:string,admin_id:int}>
  11328. */
  11329. protected function loadDeliveryStaffContactOptions(): array
  11330. {
  11331. $out = [];
  11332. $seen = [];
  11333. $groupId = $this->deliveryNotifyAuthGroupId();
  11334. if ($groupId <= 0) {
  11335. return [];
  11336. }
  11337. try {
  11338. $adminIds = Db::name('auth_group_access')
  11339. ->where('group_id', $groupId)
  11340. ->column('uid');
  11341. } catch (\Throwable $e) {
  11342. return [];
  11343. }
  11344. $adminIds = is_array($adminIds)
  11345. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  11346. : [];
  11347. if ($adminIds === []) {
  11348. return [];
  11349. }
  11350. try {
  11351. $rows = Db::name('admin')
  11352. ->where('status', 'normal')
  11353. ->where('id', 'in', $adminIds)
  11354. ->order('id', 'asc')
  11355. ->field('id,nickname,username,email,mobile')
  11356. ->select();
  11357. } catch (\Throwable $e) {
  11358. return [];
  11359. }
  11360. if (!is_array($rows)) {
  11361. return [];
  11362. }
  11363. foreach ($rows as $row) {
  11364. if (!is_array($row)) {
  11365. continue;
  11366. }
  11367. $name = trim((string)($row['nickname'] ?? ''));
  11368. if ($name === '') {
  11369. $name = trim((string)($row['username'] ?? ''));
  11370. }
  11371. if ($name === '' || isset($seen[$name])) {
  11372. continue;
  11373. }
  11374. $seen[$name] = true;
  11375. $out[] = [
  11376. 'admin_id' => (int)($row['id'] ?? 0),
  11377. 'name' => $name,
  11378. 'email' => trim((string)($row['email'] ?? '')),
  11379. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  11380. ];
  11381. }
  11382. return $out;
  11383. }
  11384. /**
  11385. * 交货情况页直达链接(邮件用,单参数避免邮箱客户端拆坏)
  11386. */
  11387. protected function buildMprocMobileDeliveryscoreUrl(string $ccydh): string
  11388. {
  11389. static $mprocCfgLoaded = false;
  11390. if (!$mprocCfgLoaded) {
  11391. $mprocCfgLoaded = true;
  11392. if (is_file(APP_PATH . 'extra/mproc.php')) {
  11393. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  11394. }
  11395. }
  11396. $base = $this->resolveMprocMobilePublicBaseUrl();
  11397. if ($base === '') {
  11398. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  11399. }
  11400. $path = '/index.php/index/index/deliveryscore';
  11401. $ccydh = trim($ccydh);
  11402. if ($ccydh === '') {
  11403. return $base . $path;
  11404. }
  11405. return $base . $path . '?ccydh=' . rawurlencode($ccydh);
  11406. }
  11407. /**
  11408. * 按订单号取已审核外发单(合并工序字段)
  11409. *
  11410. * @return array<string, mixed>|null
  11411. */
  11412. protected function loadApprovedOrderForDeliveryNotify(string $ccydh, int $sid = 0): ?array
  11413. {
  11414. $ccydh = trim($ccydh);
  11415. if ($ccydh === '' && $sid > 0) {
  11416. try {
  11417. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
  11418. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  11419. } catch (\Throwable $e) {
  11420. $ccydh = '';
  11421. }
  11422. }
  11423. if ($ccydh === '') {
  11424. return null;
  11425. }
  11426. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  11427. $approvedIn = implode(',', array_map(static function ($v) {
  11428. return "'" . str_replace("'", "''", (string)$v) . "'";
  11429. }, $approvedVals));
  11430. try {
  11431. $rows = Db::table('purchase_order')
  11432. ->where('CCYDH', $ccydh)
  11433. ->where('scydgy_id', '>', 0)
  11434. ->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%\')')
  11435. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  11436. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  11437. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,CDW,This_quantity,NGZL,pick_company_name,delivery_deadline,MBZ,cywyxm,wflow_status,status')
  11438. ->order('id', 'asc')
  11439. ->select();
  11440. } catch (\Throwable $e) {
  11441. $rows = [];
  11442. }
  11443. if (!is_array($rows) || $rows === []) {
  11444. return null;
  11445. }
  11446. $gymc = [];
  11447. $qty = [];
  11448. $first = null;
  11449. foreach ($rows as $r) {
  11450. if (!is_array($r)) {
  11451. continue;
  11452. }
  11453. if ($first === null) {
  11454. $first = $r;
  11455. }
  11456. $g = trim((string)($r['CGYMC'] ?? ''));
  11457. if ($g !== '' && !in_array($g, $gymc, true)) {
  11458. $gymc[] = $g;
  11459. }
  11460. $q = trim((string)$this->resolveProcuremenThisQuantity($r));
  11461. if ($q !== '' && !in_array($q, $qty, true)) {
  11462. $qty[] = $q;
  11463. }
  11464. }
  11465. if (!is_array($first)) {
  11466. return null;
  11467. }
  11468. $first['CGYMC'] = $gymc !== [] ? implode('、', $gymc) : '';
  11469. $first['This_quantity'] = $qty !== [] ? implode('、', $qty) : '';
  11470. $first['delivery_deadline'] = $this->mprocFormatYmdForNotify($first['delivery_deadline'] ?? '');
  11471. return $first;
  11472. }
  11473. protected function mprocFormatYmdForNotify($raw): string
  11474. {
  11475. return ProcuremenFormat::mprocYmdForNotify($raw);
  11476. }
  11477. /**
  11478. * 确保「交货情况通知生产部-邮箱」模版存在
  11479. */
  11480. protected function ensureDeliveryNotifyEmailTemplate(): void
  11481. {
  11482. static $done = false;
  11483. if ($done) {
  11484. return;
  11485. }
  11486. $done = true;
  11487. $content = "您好,{contact_name}:\n\n"
  11488. . "有订单已中标外发,需要您在手机端确认交货情况(填写库位、交货情况、交货日期等)。\n\n"
  11489. . "订单号:{ccydh}\n"
  11490. . "印件名称:{cyjmc}\n"
  11491. . "工序名称:{cgymc}\n"
  11492. . "订单数量:{this_quantity}\n"
  11493. . "中标供应商:{supplier_name}\n"
  11494. . "交货截止日期:{delivery_deadline}\n\n"
  11495. . "请点击下方链接登录后,找到该订单进行填写:\n"
  11496. . "{platform_url}\n";
  11497. try {
  11498. $row = Db::table('purchase_sms_template')
  11499. ->where('scene', 'delivery_notify_email')
  11500. ->find();
  11501. } catch (\Throwable $e) {
  11502. return;
  11503. }
  11504. $now = date('Y-m-d H:i:s');
  11505. if (is_array($row) && $row !== []) {
  11506. return;
  11507. }
  11508. try {
  11509. $data = [
  11510. 'scene' => 'delivery_notify_email',
  11511. 'title' => '交货情况确认通知 - {ccydh}',
  11512. 'content' => $content,
  11513. 'remark' => '审批通过后通知生产部填写交货情况;模版名称作邮件主题,支持变量',
  11514. 'status' => 1,
  11515. ];
  11516. try {
  11517. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  11518. } catch (\Throwable $e) {
  11519. $cols = [];
  11520. }
  11521. $colNames = [];
  11522. foreach ($cols as $c) {
  11523. if (!is_array($c)) {
  11524. continue;
  11525. }
  11526. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  11527. if ($n !== '') {
  11528. $colNames[$n] = true;
  11529. }
  11530. }
  11531. if (isset($colNames['updatetime'])) {
  11532. $data['updatetime'] = $now;
  11533. }
  11534. if (isset($colNames['createtime'])) {
  11535. $data['createtime'] = $now;
  11536. }
  11537. Db::table('purchase_sms_template')->insert($data);
  11538. } catch (\Throwable $e) {
  11539. // ignore
  11540. }
  11541. }
  11542. /**
  11543. * 通知生产部 — 可选人员名单
  11544. */
  11545. public function deliverynotifymen()
  11546. {
  11547. if (!$this->hasProcuremenPerm(['deliverynotifymen', 'deliverynotify', 'outward_detail', 'outwarddetail', 'purchaseconfirmpick', 'details'])) {
  11548. $this->error(__('You have no permission'));
  11549. }
  11550. $this->ensureDeliveryNotifyEmailTemplate();
  11551. $sid = (int)$this->request->request('scydgy_id', 0);
  11552. $ccydh = trim((string)$this->request->request('ccydh', ''));
  11553. $po = $this->loadApprovedOrderForDeliveryNotify($ccydh, $sid);
  11554. if ($po === null) {
  11555. $this->error('未找到已审核且已中标的订单,无法通知生产部');
  11556. }
  11557. $list = [];
  11558. foreach ($this->loadDeliveryStaffContactOptions() as $opt) {
  11559. $email = trim((string)($opt['email'] ?? ''));
  11560. $list[] = [
  11561. 'name' => (string)($opt['name'] ?? ''),
  11562. 'email' => $email,
  11563. 'mobile' => (string)($opt['mobile'] ?? ''),
  11564. 'can_select' => ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) ? 1 : 0,
  11565. 'checked' => 0,
  11566. ];
  11567. }
  11568. $this->success('', null, [
  11569. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  11570. 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
  11571. 'cgymc' => trim((string)($po['CGYMC'] ?? '')),
  11572. 'this_quantity' => trim((string)($po['This_quantity'] ?? '')),
  11573. 'supplier_name' => trim((string)($po['pick_company_name'] ?? '')),
  11574. 'delivery_deadline' => trim((string)($po['delivery_deadline'] ?? '')),
  11575. 'list' => $list,
  11576. ]);
  11577. }
  11578. /**
  11579. * 通知生产部 — 勾选后发邮件(staff_json / names)
  11580. */
  11581. public function deliverynotify()
  11582. {
  11583. if (!$this->request->isPost()) {
  11584. $this->error(__('Invalid parameters'));
  11585. }
  11586. if (!$this->hasProcuremenPerm(['deliverynotify', 'deliverynotifymen', 'outward_detail', 'outwarddetail', 'purchaseconfirmpick', 'details'])) {
  11587. $this->error(__('You have no permission'));
  11588. }
  11589. $this->ensureDeliveryNotifyEmailTemplate();
  11590. $sid = (int)$this->request->post('scydgy_id', 0);
  11591. $ccydh = trim((string)$this->request->post('ccydh', ''));
  11592. $po = $this->loadApprovedOrderForDeliveryNotify($ccydh, $sid);
  11593. if ($po === null) {
  11594. $this->error('未找到已审核且已中标的订单,无法通知生产部');
  11595. }
  11596. $ccydh = trim((string)($po['CCYDH'] ?? $ccydh));
  11597. $raw = $this->request->post('staff/a', []);
  11598. if (!is_array($raw) || $raw === []) {
  11599. $staffJson = $this->request->post('staff_json', '');
  11600. if (is_string($staffJson) && $staffJson !== '') {
  11601. $decoded = json_decode($staffJson, true);
  11602. $raw = is_array($decoded) ? $decoded : [];
  11603. }
  11604. }
  11605. $selectedNames = [];
  11606. foreach ((array)$raw as $item) {
  11607. if (is_array($item)) {
  11608. $n = trim((string)($item['name'] ?? ''));
  11609. } else {
  11610. $n = trim((string)$item);
  11611. }
  11612. if ($n !== '') {
  11613. $selectedNames[] = $n;
  11614. }
  11615. }
  11616. $selectedNames = array_values(array_unique($selectedNames));
  11617. if ($selectedNames === []) {
  11618. $this->error('请选择要通知的生产部人员');
  11619. }
  11620. $optionMap = [];
  11621. foreach ($this->loadDeliveryStaffContactOptions() as $opt) {
  11622. $n = trim((string)($opt['name'] ?? ''));
  11623. if ($n === '') {
  11624. continue;
  11625. }
  11626. $optionMap[$n] = $opt;
  11627. }
  11628. $targets = [];
  11629. foreach ($selectedNames as $n) {
  11630. if (!isset($optionMap[$n])) {
  11631. $this->error('人员不在生产部可选名单中:' . $n);
  11632. }
  11633. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  11634. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  11635. $this->error('未填写有效邮箱,无法通知:' . $n);
  11636. }
  11637. $targets[] = $optionMap[$n];
  11638. }
  11639. $mailConfig = $this->loadMailerConfig();
  11640. if (empty($mailConfig['host'])) {
  11641. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  11642. }
  11643. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  11644. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  11645. }
  11646. try {
  11647. $platformUrl = $this->buildMprocMobileDeliveryscoreUrl($ccydh);
  11648. } catch (\Throwable $e) {
  11649. $this->error($e->getMessage());
  11650. }
  11651. try {
  11652. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('delivery_notify_email');
  11653. } catch (\Throwable $e) {
  11654. $this->error($e->getMessage());
  11655. }
  11656. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  11657. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  11658. $qty = trim((string)($po['This_quantity'] ?? ''));
  11659. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  11660. $deadline = trim((string)($po['delivery_deadline'] ?? ''));
  11661. $firstSid = (int)($po['scydgy_id'] ?? 0);
  11662. $firstPoId = (int)($po['id'] ?? 0);
  11663. $okNames = [];
  11664. $failMsgs = [];
  11665. foreach ($targets as $contact) {
  11666. $toEmail = trim((string)($contact['email'] ?? ''));
  11667. $toName = trim((string)($contact['name'] ?? ''));
  11668. $notifyVars = [
  11669. 'contact_name' => $toName,
  11670. 'company_name' => $toName,
  11671. 'email' => $toEmail,
  11672. 'ccydh' => $ccydh,
  11673. 'cyjmc' => $cyjmc,
  11674. 'cgymc' => $cgymc,
  11675. 'this_quantity' => $qty,
  11676. 'supplier_name' => $supplier,
  11677. 'delivery_deadline' => $deadline,
  11678. 'platform_url' => $platformUrl,
  11679. ];
  11680. try {
  11681. $mailPlain = $this->renderNotifyTemplate('delivery_notify_email', $notifyVars);
  11682. $mailSubject = $mailSubjectTpl;
  11683. foreach ($notifyVars as $k => $v) {
  11684. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  11685. }
  11686. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  11687. $mailSubject = trim((string)$mailSubject);
  11688. if ($mailSubject === '') {
  11689. $mailSubject = '交货情况确认通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  11690. }
  11691. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  11692. $this->issueSendSupplierEmail([
  11693. 'company_name' => $toName,
  11694. 'email' => $toEmail,
  11695. 'mail_plain' => $mailPlain,
  11696. 'mail_body' => $mailBody,
  11697. 'ccydh' => $ccydh,
  11698. 'email_log_scene' => 'delivery_notify',
  11699. 'email_log_scydgy_id' => $firstSid,
  11700. 'email_log_purchase_order_id' => $firstPoId,
  11701. 'email_log_ccydh' => $ccydh,
  11702. 'email_log_order_batch_no' => $this->resolveProcuremenOrderBatchNo(is_array($po) ? $po : []),
  11703. 'notify_vars' => $notifyVars,
  11704. ], $mailConfig, $mailSubject);
  11705. $okNames[] = $toName . '(' . $toEmail . ')';
  11706. } catch (\Throwable $e) {
  11707. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  11708. }
  11709. }
  11710. if ($okNames === []) {
  11711. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  11712. }
  11713. if ($firstSid > 0) {
  11714. $this->addOrderLog(
  11715. $firstSid,
  11716. 'delivery_notify',
  11717. '邮箱通知生产部:' . implode('、', $okNames),
  11718. $firstPoId > 0 ? $firstPoId : null
  11719. );
  11720. }
  11721. $msg = '已通知 ' . count($okNames) . ' 人';
  11722. if ($failMsgs !== []) {
  11723. $msg .= ';部分失败:' . implode(';', $failMsgs);
  11724. }
  11725. $this->success($msg, null, [
  11726. 'ccydh' => $ccydh,
  11727. 'ok_count' => count($okNames),
  11728. 'fail_count'=> count($failMsgs),
  11729. 'platform_url' => $platformUrl,
  11730. ]);
  11731. }
  11732. /**
  11733. * 查询询价 — 下发前:返回将通知的供应商表格数据
  11734. */
  11735. public function rfqissuesuppliers()
  11736. {
  11737. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers'])) {
  11738. $this->error(__('You have no permission'));
  11739. }
  11740. $sid = (int)$this->request->param('scydgy_id', 0);
  11741. if ($sid >= 0) {
  11742. $this->error('仅支持手工新增询价单');
  11743. }
  11744. $po = $this->loadManualRfqOrderForNotify($sid);
  11745. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  11746. if ($supplierRaw === '') {
  11747. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  11748. }
  11749. $names = $this->splitRfqSalesmanNames($supplierRaw);
  11750. // 已成功发过询价邮件的供应商(含历史 pick_issue 场景)
  11751. $notifiedMap = [];
  11752. try {
  11753. $this->ensurePurchaseEmailSendLogTableOnce();
  11754. $logRows = Db::table('purchase_email_send_log')
  11755. ->where('scydgy_id', $sid)
  11756. ->where('status', 1)
  11757. ->where('scene', 'in', [
  11758. 'rfq_supplier', 'pick_issue',
  11759. '供应商询价通知', '初选下发',
  11760. ])
  11761. ->field('company_name')
  11762. ->select();
  11763. if (is_array($logRows)) {
  11764. foreach ($logRows as $lr) {
  11765. if (!is_array($lr)) {
  11766. continue;
  11767. }
  11768. $cn = trim((string)($lr['company_name'] ?? ''));
  11769. if ($cn !== '') {
  11770. $notifiedMap[$cn] = true;
  11771. }
  11772. }
  11773. }
  11774. } catch (\Throwable $e) {
  11775. }
  11776. // 兼容:明细已生成(曾下发)也视为已通知
  11777. try {
  11778. $detRows = Db::table('purchase_order_detail')
  11779. ->where('scydgy_id', $sid)
  11780. ->field('company_name')
  11781. ->select();
  11782. if (is_array($detRows)) {
  11783. foreach ($detRows as $dr) {
  11784. if (!is_array($dr)) {
  11785. continue;
  11786. }
  11787. $cn = trim((string)($dr['company_name'] ?? ''));
  11788. if ($cn !== '') {
  11789. $notifiedMap[$cn] = true;
  11790. }
  11791. }
  11792. }
  11793. } catch (\Throwable $e) {
  11794. }
  11795. $list = [];
  11796. foreach ($names as $name) {
  11797. // 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
  11798. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  11799. $email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
  11800. $phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
  11801. $username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
  11802. $okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
  11803. $notified = !empty($notifiedMap[$name]) ? 1 : 0;
  11804. $list[] = [
  11805. 'name' => $name,
  11806. 'username' => $username,
  11807. 'email' => $email,
  11808. 'phone' => $phone,
  11809. 'can_notify' => $okEmail ? 1 : 0,
  11810. 'found' => is_array($contact) ? 1 : 0,
  11811. 'notified' => $notified,
  11812. 'notify_status_text' => $notified ? '已通知' : '未通知',
  11813. ];
  11814. }
  11815. $this->success('', null, [
  11816. 'scydgy_id' => $sid,
  11817. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  11818. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  11819. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  11820. 'CDW' => trim((string)($po['CDW'] ?? '')),
  11821. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  11822. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  11823. 'CDF' => trim((string)($po['CDF'] ?? '')),
  11824. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  11825. 'list' => $list,
  11826. ]);
  11827. }
  11828. /**
  11829. * 查询询价 — 补加供应商可选名单
  11830. */
  11831. public function rfqsupplieroptions()
  11832. {
  11833. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
  11834. $this->error(__('You have no permission'));
  11835. }
  11836. $names = array_values($this->loadRfqSupplierNameOptions());
  11837. $out = [];
  11838. foreach ($names as $name) {
  11839. $out[] = ['name' => $name];
  11840. }
  11841. $this->success('', null, ['list' => $out]);
  11842. }
  11843. /**
  11844. * 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
  11845. */
  11846. public function rfqappendsuppliers()
  11847. {
  11848. if (!$this->request->isPost()) {
  11849. $this->error(__('Invalid parameters'));
  11850. }
  11851. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers'])) {
  11852. $this->error(__('You have no permission'));
  11853. }
  11854. $sid = (int)$this->request->post('scydgy_id', 0);
  11855. if ($sid >= 0) {
  11856. $this->error('仅支持手工新增询价单');
  11857. }
  11858. $po = $this->loadManualRfqOrderForNotify($sid);
  11859. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  11860. $this->error('订单已完结,无法补加供应商');
  11861. }
  11862. $raw = $this->request->post('suppliers/a', []);
  11863. if (!is_array($raw) || $raw === []) {
  11864. $suppliersJson = $this->request->post('suppliers_json', '');
  11865. if (is_string($suppliersJson) && $suppliersJson !== '') {
  11866. $decoded = json_decode($suppliersJson, true);
  11867. $raw = is_array($decoded) ? $decoded : [];
  11868. }
  11869. }
  11870. $addNames = [];
  11871. foreach ((array)$raw as $item) {
  11872. if (is_array($item)) {
  11873. $n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
  11874. } else {
  11875. $n = trim((string)$item);
  11876. }
  11877. if ($n !== '') {
  11878. $addNames[] = $n;
  11879. }
  11880. }
  11881. $addNames = array_values(array_unique($addNames));
  11882. if ($addNames === []) {
  11883. $this->error('请选择要补加的供应商');
  11884. }
  11885. $existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
  11886. if ($existingRaw === '') {
  11887. $existingRaw = trim((string)($po['pick_company_name'] ?? ''));
  11888. }
  11889. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  11890. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  11891. try {
  11892. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
  11893. } catch (\Throwable $e) {
  11894. $this->error('保存失败:' . $e->getMessage());
  11895. }
  11896. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11897. $this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  11898. $this->success('已补加供应商', null, [
  11899. 'scydgy_id' => $sid,
  11900. 'cGzzxMc' => $mergedStr,
  11901. 'added_count' => count($addNames),
  11902. ]);
  11903. }
  11904. /**
  11905. * 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
  11906. */
  11907. public function rfqissue()
  11908. {
  11909. if (!$this->request->isPost()) {
  11910. $this->error(__('Invalid parameters'));
  11911. }
  11912. if (!$this->hasProcuremenPerm(['rfqissue'])) {
  11913. $this->error(__('You have no permission'));
  11914. }
  11915. $this->ensureRfqSupplierEmailTemplate();
  11916. $sid = (int)$this->request->post('scydgy_id', 0);
  11917. if ($sid >= 0) {
  11918. $this->error('仅支持手工新增询价单');
  11919. }
  11920. $po = $this->loadManualRfqOrderForNotify($sid);
  11921. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  11922. $this->error('订单已完结,无法下发');
  11923. }
  11924. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  11925. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  11926. $this->error('订单已进入后续流程,无法再下发');
  11927. }
  11928. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  11929. if ($supplierRaw === '') {
  11930. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  11931. }
  11932. $supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
  11933. if ($supplierNames === []) {
  11934. $this->error('请先在新增询价时选择供应商');
  11935. }
  11936. $companies = [];
  11937. $missing = [];
  11938. $noEmail = [];
  11939. foreach ($supplierNames as $name) {
  11940. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  11941. if ($contact === null) {
  11942. $missing[] = $name;
  11943. continue;
  11944. }
  11945. $em = trim((string)($contact['email'] ?? ''));
  11946. if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
  11947. $noEmail[] = $name;
  11948. continue;
  11949. }
  11950. $companies[] = $contact;
  11951. }
  11952. if ($missing !== []) {
  11953. $this->error('未找到供应商档案:' . implode('、', $missing));
  11954. }
  11955. if ($noEmail !== []) {
  11956. $this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
  11957. }
  11958. if ($companies === []) {
  11959. $this->error('没有可通知的供应商');
  11960. }
  11961. $mailConfig = $this->loadMailerConfig();
  11962. if (empty($mailConfig['host'])) {
  11963. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  11964. }
  11965. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  11966. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  11967. }
  11968. $mergeRow = $po;
  11969. $mergeRow['ID'] = $sid;
  11970. $mergeRow['id'] = $sid;
  11971. $mergeRows = [$mergeRow];
  11972. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  11973. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  11974. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  11975. }
  11976. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  11977. $issueTime = date('Y-m-d H:i:s');
  11978. $nameLabels = [];
  11979. foreach ($companies as $c) {
  11980. $nameLabels[] = trim((string)($c['name'] ?? ''));
  11981. }
  11982. $logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
  11983. Db::startTrans();
  11984. try {
  11985. $this->upsertPurchaseOrderFromRow(
  11986. $mergeRow,
  11987. $sysRqDb,
  11988. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  11989. $issueTime,
  11990. $po,
  11991. null,
  11992. $scoreRule
  11993. );
  11994. foreach ($companies as $c) {
  11995. $this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
  11996. }
  11997. Db::commit();
  11998. } catch (\Throwable $e) {
  11999. Db::rollback();
  12000. $this->error($e->getMessage());
  12001. }
  12002. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  12003. if ($poId <= 0) {
  12004. try {
  12005. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  12006. } catch (\Throwable $e) {
  12007. $poId = 0;
  12008. }
  12009. }
  12010. $this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
  12011. $posNotify = [];
  12012. try {
  12013. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  12014. if (is_array($fresh)) {
  12015. $fresh['sys_rq'] = $sysRqDb;
  12016. $posNotify = [$fresh];
  12017. }
  12018. } catch (\Throwable $e) {
  12019. $posNotify = [$po];
  12020. $posNotify[0]['sys_rq'] = $sysRqDb;
  12021. }
  12022. $notifyBundle = [
  12023. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  12024. 'pos' => $posNotify,
  12025. 'merge_rows' => $mergeRows,
  12026. ];
  12027. $notifyErrors = [];
  12028. foreach ($companies as $c) {
  12029. $cname = trim((string)($c['name'] ?? ''));
  12030. try {
  12031. // 询价下发:仅邮箱通知供应商
  12032. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  12033. } catch (\Throwable $e) {
  12034. $notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
  12035. }
  12036. }
  12037. if ($notifyErrors !== []) {
  12038. Log::write('procuremen rfq issue notify fail sid=' . $sid . ': ' . implode(';', $notifyErrors), 'error');
  12039. $this->success('询价下发成功。部分供应商邮件未送达,可稍后重发。', null, [
  12040. 'scydgy_id' => $sid,
  12041. 'progress_text' => '待报价',
  12042. 'supplier_count' => count($companies),
  12043. 'notify_failed' => 1,
  12044. 'notify_fail_detail' => $notifyErrors,
  12045. ]);
  12046. }
  12047. $this->success('已询价并邮件通知供应商', null, [
  12048. 'scydgy_id' => $sid,
  12049. 'progress_text' => '待报价',
  12050. 'supplier_count' => count($companies),
  12051. 'notify_failed' => 0,
  12052. ]);
  12053. }
  12054. /**
  12055. * 查询询价 — 弹窗内向单个供应商发送询价邮件
  12056. */
  12057. public function rfqissuesendmail()
  12058. {
  12059. if (!$this->request->isPost()) {
  12060. $this->error(__('Invalid parameters'));
  12061. }
  12062. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail'])) {
  12063. $this->error(__('You have no permission'));
  12064. }
  12065. $this->ensureRfqSupplierEmailTemplate();
  12066. $sid = (int)$this->request->post('scydgy_id', 0);
  12067. $companyName = trim((string)$this->request->post('company_name', ''));
  12068. if ($sid >= 0) {
  12069. $this->error('仅支持手工新增询价单');
  12070. }
  12071. if ($companyName === '') {
  12072. $this->error('请选择供应商');
  12073. }
  12074. $po = $this->loadManualRfqOrderForNotify($sid);
  12075. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  12076. $this->error('订单已完结,无法发送');
  12077. }
  12078. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  12079. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  12080. $this->error('订单已进入后续流程,无法再发送');
  12081. }
  12082. $contact = $this->resolveCustomerContactByCompanyName($companyName, false);
  12083. if ($contact === null) {
  12084. $this->error('未找到供应商档案:' . $companyName);
  12085. }
  12086. $email = trim((string)($contact['email'] ?? ''));
  12087. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  12088. $this->error('该供应商未填写有效邮箱');
  12089. }
  12090. $mailConfig = $this->loadMailerConfig();
  12091. if (empty($mailConfig['host'])) {
  12092. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  12093. }
  12094. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  12095. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  12096. }
  12097. $mergeRow = $po;
  12098. $mergeRow['ID'] = $sid;
  12099. $mergeRow['id'] = $sid;
  12100. $mergeRows = [$mergeRow];
  12101. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  12102. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  12103. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  12104. }
  12105. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  12106. $issueTime = date('Y-m-d H:i:s');
  12107. Db::startTrans();
  12108. try {
  12109. $this->upsertPurchaseOrderFromRow(
  12110. $mergeRow,
  12111. $sysRqDb,
  12112. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  12113. $issueTime,
  12114. $po,
  12115. null,
  12116. $scoreRule
  12117. );
  12118. $this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
  12119. Db::commit();
  12120. } catch (\Throwable $e) {
  12121. Db::rollback();
  12122. $this->error($e->getMessage());
  12123. }
  12124. $posNotify = [];
  12125. try {
  12126. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  12127. if (is_array($fresh)) {
  12128. $fresh['sys_rq'] = $sysRqDb;
  12129. $posNotify = [$fresh];
  12130. }
  12131. } catch (\Throwable $e) {
  12132. $posNotify = [$po];
  12133. $posNotify[0]['sys_rq'] = $sysRqDb;
  12134. }
  12135. $notifyBundle = [
  12136. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  12137. 'pos' => $posNotify,
  12138. 'merge_rows' => $mergeRows,
  12139. ];
  12140. $mailFail = '';
  12141. try {
  12142. $this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  12143. } catch (\Throwable $e) {
  12144. $mailFail = $e->getMessage();
  12145. Log::write('procuremen rfqissuesendmail fail sid=' . $sid . ' company=' . $companyName . ': ' . $mailFail, 'error');
  12146. }
  12147. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  12148. if ($poId <= 0) {
  12149. try {
  12150. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  12151. } catch (\Throwable $e) {
  12152. $poId = 0;
  12153. }
  12154. }
  12155. $this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
  12156. if ($mailFail !== '') {
  12157. $this->success('询价已保存。邮件未送达「' . $companyName . '」:' . $mailFail . '。可稍后重发。', null, [
  12158. 'scydgy_id' => $sid,
  12159. 'notify_failed' => 1,
  12160. ]);
  12161. }
  12162. $this->success('已向「' . $companyName . '」发送询价邮件', null, [
  12163. 'scydgy_id' => $sid,
  12164. 'company_name' => $companyName,
  12165. ]);
  12166. }
  12167. /**
  12168. * 查询询价 — 查看各供应商报价(单价)
  12169. */
  12170. public function rfqquotes()
  12171. {
  12172. if (!$this->hasProcuremenPerm(['rfqquotes', 'rfqissue'])) {
  12173. $this->error(__('You have no permission'));
  12174. }
  12175. $sid = (int)$this->request->param('scydgy_id', 0);
  12176. if ($sid >= 0) {
  12177. $this->error('仅支持手工新增询价单');
  12178. }
  12179. $po = $this->loadManualRfqOrderForNotify($sid);
  12180. $rows = [];
  12181. try {
  12182. // 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
  12183. $q = Db::table('purchase_order_detail')
  12184. ->where('scydgy_id', $sid)
  12185. ->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
  12186. ->order('id', 'asc');
  12187. $this->applyActivePurchaseOrderDetailWhere($q);
  12188. $rows = $q->select();
  12189. } catch (\Throwable $e) {
  12190. try {
  12191. $q = Db::table('purchase_order_detail')
  12192. ->where('scydgy_id', $sid)
  12193. ->order('id', 'asc');
  12194. $this->applyActivePurchaseOrderDetailWhere($q);
  12195. $rows = $q->select();
  12196. } catch (\Throwable $e2) {
  12197. $rows = [];
  12198. }
  12199. }
  12200. if (!is_array($rows)) {
  12201. $rows = [];
  12202. }
  12203. $list = [];
  12204. foreach ($rows as $row) {
  12205. if (!is_array($row)) {
  12206. continue;
  12207. }
  12208. $amount = trim((string)($row['amount'] ?? ''));
  12209. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  12210. // 未报价不显示时间(createtime 是下发时间,不是报价时间)
  12211. $oper = '';
  12212. if ($isQuoted) {
  12213. $oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
  12214. if ($oper === '') {
  12215. $oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  12216. }
  12217. }
  12218. $list[] = [
  12219. 'id' => (int)($row['id'] ?? 0),
  12220. 'company_name' => trim((string)($row['company_name'] ?? '')),
  12221. 'amount' => $amount,
  12222. 'amount_text' => $isQuoted ? $amount : '',
  12223. 'is_quoted' => $isQuoted,
  12224. 'quote_label' => $isQuoted ? '已报价' : '未报价',
  12225. 'status_name' => trim((string)($row['status_name'] ?? '')),
  12226. 'oper_time' => $oper,
  12227. ];
  12228. }
  12229. $this->success('', null, [
  12230. 'scydgy_id' => $sid,
  12231. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  12232. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  12233. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  12234. 'CDW' => trim((string)($po['CDW'] ?? '')),
  12235. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  12236. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  12237. 'CDF' => trim((string)($po['CDF'] ?? '')),
  12238. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  12239. 'list' => $list,
  12240. ]);
  12241. }
  12242. /**
  12243. * 手工询价是否已下发(有下发明细或已进入待确认及之后)
  12244. */
  12245. protected function isRfqOrderIssued(array $po): bool
  12246. {
  12247. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  12248. return true;
  12249. }
  12250. $sid = (int)($po['scydgy_id'] ?? 0);
  12251. if ($sid >= 0) {
  12252. return false;
  12253. }
  12254. try {
  12255. $q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  12256. $this->applyActivePurchaseOrderDetailWhere($q);
  12257. return (int)$q->count() > 0;
  12258. } catch (\Throwable $e) {
  12259. return false;
  12260. }
  12261. }
  12262. /**
  12263. * 批量:已有下发明细的手工询价 scydgy_id
  12264. *
  12265. * @param int[] $scydgyIds
  12266. * @return array<int, bool>
  12267. */
  12268. protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
  12269. {
  12270. $set = [];
  12271. $ids = [];
  12272. foreach ($scydgyIds as $sid) {
  12273. $sid = (int)$sid;
  12274. if ($sid < 0) {
  12275. $ids[$sid] = true;
  12276. }
  12277. }
  12278. if ($ids === []) {
  12279. return $set;
  12280. }
  12281. try {
  12282. $q = Db::table('purchase_order_detail')
  12283. ->where('scydgy_id', 'in', array_keys($ids))
  12284. ->field('scydgy_id');
  12285. $this->applyActivePurchaseOrderDetailWhere($q);
  12286. $rows = $q->select();
  12287. } catch (\Throwable $e) {
  12288. return $set;
  12289. }
  12290. if (!is_array($rows)) {
  12291. return $set;
  12292. }
  12293. foreach ($rows as $row) {
  12294. if (!is_array($row)) {
  12295. continue;
  12296. }
  12297. $sid = (int)($row['scydgy_id'] ?? 0);
  12298. if ($sid < 0) {
  12299. $set[$sid] = true;
  12300. }
  12301. }
  12302. return $set;
  12303. }
  12304. /**
  12305. * 批量:已填单价(已报价)的手工询价 scydgy_id
  12306. *
  12307. * @param int[] $scydgyIds
  12308. * @return array<int, bool>
  12309. */
  12310. protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
  12311. {
  12312. $set = [];
  12313. $ids = [];
  12314. foreach ($scydgyIds as $sid) {
  12315. $sid = (int)$sid;
  12316. if ($sid < 0) {
  12317. $ids[$sid] = true;
  12318. }
  12319. }
  12320. if ($ids === []) {
  12321. return $set;
  12322. }
  12323. try {
  12324. $q = Db::table('purchase_order_detail')
  12325. ->where('scydgy_id', 'in', array_keys($ids))
  12326. ->field('scydgy_id,amount');
  12327. $this->applyActivePurchaseOrderDetailWhere($q);
  12328. $rows = $q->select();
  12329. } catch (\Throwable $e) {
  12330. return $set;
  12331. }
  12332. if (!is_array($rows)) {
  12333. return $set;
  12334. }
  12335. foreach ($rows as $row) {
  12336. if (!is_array($row)) {
  12337. continue;
  12338. }
  12339. $amount = trim((string)($row['amount'] ?? ''));
  12340. if ($amount === '' || $amount === '0' || $amount === '0.00') {
  12341. continue;
  12342. }
  12343. $sid = (int)($row['scydgy_id'] ?? 0);
  12344. if ($sid < 0) {
  12345. $set[$sid] = true;
  12346. }
  12347. }
  12348. return $set;
  12349. }
  12350. /**
  12351. * 已下发且至少一家供应商已报价,才允许通知业务员
  12352. */
  12353. protected function canRfqNotifySalesman(array $po): bool
  12354. {
  12355. if (!$this->isRfqOrderIssued($po)) {
  12356. return false;
  12357. }
  12358. $sid = (int)($po['scydgy_id'] ?? 0);
  12359. if ($sid >= 0) {
  12360. return false;
  12361. }
  12362. $quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
  12363. return isset($quoted[$sid]);
  12364. }
  12365. protected function assertRfqCanNotifySalesman(array $po): void
  12366. {
  12367. if (!$this->isRfqOrderIssued($po)) {
  12368. $this->error('请先询价并等待供应商报价后再通知业务员');
  12369. }
  12370. if (!$this->canRfqNotifySalesman($po)) {
  12371. $this->error('供应商尚未报价,暂不能通知业务员');
  12372. }
  12373. }
  12374. /**
  12375. * 加载手工询价单(含可见性校验)
  12376. *
  12377. * @return array<string, mixed>
  12378. */
  12379. protected function loadManualRfqOrderForNotify(int $scydgyId): array
  12380. {
  12381. try {
  12382. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  12383. } catch (\Throwable $e) {
  12384. $po = null;
  12385. }
  12386. if (!is_array($po)) {
  12387. $this->error('订单不存在');
  12388. }
  12389. $modRq = trim((string)($po['mod_rq'] ?? ''));
  12390. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  12391. $this->error('订单不存在');
  12392. }
  12393. if ($this->auth->isSuperAdmin()) {
  12394. return $po;
  12395. }
  12396. if ($this->canViewManualRfqOrder($po)) {
  12397. return $po;
  12398. }
  12399. $this->error('无权操作该订单');
  12400. }
  12401. /**
  12402. * @return string[]
  12403. */
  12404. protected function splitRfqSalesmanNames(string $raw): array
  12405. {
  12406. $parts = [];
  12407. $raw = trim($raw);
  12408. if ($raw === '') {
  12409. return [];
  12410. }
  12411. foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
  12412. $v = trim((string)$piece);
  12413. if ($v !== '' && !in_array($v, $parts, true)) {
  12414. $parts[] = $v;
  12415. }
  12416. }
  12417. return $parts;
  12418. }
  12419. /**
  12420. * 按姓名匹配 fa_admin 邮箱
  12421. *
  12422. * @param string[] $names
  12423. * @return array<int, array{admin_id:int,name:string,email:string}>
  12424. */
  12425. protected function resolveRfqSalesmanContactRows(array $names): array
  12426. {
  12427. $out = [];
  12428. foreach ($names as $name) {
  12429. $name = trim((string)$name);
  12430. if ($name === '') {
  12431. continue;
  12432. }
  12433. $adminId = 0;
  12434. $email = '';
  12435. try {
  12436. $row = Db::name('admin')
  12437. ->where(function ($q) use ($name) {
  12438. $q->where('nickname', $name)->whereOr('username', $name);
  12439. })
  12440. ->where('status', 'normal')
  12441. ->order('id', 'asc')
  12442. ->field('id,nickname,username,email')
  12443. ->find();
  12444. } catch (\Throwable $e) {
  12445. $row = null;
  12446. }
  12447. if (is_array($row)) {
  12448. $adminId = (int)($row['id'] ?? 0);
  12449. $email = trim((string)($row['email'] ?? ''));
  12450. $disp = trim((string)($row['nickname'] ?? ''));
  12451. if ($disp === '') {
  12452. $disp = trim((string)($row['username'] ?? ''));
  12453. }
  12454. if ($disp !== '') {
  12455. $name = $disp;
  12456. }
  12457. }
  12458. $out[] = [
  12459. 'admin_id' => $adminId,
  12460. 'name' => $name,
  12461. 'email' => $email,
  12462. ];
  12463. }
  12464. return $out;
  12465. }
  12466. /**
  12467. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  12468. */
  12469. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  12470. {
  12471. if ($scydgyId >= 0) {
  12472. return;
  12473. }
  12474. try {
  12475. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  12476. } catch (\Throwable $e) {
  12477. $po = null;
  12478. }
  12479. if (!is_array($po)) {
  12480. $this->error('订单不存在');
  12481. }
  12482. $modRq = trim((string)($po['mod_rq'] ?? ''));
  12483. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  12484. $this->error('订单不存在');
  12485. }
  12486. if ($this->auth->isSuperAdmin()) {
  12487. return;
  12488. }
  12489. [, $adminName] = $this->GetUseName();
  12490. $cywy = trim((string)($po['cywyxm'] ?? ''));
  12491. if ($cywy !== '' && $cywy === $adminName) {
  12492. return;
  12493. }
  12494. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  12495. try {
  12496. if ($this->auth->check($rule)) {
  12497. return;
  12498. }
  12499. } catch (\Throwable $e) {
  12500. }
  12501. }
  12502. $this->error('无权查看该订单');
  12503. }
  12504. /**
  12505. * 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
  12506. */
  12507. protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
  12508. {
  12509. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  12510. return ProcuremenStatus::PO_COMPLETED;
  12511. }
  12512. $sid = (int)($row['scydgy_id'] ?? 0);
  12513. if ($sid < 0) {
  12514. if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
  12515. return '已通知业务员';
  12516. }
  12517. if ($hasQuoted) {
  12518. return '供应商已报价';
  12519. }
  12520. if ($hasIssued
  12521. || ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
  12522. || ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
  12523. return '待报价';
  12524. }
  12525. try {
  12526. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  12527. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  12528. if ((int)$detCntQuery->count() > 0) {
  12529. return '待报价';
  12530. }
  12531. } catch (\Throwable $e) {
  12532. }
  12533. return '待询价';
  12534. }
  12535. if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
  12536. return '待入库评分';
  12537. }
  12538. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  12539. return '待采购确认';
  12540. }
  12541. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  12542. return '待确认供应商';
  12543. }
  12544. return '待协助下发';
  12545. }
  12546. /**
  12547. * 协助初选列表 — 批量软删除
  12548. */
  12549. public function pickDelete()
  12550. {
  12551. if (!$this->request->isPost() || !$this->request->isAjax()) {
  12552. $this->error(__('Invalid parameters'));
  12553. }
  12554. if (!$this->procuremenCanPickDelete()) {
  12555. $this->error(__('You have no permission'));
  12556. }
  12557. $rowsRaw = $this->request->post('rows_json', '[]');
  12558. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  12559. if (!is_array($rows) || $rows === []) {
  12560. $this->error('请至少勾选一条工序');
  12561. }
  12562. $done = 0;
  12563. Db::startTrans();
  12564. try {
  12565. foreach ($rows as $row) {
  12566. if (!is_array($row)) {
  12567. continue;
  12568. }
  12569. $this->softDeleteProcuremenPickRow($row);
  12570. $done++;
  12571. }
  12572. if ($done < 1) {
  12573. throw new \Exception('没有可删除的工序');
  12574. }
  12575. Db::commit();
  12576. } catch (\InvalidArgumentException $e) {
  12577. Db::rollback();
  12578. $this->error($e->getMessage());
  12579. } catch (\Throwable $e) {
  12580. Db::rollback();
  12581. $this->error($e->getMessage());
  12582. }
  12583. $this->pickHiddenScydgySetCache = null;
  12584. $this->success('已删除 ' . $done . ' 条工序');
  12585. }
  12586. /**
  12587. * 下发 — 手工新增工序(弹窗)
  12588. */
  12589. public function pickAdd()
  12590. {
  12591. if ($this->request->isPost()) {
  12592. $params = $this->request->post('row/a');
  12593. if (!is_array($params)) {
  12594. $this->error(__('Parameter %s can not be empty', ''));
  12595. }
  12596. try {
  12597. $sid = $this->saveManualPickOrder($params);
  12598. } catch (\InvalidArgumentException $e) {
  12599. $this->error($e->getMessage());
  12600. } catch (\Throwable $e) {
  12601. $this->error($e->getMessage());
  12602. }
  12603. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  12604. }
  12605. return $this->view->fetch('procuremen/pick_add');
  12606. }
  12607. /**
  12608. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  12609. */
  12610. public function pickSubmit()
  12611. {
  12612. if (!$this->request->isPost()) {
  12613. $this->error(__('Invalid parameters'));
  12614. }
  12615. // ---------- 接口订单数据 ----------
  12616. $rowJson = $this->request->post('row_json', '');
  12617. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  12618. $companiesJson = $this->request->post('companies_json', '[]');
  12619. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  12620. $companies = json_decode($companiesJson, true);
  12621. if (!is_array($companies)) {
  12622. $this->error('供应商数据无效');
  12623. }
  12624. $postedCompanyCount = 0;
  12625. $skippedCompanyCount = 0;
  12626. foreach ($companies as $c) {
  12627. if (is_array($c) && (trim((string)($c['name'] ?? $c['company_name'] ?? '')) !== '' || trim((string)($c['id'] ?? '')) !== '')) {
  12628. $postedCompanyCount++;
  12629. }
  12630. }
  12631. $issueCompanies = $this->normalizePickCompanies($companies);
  12632. if ($issueCompanies === []) {
  12633. $this->error('请至少选择一家合作供应商(须同时具备有效手机号与邮箱)');
  12634. }
  12635. // 不可用供应商静默跳过,不向操作员报错;成功提示中说明实际下发家数
  12636. if ($postedCompanyCount > 0 && count($issueCompanies) < $postedCompanyCount) {
  12637. $skippedCompanyCount = $postedCompanyCount - count($issueCompanies);
  12638. Log::write(
  12639. 'procuremen pickSubmit skip companies: posted=' . $postedCompanyCount
  12640. . ' issued=' . count($issueCompanies),
  12641. 'notice'
  12642. );
  12643. }
  12644. $issueNameLabels = [];
  12645. foreach ($issueCompanies as $pc) {
  12646. $issueNameLabels[] = $pc['name'];
  12647. }
  12648. $issueNamesSummary = implode('、', $issueNameLabels);
  12649. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  12650. if ($sysRq === '') {
  12651. $this->error('请选择招标截止日期');
  12652. }
  12653. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  12654. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  12655. (string)$this->request->post('delivery_deadline', ''),
  12656. true
  12657. );
  12658. $scoreRuleId = (int)$this->request->post('score_rule_id', 0);
  12659. if ($scoreRuleId <= 0) {
  12660. $this->error('请选择订单类型');
  12661. }
  12662. $scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
  12663. if ((int)($scoreRule['id'] ?? 0) <= 0) {
  12664. $this->error('订单类型无效,请刷新后重选');
  12665. }
  12666. $scoreRuleId = (int)$scoreRule['id'];
  12667. $this->ensurePurchaseOrderScoreRuleIdColumn();
  12668. $logMsg = '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  12669. $bidDispForLog = $this->formatProcuremenSysRqForDisplay($sysRqDb);
  12670. $delDispForLog = $this->formatProcuremenDeliveryDeadlineForInput($deliveryDeadlineDb);
  12671. if ($delDispForLog === '') {
  12672. $delDispForLog = $this->formatDeliveryYmd($deliveryDeadlineDb);
  12673. }
  12674. $orderTypeForLog = trim((string)($scoreRule['name'] ?? ''));
  12675. $logExtra = [];
  12676. if ($bidDispForLog !== '' && $bidDispForLog !== '—') {
  12677. $logExtra[] = '招标截止日期:' . $bidDispForLog;
  12678. }
  12679. if ($delDispForLog !== '') {
  12680. $logExtra[] = '交货截止日期:' . $delDispForLog;
  12681. }
  12682. if ($orderTypeForLog !== '') {
  12683. $logExtra[] = '订单类型:' . $orderTypeForLog;
  12684. }
  12685. if ($logExtra !== []) {
  12686. $logMsg .= ';' . implode(';', $logExtra);
  12687. }
  12688. $issueTime = date('Y-m-d H:i:s');
  12689. try {
  12690. $issueBatchNo = $this->allocateProcuremenIssueBatchNo();
  12691. } catch (\Throwable $e) {
  12692. $this->error($e->getMessage() !== '' ? $e->getMessage() : '批次号生成失败,请重试');
  12693. }
  12694. $logSidList = [];
  12695. foreach ($mergeRows as $row) {
  12696. if (!is_array($row)) {
  12697. continue;
  12698. }
  12699. $sid = $this->extractScydgyRowId($row);
  12700. if ($this->isValidScydgyRowId($sid)) {
  12701. $logSidList[$sid] = true;
  12702. }
  12703. }
  12704. if ($logSidList === []) {
  12705. $this->error('未找到有效工序,无法下发');
  12706. }
  12707. // 防连点/并发:同一批工序加命名锁,已下发则直接拒绝(避免重复短信邮件)
  12708. $sidKeys = array_keys($logSidList);
  12709. sort($sidKeys, SORT_NUMERIC);
  12710. $pickLockName = 'procuremen_pick_submit_' . md5(implode(',', $sidKeys));
  12711. if (!$this->acquireProcuremenNamedLock($pickLockName, 15)) {
  12712. $this->error('下发处理中,请勿重复点击');
  12713. }
  12714. $existingBySid = [];
  12715. try {
  12716. try {
  12717. $existingRows = Db::table('purchase_order')
  12718. ->where('scydgy_id', 'in', $sidKeys)
  12719. ->select();
  12720. if (is_array($existingRows)) {
  12721. foreach ($existingRows as $poRow) {
  12722. if (!is_array($poRow)) {
  12723. continue;
  12724. }
  12725. $sid = (int)($poRow['scydgy_id'] ?? 0);
  12726. if ($this->isValidScydgyRowId($sid)) {
  12727. $existingBySid[$sid] = $poRow;
  12728. }
  12729. }
  12730. }
  12731. } catch (\Throwable $e) {
  12732. $existingBySid = [];
  12733. }
  12734. foreach ($sidKeys as $sid) {
  12735. $poRow = $existingBySid[$sid] ?? null;
  12736. if (!is_array($poRow)) {
  12737. continue;
  12738. }
  12739. if ($this->isPurchaseOrderSoftDeleted($poRow['mod_rq'] ?? null)) {
  12740. continue;
  12741. }
  12742. $label = $this->formatProcuremenRowLabel(['CCYDH' => $poRow['CCYDH'] ?? '', 'CGYMC' => $poRow['CGYMC'] ?? '']);
  12743. if (ProcuremenStatus::isPoCompleted($poRow['status'] ?? '')) {
  12744. $this->error(($label !== '' ? $label : ('工序#' . $sid)) . '已完结,无法再次下发');
  12745. }
  12746. if (!ProcuremenStatus::isWflowPendingIssue($poRow['wflow_status'] ?? '')) {
  12747. $this->error(($label !== '' ? $label : ('工序#' . $sid)) . '已下发或进入后续流程,请勿重复提交');
  12748. }
  12749. }
  12750. Db::startTrans();
  12751. try {
  12752. $this->enrichProcuremenRowsMbz($mergeRows);
  12753. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  12754. foreach ($mergeRows as $row) {
  12755. if (!is_array($row)) {
  12756. continue;
  12757. }
  12758. $sid = $this->extractScydgyRowId($row);
  12759. $this->upsertPurchaseOrderFromRow(
  12760. $row,
  12761. $sysRqDb,
  12762. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  12763. $issueTime,
  12764. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  12765. $deliveryDeadlineDb,
  12766. $scoreRule,
  12767. $issueBatchNo
  12768. );
  12769. }
  12770. foreach ($issueCompanies as $c) {
  12771. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  12772. }
  12773. Db::commit();
  12774. } catch (\Throwable $e) {
  12775. Db::rollback();
  12776. $this->error($e->getMessage());
  12777. }
  12778. } finally {
  12779. $this->releaseProcuremenNamedLock($pickLockName);
  12780. }
  12781. $poIdBySid = [];
  12782. if ($logSidList !== []) {
  12783. try {
  12784. $poIdBySid = Db::table('purchase_order')
  12785. ->where('scydgy_id', 'in', array_keys($logSidList))
  12786. ->column('id', 'scydgy_id');
  12787. } catch (\Throwable $e) {
  12788. $poIdBySid = [];
  12789. }
  12790. }
  12791. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  12792. if ($logSidList !== []) {
  12793. list($adminId, $adminName) = $this->GetUseName();
  12794. $logRows = [];
  12795. $seenLogSid = [];
  12796. foreach ($mergeRows as $row) {
  12797. if (!is_array($row)) {
  12798. continue;
  12799. }
  12800. $ids = $this->extractScydgyRowId($row);
  12801. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  12802. continue;
  12803. }
  12804. $seenLogSid[$ids] = true;
  12805. $poIdLog = null;
  12806. if (isset($poIdBySid[$ids])) {
  12807. $tid = (int)$poIdBySid[$ids];
  12808. $poIdLog = $tid > 0 ? $tid : null;
  12809. }
  12810. $logRows[] = ProcuremenOperLog::buildInsertRow(
  12811. $ids,
  12812. 'issue_submit',
  12813. $logMsg,
  12814. $poIdLog,
  12815. (int)$adminId,
  12816. (string)$adminName
  12817. );
  12818. }
  12819. if ($logRows !== []) {
  12820. try {
  12821. Db::table('purchase_order_oper_log')->insertAll($logRows);
  12822. } catch (\Throwable $e) {
  12823. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  12824. }
  12825. }
  12826. }
  12827. $posNotify = [];
  12828. if ($logSidList !== []) {
  12829. try {
  12830. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  12831. } catch (\Throwable $e) {
  12832. $posNotify = [];
  12833. }
  12834. }
  12835. if (!is_array($posNotify)) {
  12836. $posNotify = [];
  12837. }
  12838. foreach ($posNotify as $i => $prow) {
  12839. if (is_array($posNotify[$i])) {
  12840. $posNotify[$i]['sys_rq'] = $sysRqDb;
  12841. }
  12842. }
  12843. $ccydhPick = '';
  12844. foreach ($mergeRows as $row) {
  12845. if (!is_array($row)) {
  12846. continue;
  12847. }
  12848. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  12849. if ($ccydhPick !== '') {
  12850. break;
  12851. }
  12852. }
  12853. $notifyBundleBase = [
  12854. 'ccydh' => $ccydhPick,
  12855. 'pos' => $posNotify,
  12856. 'merge_rows' => $mergeRows,
  12857. 'score_rule' => is_array($scoreRule) ? $scoreRule : null,
  12858. ];
  12859. // 写库已成功:先立刻回成功给前端,再后台发短信/邮件(避免多家串行超时转圈/误报失败)
  12860. $okCount = count($issueCompanies);
  12861. $skipHint = '';
  12862. if (!empty($skippedCompanyCount) && (int)$skippedCompanyCount > 0) {
  12863. $skipHint = '(已自动跳过 ' . (int)$skippedCompanyCount . ' 家资料不完整的供应商)';
  12864. }
  12865. $payload = [
  12866. 'issued' => 1,
  12867. 'supplier_count' => $okCount,
  12868. 'notify_pending' => 1,
  12869. 'notify_failed' => 0,
  12870. ];
  12871. $successMsg = '下发成功' . $skipHint . ',已向 ' . $okCount
  12872. . ' 家供应商发起通知。';
  12873. if ($this->isProcuremenNotifyDryRun()) {
  12874. $this->notifyDryRunPreview = [];
  12875. $notifyErrors = [];
  12876. foreach ($issueCompanies as $c) {
  12877. if (!is_array($c)) {
  12878. continue;
  12879. }
  12880. $cname = trim((string)($c['name'] ?? ''));
  12881. if ($cname === '') {
  12882. continue;
  12883. }
  12884. try {
  12885. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  12886. } catch (\Throwable $e) {
  12887. $notifyErrors[] = $cname . ':' . $e->getMessage();
  12888. }
  12889. }
  12890. $this->success('【演练模式】已保存并生成通知预览', '', [
  12891. 'notify_dry_run' => true,
  12892. 'notify_preview' => $this->notifyDryRunPreview,
  12893. 'notify_fail_detail' => $notifyErrors,
  12894. ]);
  12895. }
  12896. $this->respondSuccessThenContinue($successMsg, $payload);
  12897. @set_time_limit(300);
  12898. @ini_set('max_execution_time', '300');
  12899. $notifyOk = 0;
  12900. $notifyErrors = [];
  12901. foreach ($issueCompanies as $c) {
  12902. if (!is_array($c)) {
  12903. continue;
  12904. }
  12905. $cname = trim((string)($c['name'] ?? ''));
  12906. if ($cname === '') {
  12907. continue;
  12908. }
  12909. try {
  12910. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  12911. $notifyOk++;
  12912. } catch (\Throwable $e) {
  12913. $notifyErrors[] = $cname . ':' . $e->getMessage();
  12914. Log::write('procuremen pickSubmit background notify fail ' . $cname . ': ' . $e->getMessage(), 'error');
  12915. }
  12916. }
  12917. if ($notifyErrors !== []) {
  12918. Log::write(
  12919. 'procuremen pickSubmit background notify summary ok=' . $notifyOk
  12920. . ' fail=' . count($notifyErrors) . ' ' . implode(';', $notifyErrors),
  12921. 'error'
  12922. );
  12923. }
  12924. exit;
  12925. }
  12926. /**
  12927. * 确认供应商弹窗
  12928. */
  12929. public function auditIssue()
  12930. {
  12931. $ids = $this->request->param('ids', $this->request->param('id', ''));
  12932. if (is_array($ids)) {
  12933. $ids = isset($ids[0]) ? $ids[0] : '';
  12934. }
  12935. $ids = trim((string)$ids);
  12936. if ($ids === '') {
  12937. $this->error(__('Invalid parameters'));
  12938. }
  12939. if ($this->request->isPost()) {
  12940. $this->error('请使用弹窗内「确认」提交');
  12941. }
  12942. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  12943. $pos = $bundle['pos'];
  12944. if ($pos === []) {
  12945. $this->error('该订单不在待确认供应商状态');
  12946. }
  12947. $po = $pos[0];
  12948. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  12949. if ($quoteGroups === []) {
  12950. $toastMsg = '暂无下发明细,请确认该订单已在「供应商初选」完成下发';
  12951. // 弹层内不要走整页跳转提示,仅 Toastr 后关闭
  12952. $this->view->assign('toastMsg', $toastMsg);
  12953. return $this->view->fetch('procuremen/toast_close');
  12954. }
  12955. $pickedName = '';
  12956. foreach ($pos as $poRow) {
  12957. if (!is_array($poRow)) {
  12958. continue;
  12959. }
  12960. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  12961. if ($pn !== '') {
  12962. $pickedName = $pn;
  12963. break;
  12964. }
  12965. }
  12966. $this->view->assign('po', $po);
  12967. $this->view->assign('scydgyId', $ids);
  12968. $this->view->assign('orderCcydh', $bundle['ccydh']);
  12969. $mergeRows = $bundle['merge_rows'];
  12970. $this->view->assign('processRows', $mergeRows);
  12971. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  12972. $this->view->assign('processCount', count($mergeRows));
  12973. $this->view->assign('orderBatchNo', $this->resolveBundleOrderBatchNo($bundle));
  12974. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  12975. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  12976. $this->view->assign('pickedCompanyName', $pickedName);
  12977. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  12978. if ($sysRqForView === '') {
  12979. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  12980. }
  12981. $this->view->assign('sysRq', $sysRqForView);
  12982. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  12983. if ($deliveryDeadlineForView === '') {
  12984. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  12985. }
  12986. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  12987. $this->ensurePurchaseOrderManualPickColumns();
  12988. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
  12989. $manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
  12990. $manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
  12991. $isRejected = 0;
  12992. foreach ($pos as $poRow) {
  12993. if (!is_array($poRow)) {
  12994. continue;
  12995. }
  12996. if (ProcuremenStatus::isWflowRejected($poRow['wflow_status'] ?? '')) {
  12997. $isRejected = 1;
  12998. break;
  12999. }
  13000. }
  13001. $quoteVisible = ($bidOpenVerified || $manualPicked || $isRejected) ? 1 : 0;
  13002. if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
  13003. $pickedName = $manualPickInfo['company'];
  13004. }
  13005. // 驳回后:仅一家供应商时自动选定,便于直接确认;多家则留空供用户选择
  13006. $quoteGroupCount = 0;
  13007. $onlyQuoteCompany = '';
  13008. foreach ($quoteGroups as $g) {
  13009. if (!is_array($g)) {
  13010. continue;
  13011. }
  13012. $nm = trim((string)($g['name'] ?? ''));
  13013. if ($nm === '') {
  13014. continue;
  13015. }
  13016. $quoteGroupCount++;
  13017. if ($onlyQuoteCompany === '') {
  13018. $onlyQuoteCompany = $nm;
  13019. }
  13020. }
  13021. if ($isRejected) {
  13022. // 驳回需重新选定:清空锁定用的已选名;仅一家时再自动勾选
  13023. $pickedName = ($quoteGroupCount === 1) ? $onlyQuoteCompany : '';
  13024. }
  13025. $this->view->assign('pickedCompanyName', $pickedName);
  13026. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  13027. $this->view->assign('manualPicked', $manualPicked);
  13028. $this->view->assign('isRejected', $isRejected);
  13029. $this->view->assign('quoteGroupCount', $quoteGroupCount);
  13030. $this->view->assign('manualPickReason', $manualPickInfo['reason']);
  13031. $this->view->assign('quoteVisible', $quoteVisible);
  13032. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
  13033. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  13034. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
  13035. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
  13036. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  13037. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  13038. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  13039. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  13040. return $this->view->fetch('procuremen/audit_issue');
  13041. }
  13042. /**
  13043. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  13044. *
  13045. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  13046. */
  13047. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  13048. {
  13049. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13050. return false;
  13051. }
  13052. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13053. return false;
  13054. }
  13055. return true;
  13056. }
  13057. /**
  13058. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  13059. *
  13060. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  13061. */
  13062. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  13063. {
  13064. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13065. return false;
  13066. }
  13067. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13068. return false;
  13069. }
  13070. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  13071. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  13072. return true;
  13073. }
  13074. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  13075. }
  13076. /**
  13077. * 确认页 — 补加供应商弹窗
  13078. */
  13079. public function auditAppend()
  13080. {
  13081. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  13082. $this->error(__('You have no permission'));
  13083. }
  13084. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  13085. if (is_array($ids)) {
  13086. $ids = isset($ids[0]) ? $ids[0] : '';
  13087. }
  13088. $ids = trim((string)$ids);
  13089. if ($ids === '') {
  13090. $this->error(__('Invalid parameters'));
  13091. }
  13092. if ($this->request->isPost()) {
  13093. $this->error('请使用弹窗内「确认」提交');
  13094. }
  13095. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  13096. if (($bundle['pos'] ?? []) === []) {
  13097. $this->error('该订单不在待确认供应商状态');
  13098. }
  13099. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  13100. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13101. $this->error('已开标验证,不能再补加供应商');
  13102. }
  13103. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13104. $this->error('已指定供应商,不能再补加供应商');
  13105. }
  13106. $this->error('已经超过了招标截止日期,不可操作');
  13107. }
  13108. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13109. $existingNames = [];
  13110. foreach ($quoteGroups as $g) {
  13111. if (!is_array($g)) {
  13112. continue;
  13113. }
  13114. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  13115. if ($n !== '') {
  13116. $existingNames[$n] = true;
  13117. }
  13118. }
  13119. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  13120. $mergeRows = $bundle['merge_rows'] ?? [];
  13121. $this->view->assign('scydgyId', $ids);
  13122. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  13123. $this->view->assign('po', $po);
  13124. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  13125. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  13126. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  13127. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  13128. if ($sysRqForView === '') {
  13129. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  13130. }
  13131. $this->view->assign('sysRq', $sysRqForView);
  13132. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  13133. if ($deliveryDeadlineForView === '') {
  13134. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  13135. }
  13136. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  13137. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  13138. }
  13139. /**
  13140. * 确认页 — 补加供应商提交
  13141. */
  13142. public function auditAppendSubmit()
  13143. {
  13144. if (!$this->request->isPost()) {
  13145. $this->error(__('Invalid parameters'));
  13146. }
  13147. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  13148. $this->error(__('You have no permission'));
  13149. }
  13150. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  13151. if ($ids === '') {
  13152. $this->error(__('Invalid parameters'));
  13153. }
  13154. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  13155. if (($bundle['pos'] ?? []) === []) {
  13156. $this->error('该订单不在待确认供应商状态');
  13157. }
  13158. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  13159. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13160. $this->error('已开标验证,不能再补加供应商');
  13161. }
  13162. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13163. $this->error('已指定供应商,不能再补加供应商');
  13164. }
  13165. $this->error('已经超过了招标截止日期,不可操作');
  13166. }
  13167. $companiesJson = $this->request->post('companies_json', '[]');
  13168. $companies = json_decode((string)$companiesJson, true);
  13169. if (!is_array($companies)) {
  13170. $this->error('供应商数据无效');
  13171. }
  13172. $issueCompanies = $this->normalizePickCompanies($companies);
  13173. if ($issueCompanies === []) {
  13174. $this->error('请至少选择一家合作供应商');
  13175. }
  13176. $mergeRows = $bundle['merge_rows'] ?? [];
  13177. if (!is_array($mergeRows) || $mergeRows === []) {
  13178. $this->error('未找到工序行,无法补加');
  13179. }
  13180. $existingNames = [];
  13181. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  13182. if (!is_array($g)) {
  13183. continue;
  13184. }
  13185. $n = trim((string)($g['company_name'] ?? ''));
  13186. if ($n !== '') {
  13187. $existingNames[$n] = true;
  13188. }
  13189. }
  13190. $toAdd = [];
  13191. foreach ($issueCompanies as $c) {
  13192. if (!is_array($c)) {
  13193. continue;
  13194. }
  13195. $n = trim((string)($c['name'] ?? ''));
  13196. if ($n === '' || isset($existingNames[$n])) {
  13197. continue;
  13198. }
  13199. $toAdd[] = $c;
  13200. }
  13201. if ($toAdd === []) {
  13202. $this->error('所选供应商均已在本单中,请选择新的供应商');
  13203. }
  13204. $addedNames = [];
  13205. Db::startTrans();
  13206. try {
  13207. foreach ($toAdd as $c) {
  13208. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  13209. $addedNames[] = trim((string)($c['name'] ?? ''));
  13210. }
  13211. Db::commit();
  13212. } catch (\Throwable $e) {
  13213. Db::rollback();
  13214. $this->error($e->getMessage());
  13215. }
  13216. $notifyBundleBase = [
  13217. 'ccydh' => $bundle['ccydh'] ?? '',
  13218. 'pos' => $bundle['pos'] ?? [],
  13219. 'merge_rows' => $mergeRows,
  13220. ];
  13221. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  13222. $seenLogSid = [];
  13223. foreach ($bundle['pos'] ?? [] as $poRow) {
  13224. if (!is_array($poRow)) {
  13225. continue;
  13226. }
  13227. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13228. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  13229. continue;
  13230. }
  13231. $seenLogSid[$sid] = true;
  13232. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  13233. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  13234. }
  13235. if ($seenLogSid === []) {
  13236. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  13237. if ($this->isValidScydgyRowId($logSid)) {
  13238. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  13239. }
  13240. }
  13241. if ($this->isProcuremenNotifyDryRun()) {
  13242. $this->notifyDryRunPreview = [];
  13243. $notifyErrors = [];
  13244. foreach ($toAdd as $c) {
  13245. if (!is_array($c)) {
  13246. continue;
  13247. }
  13248. $cname = trim((string)($c['name'] ?? ''));
  13249. if ($cname === '') {
  13250. continue;
  13251. }
  13252. try {
  13253. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  13254. } catch (\Throwable $e) {
  13255. $notifyErrors[] = $cname . ':' . $e->getMessage();
  13256. }
  13257. }
  13258. $this->success('【演练模式】已补加并生成通知预览', '', [
  13259. 'append_ok' => 1,
  13260. 'notify_dry_run' => true,
  13261. 'notify_preview' => $this->notifyDryRunPreview,
  13262. 'notify_fail_detail' => $notifyErrors,
  13263. ]);
  13264. }
  13265. $this->respondSuccessThenContinue(
  13266. '已补加 ' . count($toAdd) . ' 家供应商并发起通知。',
  13267. ['append_ok' => 1, 'notify_pending' => 1, 'notify_failed' => 0]
  13268. );
  13269. $notifyErrors = [];
  13270. foreach ($toAdd as $c) {
  13271. if (!is_array($c)) {
  13272. continue;
  13273. }
  13274. $cname = trim((string)($c['name'] ?? ''));
  13275. if ($cname === '') {
  13276. continue;
  13277. }
  13278. try {
  13279. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  13280. } catch (\Throwable $e) {
  13281. $notifyErrors[] = $cname . ':' . $e->getMessage();
  13282. Log::write('procuremen auditAppend background notify fail ' . $cname . ': ' . $e->getMessage(), 'error');
  13283. }
  13284. }
  13285. if ($notifyErrors !== []) {
  13286. Log::write('procuremen auditAppend background notify summary: ' . implode(';', $notifyErrors), 'error');
  13287. }
  13288. exit;
  13289. }
  13290. /**
  13291. * 开标双重验证 — 可选验证人列表
  13292. */
  13293. public function bidOpenUsers()
  13294. {
  13295. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  13296. $this->error('无权限');
  13297. }
  13298. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  13299. if ($scydgyId !== '') {
  13300. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13301. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13302. $this->success('已完成开标验证', null, [
  13303. 'verified' => 1,
  13304. 'users' => [],
  13305. ]);
  13306. }
  13307. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13308. $this->error('本单已指定供应商,无需再开标');
  13309. }
  13310. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  13311. }
  13312. $this->success('', null, [
  13313. 'verified' => 0,
  13314. 'users' => $this->listBidOpenVerifierCandidates(),
  13315. ]);
  13316. }
  13317. /**
  13318. * 开标双重验证 — 向指定管理员发送短信验证码
  13319. */
  13320. public function bidOpenSendCode()
  13321. {
  13322. if (!$this->request->isPost()) {
  13323. $this->error(__('Invalid parameters'));
  13324. }
  13325. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  13326. $this->error('无权限');
  13327. }
  13328. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13329. $adminId = (int)$this->request->post('admin_id', 0);
  13330. if ($scydgyId === '' || $adminId <= 0) {
  13331. $this->error('参数无效');
  13332. }
  13333. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13334. if ($bundle['pos'] === []) {
  13335. $this->error('该订单不在待确认供应商状态');
  13336. }
  13337. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13338. $this->success('已完成开标验证,无需重复发送');
  13339. }
  13340. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13341. $this->error('本单已指定供应商,无需再开标');
  13342. }
  13343. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  13344. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  13345. if ($ccydh === '') {
  13346. $this->error('订单号无效');
  13347. }
  13348. $admin = $this->loadBidOpenAdminUser($adminId);
  13349. if ($admin === null) {
  13350. $this->error('验证人无效或未绑定手机号');
  13351. }
  13352. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  13353. $cd = max(30, min(120, $cd));
  13354. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  13355. $this->error('发送过于频繁,请稍后再试');
  13356. }
  13357. $code = (string)random_int(100000, 999999);
  13358. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  13359. $ttl = max(60, min(600, $ttl));
  13360. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  13361. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  13362. try {
  13363. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  13364. } catch (\Throwable $e) {
  13365. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  13366. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  13367. $this->error($e->getMessage());
  13368. }
  13369. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  13370. }
  13371. /**
  13372. * 开标双重验证 — 两人验证码校验并记录
  13373. */
  13374. public function bidOpenVerify()
  13375. {
  13376. if (!$this->request->isPost()) {
  13377. $this->error(__('Invalid parameters'));
  13378. }
  13379. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  13380. $this->error('无权限');
  13381. }
  13382. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13383. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  13384. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  13385. $code1 = trim((string)$this->request->post('code1', ''));
  13386. $code2 = trim((string)$this->request->post('code2', ''));
  13387. if ($scydgyId === '') {
  13388. $this->error('参数无效');
  13389. }
  13390. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  13391. $this->error('请选择两位验证人');
  13392. }
  13393. if ($verifier1Id === $verifier2Id) {
  13394. $this->error('两位验证人不能相同');
  13395. }
  13396. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  13397. $this->error('请输入6位短信验证码');
  13398. }
  13399. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13400. if ($bundle['pos'] === []) {
  13401. $this->error('该订单不在待确认供应商状态');
  13402. }
  13403. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  13404. if ($ccydh === '') {
  13405. $this->error('订单号无效');
  13406. }
  13407. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13408. $this->success('已完成开标验证');
  13409. }
  13410. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  13411. $this->error('本单已指定供应商,无需再开标');
  13412. }
  13413. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  13414. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  13415. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  13416. if ($verifier1 === null || $verifier2 === null) {
  13417. $this->error('验证人无效或未绑定手机号');
  13418. }
  13419. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  13420. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  13421. }
  13422. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  13423. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  13424. }
  13425. try {
  13426. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  13427. } catch (\Throwable $e) {
  13428. $this->error($e->getMessage());
  13429. }
  13430. $this->success('开标验证成功,可查看供应商报价与交货日期');
  13431. }
  13432. /**
  13433. * 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
  13434. */
  13435. public function auditManualPick()
  13436. {
  13437. if (!$this->request->isPost()) {
  13438. $this->error(__('Invalid parameters'));
  13439. }
  13440. if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
  13441. $this->error('无权限');
  13442. }
  13443. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13444. if ($scydgyId === '') {
  13445. $this->error('参数无效');
  13446. }
  13447. $companyName = trim((string)$this->request->post('selected_company', ''));
  13448. $reason = trim((string)$this->request->post('pick_reason', ''));
  13449. if ($companyName === '') {
  13450. $this->error('请选择一家供应商');
  13451. }
  13452. if ($reason === '') {
  13453. $this->error('请填写选择说明');
  13454. }
  13455. if (mb_strlen($reason) > 500) {
  13456. $this->error('选择说明不能超过500字');
  13457. }
  13458. $this->ensurePurchaseOrderManualPickColumns();
  13459. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13460. $pos = $bundle['pos'];
  13461. if ($pos === []) {
  13462. $this->error('该订单不在待确认供应商状态');
  13463. }
  13464. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  13465. $this->error('本单已开标验证,请直接在列表中选定供应商后确认');
  13466. }
  13467. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13468. if ($quoteGroups === []) {
  13469. $this->error('暂无供应商,请确认已完成协助初选通知');
  13470. }
  13471. $matched = null;
  13472. foreach ($quoteGroups as $g) {
  13473. if (!is_array($g)) {
  13474. continue;
  13475. }
  13476. if (trim((string)($g['name'] ?? '')) === $companyName) {
  13477. $matched = $g;
  13478. break;
  13479. }
  13480. }
  13481. if ($matched === null) {
  13482. $this->error('所选供应商不在本单报价列表中');
  13483. }
  13484. $logMsg = '指定供应商:' . $companyName . ';说明:' . $reason;
  13485. Db::startTrans();
  13486. try {
  13487. foreach ($pos as $poRow) {
  13488. if (!is_array($poRow)) {
  13489. continue;
  13490. }
  13491. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13492. if (!$this->isValidScydgyRowId($sid)) {
  13493. continue;
  13494. }
  13495. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  13496. 'pick_company_name' => $companyName,
  13497. 'manual_pick' => 1,
  13498. 'manual_pick_reason' => $reason,
  13499. ]);
  13500. }
  13501. Db::commit();
  13502. } catch (\Throwable $e) {
  13503. Db::rollback();
  13504. $this->error($e->getMessage());
  13505. }
  13506. foreach ($pos as $poRow) {
  13507. if (!is_array($poRow)) {
  13508. continue;
  13509. }
  13510. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13511. if (!$this->isValidScydgyRowId($sid)) {
  13512. continue;
  13513. }
  13514. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  13515. $this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  13516. }
  13517. // 自选后可见报价:按本批各订单分别计算评分(与开标后一致)
  13518. try {
  13519. $bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13520. $this->saveProcuremenSupplierScoresForBundle($bundleFresh, date('Y-m'));
  13521. } catch (\Throwable $e) {
  13522. Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
  13523. }
  13524. $this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
  13525. }
  13526. /**
  13527. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  13528. */
  13529. public function auditSubmit()
  13530. {
  13531. if (!$this->request->isPost()) {
  13532. $this->error(__('Invalid parameters'));
  13533. }
  13534. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13535. if ($scydgyId === '') {
  13536. $this->error('参数无效');
  13537. }
  13538. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  13539. $pos = $bundle['pos'];
  13540. $mergeRows = $bundle['merge_rows'];
  13541. if ($pos === [] || $mergeRows === []) {
  13542. $this->error('该订单不在待确认供应商状态');
  13543. }
  13544. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13545. if ($quoteGroups === []) {
  13546. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  13547. }
  13548. $companyName = trim((string)$this->request->post('selected_company', ''));
  13549. if ($companyName === '') {
  13550. $this->error('请选择一家供应商');
  13551. }
  13552. $matched = null;
  13553. foreach ($quoteGroups as $g) {
  13554. if (!is_array($g)) {
  13555. continue;
  13556. }
  13557. if (trim((string)($g['name'] ?? '')) === $companyName) {
  13558. $matched = $g;
  13559. break;
  13560. }
  13561. }
  13562. if ($matched === null) {
  13563. $this->error('所选供应商不在本单报价列表中');
  13564. }
  13565. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  13566. if ($sysRqDb === '') {
  13567. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  13568. } else {
  13569. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  13570. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  13571. }
  13572. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  13573. $this->error('未到招标截止日期,暂不可确认');
  13574. }
  13575. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
  13576. && !$this->isProcuremenManualPickedForBundle($bundle)
  13577. ) {
  13578. $this->error('请先完成开标双重验证或指定供应商后再确认');
  13579. }
  13580. $logMsg = '确认供应商:' . $companyName;
  13581. Db::startTrans();
  13582. try {
  13583. foreach ($pos as $poRow) {
  13584. if (!is_array($poRow)) {
  13585. continue;
  13586. }
  13587. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13588. if (!$this->isValidScydgyRowId($sid)) {
  13589. continue;
  13590. }
  13591. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  13592. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  13593. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  13594. 'pick_company_name' => $companyName,
  13595. 'sys_rq' => $sysRqDb,
  13596. ]);
  13597. }
  13598. Db::commit();
  13599. } catch (\Throwable $e) {
  13600. Db::rollback();
  13601. $this->error($e->getMessage());
  13602. }
  13603. foreach ($pos as $poRow) {
  13604. if (!is_array($poRow)) {
  13605. continue;
  13606. }
  13607. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13608. if (!$this->isValidScydgyRowId($sid)) {
  13609. continue;
  13610. }
  13611. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  13612. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  13613. }
  13614. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  13615. }
  13616. /**
  13617. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  13618. */
  13619. public function auditResendSms()
  13620. {
  13621. if (!$this->request->isPost()) {
  13622. $this->error(__('Invalid parameters'));
  13623. }
  13624. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13625. if ($scydgyId === '') {
  13626. $this->error('参数无效');
  13627. }
  13628. $loaded = $this->loadAuditResendBundle($scydgyId);
  13629. $mergeRows = $loaded['merge_rows'];
  13630. $bundle = $loaded['bundle'];
  13631. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  13632. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13633. if ($quoteGroups === []) {
  13634. $this->error('暂无可通知的供应商');
  13635. }
  13636. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  13637. $companiesJson = (string)$this->request->post('companies_json', '');
  13638. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  13639. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  13640. }
  13641. /**
  13642. * 确认供应商 — 二次发送邮件(可选单家/批量)
  13643. */
  13644. public function auditResendEmail()
  13645. {
  13646. if (!$this->request->isPost()) {
  13647. $this->error(__('Invalid parameters'));
  13648. }
  13649. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  13650. if ($scydgyId === '') {
  13651. $this->error('参数无效');
  13652. }
  13653. $loaded = $this->loadAuditResendBundle($scydgyId);
  13654. $mergeRows = $loaded['merge_rows'];
  13655. $bundle = $loaded['bundle'];
  13656. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  13657. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  13658. if ($quoteGroups === []) {
  13659. $this->error('暂无可通知的供应商');
  13660. }
  13661. $companiesJson = (string)$this->request->post('companies_json', '');
  13662. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  13663. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  13664. if ($companiesJson === '' && $selectedCompany === '') {
  13665. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  13666. }
  13667. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  13668. }
  13669. /**
  13670. * 废弃单个订单 bundle(退回供应商初选,明细归档留痕)
  13671. *
  13672. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  13673. * @return array<int, true> 已处理的 scydgy_id 集合
  13674. */
  13675. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回供应商初选'): array
  13676. {
  13677. $pos = $bundle['pos'] ?? [];
  13678. if (!is_array($pos) || $pos === []) {
  13679. return [];
  13680. }
  13681. $sids = [];
  13682. $poIdBySid = [];
  13683. foreach ($pos as $poRow) {
  13684. if (!is_array($poRow)) {
  13685. continue;
  13686. }
  13687. $sid = (int)($poRow['scydgy_id'] ?? 0);
  13688. if ($this->isValidScydgyRowId($sid)) {
  13689. $sids[$sid] = true;
  13690. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  13691. if ($poId > 0) {
  13692. $poIdBySid[$sid] = $poId;
  13693. }
  13694. }
  13695. }
  13696. if ($sids === []) {
  13697. return [];
  13698. }
  13699. $logMsg = '重新下发';
  13700. $suffix = trim((string)$logSuffix, ',, ');
  13701. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  13702. $logMsg .= ':从历史存证退回供应商初选';
  13703. } else {
  13704. $logMsg .= ':退回供应商初选';
  13705. }
  13706. Db::table('purchase_order')
  13707. ->where('scydgy_id', 'in', array_keys($sids))
  13708. ->update([
  13709. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  13710. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  13711. 'pick_company_name' => '',
  13712. 'pick_time' => null,
  13713. 'sys_rq' => null,
  13714. 'mod_rq' => null,
  13715. 'manual_pick' => 0,
  13716. 'manual_pick_reason' => '',
  13717. ]);
  13718. // 重新下发后需重新开标;清掉本批按订单号/批次号记录的开标验证
  13719. $ccydhSet = [];
  13720. $batchSet = [];
  13721. foreach ($pos as $poRow) {
  13722. if (!is_array($poRow)) {
  13723. continue;
  13724. }
  13725. foreach ($this->expandProcuremenCcydhTokens($poRow['CCYDH'] ?? '') as $dh) {
  13726. $ccydhSet[$dh] = true;
  13727. }
  13728. $bn = $this->resolveProcuremenOrderBatchNo($poRow);
  13729. if ($bn !== '') {
  13730. $batchSet[$bn] = true;
  13731. }
  13732. }
  13733. $this->clearProcuremenBidOpenRecords(array_keys($ccydhSet), array_keys($batchSet));
  13734. $this->clearProcuremenSupplierScoresForCcydhs(array_keys($ccydhSet));
  13735. // 同订单其它旧批次(有明确批次号、未完结)软删除,避免列表/弹窗仍读到旧批「已开标/已指定」
  13736. $keepBatch = '';
  13737. if ($batchSet !== []) {
  13738. $batchKeys = array_keys($batchSet);
  13739. $keepBatch = (string)reset($batchKeys);
  13740. }
  13741. $this->softDeleteOtherBatchPurchaseOrders(array_keys($ccydhSet), array_keys($sids), $keepBatch);
  13742. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  13743. foreach (array_keys($sids) as $sid) {
  13744. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  13745. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  13746. }
  13747. return $sids;
  13748. }
  13749. /**
  13750. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  13751. *
  13752. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  13753. */
  13754. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  13755. {
  13756. $scydgyId = trim($scydgyId);
  13757. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  13758. if ($scydgyId === '') {
  13759. return $empty;
  13760. }
  13761. try {
  13762. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  13763. } catch (\Throwable $e) {
  13764. $anchor = null;
  13765. }
  13766. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  13767. return $empty;
  13768. }
  13769. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  13770. if ($ccydh === '') {
  13771. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  13772. }
  13773. try {
  13774. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  13775. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  13776. $pos = $query->order('scydgy_id', 'asc')->select();
  13777. } catch (\Throwable $e) {
  13778. $pos = [$anchor];
  13779. }
  13780. if (!is_array($pos) || $pos === []) {
  13781. $pos = [$anchor];
  13782. }
  13783. return [
  13784. 'ccydh' => $ccydh,
  13785. 'pos' => $pos,
  13786. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  13787. ];
  13788. }
  13789. protected function purchaseOrderRowIsCompleted(array $po): bool
  13790. {
  13791. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  13792. }
  13793. /**
  13794. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  13795. *
  13796. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  13797. */
  13798. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  13799. {
  13800. $scydgyId = trim($scydgyId);
  13801. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  13802. if ($scydgyId === '') {
  13803. return $empty;
  13804. }
  13805. try {
  13806. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  13807. } catch (\Throwable $e) {
  13808. $anchor = null;
  13809. }
  13810. if (!is_array($anchor)) {
  13811. return $empty;
  13812. }
  13813. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  13814. if ($ccydh === '') {
  13815. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  13816. }
  13817. try {
  13818. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  13819. } catch (\Throwable $e) {
  13820. $pos = [$anchor];
  13821. }
  13822. if (!is_array($pos) || $pos === []) {
  13823. $pos = [$anchor];
  13824. }
  13825. $pos = $this->filterPurchaseOrdersSameIssueBatch($pos, $anchor);
  13826. return [
  13827. 'ccydh' => $ccydh,
  13828. 'pos' => $pos,
  13829. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  13830. ];
  13831. }
  13832. /**
  13833. * 废弃订单 — 退回供应商初选重新询价(支持单条或批量)
  13834. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  13835. */
  13836. public function auditAbandon()
  13837. {
  13838. if (!$this->request->isPost()) {
  13839. $this->error(__('Invalid parameters'));
  13840. }
  13841. $anchorIds = [];
  13842. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  13843. if ($batchRaw !== '') {
  13844. $decoded = json_decode($batchRaw, true);
  13845. if (is_array($decoded)) {
  13846. foreach ($decoded as $id) {
  13847. $s = trim((string)$id);
  13848. if ($s !== '') {
  13849. $anchorIds[] = $s;
  13850. }
  13851. }
  13852. }
  13853. }
  13854. if ($anchorIds === []) {
  13855. $single = trim((string)$this->request->post('scydgy_id', ''));
  13856. if ($single !== '') {
  13857. $anchorIds[] = $single;
  13858. }
  13859. }
  13860. if ($anchorIds === []) {
  13861. $this->error('请至少选择一条订单');
  13862. }
  13863. $processedCcydh = [];
  13864. $doneOrders = 0;
  13865. $allSids = [];
  13866. Db::startTrans();
  13867. try {
  13868. foreach ($anchorIds as $anchorId) {
  13869. $fromArchive = false;
  13870. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  13871. if (($bundle['pos'] ?? []) === []) {
  13872. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  13873. $fromArchive = ($bundle['pos'] ?? []) !== [];
  13874. }
  13875. if (($bundle['pos'] ?? []) === []) {
  13876. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  13877. $fromArchive = ($bundle['pos'] ?? []) !== [];
  13878. }
  13879. if (($bundle['pos'] ?? []) === []) {
  13880. continue;
  13881. }
  13882. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  13883. $batchTime = '';
  13884. if (!empty($bundle['pos'][0]) && is_array($bundle['pos'][0])) {
  13885. $batchTime = $this->procuremenIssueBatchTime($bundle['pos'][0]);
  13886. }
  13887. $dedupeKey = $ccydh !== '' ? ($ccydh . '|' . $batchTime) : ('sid:' . $anchorId);
  13888. if (isset($processedCcydh[$dedupeKey])) {
  13889. continue;
  13890. }
  13891. $processedCcydh[$dedupeKey] = true;
  13892. $sids = $fromArchive
  13893. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回供应商初选')
  13894. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  13895. if ($sids === []) {
  13896. continue;
  13897. }
  13898. $doneOrders++;
  13899. foreach (array_keys($sids) as $sid) {
  13900. $allSids[(int)$sid] = true;
  13901. }
  13902. }
  13903. if ($doneOrders < 1) {
  13904. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  13905. }
  13906. Db::commit();
  13907. } catch (\Throwable $e) {
  13908. Db::rollback();
  13909. $this->error($e->getMessage());
  13910. }
  13911. $this->pickHiddenScydgySetCache = null;
  13912. $msg = $doneOrders > 1
  13913. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回供应商初选,历史下发与操作记录已保留')
  13914. : '已退回供应商初选,请重新选择供应商下发(历史记录已保留)';
  13915. $this->success($msg);
  13916. }
  13917. /**
  13918. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  13919. */
  13920. public function archiveAbandon()
  13921. {
  13922. return $this->auditAbandon();
  13923. }
  13924. /**
  13925. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  13926. */
  13927. public function purchaseApprovalReject()
  13928. {
  13929. if (!$this->request->isPost() || !$this->request->isAjax()) {
  13930. $this->error(__('Invalid parameters'));
  13931. }
  13932. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  13933. $this->error(__('You have no permission'));
  13934. }
  13935. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  13936. $decoded = json_decode($batchRaw, true);
  13937. if (!is_array($decoded) || $decoded === []) {
  13938. $this->error('提交数据无效');
  13939. }
  13940. $done = 0;
  13941. Db::startTrans();
  13942. try {
  13943. foreach ($decoded as $item) {
  13944. if (!is_array($item)) {
  13945. continue;
  13946. }
  13947. $sid = (int)($item['scydgy_id'] ?? 0);
  13948. if (!$this->isValidScydgyRowId($sid)) {
  13949. continue;
  13950. }
  13951. $this->runPurchaseApprovalRejectForSid($sid);
  13952. $done++;
  13953. }
  13954. if ($done < 1) {
  13955. throw new \Exception('所选订单均不在待审批状态');
  13956. }
  13957. Db::commit();
  13958. } catch (\Throwable $e) {
  13959. Db::rollback();
  13960. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  13961. }
  13962. $this->pickHiddenScydgySetCache = null;
  13963. $this->success('已驳回并退回「确认供应商」');
  13964. }
  13965. /**
  13966. * @throws \Exception
  13967. */
  13968. protected function runPurchaseApprovalRejectForSid(int $sid): void
  13969. {
  13970. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  13971. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  13972. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  13973. $allIds = $this->purchaseOrderDetail($sid);
  13974. if ($allIds === []) {
  13975. throw new \Exception('未找到下发明细');
  13976. }
  13977. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  13978. 'wflow_status' => ProcuremenStatus::WFLOW_REJECTED,
  13979. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  13980. 'pick_company_name' => '',
  13981. ]);
  13982. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  13983. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  13984. $poId = 0;
  13985. try {
  13986. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  13987. if (is_array($po)) {
  13988. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  13989. }
  13990. } catch (\Throwable $e) {
  13991. }
  13992. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  13993. }
  13994. /**
  13995. * 审核弹窗(旧入口,POST 已关闭)
  13996. */
  13997. public function review()
  13998. {
  13999. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  14000. $this->error(__('You have no permission'));
  14001. }
  14002. if ($this->request->isPost()) {
  14003. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  14004. }
  14005. $this->view->assign('pickMode', 0);
  14006. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  14007. }
  14008. /**
  14009. * 审核弹窗获取公司列表
  14010. */
  14011. public function reviewCompanies()
  14012. {
  14013. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  14014. $this->error(__('You have no permission'));
  14015. }
  14016. if (!$this->request->isAjax()) {
  14017. $this->error(__('Invalid parameters'));
  14018. }
  14019. $list = [];
  14020. try {
  14021. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  14022. $rows = Db::table('customer')
  14023. ->where(function ($q) {
  14024. $q->where('status', 1)
  14025. ->whereOr('status', '1')
  14026. ->whereOr('status', '')
  14027. ->whereNull('status');
  14028. })
  14029. ->order('id', 'desc')
  14030. ->select();
  14031. } catch (\Throwable $e) {
  14032. $this->success('', '', []);
  14033. return;
  14034. }
  14035. if (!is_array($rows)) {
  14036. $this->success('', '', []);
  14037. return;
  14038. }
  14039. $detailColCandidates = [
  14040. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  14041. 'company_detail', 'company_desc', 'address',
  14042. ];
  14043. foreach ($rows as $row) {
  14044. if (!is_array($row)) {
  14045. continue;
  14046. }
  14047. $norm = [];
  14048. foreach ($row as $k => $v) {
  14049. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  14050. }
  14051. $row = $norm;
  14052. $st = $row['status'] ?? '';
  14053. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  14054. continue;
  14055. }
  14056. $payload = $this->buildCustomerContactPayloadFromRow($row, false);
  14057. if ($payload === null) {
  14058. continue;
  14059. }
  14060. $detail = '';
  14061. foreach ($detailColCandidates as $dk) {
  14062. if (!isset($row[$dk])) {
  14063. continue;
  14064. }
  14065. $dv = trim((string)$row[$dk]);
  14066. if ($dv !== '') {
  14067. $detail = $dv;
  14068. break;
  14069. }
  14070. }
  14071. $payload['detail'] = $detail;
  14072. $list[] = $this->maskSupplierContactFields($payload);
  14073. }
  14074. $this->success('', '', $list);
  14075. }
  14076. /**
  14077. * 采购确认-下发明细弹窗:
  14078. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  14079. */
  14080. public function outward_detail()
  14081. {
  14082. $ids = $this->request->param('ids', $this->request->param('id', ''));
  14083. if (is_array($ids)) {
  14084. $ids = isset($ids[0]) ? $ids[0] : '';
  14085. }
  14086. $ids = trim((string)$ids);
  14087. if ($ids === '') {
  14088. $this->error(__('Invalid parameters'));
  14089. }
  14090. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  14091. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  14092. $wffTab = 'all';
  14093. }
  14094. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  14095. $purchaseOrderId = 0;
  14096. $po = null;
  14097. try {
  14098. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  14099. if (is_array($po)) {
  14100. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  14101. }
  14102. } catch (\Throwable $e) {
  14103. $purchaseOrderId = 0;
  14104. $po = null;
  14105. }
  14106. if (!$isPurchaseConfirm && is_array($po)) {
  14107. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  14108. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  14109. $isPurchaseConfirm = true;
  14110. }
  14111. }
  14112. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  14113. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  14114. $confirmProcessCount = 1;
  14115. $confirmPickGroups = [];
  14116. $processDisplayRows = [];
  14117. $allDetailsBySid = [];
  14118. $requiredSidList = [];
  14119. $sidList = [$ids];
  14120. if ($isPurchaseConfirm) {
  14121. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  14122. if (!$this->canViewProcuremenSupplierQuotesForBundle($confirmBundle)) {
  14123. $this->error('本单尚未开标或指定供应商,不能审批');
  14124. }
  14125. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  14126. if ($mergeRows !== []) {
  14127. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  14128. }
  14129. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  14130. if ($confirmBundle['pos'] !== []) {
  14131. $sidList = [];
  14132. foreach ($confirmBundle['pos'] as $poRow) {
  14133. if (!is_array($poRow)) {
  14134. continue;
  14135. }
  14136. $sid = (int)($poRow['scydgy_id'] ?? 0);
  14137. if (!$this->isValidScydgyRowId($sid)) {
  14138. continue;
  14139. }
  14140. $sidList[] = (string)$sid;
  14141. $requiredSidList[] = $sid;
  14142. }
  14143. }
  14144. if ($sidList === []) {
  14145. $sidList = [$ids];
  14146. $requiredSidList = [(int)$ids];
  14147. }
  14148. $confirmProcessCount = max(1, count($requiredSidList));
  14149. if (is_array($po) && $purchaseOrderId <= 0) {
  14150. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  14151. }
  14152. }
  14153. $rows = [];
  14154. try {
  14155. if (count($sidList) === 1) {
  14156. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  14157. } else {
  14158. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  14159. }
  14160. } catch (\Throwable $e) {
  14161. $rows = [];
  14162. }
  14163. if ($isPurchaseConfirm) {
  14164. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  14165. }
  14166. foreach ($rows as &$r) {
  14167. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  14168. $r['id'] = $r['ID'];
  14169. }
  14170. if (isset($r['createtime'])) {
  14171. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  14172. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  14173. } else {
  14174. $r['createtime_text'] = (string)$r['createtime'];
  14175. }
  14176. } else {
  14177. $r['createtime_text'] = '';
  14178. }
  14179. if (is_array($r)) {
  14180. $r = $this->maskSupplierContactFields($r);
  14181. }
  14182. }
  14183. unset($r);
  14184. $pickedCompanyName = '';
  14185. $manualPicked = 0;
  14186. $manualPickReason = '';
  14187. $quoteVisible = 0;
  14188. $bidOpenVerified = 0;
  14189. if ($isPurchaseConfirm) {
  14190. // 确认包为空时,用当前主单兜底,避免指定说明读不到
  14191. if (($confirmBundle['ccydh'] ?? '') === '' && is_array($po)) {
  14192. $confirmBundle['ccydh'] = trim((string)($po['CCYDH'] ?? ''));
  14193. }
  14194. if (($confirmBundle['pos'] ?? []) === [] && is_array($po)) {
  14195. $confirmBundle['pos'] = [$po];
  14196. }
  14197. $manualPickInfo = $this->resolveProcuremenManualPickInfo($confirmBundle);
  14198. $manualPicked = $this->isProcuremenManualPickedForBundle($confirmBundle) ? 1 : 0;
  14199. $manualPickReason = (string)($manualPickInfo['reason'] ?? '');
  14200. if ($manualPickInfo['company'] !== '') {
  14201. $pickedCompanyName = $manualPickInfo['company'];
  14202. }
  14203. if ($pickedCompanyName === '') {
  14204. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  14205. if (!is_array($poRow)) {
  14206. continue;
  14207. }
  14208. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  14209. if ($pn !== '') {
  14210. $pickedCompanyName = $pn;
  14211. break;
  14212. }
  14213. }
  14214. }
  14215. // 再兜底:直接读当前主单字段
  14216. if (is_array($po) && (int)($po['manual_pick'] ?? 0) === 1) {
  14217. $manualPicked = 1;
  14218. if ($manualPickReason === '') {
  14219. $manualPickReason = trim((string)($po['manual_pick_reason'] ?? ''));
  14220. }
  14221. if ($pickedCompanyName === '') {
  14222. $pickedCompanyName = trim((string)($po['pick_company_name'] ?? ''));
  14223. }
  14224. }
  14225. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle) ? 1 : 0;
  14226. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  14227. }
  14228. $this->view->assign('rows', $rows ?: []);
  14229. $this->view->assign('rowCount', count($rows ?: []));
  14230. $this->view->assign('scydgyId', $ids);
  14231. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  14232. $this->view->assign('headTitle', $headTitle);
  14233. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  14234. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  14235. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  14236. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  14237. $this->view->assign('orderBatchNo', $this->resolveBundleOrderBatchNo($confirmBundle));
  14238. $this->view->assign('processDisplayRows', $processDisplayRows);
  14239. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  14240. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  14241. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  14242. $this->view->assign('manualPicked', $manualPicked);
  14243. $this->view->assign('manualPickReason', $manualPickReason);
  14244. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  14245. $this->view->assign('quoteVisible', $quoteVisible);
  14246. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
  14247. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  14248. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
  14249. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
  14250. $sysRqDisplay = '—';
  14251. if ($isPurchaseConfirm) {
  14252. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  14253. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  14254. );
  14255. }
  14256. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  14257. $this->view->assign('sysRq', $isPurchaseConfirm
  14258. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  14259. : '');
  14260. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  14261. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  14262. : '');
  14263. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  14264. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  14265. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  14266. if ($isPurchaseConfirm) {
  14267. return $this->view->fetch();
  14268. }
  14269. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  14270. $this->view->engine->layout(false);
  14271. try {
  14272. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  14273. $this->view->assign('dialogBody', $bodyHtml);
  14274. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  14275. } finally {
  14276. if ($restoreLayout) {
  14277. $this->view->engine->layout($restoreLayout);
  14278. }
  14279. }
  14280. }
  14281. /**
  14282. * 月度导出记录表(不存在时自动创建)
  14283. */
  14284. protected function ensurePurchaseMonthExportLogTable(): void
  14285. {
  14286. try {
  14287. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  14288. } catch (\Throwable $e) {
  14289. Db::execute(
  14290. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  14291. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  14292. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  14293. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  14294. `admin_name` varchar(64) NOT NULL DEFAULT '',
  14295. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  14296. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  14297. `createtime` int(10) unsigned DEFAULT NULL,
  14298. PRIMARY KEY (`id`),
  14299. KEY `idx_ym` (`ym`),
  14300. KEY `idx_ct` (`createtime`)
  14301. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  14302. );
  14303. }
  14304. }
  14305. /**
  14306. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  14307. *
  14308. * @param array<int, mixed> $dbRows
  14309. * @return array<int, array<string, mixed>>
  14310. */
  14311. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  14312. {
  14313. $keyword = trim((string)$this->request->get('search', ''));
  14314. if ($keyword === '') {
  14315. $keyword = trim((string)$this->request->request('search', ''));
  14316. }
  14317. $filter = $this->request->get('filter', '');
  14318. $op = $this->request->get('op', '');
  14319. if (is_string($filter) && $filter !== '') {
  14320. $filterArr = (array)json_decode($filter, true);
  14321. } else {
  14322. $filterArr = is_array($filter) ? $filter : [];
  14323. }
  14324. if (is_string($op) && $op !== '') {
  14325. $opArr = (array)json_decode($op, true);
  14326. } else {
  14327. $opArr = is_array($op) ? $op : [];
  14328. }
  14329. if ($keyword === '' && $filterArr === []) {
  14330. return array_values(array_filter($dbRows, 'is_array'));
  14331. }
  14332. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  14333. $out = [];
  14334. foreach ($dbRows as $row) {
  14335. if (!is_array($row)) {
  14336. continue;
  14337. }
  14338. if ($keyword !== '') {
  14339. $hit = false;
  14340. foreach ($searchFields as $f) {
  14341. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  14342. $hit = true;
  14343. break;
  14344. }
  14345. }
  14346. if (!$hit) {
  14347. continue;
  14348. }
  14349. }
  14350. $passFilter = true;
  14351. foreach ($filterArr as $field => $val) {
  14352. $field = (string)$field;
  14353. $val = trim((string)$val);
  14354. if ($field === '' || $val === '') {
  14355. continue;
  14356. }
  14357. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  14358. continue;
  14359. }
  14360. $cell = (string)($row[$field] ?? '');
  14361. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  14362. if ($mode === '=' || $mode === 'EQUAL') {
  14363. if (strcasecmp($cell, $val) !== 0) {
  14364. $passFilter = false;
  14365. break;
  14366. }
  14367. } elseif (mb_stripos($cell, $val) === false) {
  14368. $passFilter = false;
  14369. break;
  14370. }
  14371. }
  14372. if (!$passFilter) {
  14373. continue;
  14374. }
  14375. $out[] = $row;
  14376. }
  14377. return $out;
  14378. }
  14379. /**
  14380. * 按月份导出:审批通过订单(与月度列表一致),按审批月份筛选。
  14381. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  14382. */
  14383. public function export_month_outward()
  14384. {
  14385. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  14386. $this->error(__('You have no permission'));
  14387. }
  14388. $bundle = $this->prepareMonthOutwardExportBundle();
  14389. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  14390. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  14391. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  14392. $spreadsheet = new Spreadsheet();
  14393. $sheet = $spreadsheet->getActiveSheet();
  14394. $sheet->setTitle('外协加工明细');
  14395. $mon = (int)substr($ym, 5, 2);
  14396. $sheet->mergeCells('A1:H1');
  14397. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  14398. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  14399. $sheet->getStyle('A1')->getAlignment()
  14400. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  14401. ->setVertical(Alignment::VERTICAL_CENTER);
  14402. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  14403. $col = 'A';
  14404. foreach ($headers as $h) {
  14405. $sheet->setCellValue($col . '2', $h);
  14406. $col++;
  14407. }
  14408. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  14409. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  14410. $rowNum = 3;
  14411. $sumSubtotalCounts = 0;
  14412. $grandAmount = 0.0;
  14413. $globalSeq = 0;
  14414. if ($groups === []) {
  14415. $sheet->mergeCells('A3:H3');
  14416. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  14417. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  14418. $rowNum = 4;
  14419. } else {
  14420. foreach ($groups as $items) {
  14421. if ($items === []) {
  14422. continue;
  14423. }
  14424. $groupLineCount = count($items);
  14425. $subAmount = 0.0;
  14426. foreach ($items as $line) {
  14427. $globalSeq++;
  14428. $dr = $line['detail'];
  14429. $amt = $this->procuremenExportAmount($dr);
  14430. $subAmount += $amt;
  14431. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  14432. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  14433. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  14434. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  14435. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  14436. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  14437. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  14438. $sheet->setCellValue('H' . $rowNum, $amt);
  14439. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  14440. $rowNum++;
  14441. }
  14442. $sumSubtotalCounts += $groupLineCount;
  14443. $grandAmount += $subAmount;
  14444. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  14445. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  14446. $sheet->getStyle('G' . $rowNum)->getAlignment()
  14447. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  14448. ->setVertical(Alignment::VERTICAL_CENTER);
  14449. $rowNum++;
  14450. }
  14451. }
  14452. $sheet->setCellValue('A' . $rowNum, '总计');
  14453. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  14454. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  14455. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  14456. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  14457. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  14458. $lastRow = $rowNum;
  14459. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  14460. 'borders' => [
  14461. 'allBorders' => [
  14462. 'borderStyle' => Border::BORDER_THIN,
  14463. 'color' => ['rgb' => '000000'],
  14464. ],
  14465. ],
  14466. ]);
  14467. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  14468. if ($lastRow >= 3) {
  14469. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14470. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14471. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14472. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14473. }
  14474. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  14475. $sheet->getColumnDimension('A')->setWidth(7);
  14476. $sheet->getColumnDimension('B')->setWidth(16);
  14477. $sheet->getColumnDimension('C')->setWidth(52);
  14478. $sheet->getColumnDimension('D')->setWidth(32);
  14479. $sheet->getColumnDimension('E')->setWidth(12);
  14480. $sheet->getColumnDimension('F')->setWidth(44);
  14481. $sheet->getColumnDimension('G')->setWidth(26);
  14482. $sheet->getColumnDimension('H')->setWidth(13);
  14483. $sheet->getRowDimension(1)->setRowHeight(28);
  14484. $ymCompact = str_replace('-', '', $ym);
  14485. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  14486. $filename = $fileBase . '.xlsx';
  14487. try {
  14488. $this->ensurePurchaseMonthExportLogTable();
  14489. list($adminId, $adminName) = $this->GetUseName();
  14490. Db::table('purchase_month_export_log')->insert([
  14491. 'ym' => $ym,
  14492. 'admin_id' => (int)$adminId,
  14493. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  14494. 'row_count' => count($exportLines),
  14495. 'total_amount' => round($grandAmount, 2),
  14496. 'createtime' => time(),
  14497. ]);
  14498. } catch (\Throwable $e) {
  14499. Log::write('month export log: ' . $e->getMessage(), 'error');
  14500. }
  14501. if (ob_get_length()) {
  14502. ob_end_clean();
  14503. }
  14504. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  14505. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  14506. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  14507. header('Cache-Control: max-age=0');
  14508. $writer = new Xlsx($spreadsheet);
  14509. $writer->save('php://output');
  14510. $spreadsheet->disconnectWorksheets();
  14511. unset($spreadsheet);
  14512. exit;
  14513. }
  14514. /**
  14515. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  14516. */
  14517. public function export_month_quote()
  14518. {
  14519. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  14520. $this->error(__('You have no permission'));
  14521. }
  14522. $bundle = $this->prepareMonthOutwardExportBundle();
  14523. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  14524. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  14525. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  14526. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  14527. $spreadsheet = new Spreadsheet();
  14528. $sheet = $spreadsheet->getActiveSheet();
  14529. $sheet->setTitle('供应商报价明细');
  14530. $mon = (int)substr($ym, 5, 2);
  14531. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  14532. $sheet->getColumnDimension('A')->setWidth(7);
  14533. $sheet->getColumnDimension('B')->setWidth(16);
  14534. $sheet->getColumnDimension('C')->setWidth(52);
  14535. $sheet->getColumnDimension('D')->setWidth(26);
  14536. $sheet->getColumnDimension('E')->setWidth(32);
  14537. $sheet->getColumnDimension('F')->setWidth(12);
  14538. $sheet->getColumnDimension('G')->setWidth(14);
  14539. $sheet->getColumnDimension('H')->setWidth(12);
  14540. if ($quoteLastRow < 1) {
  14541. $quoteLastRow = 3;
  14542. }
  14543. $ymCompact = str_replace('-', '', $ym);
  14544. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  14545. if (ob_get_length()) {
  14546. ob_end_clean();
  14547. }
  14548. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  14549. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  14550. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  14551. header('Cache-Control: max-age=0');
  14552. $writer = new Xlsx($spreadsheet);
  14553. $writer->save('php://output');
  14554. $spreadsheet->disconnectWorksheets();
  14555. unset($spreadsheet);
  14556. exit;
  14557. }
  14558. /**
  14559. * 月度导出公共数据:审批通过订单按月份/搜索筛选后的主表与明细(不要求已完结)
  14560. *
  14561. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  14562. */
  14563. protected function prepareMonthOutwardExportBundle(): array
  14564. {
  14565. $this->request->filter(['strip_tags', 'trim']);
  14566. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  14567. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  14568. $ym = date('Y-m');
  14569. }
  14570. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  14571. $softDel = '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')';
  14572. $dbRows = [];
  14573. try {
  14574. $dbRows = Db::table('purchase_order')
  14575. ->where('wflow_status', 'in', $approvedVals)
  14576. ->whereRaw($softDel)
  14577. ->select();
  14578. } catch (\Throwable $e) {
  14579. $dbRows = [];
  14580. }
  14581. if (!is_array($dbRows)) {
  14582. $dbRows = [];
  14583. }
  14584. $completeTsMap = [];
  14585. $sidList = [];
  14586. foreach ($dbRows as $dbRow) {
  14587. if (!is_array($dbRow)) {
  14588. continue;
  14589. }
  14590. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  14591. if ($sid > 0) {
  14592. $sidList[$sid] = true;
  14593. }
  14594. }
  14595. if ($sidList !== []) {
  14596. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  14597. }
  14598. // 导出按「查看月份」取当月审批通过单;搜索只在当月内再缩小
  14599. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  14600. if (!is_array($dbRow)) {
  14601. return false;
  14602. }
  14603. if (!ProcuremenStatus::isWflowApproved($dbRow['wflow_status'] ?? '')) {
  14604. return false;
  14605. }
  14606. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  14607. if ($done['ts'] <= 0) {
  14608. return false;
  14609. }
  14610. return date('Y-m', $done['ts']) === $ym;
  14611. }));
  14612. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  14613. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  14614. $mainBySid = [];
  14615. foreach ($pool as $rw) {
  14616. if (!is_array($rw)) {
  14617. continue;
  14618. }
  14619. $rid = (int)($rw['ID'] ?? 0);
  14620. if ($rid > 0) {
  14621. $mainBySid[$rid] = $rw;
  14622. }
  14623. }
  14624. if ($mainBySid === []) {
  14625. $detailRows = [];
  14626. } else {
  14627. try {
  14628. $detailRows = Db::table('purchase_order_detail')
  14629. ->where('scydgy_id', 'in', array_keys($mainBySid))
  14630. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  14631. ->order('status', 'desc')
  14632. ->order('CCYDH', 'asc')
  14633. ->order('company_name', 'asc')
  14634. ->order('id', 'asc')
  14635. ->select();
  14636. } catch (\Throwable $e) {
  14637. try {
  14638. $detailRows = Db::table('purchase_order_detail')
  14639. ->where('scydgy_id', 'in', array_keys($mainBySid))
  14640. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  14641. ->order('status', 'desc')
  14642. ->order('CCYDH', 'asc')
  14643. ->order('company_name', 'asc')
  14644. ->order('ID', 'asc')
  14645. ->select();
  14646. } catch (\Throwable $e2) {
  14647. $detailRows = [];
  14648. }
  14649. }
  14650. }
  14651. if (!is_array($detailRows)) {
  14652. $detailRows = [];
  14653. }
  14654. $exportLines = [];
  14655. $detailSidSeen = [];
  14656. foreach ($detailRows as $dr) {
  14657. if (!is_array($dr)) {
  14658. continue;
  14659. }
  14660. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  14661. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  14662. continue;
  14663. }
  14664. if (isset($detailSidSeen[$sid])) {
  14665. continue;
  14666. }
  14667. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  14668. continue;
  14669. }
  14670. $detailSidSeen[$sid] = true;
  14671. $m = $mainBySid[$sid];
  14672. $company = trim((string)($m['pick_company_name'] ?? ''));
  14673. if ($company === '') {
  14674. $company = trim((string)($dr['company_name'] ?? ''));
  14675. }
  14676. $exportLines[] = [
  14677. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  14678. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  14679. 'company_name' => $company,
  14680. 'CDF' => (string)($m['CDF'] ?? ''),
  14681. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  14682. 'gx' => $this->procuremenExportGxText($m),
  14683. 'detail' => $dr,
  14684. ];
  14685. }
  14686. foreach ($detailRows as $dr) {
  14687. if (!is_array($dr)) {
  14688. continue;
  14689. }
  14690. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  14691. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  14692. continue;
  14693. }
  14694. $detailSidSeen[$sid] = true;
  14695. $m = $mainBySid[$sid];
  14696. $company = trim((string)($m['pick_company_name'] ?? ''));
  14697. if ($company === '') {
  14698. $company = trim((string)($dr['company_name'] ?? ''));
  14699. }
  14700. $exportLines[] = [
  14701. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  14702. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  14703. 'company_name' => $company,
  14704. 'CDF' => (string)($m['CDF'] ?? ''),
  14705. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  14706. 'gx' => $this->procuremenExportGxText($m),
  14707. 'detail' => $dr,
  14708. ];
  14709. }
  14710. foreach ($mainBySid as $sid => $m) {
  14711. if (isset($detailSidSeen[$sid])) {
  14712. continue;
  14713. }
  14714. $company = trim((string)($m['pick_company_name'] ?? ''));
  14715. $exportLines[] = [
  14716. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  14717. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  14718. 'company_name' => $company,
  14719. 'CDF' => (string)($m['CDF'] ?? ''),
  14720. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  14721. 'gx' => $this->procuremenExportGxText($m),
  14722. 'detail' => [],
  14723. ];
  14724. }
  14725. $groups = [];
  14726. foreach ($exportLines as $line) {
  14727. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  14728. if (!isset($groups[$k])) {
  14729. $groups[$k] = [];
  14730. }
  14731. $groups[$k][] = $line;
  14732. }
  14733. ksort($groups, SORT_STRING);
  14734. return [
  14735. 'ym' => $ym,
  14736. 'mainBySid' => $mainBySid,
  14737. 'detailRows' => $detailRows,
  14738. 'exportLines' => $exportLines,
  14739. 'groups' => $groups,
  14740. ];
  14741. }
  14742. /**
  14743. * 导出用:工序列文案
  14744. */
  14745. protected function procuremenExportGxText(array $r)
  14746. {
  14747. return ProcuremenFormat::exportGxText($r);
  14748. }
  14749. /**
  14750. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  14751. */
  14752. protected function procuremenExportAmount(array $r)
  14753. {
  14754. return ProcuremenFormat::exportAmount($r);
  14755. }
  14756. /**
  14757. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  14758. *
  14759. * @param array<int, array<string, mixed>> $detailRows
  14760. * @param array<int, array<string, mixed>> $mainBySid
  14761. * @return array<int, array<string, mixed>>
  14762. */
  14763. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  14764. {
  14765. $lines = [];
  14766. foreach ($detailRows as $dr) {
  14767. if (!is_array($dr)) {
  14768. continue;
  14769. }
  14770. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  14771. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  14772. continue;
  14773. }
  14774. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  14775. continue;
  14776. }
  14777. $cn = trim((string)($dr['company_name'] ?? ''));
  14778. if ($cn === '') {
  14779. continue;
  14780. }
  14781. $m = $mainBySid[$sid];
  14782. $am = trim((string)($dr['amount'] ?? ''));
  14783. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  14784. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  14785. $amountText = $amountFilled
  14786. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  14787. : '未填写';
  14788. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  14789. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  14790. if ($deliveryShow === '' && $deliveryRaw !== '') {
  14791. $deliveryShow = $deliveryRaw;
  14792. }
  14793. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  14794. ? $deliveryShow
  14795. : '未填写';
  14796. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  14797. $lines[] = [
  14798. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  14799. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  14800. 'gx' => $this->procuremenExportGxText($m),
  14801. 'company_name' => $cn,
  14802. 'amount_text' => $amountText,
  14803. 'amount_num' => $amountFilled ? $amountNum : null,
  14804. 'delivery_text' => $deliveryText,
  14805. 'picked_text' => $picked ? '中标' : '未中标',
  14806. 'picked' => $picked,
  14807. ];
  14808. }
  14809. $winnerSupplierByOrder = [];
  14810. foreach ($lines as $line) {
  14811. $dh = trim((string)($line['CCYDH'] ?? ''));
  14812. $cn = trim((string)($line['company_name'] ?? ''));
  14813. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  14814. $winnerSupplierByOrder[$dh][$cn] = true;
  14815. }
  14816. }
  14817. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  14818. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  14819. if ($c !== 0) {
  14820. return $c;
  14821. }
  14822. $dh = trim((string)($a['CCYDH'] ?? ''));
  14823. $aCn = trim((string)($a['company_name'] ?? ''));
  14824. $bCn = trim((string)($b['company_name'] ?? ''));
  14825. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  14826. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  14827. if ($aSupplierWin !== $bSupplierWin) {
  14828. return $aSupplierWin ? -1 : 1;
  14829. }
  14830. $c = strcmp($aCn, $bCn);
  14831. if ($c !== 0) {
  14832. return $c;
  14833. }
  14834. if (!empty($a['picked']) !== !empty($b['picked'])) {
  14835. return !empty($a['picked']) ? -1 : 1;
  14836. }
  14837. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  14838. if ($c !== 0) {
  14839. return $c;
  14840. }
  14841. return 0;
  14842. });
  14843. return $lines;
  14844. }
  14845. /**
  14846. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  14847. *
  14848. * @param array<int, array<string, mixed>> $quoteLines
  14849. */
  14850. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  14851. {
  14852. $mon = (int)substr($ym, 5, 2);
  14853. $titleRow = $startRow;
  14854. $headerRow = $startRow + 1;
  14855. $dataStartRow = $startRow + 2;
  14856. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  14857. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  14858. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  14859. $sheet->getStyle('A' . $titleRow)->getAlignment()
  14860. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  14861. ->setVertical(Alignment::VERTICAL_CENTER);
  14862. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  14863. $col = 'A';
  14864. foreach ($headers as $h) {
  14865. $sheet->setCellValue($col . $headerRow, $h);
  14866. $col++;
  14867. }
  14868. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  14869. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  14870. $rowNum = $dataStartRow;
  14871. if ($quoteLines === []) {
  14872. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  14873. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  14874. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  14875. $rowNum = $dataStartRow + 1;
  14876. } else {
  14877. $i = 0;
  14878. foreach ($quoteLines as $line) {
  14879. $i++;
  14880. $sheet->setCellValue('A' . $rowNum, $i);
  14881. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  14882. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  14883. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  14884. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  14885. if ($line['amount_num'] !== null) {
  14886. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  14887. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  14888. } else {
  14889. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  14890. }
  14891. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  14892. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  14893. if (!empty($line['picked'])) {
  14894. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  14895. }
  14896. $rowNum++;
  14897. }
  14898. }
  14899. $lastRow = $rowNum - 1;
  14900. if ($lastRow >= $headerRow) {
  14901. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  14902. 'borders' => [
  14903. 'allBorders' => [
  14904. 'borderStyle' => Border::BORDER_THIN,
  14905. 'color' => ['rgb' => '000000'],
  14906. ],
  14907. ],
  14908. ]);
  14909. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  14910. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14911. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14912. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  14913. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  14914. if ($lastRow >= $dataStartRow) {
  14915. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  14916. }
  14917. }
  14918. return $lastRow;
  14919. }
  14920. /**
  14921. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  14922. */
  14923. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  14924. {
  14925. if ($lastRow < $dataStartRow || $headerRow < 1) {
  14926. return;
  14927. }
  14928. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  14929. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  14930. ->setVertical(Alignment::VERTICAL_CENTER);
  14931. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  14932. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  14933. ->setVertical(Alignment::VERTICAL_CENTER);
  14934. if ($lastCol > 'B') {
  14935. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  14936. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  14937. ->setVertical(Alignment::VERTICAL_CENTER);
  14938. }
  14939. }
  14940. /**
  14941. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  14942. */
  14943. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  14944. {
  14945. return ProcuremenFormat::sanitizePdfOrderKey($ccydh);
  14946. }
  14947. /**
  14948. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  14949. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  14950. *
  14951. * @return array{objectKey: string, webPath: string}
  14952. */
  14953. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  14954. {
  14955. return ProcuremenFormat::buildConfirmPdfPaths($scydgyId, $ccydhRaw);
  14956. }
  14957. /**
  14958. * 采购确认成功后 / 已完结刷新:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  14959. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  14960. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  14961. * 说明:审批通过时会先存一版;质量+交货评分使订单「已完结」后,详情页打开或评分保存完成时会再重存,以含最终步骤与操作记录。
  14962. *
  14963. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  14964. */
  14965. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  14966. {
  14967. if (!$this->isValidScydgyRowId($scydgyId)) {
  14968. return '';
  14969. }
  14970. $ids = trim((string)$scydgyId);
  14971. $prep = $this->prepareProcuremenDetailsView($ids);
  14972. if (!$prep['ok']) {
  14973. return '';
  14974. }
  14975. $ccydh = $prep['ccydh'];
  14976. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  14977. $objectKey = $paths['objectKey'];
  14978. $webPath = $paths['webPath'];
  14979. $cyjmc = '';
  14980. try {
  14981. $poMeta = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->field('CYJMC')->find();
  14982. if (is_array($poMeta)) {
  14983. $cyjmc = trim((string)($poMeta['CYJMC'] ?? ''));
  14984. }
  14985. } catch (\Throwable $e) {
  14986. $cyjmc = '';
  14987. }
  14988. $genTime = date('Y-m-d H:i:s');
  14989. $metaIds = '工序行ID ' . $ids . ' | 主表订单ID ' . (int)$purchaseOrderId;
  14990. $metaLeft = $metaIds . ($cyjmc !== '' ? ' | ' . $cyjmc : '');
  14991. // PDF 进度:去掉「未发」;节点用纯色圆点(不用图片,避免 mPDF 破图)
  14992. $pdfSteps = [];
  14993. $viewSteps = $prep['steps'] ?? [];
  14994. if (is_array($viewSteps)) {
  14995. foreach ($viewSteps as $st) {
  14996. if (!is_array($st)) {
  14997. continue;
  14998. }
  14999. if (trim((string)($st['title'] ?? '')) === '未发') {
  15000. continue;
  15001. }
  15002. $pdfSteps[] = $st;
  15003. }
  15004. }
  15005. $pdfStepW = count($pdfSteps) > 0 ? (round(100 / count($pdfSteps), 2) . '%') : '16.66%';
  15006. $nPdf = count($pdfSteps);
  15007. foreach ($pdfSteps as $idx => &$pst) {
  15008. if ($idx === 0) {
  15009. $pst['pdf_left_bg'] = '';
  15010. } else {
  15011. $pst['pdf_left_bg'] = !empty($pdfSteps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  15012. }
  15013. if ($idx >= $nPdf - 1) {
  15014. $pst['pdf_right_bg'] = '';
  15015. } else {
  15016. $pst['pdf_right_bg'] = !empty($pst['done']) ? '#1890ff' : '#e0e0e0';
  15017. }
  15018. }
  15019. unset($pst);
  15020. $this->view->assign([
  15021. 'pdf_export' => 1,
  15022. 'pdfMetaLine' => $metaLeft,
  15023. 'pdfMetaLeft' => $metaLeft,
  15024. 'pdfMetaIds' => $metaIds,
  15025. 'pdfMetaTitle' => $cyjmc,
  15026. 'pdfMetaTime' => 'PDF生成时间 ' . $genTime,
  15027. 'pdfSteps' => $pdfSteps,
  15028. 'pdfStepWidth' => $pdfStepW,
  15029. ]);
  15030. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  15031. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  15032. $this->view->engine->layout(false);
  15033. try {
  15034. $html = $this->view->fetch('procuremen/details_pdf_shell');
  15035. } catch (\Throwable $e) {
  15036. if ($restoreLayout) {
  15037. $this->view->engine->layout($restoreLayout);
  15038. }
  15039. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  15040. $this->view->assign([
  15041. 'pdf_export' => '', 'pdfMetaLine' => '', 'pdfMetaLeft' => '',
  15042. 'pdfMetaIds' => '', 'pdfMetaTitle' => '', 'pdfMetaTime' => '',
  15043. 'pdfSteps' => [], 'pdfStepWidth' => '',
  15044. ]);
  15045. return '';
  15046. }
  15047. if ($restoreLayout) {
  15048. $this->view->engine->layout($restoreLayout);
  15049. }
  15050. $this->view->assign([
  15051. 'pdf_export' => '', 'pdfMetaLine' => '', 'pdfMetaLeft' => '',
  15052. 'pdfMetaIds' => '', 'pdfMetaTitle' => '', 'pdfMetaTime' => '',
  15053. 'pdfSteps' => [], 'pdfStepWidth' => '',
  15054. ]);
  15055. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  15056. if (!is_dir($tempDir)) {
  15057. @mkdir($tempDir, 0755, true);
  15058. }
  15059. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  15060. try {
  15061. $mpdf = new \Mpdf\Mpdf([
  15062. 'mode' => 'utf-8',
  15063. 'format' => 'A4',
  15064. 'margin_left' => 12,
  15065. 'margin_right' => 12,
  15066. 'margin_top' => 14,
  15067. 'margin_bottom' => 14,
  15068. 'tempDir' => $tempDir,
  15069. 'autoScriptToLang' => true,
  15070. 'autoLangToFont' => true,
  15071. ]);
  15072. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  15073. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  15074. $mpdf->SetBasePath('http://127.0.0.1/');
  15075. $mpdf->WriteHTML($html);
  15076. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  15077. } catch (\Throwable $e) {
  15078. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  15079. if (is_file($tempPdf)) {
  15080. @unlink($tempPdf);
  15081. }
  15082. return '';
  15083. }
  15084. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  15085. if ($ossUrl !== '') {
  15086. @unlink($tempPdf);
  15087. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  15088. return $ossUrl;
  15089. }
  15090. $pi = pathinfo($objectKey);
  15091. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  15092. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  15093. if ($baseFile === '') {
  15094. @unlink($tempPdf);
  15095. return '';
  15096. }
  15097. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  15098. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  15099. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  15100. @unlink($tempPdf);
  15101. return '';
  15102. }
  15103. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  15104. if (!@copy($tempPdf, $fullPath)) {
  15105. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  15106. @unlink($tempPdf);
  15107. return '';
  15108. }
  15109. @unlink($tempPdf);
  15110. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  15111. return $webPath;
  15112. }
  15113. /**
  15114. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  15115. */
  15116. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  15117. {
  15118. if ($scydgyId <= 0 || $webPath === '') {
  15119. return;
  15120. }
  15121. try {
  15122. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  15123. } catch (\Throwable $e) {
  15124. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  15125. }
  15126. }
  15127. /**
  15128. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  15129. *
  15130. * @param array<string, string> $vars
  15131. * @return array<string, string>
  15132. */
  15133. protected function normalizeSmsTemplateVars(array $vars): array
  15134. {
  15135. return ProcuremenFormat::normalizeSmsTemplateVars($vars);
  15136. }
  15137. /**
  15138. * 按手机号或公司名称查 customer 表联系人姓名
  15139. */
  15140. protected function resolveCustomerContactName(string $phone, string $companyName): string
  15141. {
  15142. $phone = trim($phone);
  15143. $companyName = trim($companyName);
  15144. try {
  15145. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  15146. $row = Db::table('customer')
  15147. ->where(function ($q) use ($phone) {
  15148. $q->where('phone', $phone)->whereOr('account', $phone);
  15149. })
  15150. ->order('id', 'asc')
  15151. ->find();
  15152. if (is_array($row)) {
  15153. $nm = trim((string)($row['username'] ?? ''));
  15154. if ($nm !== '') {
  15155. return $nm;
  15156. }
  15157. }
  15158. }
  15159. if ($companyName !== '') {
  15160. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  15161. if (is_array($row)) {
  15162. return trim((string)($row['username'] ?? ''));
  15163. }
  15164. }
  15165. } catch (\Throwable $e) {
  15166. }
  15167. return '';
  15168. }
  15169. /**
  15170. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;;http(s) 链接做成可点的 &lt;a&gt;(微信 QQ 邮箱提醒纯文本 URL 常不可点)
  15171. */
  15172. protected function plainTextToHtmlEmailBody(string $text): string
  15173. {
  15174. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  15175. $parts = explode("\n", $text);
  15176. $out = [];
  15177. foreach ($parts as $line) {
  15178. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  15179. $out[] = $line;
  15180. } else {
  15181. $esc = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  15182. // 保留工序行空格,便于「单位/工作量」列对齐
  15183. $esc = str_replace(' ', '&nbsp;', $esc);
  15184. $esc = preg_replace(
  15185. '#(https?://[^\s<>"\']+)#iu',
  15186. '<a href="$1" style="color:#1565c0;text-decoration:underline;word-break:break-all;">$1</a>',
  15187. $esc
  15188. );
  15189. $out[] = $esc;
  15190. }
  15191. }
  15192. return implode("<br>\n", $out);
  15193. }
  15194. /**
  15195. * 短信场景:去掉链接类变量,避免误填 URL
  15196. *
  15197. * @param array<string, string> $vars
  15198. * @return array<string, string>
  15199. */
  15200. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  15201. {
  15202. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  15203. return $vars;
  15204. }
  15205. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  15206. $vars[$k] = '';
  15207. }
  15208. return $vars;
  15209. }
  15210. /**
  15211. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  15212. *
  15213. * @param array<string, string> $vars
  15214. */
  15215. protected function renderNotifyTemplate(string $scene, array $vars): string
  15216. {
  15217. $vars = $this->normalizeSmsTemplateVars($vars);
  15218. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  15219. $row = $this->loadNotifyTemplateRow($scene);
  15220. if ($row === null) {
  15221. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  15222. }
  15223. $tpl = trim((string)($row['content'] ?? ''));
  15224. if ($tpl === '') {
  15225. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  15226. }
  15227. foreach ($vars as $k => $v) {
  15228. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  15229. }
  15230. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  15231. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  15232. return $tpl;
  15233. }
  15234. protected function resolveProcuremenEmailSubject(string $scene): string
  15235. {
  15236. // 采购确认结果邮箱:title 仅作说明,邮件主题用固定文案(不用 title)
  15237. if (in_array($scene, ['confirm_ok_email', 'confirm_fail_email'], true)) {
  15238. $this->ensureConfirmResultEmailTemplates();
  15239. $fallback = [
  15240. 'confirm_ok_email' => '采购确认结果:已通过',
  15241. 'confirm_fail_email' => '采购确认结果:未通过',
  15242. ];
  15243. return $fallback[$scene] ?? '协助采购通知';
  15244. }
  15245. // 询价 / 交货确认邮箱:沿用模版 title 作邮件主题(与历史配置一致)
  15246. if (in_array($scene, ['rfq_salesman_email', 'rfq_supplier_email', 'delivery_notify_email'], true)) {
  15247. $row = $this->loadNotifyTemplateRow($scene);
  15248. $title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
  15249. if ($title !== '') {
  15250. return $title;
  15251. }
  15252. $fallback = [
  15253. 'rfq_supplier_email' => '供应商询价通知',
  15254. 'rfq_salesman_email' => '协助采购询价通知',
  15255. 'delivery_notify_email' => '交货情况确认通知',
  15256. ];
  15257. return $fallback[$scene] ?? '协助采购通知';
  15258. }
  15259. $map = [
  15260. 'review_email' => '您有新的协助加工订单',
  15261. ];
  15262. $subject = trim((string)($map[$scene] ?? ''));
  15263. if ($subject === '') {
  15264. $this->error('未配置邮件主题:' . $scene);
  15265. }
  15266. return $subject;
  15267. }
  15268. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  15269. {
  15270. $map = [
  15271. 'review_email' => '协助下发-邮箱',
  15272. 'review_sms' => '协助下发-短信',
  15273. 'confirm_ok' => '采购确认-通过',
  15274. 'confirm_fail' => '采购确认-未通过',
  15275. 'confirm_ok_email' => '采购确认通过-邮箱',
  15276. 'confirm_fail_email' => '采购确认未通过-邮箱',
  15277. 'bid_open' => '开标双重验证',
  15278. 'rfq_salesman_email' => '询价通知业务员-邮箱',
  15279. 'rfq_supplier_email' => '供应商询价通知',
  15280. 'delivery_notify_email'=> '交货情况通知生产部-邮箱',
  15281. ];
  15282. $label = $map[$scene] ?? $scene;
  15283. if ($titleRequired) {
  15284. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  15285. }
  15286. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  15287. }
  15288. /**
  15289. * 是否开启协助通知演练(不发真实短信/邮件)
  15290. */
  15291. protected function isProcuremenNotifyDryRun(): bool
  15292. {
  15293. return (bool)Config::get('procuremen_notify_dry_run');
  15294. }
  15295. /**
  15296. * @param array<string, mixed> $payload
  15297. */
  15298. protected function recordNotifyDryRunPreview(array $payload): void
  15299. {
  15300. $this->notifyDryRunPreview[] = $payload;
  15301. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  15302. }
  15303. /**
  15304. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  15305. * @throws \Exception
  15306. */
  15307. protected function smsbao($phone, $content)
  15308. {
  15309. if ($this->isProcuremenNotifyDryRun()) {
  15310. $this->recordNotifyDryRunPreview([
  15311. 'scene' => 'sms_only',
  15312. 'phone' => $phone,
  15313. 'sms_content' => $content,
  15314. ]);
  15315. return;
  15316. }
  15317. $statusStr = [
  15318. '0' => '短信发送成功',
  15319. '-1' => '参数不全',
  15320. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  15321. '30' => '密码错误',
  15322. '40' => '账号不存在',
  15323. '41' => '余额不足',
  15324. '42' => '帐户已过期',
  15325. '43' => 'IP地址限制',
  15326. '50' => '内容含有敏感词',
  15327. ];
  15328. $smsapi = 'http://api.smsbao.com/';
  15329. $user = 'zhuwei123';
  15330. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  15331. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  15332. $result = @file_get_contents($sendurl);
  15333. if ($result === false) {
  15334. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  15335. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  15336. }
  15337. $result = trim((string)$result);
  15338. if ($result !== '0') {
  15339. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  15340. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  15341. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  15342. }
  15343. }
  15344. }