Procuremen.php 533 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenGuard;
  6. use app\common\library\ProcuremenOperLog;
  7. use app\common\library\ProcuremenSchema;
  8. use app\common\library\ProcuremenStatus;
  9. use app\common\library\ProcuremenSupplierScore;
  10. use app\common\library\ProcuremenTime;
  11. use PHPMailer\PHPMailer\PHPMailer;
  12. use think\Config;
  13. use think\Cache;
  14. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  15. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  16. use PhpOffice\PhpSpreadsheet\Style\Border;
  17. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  18. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  19. use think\Db;
  20. use think\Log;
  21. class Procuremen extends Backend
  22. {
  23. /**
  24. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  25. */
  26. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,b.czlyq,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  27. /**
  28. * Procuremen模型对象
  29. * @var \app\admin\model\Procuremen
  30. */
  31. protected $model = null;
  32. /**
  33. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  34. */
  35. protected $notifyDryRunPreview = [];
  36. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  37. protected $procuremenRedisCache = null;
  38. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  39. protected $pickHiddenScydgySetCache = null;
  40. /** 邮件发送日志表结构已就绪缓存键 */
  41. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  42. /**
  43. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  44. * @var array
  45. */
  46. protected $noNeedRight = [
  47. 'pickreview', 'review', 'reviewcompanies',
  48. // 方法内用 hasProcuremenPerm 校验(兼容 auditsubmit / auditissue)
  49. 'auditmanualpick',
  50. // 与 rfqlist 同权,方法内校验
  51. 'rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqissuesuppliers', 'rfqissue', 'rfqissuesendmail', 'rfqquotes',
  52. 'rfqappendsuppliers', 'rfqsupplieroptions', 'rfqsalesmanoptions', 'rfqappendsalesmen',
  53. ];
  54. public function _initialize()
  55. {
  56. parent::_initialize();
  57. $this->model = new \app\admin\model\Procuremen;
  58. $this->maybeMigrateLegacyWflowStatusText();
  59. $this->assignProcuremenAuthConfig();
  60. try {
  61. ProcuremenSchema::ensureAll();
  62. } catch (\Throwable $e) {
  63. }
  64. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  65. $this->ensurePurchaseEmailSendLogTableOnce();
  66. }
  67. }
  68. /**
  69. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  70. */
  71. protected function maybeMigrateLegacyWflowStatusText(): void
  72. {
  73. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  74. if (is_file($flagFile)) {
  75. return;
  76. }
  77. $map = [
  78. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  79. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  80. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  81. '3' => ProcuremenStatus::WFLOW_APPROVED,
  82. ];
  83. try {
  84. foreach ($map as $num => $text) {
  85. Db::table('purchase_order')
  86. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  87. ->update(['wflow_status' => $text]);
  88. }
  89. @file_put_contents($flagFile, date('c'));
  90. } catch (\Throwable $e) {
  91. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  92. }
  93. }
  94. /**
  95. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  96. *
  97. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  98. */
  99. protected function hasProcuremenPerm(array $actions): bool
  100. {
  101. foreach ($actions as $action) {
  102. $action = strtolower(trim((string)$action));
  103. if ($action === '') {
  104. continue;
  105. }
  106. if (strpos($action, 'procuremen/') !== 0) {
  107. $action = 'procuremen/' . $action;
  108. }
  109. if ($this->auth->check($action)) {
  110. return true;
  111. }
  112. }
  113. $suffixes = [];
  114. foreach ($actions as $action) {
  115. $action = strtolower(trim((string)$action));
  116. $action = preg_replace('#^procuremen/#', '', $action);
  117. if ($action !== '') {
  118. $suffixes[$action] = true;
  119. }
  120. }
  121. if ($suffixes === []) {
  122. return false;
  123. }
  124. try {
  125. foreach ($this->auth->getRuleList() as $rule) {
  126. $rule = strtolower((string)$rule);
  127. if (strpos($rule, 'procuremen/') !== 0) {
  128. continue;
  129. }
  130. foreach (array_keys($suffixes) as $suffix) {
  131. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  132. return true;
  133. }
  134. }
  135. }
  136. } catch (\Throwable $e) {
  137. }
  138. return false;
  139. }
  140. /**
  141. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  142. *
  143. * @param string[] $actions
  144. */
  145. protected function hasProcuremenPermStrict(array $actions): bool
  146. {
  147. foreach ($actions as $action) {
  148. $action = strtolower(trim((string)$action));
  149. if ($action === '') {
  150. continue;
  151. }
  152. if (strpos($action, 'procuremen/') !== 0) {
  153. $action = 'procuremen/' . $action;
  154. }
  155. if ($this->auth->check($action)) {
  156. return true;
  157. }
  158. }
  159. return false;
  160. }
  161. /**
  162. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  163. *
  164. * @param string[] $titles
  165. */
  166. protected function authHasAssignedRuleTitle(array $titles): bool
  167. {
  168. $titles = array_values(array_filter(array_map('trim', $titles)));
  169. if ($titles === []) {
  170. return false;
  171. }
  172. try {
  173. $ids = $this->auth->getRuleIds();
  174. if (in_array('*', $ids, true)) {
  175. return true;
  176. }
  177. if ($ids === []) {
  178. return false;
  179. }
  180. $rows = Db::name('auth_rule')
  181. ->where('status', 'normal')
  182. ->whereIn('id', $ids)
  183. ->column('title');
  184. foreach ($rows as $title) {
  185. $t = trim((string)$title);
  186. if ($t !== '' && in_array($t, $titles, true)) {
  187. return true;
  188. }
  189. }
  190. } catch (\Throwable $e) {
  191. }
  192. return false;
  193. }
  194. protected function procuremenCanPickDelete(): bool
  195. {
  196. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  197. return true;
  198. }
  199. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  200. }
  201. protected function procuremenCanComplete(): bool
  202. {
  203. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  204. return true;
  205. }
  206. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  207. }
  208. protected function procuremenCanDispatch(): bool
  209. {
  210. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  211. }
  212. /**
  213. * 前端按钮显隐(Config.procuremenAuth)
  214. */
  215. protected function assignProcuremenAuthConfig(): void
  216. {
  217. $authMap = [
  218. 'pickreview' => $this->procuremenCanDispatch(),
  219. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  220. 'pickdelete' => $this->procuremenCanPickDelete(),
  221. 'completedirectly' => $this->procuremenCanComplete(),
  222. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  223. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  224. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  225. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  226. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  227. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  228. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  229. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  230. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  231. 'details' => $this->hasProcuremenPerm(['details']),
  232. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  233. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  234. 'export_month_quote' => $this->hasProcuremenPerm(['export_month_quote', 'exportMonthQuote', 'export_month_outward', 'exportMonthOutward']),
  235. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  236. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  237. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  238. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  239. 'auditmanualpick' => $this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue']),
  240. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  241. 'add' => $this->hasProcuremenPerm(['add']),
  242. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  243. // 查询询价三个操作按钮:各自独立,不再因有 rfqlist 就全部放开
  244. 'rfqissue' => $this->hasProcuremenPerm(['rfqissue']),
  245. 'rfqquotes' => $this->hasProcuremenPerm(['rfqquotes']),
  246. 'rfqnotifysalesman' => $this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen']),
  247. 'rfqnotifysalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman']),
  248. // 询价附属接口:有「询价」按钮权限即可(无需再单独勾选)
  249. 'rfqissuesuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers']),
  250. 'rfqissuesendmail' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail']),
  251. 'rfqappendsuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers']),
  252. 'rfqsupplieroptions' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions']),
  253. 'rfqsalesmanoptions' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen']),
  254. 'rfqappendsalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen']),
  255. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  256. ];
  257. $this->assignconfig('procuremenAuth', $authMap);
  258. }
  259. /**
  260. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  261. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  262. * 列表 Tab 写入 hash(mproc_tab),避免邮件客户端拆坏多 query 参数;浏览器端再补全 tab=
  263. *
  264. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  265. * @param string $listTab rfq|draft|submitted|done|rfq_submitted,空则仅靠服务端按状态推断
  266. */
  267. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId, $listTab = '')
  268. {
  269. static $mprocCfgLoaded = false;
  270. if (!$mprocCfgLoaded) {
  271. $mprocCfgLoaded = true;
  272. if (is_file(APP_PATH . 'extra/mproc.php')) {
  273. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  274. }
  275. }
  276. $eid = (int)$purchaseOrderDetailId;
  277. $base = $this->resolveMprocMobilePublicBaseUrl();
  278. if ($base === '') {
  279. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  280. }
  281. $path = trim((string)Config::get('mproc.mobile_index_path'));
  282. if ($path === '') {
  283. $path = '/index.php/index/index/index';
  284. } else {
  285. $path = '/' . ltrim($path, '/');
  286. }
  287. $tab = trim((string)$listTab);
  288. if (!in_array($tab, ['rfq', 'rfq_submitted', 'draft', 'submitted', 'done'], true)) {
  289. $tab = '';
  290. }
  291. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份 Tab
  292. if ($eid > 0) {
  293. $hash = 'mproc_fe=' . $eid;
  294. if ($tab !== '') {
  295. $hash .= '&mproc_tab=' . $tab;
  296. }
  297. return $base . $path . '?focus_eid=' . $eid . '#' . $hash;
  298. }
  299. return $base . $path . '?main_tab=orders' . ($tab !== '' ? ('&tab=' . $tab) : '');
  300. }
  301. /**
  302. * 业务员手机端「订单询价」直达链接(默认待询价)
  303. *
  304. * @param int $scydgyId 手工询价 scydgy_id(负数)
  305. * @param string $status pending|quoted
  306. */
  307. protected function buildMprocMobileRfqAddUrl($scydgyId = 0, $status = 'pending')
  308. {
  309. static $mprocCfgLoaded = false;
  310. if (!$mprocCfgLoaded) {
  311. $mprocCfgLoaded = true;
  312. if (is_file(APP_PATH . 'extra/mproc.php')) {
  313. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  314. }
  315. }
  316. $base = $this->resolveMprocMobilePublicBaseUrl();
  317. if ($base === '') {
  318. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  319. }
  320. $indexPath = trim((string)Config::get('mproc.mobile_index_path'));
  321. if ($indexPath === '') {
  322. $indexPath = '/index.php/index/index/index';
  323. } else {
  324. $indexPath = '/' . ltrim($indexPath, '/');
  325. }
  326. $path = preg_replace('#/index$#', '/rfqadd', rtrim($indexPath, '/'));
  327. if ($path === null || $path === '' || substr($path, -6) === '/index') {
  328. $path = '/index.php/index/index/rfqadd';
  329. }
  330. $status = trim((string)$status) === 'quoted' ? 'quoted' : 'pending';
  331. $sid = (int)$scydgyId;
  332. $q = 'status=' . $status;
  333. $hash = '';
  334. if ($sid < 0) {
  335. $q .= '&focus_sid=' . $sid;
  336. $hash = '#mproc_fs=' . $sid;
  337. }
  338. return $base . $path . '?' . $q . $hash;
  339. }
  340. /**
  341. * 邮件/短信外链:须为带点的公网域名
  342. */
  343. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  344. {
  345. $u = trim((string)$baseUrl);
  346. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  347. return false;
  348. }
  349. $host = parse_url($u, PHP_URL_HOST);
  350. if (!is_string($host) || $host === '') {
  351. return false;
  352. }
  353. if (strcasecmp($host, 'localhost') === 0) {
  354. return false;
  355. }
  356. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  357. return false;
  358. }
  359. if (strpos($host, '.') === false) {
  360. return false;
  361. }
  362. return true;
  363. }
  364. /**
  365. * 解析用于协助邮件/短信的手机端站点根
  366. */
  367. protected function resolveMprocMobilePublicBaseUrl()
  368. {
  369. $candidates = [];
  370. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  371. $candidates[] = trim((string)Config::get('site.indexurl'));
  372. $cdn = trim((string)Config::get('site.cdnurl'));
  373. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  374. $candidates[] = rtrim($cdn, '/');
  375. }
  376. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  377. $candidates[] = $reqBase;
  378. foreach ($candidates as $c) {
  379. if ($c === '') {
  380. continue;
  381. }
  382. $c = rtrim($c, '/');
  383. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  384. return $c;
  385. }
  386. }
  387. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  388. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  389. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  390. return $reqBase;
  391. }
  392. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  393. return '';
  394. }
  395. /**
  396. * 获取 Redis 中 procuremen_redis
  397. */
  398. protected function ProcuremenRedis(): array
  399. {
  400. if ($this->procuremenRedisCache !== null) {
  401. return $this->procuremenRedisCache;
  402. }
  403. try {
  404. $redis = redis();
  405. $raw = $redis->get('procuremen_redis');
  406. if ($raw === false || $raw === '') {
  407. $this->procuremenRedisCache = [];
  408. return $this->procuremenRedisCache;
  409. }
  410. $decoded = json_decode($raw, true);
  411. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  412. $this->procuremenRedisCache = [];
  413. return $this->procuremenRedisCache;
  414. }
  415. $this->procuremenRedisCache = $decoded['data'];
  416. // 整包已解码时顺带补齐侧栏小键,避免下次首屏再扫库
  417. if ($this->loadProcuremenSidebarYmList() === []) {
  418. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($this->procuremenRedisCache));
  419. }
  420. return $this->procuremenRedisCache;
  421. } catch (\Throwable $e) {
  422. $this->procuremenRedisCache = [];
  423. return $this->procuremenRedisCache;
  424. }
  425. }
  426. /**
  427. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  428. *
  429. * @return array<int, array<string, mixed>>
  430. */
  431. protected function procuremenFetchErpPoolFromDb(): array
  432. {
  433. try {
  434. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  435. $endTime = date('Y-m-d 23:59:59');
  436. $list = Db::table('scydgy')
  437. ->alias('a')
  438. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  439. ->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')
  440. ->where([
  441. 'a.bwjg' => 1,
  442. 'a.iEndBz' => 0,
  443. 'a.iType' => 0,
  444. 'a.iStatus' => 10,
  445. ])
  446. ->where('a.dStamp', '>=', $startTime)
  447. ->where('a.dStamp', '<=', $endTime)
  448. ->order('a.dStamp', 'desc')
  449. ->select();
  450. if (!is_array($list)) {
  451. return [];
  452. }
  453. try {
  454. $redis = redis();
  455. $payload = [
  456. 'code' => 200,
  457. 'msg' => 'success',
  458. 'data' => $list,
  459. ];
  460. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  461. $this->procuremenRedisCache = $list;
  462. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($list));
  463. $this->clearPickMonthPoolCaches();
  464. $this->warmPickMonthPoolCachesFromPool($list);
  465. } catch (\Throwable $e) {
  466. }
  467. return $list;
  468. } catch (\Throwable $e) {
  469. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  470. return [];
  471. }
  472. }
  473. /**
  474. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  475. *
  476. * @return array<int, array<string, mixed>>
  477. */
  478. protected function procuremenEnsureRedisPool(): array
  479. {
  480. $pool = $this->ProcuremenRedis();
  481. if (is_array($pool) && $pool !== []) {
  482. return $pool;
  483. }
  484. static $warmed = false;
  485. if ($warmed) {
  486. return is_array($pool) ? $pool : [];
  487. }
  488. $warmed = true;
  489. return $this->procuremenFetchErpPoolFromDb();
  490. }
  491. /**
  492. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  493. *
  494. * @param array<string, mixed> $row
  495. */
  496. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  497. {
  498. $t = $this->procuremenRowListSortTime($row, $primary);
  499. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  500. return null;
  501. }
  502. $mo = (int)$m[2];
  503. if ($mo < 1 || $mo > 12) {
  504. return null;
  505. }
  506. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  507. }
  508. /**
  509. * @param array<int, array{year:string, months:array}> $sidebar
  510. * @return array<int, array{year:string, months:array}>
  511. */
  512. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  513. {
  514. $ym = trim($ym);
  515. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  516. return $sidebar;
  517. }
  518. foreach ($sidebar as $block) {
  519. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  520. continue;
  521. }
  522. foreach ($block['months'] as $item) {
  523. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  524. return $sidebar;
  525. }
  526. }
  527. }
  528. $y = substr($ym, 0, 4);
  529. $mo = (int)substr($ym, 5, 2);
  530. $sidebar[] = [
  531. 'year' => $y,
  532. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  533. ];
  534. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  535. }
  536. /**
  537. * @param array<int, array{year:string, months:array}> $sidebar
  538. * @return string[]
  539. */
  540. protected function flattenProcuremenSidebarYms(array $sidebar): array
  541. {
  542. $yms = [];
  543. foreach ($sidebar as $block) {
  544. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  545. continue;
  546. }
  547. foreach ($block['months'] as $item) {
  548. if (!is_array($item)) {
  549. continue;
  550. }
  551. $ym = trim((string)($item['ym'] ?? ''));
  552. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  553. $yms[$ym] = true;
  554. }
  555. }
  556. }
  557. return array_keys($yms);
  558. }
  559. /**
  560. * 左侧菜单(协助初选)
  561. * 优先 Redis 月份小键;为空时用轻量 DISTINCT 查库补齐(避免只显示空当月、漏掉有数据的月份)。
  562. */
  563. protected function GetIndexYearMonths()
  564. {
  565. $ymList = $this->ensureProcuremenPickSidebarYmList();
  566. if ($ymList === []) {
  567. $def = date('Y-m');
  568. $ymList = [preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m')];
  569. }
  570. return $this->buildYearMonthSidebar($ymList);
  571. }
  572. /**
  573. * 初选侧栏月份:以轻量 DISTINCT 查库为准(有数据才显示),并写回 Redis 小键。
  574. *
  575. * @return string[]
  576. */
  577. protected function ensureProcuremenPickSidebarYmList(bool $forceRefresh = false): array
  578. {
  579. static $memo = null;
  580. if (!$forceRefresh && is_array($memo)) {
  581. return $memo;
  582. }
  583. $fromDb = $this->queryProcuremenPickSidebarYmListLight();
  584. if ($fromDb !== []) {
  585. $this->saveProcuremenSidebarYmList($fromDb);
  586. $memo = $fromDb;
  587. return $memo;
  588. }
  589. // 库侧暂无初选数据时,再回退 Redis / 当月,避免侧栏空白
  590. $cached = $this->loadProcuremenSidebarYmList();
  591. if ($cached !== []) {
  592. $memo = $cached;
  593. return $memo;
  594. }
  595. $memo = [date('Y-m')];
  596. return $memo;
  597. }
  598. /**
  599. * @return string[] 形如 2026-07
  600. */
  601. protected function loadProcuremenSidebarYmList(): array
  602. {
  603. try {
  604. $raw = redis()->get('procuremen_redis_yms');
  605. if ($raw === false || $raw === null || $raw === '') {
  606. return [];
  607. }
  608. $decoded = json_decode((string)$raw, true);
  609. if (!is_array($decoded)) {
  610. return [];
  611. }
  612. $out = [];
  613. foreach ($decoded as $ym) {
  614. $ym = trim((string)$ym);
  615. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  616. $out[$ym] = true;
  617. }
  618. }
  619. return array_keys($out);
  620. } catch (\Throwable $e) {
  621. return [];
  622. }
  623. }
  624. /**
  625. * @param string[] $ymList
  626. */
  627. protected function saveProcuremenSidebarYmList(array $ymList): void
  628. {
  629. $out = [];
  630. foreach ($ymList as $ym) {
  631. $ym = trim((string)$ym);
  632. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  633. $out[$ym] = true;
  634. }
  635. }
  636. if ($out === []) {
  637. return;
  638. }
  639. try {
  640. redis()->set('procuremen_redis_yms', json_encode(array_keys($out), JSON_UNESCAPED_UNICODE));
  641. } catch (\Throwable $e) {
  642. }
  643. }
  644. /**
  645. * @param array<int, array<string, mixed>> $pool
  646. * @return string[]
  647. */
  648. protected function extractYearMonthsFromPoolRows(array $pool): array
  649. {
  650. $ymSet = [];
  651. foreach ($pool as $r) {
  652. if (!is_array($r)) {
  653. continue;
  654. }
  655. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  656. continue;
  657. }
  658. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  659. if ($ym !== null) {
  660. $ymSet[$ym] = true;
  661. }
  662. }
  663. return array_keys($ymSet);
  664. }
  665. /**
  666. * 轻量查询初选侧栏月份(只取 DISTINCT 年月,不拉整包工序)
  667. *
  668. * @return string[]
  669. */
  670. protected function queryProcuremenPickSidebarYmListLight(): array
  671. {
  672. try {
  673. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  674. $endTime = date('Y-m-d 23:59:59');
  675. $sql = 'SELECT DISTINCT DATE_FORMAT('
  676. . 'IF(b.dputrecord IS NOT NULL AND TRIM(CAST(b.dputrecord AS CHAR(32))) <> \'\''
  677. . ' AND TRIM(CAST(b.dputrecord AS CHAR(32))) NOT LIKE \'0000-00-00%\','
  678. . ' b.dputrecord, a.dStamp), \'%Y-%m\') AS ym'
  679. . ' FROM scydgy a'
  680. . ' INNER JOIN mcyd b ON b.ICYDID = a.ICYDID AND b.iStatus >= 10'
  681. . ' WHERE a.bwjg = 1 AND a.iEndBz = 0 AND a.iType = 0 AND a.iStatus = 10'
  682. . ' AND a.dStamp >= ? AND a.dStamp <= ?';
  683. $rows = Db::query($sql, [$startTime, $endTime]);
  684. if (!is_array($rows)) {
  685. return [];
  686. }
  687. $out = [];
  688. foreach ($rows as $r) {
  689. $ym = trim((string)($r['ym'] ?? ''));
  690. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  691. $out[$ym] = true;
  692. }
  693. }
  694. return array_keys($out);
  695. } catch (\Throwable $e) {
  696. Log::write('初选侧栏月份轻量查询失败:' . $e->getMessage(), 'warning');
  697. return [];
  698. }
  699. }
  700. /**
  701. * @return string[] 含当月在内的近 N 个自然月
  702. */
  703. protected function buildRecentCalendarYmList(int $months = 12): array
  704. {
  705. $months = max(1, min(24, $months));
  706. $out = [];
  707. $base = strtotime(date('Y-m-01'));
  708. for ($i = 0; $i < $months; $i++) {
  709. $out[] = date('Y-m', strtotime('-' . $i . ' month', $base));
  710. }
  711. return $out;
  712. }
  713. /**
  714. * 初选按月工序池:优先月缓存;未命中则直接按月查 ERP。
  715. * 禁止为列表去解近一年整包 Redis(解包/连接异常会造成长时间转圈)。
  716. *
  717. * @return array<int, array<string, mixed>>
  718. */
  719. protected function loadPickPoolForYm(string $ym): array
  720. {
  721. $ym = trim($ym);
  722. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  723. return [];
  724. }
  725. $hit = $this->readPickMonthPoolCache($ym);
  726. if ($hit !== null) {
  727. return $hit;
  728. }
  729. return $this->queryPickPoolForYmFromDb($ym);
  730. }
  731. /**
  732. * @return array<int, array<string, mixed>>|null null=无有效缓存(含旧版空数组误缓存)
  733. */
  734. protected function readPickMonthPoolCache(string $ym): ?array
  735. {
  736. try {
  737. $raw = redis()->get('procuremen_pick_pool:' . $ym);
  738. if ($raw === false || $raw === null || $raw === '') {
  739. return null;
  740. }
  741. $decoded = json_decode((string)$raw, true);
  742. if (!is_array($decoded)) {
  743. return null;
  744. }
  745. // 新格式:{ok:1, rows:[...]},空月也算有效(已从整包确认)
  746. if (isset($decoded['ok']) && (int)$decoded['ok'] === 1 && isset($decoded['rows']) && is_array($decoded['rows'])) {
  747. return $decoded['rows'];
  748. }
  749. // 旧格式:仅非空行列表可命中;[] 多半是错误 SQL 写入,视为未命中
  750. if ($decoded === []) {
  751. try {
  752. redis()->del('procuremen_pick_pool:' . $ym);
  753. } catch (\Throwable $e) {
  754. }
  755. return null;
  756. }
  757. if (isset($decoded[0]) && is_array($decoded[0])) {
  758. return $decoded;
  759. }
  760. return null;
  761. } catch (\Throwable $e) {
  762. return null;
  763. }
  764. }
  765. /**
  766. * @param array<int, array<string, mixed>> $rows
  767. */
  768. protected function writePickMonthPoolCache(string $ym, array $rows): void
  769. {
  770. try {
  771. redis()->setex(
  772. 'procuremen_pick_pool:' . $ym,
  773. 600,
  774. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  775. );
  776. } catch (\Throwable $e) {
  777. }
  778. }
  779. /**
  780. * @param array<int, array<string, mixed>> $pool
  781. * @return array<int, array<string, mixed>>
  782. */
  783. protected function filterPoolRowsByYm(array $pool, string $ym): array
  784. {
  785. $out = [];
  786. foreach ($pool as $r) {
  787. if (!is_array($r)) {
  788. continue;
  789. }
  790. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  791. continue;
  792. }
  793. if ($this->procuremenRowYearMonth($r, 'dputrecord') === $ym) {
  794. $out[] = $r;
  795. }
  796. }
  797. return $out;
  798. }
  799. /**
  800. * 按 dStamp 取当月附近数据,再用列表规则(dputrecord 优先)精确到 ym
  801. *
  802. * @return array<int, array<string, mixed>>
  803. */
  804. protected function queryPickPoolForYmFromDb(string $ym): array
  805. {
  806. $monthStart = $ym . '-01 00:00:00';
  807. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  808. // 略放大窗口,避免 dStamp 与 dputrecord 跨月导致漏数;最终仍按 ym 精确过滤
  809. $queryStart = date('Y-m-d 00:00:00', strtotime($monthStart . ' -7 days'));
  810. $queryEnd = date('Y-m-d 23:59:59', strtotime($monthEnd . ' +7 days'));
  811. try {
  812. $list = Db::table('scydgy')
  813. ->alias('a')
  814. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  815. ->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')
  816. ->where([
  817. 'a.bwjg' => 1,
  818. 'a.iEndBz' => 0,
  819. 'a.iType' => 0,
  820. 'a.iStatus' => 10,
  821. ])
  822. ->where('a.dStamp', '>=', $queryStart)
  823. ->where('a.dStamp', '<=', $queryEnd)
  824. ->order('a.dStamp', 'desc')
  825. ->select();
  826. } catch (\Throwable $e) {
  827. Log::write('初选按月取数失败 ym=' . $ym . ':' . $e->getMessage(), 'error');
  828. return [];
  829. }
  830. if (!is_array($list)) {
  831. $list = [];
  832. }
  833. $out = $this->filterPoolRowsByYm($list, $ym);
  834. // 新格式缓存(含空月),避免重复打库;读侧只认 ok=1
  835. $this->writePickMonthPoolCache($ym, $out);
  836. try {
  837. $yms = $this->loadProcuremenSidebarYmList();
  838. if ($out !== [] && ($yms === [] || !in_array($ym, $yms, true))) {
  839. $yms[] = $ym;
  840. $this->saveProcuremenSidebarYmList($yms);
  841. }
  842. } catch (\Throwable $e) {
  843. }
  844. return $out;
  845. }
  846. /**
  847. * 整包写入后拆成按月小缓存,供初选列表秒开
  848. *
  849. * @param array<int, array<string, mixed>> $pool
  850. */
  851. protected function warmPickMonthPoolCachesFromPool(array $pool): void
  852. {
  853. if ($pool === []) {
  854. return;
  855. }
  856. $byYm = [];
  857. foreach ($pool as $r) {
  858. if (!is_array($r)) {
  859. continue;
  860. }
  861. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  862. continue;
  863. }
  864. $rowYm = $this->procuremenRowYearMonth($r, 'dputrecord');
  865. if ($rowYm === null) {
  866. continue;
  867. }
  868. $byYm[$rowYm][] = $r;
  869. }
  870. if ($byYm === []) {
  871. return;
  872. }
  873. try {
  874. $redis = redis();
  875. foreach ($byYm as $rowYm => $rows) {
  876. $redis->setex(
  877. 'procuremen_pick_pool:' . $rowYm,
  878. 600,
  879. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  880. );
  881. }
  882. try {
  883. $redis->del('procuremen_pick_hidden_scydgy_v1');
  884. } catch (\Throwable $e) {
  885. }
  886. } catch (\Throwable $e) {
  887. }
  888. }
  889. /**
  890. * 刷新整包后清理近月缓存,避免脏读
  891. */
  892. protected function clearPickMonthPoolCaches(int $months = 24): void
  893. {
  894. try {
  895. $redis = redis();
  896. foreach ($this->buildRecentCalendarYmList($months) as $ym) {
  897. try {
  898. $redis->del('procuremen_pick_pool:' . $ym);
  899. } catch (\Throwable $e) {
  900. }
  901. }
  902. } catch (\Throwable $e) {
  903. }
  904. $this->invalidatePickHiddenScydgyCache();
  905. }
  906. /**
  907. * 下发/完结后清隐藏集缓存,避免初选列表最多 90 秒仍显示已下发行
  908. */
  909. protected function invalidatePickHiddenScydgyCache(): void
  910. {
  911. $this->pickHiddenScydgySetCache = null;
  912. try {
  913. redis()->del('procuremen_pick_hidden_scydgy_v1');
  914. } catch (\Throwable $e) {
  915. }
  916. }
  917. /** 列表/首屏读完鉴权后尽早释放 session,避免多 iframe 串行卡死 */
  918. protected function procuremenReleaseSessionLock(): void
  919. {
  920. if (session_status() === PHP_SESSION_ACTIVE) {
  921. @session_write_close();
  922. }
  923. }
  924. /**
  925. * @param string[] $ymList 形如 2026-06
  926. * @return array<int, array{year:string, months:array}>
  927. */
  928. protected function buildYearMonthSidebar(array $ymList): array
  929. {
  930. rsort($ymList, SORT_STRING);
  931. $byYear = [];
  932. foreach ($ymList as $ym) {
  933. $y = substr($ym, 0, 4);
  934. $mo = (int)substr($ym, 5, 2);
  935. if (!isset($byYear[$y])) {
  936. $byYear[$y] = [];
  937. }
  938. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  939. }
  940. krsort($byYear, SORT_NUMERIC);
  941. foreach ($byYear as $y => $items) {
  942. usort($byYear[$y], function ($a, $b) {
  943. return strcmp($b['ym'], $a['ym']);
  944. });
  945. }
  946. $sidebar = [];
  947. foreach ($byYear as $y => $months) {
  948. $sidebar[] = ['year' => $y, 'months' => $months];
  949. }
  950. return $sidebar;
  951. }
  952. /**
  953. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  954. */
  955. protected function GetIssuedOrderYearMonths(string $stage): array
  956. {
  957. $ymSet = [];
  958. try {
  959. $query = Db::table('purchase_order');
  960. $this->applyPurchaseOrderNotDeletedWhere($query);
  961. if ($stage === 'audit') {
  962. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  963. } elseif ($stage === 'confirm') {
  964. $this->applyPurchaseOrderConfirmStageWhere($query);
  965. } else {
  966. return $this->GetIndexYearMonths();
  967. }
  968. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  969. if (is_array($rows)) {
  970. foreach ($rows as $r) {
  971. if (!is_array($r)) {
  972. continue;
  973. }
  974. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  975. if ($ym !== null) {
  976. $ymSet[$ym] = true;
  977. }
  978. }
  979. }
  980. } catch (\Throwable $e) {
  981. $ymSet = [];
  982. }
  983. $ymList = array_keys($ymSet);
  984. if ($ymList === []) {
  985. $def = $this->resolveProcuremenDefaultYm($stage);
  986. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  987. }
  988. return $this->buildYearMonthSidebar($ymList);
  989. }
  990. /**
  991. * 列表默认月份:已下发类取最近有数据的月份;初选也取最近有数据月份(避免跨月后落到空当月)
  992. */
  993. protected function resolveProcuremenDefaultYm(string $stage): string
  994. {
  995. if ($stage === 'pick') {
  996. $yms = $this->ensureProcuremenPickSidebarYmList();
  997. if ($yms !== []) {
  998. rsort($yms, SORT_STRING);
  999. return $yms[0];
  1000. }
  1001. return date('Y-m');
  1002. }
  1003. try {
  1004. $query = Db::table('purchase_order');
  1005. $this->applyPurchaseOrderNotDeletedWhere($query);
  1006. if ($stage === 'audit') {
  1007. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1008. } elseif ($stage === 'confirm') {
  1009. $this->applyPurchaseOrderConfirmStageWhere($query);
  1010. } else {
  1011. return date('Y-m');
  1012. }
  1013. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  1014. if ($latest === null || $latest === '') {
  1015. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  1016. }
  1017. $t = $this->formatProcuremenDetailTime($latest);
  1018. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  1019. return $m[1] . '-' . $m[2];
  1020. }
  1021. } catch (\Throwable $e) {
  1022. }
  1023. return date('Y-m');
  1024. }
  1025. protected function applyPurchaseOrderNotDeletedWhere($query): void
  1026. {
  1027. $query->whereRaw(
  1028. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  1029. );
  1030. }
  1031. /**
  1032. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  1033. */
  1034. protected function applyPurchaseOrderConfirmStageWhere($query): void
  1035. {
  1036. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  1037. $quoted = [];
  1038. foreach ($vals as $v) {
  1039. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  1040. }
  1041. if ($quoted === []) {
  1042. $query->whereRaw('1 = 0');
  1043. return;
  1044. }
  1045. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  1046. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  1047. }
  1048. /**
  1049. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  1050. *
  1051. * @param array<string, mixed> $row
  1052. * @return array<string, mixed>
  1053. */
  1054. protected function normalizePurchaseOrderListTimeRow(array $row): array
  1055. {
  1056. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  1057. $pick = trim((string)($row['pick_time'] ?? ''));
  1058. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  1059. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  1060. $t = trim((string)($row[$key] ?? ''));
  1061. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1062. $row['pick_time'] = $t;
  1063. break;
  1064. }
  1065. }
  1066. }
  1067. return $row;
  1068. }
  1069. /**
  1070. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  1071. */
  1072. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  1073. {
  1074. if (!in_array($stage, ['audit', 'confirm'], true)) {
  1075. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1076. }
  1077. if ($pool === []) {
  1078. $def = $this->resolveProcuremenDefaultYm($stage);
  1079. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  1080. }
  1081. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  1082. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1083. return false;
  1084. }
  1085. $monthStart = $ym . '-01 00:00:00';
  1086. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1087. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  1088. return $probe !== [];
  1089. };
  1090. if ($tryYm($requestedYm)) {
  1091. return $requestedYm;
  1092. }
  1093. $fallback = $this->resolveProcuremenDefaultYm($stage);
  1094. if ($tryYm($fallback)) {
  1095. return $fallback;
  1096. }
  1097. $bestYm = '';
  1098. $bestTime = '';
  1099. foreach ($pool as $row) {
  1100. if (!is_array($row)) {
  1101. continue;
  1102. }
  1103. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  1104. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  1105. continue;
  1106. }
  1107. $ymRow = $m[1];
  1108. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  1109. $bestTime = $t;
  1110. $bestYm = $ymRow;
  1111. }
  1112. }
  1113. if ($bestYm !== '') {
  1114. return $bestYm;
  1115. }
  1116. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1117. }
  1118. protected function isPurchaseOrderDetailVoid(array $row): bool
  1119. {
  1120. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  1121. return true;
  1122. }
  1123. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  1124. }
  1125. /**
  1126. * 仅当前有效下发明细(排除废弃归档)
  1127. */
  1128. protected function applyActivePurchaseOrderDetailWhere($query): void
  1129. {
  1130. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1131. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  1132. }
  1133. /**
  1134. * @param array<string, mixed> $detailRow
  1135. */
  1136. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  1137. {
  1138. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  1139. return false;
  1140. }
  1141. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  1142. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  1143. }
  1144. /**
  1145. * 废弃退回初选:下发明细标记归档,不物理删除
  1146. *
  1147. * @param array<int, int|string> $scydgyIds
  1148. */
  1149. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  1150. {
  1151. $ids = [];
  1152. foreach ($scydgyIds as $sid) {
  1153. $n = (int)$sid;
  1154. if ($this->isValidScydgyRowId($n) || $n < 0) {
  1155. $ids[$n] = true;
  1156. }
  1157. }
  1158. if ($ids === []) {
  1159. return;
  1160. }
  1161. $void = ProcuremenStatus::POD_VOID;
  1162. Db::table('purchase_order_detail')
  1163. ->where('scydgy_id', 'in', array_keys($ids))
  1164. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1165. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  1166. ->update([
  1167. 'status' => $void,
  1168. 'status_name' => $void,
  1169. ]);
  1170. }
  1171. /**
  1172. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  1173. */
  1174. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  1175. {
  1176. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  1177. $norm = function (string $col) use ($p): string {
  1178. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  1179. };
  1180. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  1181. $parts = [];
  1182. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  1183. if ($key === 'createtime') {
  1184. $parts[] = $createtime;
  1185. } else {
  1186. $parts[] = $norm($key);
  1187. }
  1188. }
  1189. return 'COALESCE(' . implode(', ', $parts) . ')';
  1190. }
  1191. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  1192. {
  1193. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  1194. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  1195. }
  1196. /**
  1197. * @return array<int, array<string, mixed>>
  1198. */
  1199. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  1200. {
  1201. $this->ensurePurchaseOrderCzlyqColumn();
  1202. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1203. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  1204. try {
  1205. $query = Db::table('purchase_order')->field($fields);
  1206. $this->applyPurchaseOrderNotDeletedWhere($query);
  1207. if ($stage === 'audit') {
  1208. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1209. } elseif ($stage === 'confirm') {
  1210. $this->applyPurchaseOrderConfirmStageWhere($query);
  1211. } else {
  1212. return [];
  1213. }
  1214. $query->order('pick_time', 'desc')->order('id', 'desc');
  1215. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  1216. $monthStart = $ym . '-01 00:00:00';
  1217. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1218. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  1219. }
  1220. $rows = $query->select();
  1221. } catch (\Throwable $e) {
  1222. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  1223. $rows = [];
  1224. }
  1225. return is_array($rows) ? $rows : [];
  1226. }
  1227. /**
  1228. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  1229. */
  1230. protected function resolveProcuremenListStage(): string
  1231. {
  1232. $tab = trim((string)$this->request->request('wff_tab', ''));
  1233. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  1234. return $tab;
  1235. }
  1236. $action = strtolower((string)$this->request->action());
  1237. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  1238. return $action;
  1239. }
  1240. return 'pick';
  1241. }
  1242. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  1243. {
  1244. $this->procuremenReleaseSessionLock();
  1245. $rootTrue = rtrim((string)$this->request->root(true), '/');
  1246. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  1247. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  1248. $indexPhpRoot = $rootTrue . '/index.php';
  1249. }
  1250. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  1251. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  1252. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  1253. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  1254. $this->view->assign('defaultYm', $defaultYm);
  1255. $this->view->assign('sidebarYearMonths', $sidebar);
  1256. $this->view->assign('procuremenStage', $stage);
  1257. $this->view->assign('procuremenPageTitle', $pageTitle);
  1258. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  1259. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  1260. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  1261. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  1262. $this->assignconfig('procuremenFilterOptions', $this->buildProcuremenFilterOptions($stage));
  1263. }
  1264. /**
  1265. * 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
  1266. *
  1267. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1268. */
  1269. protected function buildProcuremenFilterOptions(string $stage): array
  1270. {
  1271. $buckets = [
  1272. 'czlyq' => [],
  1273. 'CCLBMMC' => [],
  1274. 'cywyxm' => [],
  1275. 'CGYMC' => [],
  1276. ];
  1277. $maxPerField = 300;
  1278. try {
  1279. if ($stage === 'pick') {
  1280. // 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
  1281. return $buckets;
  1282. }
  1283. if (in_array($stage, ['audit', 'confirm'], true)) {
  1284. $this->ensurePurchaseOrderCzlyqColumn();
  1285. foreach (array_keys($buckets) as $field) {
  1286. try {
  1287. $query = Db::table('purchase_order')->field($field);
  1288. $this->applyPurchaseOrderNotDeletedWhere($query);
  1289. if ($stage === 'audit') {
  1290. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1291. } else {
  1292. $this->applyPurchaseOrderConfirmStageWhere($query);
  1293. }
  1294. $query->where($field, '<>', '')->whereNotNull($field);
  1295. $vals = $query->distinct(true)->limit($maxPerField)->column($field);
  1296. if (!is_array($vals)) {
  1297. continue;
  1298. }
  1299. foreach ($vals as $v) {
  1300. $v = trim((string)$v);
  1301. if ($v !== '') {
  1302. $buckets[$field][$v] = $v;
  1303. }
  1304. }
  1305. } catch (\Throwable $e) {
  1306. // 单字段失败不影响其它
  1307. }
  1308. }
  1309. }
  1310. } catch (\Throwable $e) {
  1311. Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
  1312. }
  1313. foreach ($buckets as &$set) {
  1314. if ($set !== []) {
  1315. ksort($set, SORT_STRING);
  1316. }
  1317. }
  1318. unset($set);
  1319. return $buckets;
  1320. }
  1321. /**
  1322. * filter JSON 是否含有效条件
  1323. *
  1324. * @param array<string, mixed> $filterArr
  1325. */
  1326. protected function procuremenFilterArrHasValue(array $filterArr): bool
  1327. {
  1328. foreach ($filterArr as $v) {
  1329. if (is_array($v)) {
  1330. if (array_filter($v, function ($x) {
  1331. return $x !== '' && $x !== null;
  1332. })) {
  1333. return true;
  1334. }
  1335. } elseif ($v !== '' && $v !== null) {
  1336. return true;
  1337. }
  1338. }
  1339. return false;
  1340. }
  1341. /**
  1342. * 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
  1343. *
  1344. * @param array<string, mixed> $filterArr
  1345. * @param array<string, mixed> $opArr
  1346. */
  1347. protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
  1348. {
  1349. if ($search !== '') {
  1350. return false;
  1351. }
  1352. foreach ($filterArr as $fk => $fv) {
  1353. if (is_array($fv)) {
  1354. continue;
  1355. }
  1356. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  1357. continue;
  1358. }
  1359. if ($fv === null) {
  1360. continue;
  1361. }
  1362. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  1363. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  1364. if ($sym === '' || $sym === '=') {
  1365. continue;
  1366. }
  1367. return false;
  1368. }
  1369. return true;
  1370. }
  1371. /**
  1372. * 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
  1373. *
  1374. * @param array<int, mixed> $rows
  1375. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1376. */
  1377. protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
  1378. {
  1379. $buckets = [
  1380. 'czlyq' => [],
  1381. 'CCLBMMC' => [],
  1382. 'cywyxm' => [],
  1383. 'CGYMC' => [],
  1384. ];
  1385. foreach ($rows as $r) {
  1386. if (!is_array($r)) {
  1387. continue;
  1388. }
  1389. foreach ($buckets as $field => &$set) {
  1390. if (count($set) >= $maxPerField) {
  1391. continue;
  1392. }
  1393. $v = trim((string)($r[$field] ?? ''));
  1394. if ($v !== '') {
  1395. $set[$v] = $v;
  1396. }
  1397. }
  1398. unset($set);
  1399. $full = true;
  1400. foreach ($buckets as $set) {
  1401. if (count($set) < $maxPerField) {
  1402. $full = false;
  1403. break;
  1404. }
  1405. }
  1406. if ($full) {
  1407. break;
  1408. }
  1409. }
  1410. foreach ($buckets as &$set) {
  1411. if ($set !== []) {
  1412. // 保证 json 编码为对象(避免 list 下标 0,1,2… 被前端当选项)
  1413. $normalized = [];
  1414. foreach ($set as $k => $v) {
  1415. $s = trim((string)(is_scalar($v) ? $v : $k));
  1416. if ($s === '') {
  1417. continue;
  1418. }
  1419. $normalized[$s] = $s;
  1420. }
  1421. ksort($normalized, SORT_STRING);
  1422. $set = $normalized;
  1423. }
  1424. }
  1425. unset($set);
  1426. return $buckets;
  1427. }
  1428. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  1429. public function pick()
  1430. {
  1431. $this->request->filter(['strip_tags', 'trim']);
  1432. if (!$this->request->isAjax()) {
  1433. $this->assignProcuremenListPage('pick', '协助下发');
  1434. return $this->view->fetch('procuremen/index');
  1435. }
  1436. return $this->index();
  1437. }
  1438. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  1439. public function audit()
  1440. {
  1441. $this->request->filter(['strip_tags', 'trim']);
  1442. if (!$this->request->isAjax()) {
  1443. $this->assignProcuremenListPage('audit', '确认供应商');
  1444. return $this->view->fetch('procuremen/index');
  1445. }
  1446. return $this->index();
  1447. }
  1448. /** 采购确认(定标) */
  1449. public function confirm()
  1450. {
  1451. $this->request->filter(['strip_tags', 'trim']);
  1452. if (!$this->request->isAjax()) {
  1453. $this->assignProcuremenListPage('confirm', '采购确认');
  1454. return $this->view->fetch('procuremen/index');
  1455. }
  1456. return $this->index();
  1457. }
  1458. /**
  1459. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  1460. */
  1461. public function index()
  1462. {
  1463. $this->request->filter(['strip_tags', 'trim']);
  1464. if (!$this->request->isAjax()) {
  1465. $this->assignProcuremenListPage('pick', '协助下发');
  1466. return $this->view->fetch('procuremen/index');
  1467. }
  1468. if ($this->request->request('keyField')) {
  1469. return $this->selectpage();
  1470. }
  1471. $this->procuremenReleaseSessionLock();
  1472. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  1473. $limit = max(10, min(500, (int)$limit));
  1474. $ym = $this->request->request('ym', '');
  1475. $ym = is_string($ym) ? trim($ym) : '';
  1476. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  1477. $wffTab = $this->resolveProcuremenListStage();
  1478. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1479. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  1480. ? $this->resolveProcuremenDefaultYm($wffTab)
  1481. : date('Y-m');
  1482. }
  1483. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1484. $ym = date('Y-m');
  1485. }
  1486. $monthStart = $ym . '-01 00:00:00';
  1487. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1488. $search = trim((string)$this->request->get('search', ''));
  1489. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  1490. $opArr = (array)json_decode($this->request->get('op', ''), true);
  1491. if (!is_array($filterArr)) {
  1492. $filterArr = [];
  1493. }
  1494. if (!is_array($opArr)) {
  1495. $opArr = [];
  1496. }
  1497. // 开标状态为计算字段,不能进池内等值筛选;单独抽出后在合并后再滤
  1498. $bidOpenStatusFilter = '';
  1499. foreach (['bid_open_status_text', 'a.bid_open_status_text'] as $bidFk) {
  1500. if (!array_key_exists($bidFk, $filterArr)) {
  1501. continue;
  1502. }
  1503. $bidOpenStatusFilter = trim((string)$filterArr[$bidFk]);
  1504. unset($filterArr[$bidFk], $opArr[$bidFk]);
  1505. }
  1506. // 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
  1507. $applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
  1508. $hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
  1509. try {
  1510. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  1511. if ($wffTab === 'audit') {
  1512. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  1513. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  1514. );
  1515. } elseif ($wffTab === 'confirm') {
  1516. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  1517. if ($dbRows === []) {
  1518. try {
  1519. $dbRows = Db::table('purchase_order')
  1520. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1521. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  1522. ->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%\')')
  1523. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  1524. ->order('pick_time', 'desc')->order('id', 'desc')
  1525. ->select();
  1526. } catch (\Throwable $e) {
  1527. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  1528. $dbRows = [];
  1529. }
  1530. }
  1531. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  1532. if ($pool === []) {
  1533. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1534. }
  1535. } else {
  1536. // 初选:按月直查 ERP(不解整包 Redis,避免长时间转圈)
  1537. if ($applyMonthRange) {
  1538. $pool = $this->loadPickPoolForYm($ym);
  1539. } else {
  1540. $pool = $this->procuremenEnsureRedisPool();
  1541. }
  1542. if (!is_array($pool)) {
  1543. $pool = [];
  1544. }
  1545. // 只针对本页候选 ID 查隐藏集,避免全表扫 purchase_order_detail
  1546. $hideSet = $this->loadPickHiddenScydgySetForIds($this->extractScydgyIdsFromPool($pool));
  1547. if ($pool !== [] && $hideSet !== []) {
  1548. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1549. if (!is_array($r)) {
  1550. return false;
  1551. }
  1552. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1553. return $id <= 0 || !isset($hideSet[$id]);
  1554. }));
  1555. }
  1556. // 手工新增(YW / scydgy_id<0)只走「新增询价/查询询价」,不进初选表格
  1557. if ($pool === []) {
  1558. return json([
  1559. 'total' => 0,
  1560. 'rows' => [],
  1561. 'activeYm' => $ym,
  1562. 'filterOptions' => (
  1563. (int)$offset === 0
  1564. && !$hasActiveSearch
  1565. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1566. )
  1567. ? $this->extractProcuremenFilterOptionsFromRows([])
  1568. : new \stdClass(),
  1569. ]);
  1570. }
  1571. }
  1572. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  1573. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  1574. $monthStart = $ym . '-01 00:00:00';
  1575. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1576. }
  1577. $filtered = $this->filterProcuremenIndexPool(
  1578. $pool,
  1579. $monthStart,
  1580. $monthEnd,
  1581. $applyMonthRange,
  1582. $search,
  1583. $filterArr,
  1584. $opArr,
  1585. $listTimePrimary
  1586. );
  1587. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1588. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1589. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1590. }
  1591. if ($wffTab === 'audit' && $bidOpenStatusFilter !== '') {
  1592. $filtered = $this->filterProcuremenPoolByBidOpenStatus($filtered, $bidOpenStatusFilter);
  1593. }
  1594. $sortField = 'ID';
  1595. if (is_string($sort) && $sort !== '') {
  1596. $parts = explode(',', $sort);
  1597. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1598. if ($sortField === '') {
  1599. $sortField = 'ID';
  1600. }
  1601. }
  1602. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1603. $nFiltered = count($filtered);
  1604. if ($nFiltered > 1) {
  1605. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1606. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1607. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1608. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1609. if ($ta === $tb) {
  1610. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1611. }
  1612. if ($ta === '') {
  1613. return 1;
  1614. }
  1615. if ($tb === '') {
  1616. return -1;
  1617. }
  1618. return strcmp($ta, $tb) * $ord;
  1619. });
  1620. } elseif ($sortField === 'ID') {
  1621. $sortKeys = [];
  1622. foreach ($filtered as $i => $row) {
  1623. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1624. }
  1625. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1626. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1627. } elseif ($sortField === 'CCYDH') {
  1628. usort($filtered, function ($a, $b) use ($ord) {
  1629. $sa = trim((string)($a['CCYDH'] ?? ''));
  1630. $sb = trim((string)($b['CCYDH'] ?? ''));
  1631. if ($sa === $sb) {
  1632. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1633. }
  1634. if ($sa === '') {
  1635. return 1;
  1636. }
  1637. if ($sb === '') {
  1638. return -1;
  1639. }
  1640. return strcmp($sa, $sb) * $ord;
  1641. });
  1642. } else {
  1643. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1644. $va = $a[$sortField] ?? null;
  1645. $vb = $b[$sortField] ?? null;
  1646. $sa = (string)$va;
  1647. $sb = (string)$vb;
  1648. if ($sa === $sb) {
  1649. return 0;
  1650. }
  1651. return strcmp($sa, $sb) * $ord;
  1652. });
  1653. }
  1654. }
  1655. $offset = max(0, (int)$offset);
  1656. $limit = max(1, (int)$limit);
  1657. $rows = array_slice($filtered, $offset, $limit);
  1658. foreach ($rows as &$rw) {
  1659. if (!is_array($rw)) {
  1660. continue;
  1661. }
  1662. $rid = (int)($rw['ID'] ?? 0);
  1663. $rw['_iss_out'] = ($wffTab !== 'pick');
  1664. }
  1665. unset($rw);
  1666. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1667. $idList = [];
  1668. foreach ($rows as $rw) {
  1669. if (!is_array($rw)) {
  1670. continue;
  1671. }
  1672. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1673. foreach ($rw['_order_merge_rows'] as $mr) {
  1674. $mid = (int)($mr['ID'] ?? 0);
  1675. if ($this->isValidScydgyRowId($mid)) {
  1676. $idList[$mid] = true;
  1677. }
  1678. }
  1679. }
  1680. $id = (int)($rw['ID'] ?? 0);
  1681. if ($this->isValidScydgyRowId($id)) {
  1682. $idList[$id] = true;
  1683. }
  1684. }
  1685. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1686. foreach ($rows as &$rw) {
  1687. if (!is_array($rw)) {
  1688. continue;
  1689. }
  1690. $mergeIds = [];
  1691. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1692. foreach ($rw['_order_merge_rows'] as $mr) {
  1693. $mid = (int)($mr['ID'] ?? 0);
  1694. if ($this->isValidScydgyRowId($mid)) {
  1695. $mergeIds[$mid] = true;
  1696. }
  1697. }
  1698. }
  1699. $rid = (int)($rw['ID'] ?? 0);
  1700. if ($this->isValidScydgyRowId($rid)) {
  1701. $mergeIds[$rid] = true;
  1702. }
  1703. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1704. $rw['po_detail_count'] = $s['cnt'];
  1705. $rw['po_amount_fill_cnt'] = $s['amt'];
  1706. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1707. }
  1708. unset($rw);
  1709. }
  1710. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1711. $idList = [];
  1712. foreach ($rows as $rw) {
  1713. if (!is_array($rw)) {
  1714. continue;
  1715. }
  1716. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1717. foreach ($rw['_order_merge_rows'] as $mr) {
  1718. $mid = (int)($mr['ID'] ?? 0);
  1719. if ($this->isValidScydgyRowId($mid)) {
  1720. $idList[$mid] = true;
  1721. }
  1722. }
  1723. }
  1724. $id = (int)($rw['ID'] ?? 0);
  1725. if ($this->isValidScydgyRowId($id)) {
  1726. $idList[$id] = true;
  1727. }
  1728. }
  1729. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1730. $bidOpenSet = [];
  1731. $manualPickSet = [];
  1732. if ($wffTab === 'audit') {
  1733. $ccydhList = [];
  1734. foreach ($rows as $rw0) {
  1735. if (!is_array($rw0)) {
  1736. continue;
  1737. }
  1738. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1739. if ($c0 !== '') {
  1740. $ccydhList[] = $c0;
  1741. }
  1742. }
  1743. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1744. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  1745. }
  1746. foreach ($rows as &$rw) {
  1747. if (!is_array($rw)) {
  1748. continue;
  1749. }
  1750. $mergeIds = [];
  1751. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1752. foreach ($rw['_order_merge_rows'] as $mr) {
  1753. $mid = (int)($mr['ID'] ?? 0);
  1754. if ($this->isValidScydgyRowId($mid)) {
  1755. $mergeIds[$mid] = true;
  1756. }
  1757. }
  1758. }
  1759. $rid = (int)($rw['ID'] ?? 0);
  1760. if ($this->isValidScydgyRowId($rid)) {
  1761. $mergeIds[$rid] = true;
  1762. }
  1763. $buckets = [];
  1764. foreach (array_keys($mergeIds) as $mid) {
  1765. if (isset($quoteBucket[$mid])) {
  1766. $buckets[] = $quoteBucket[$mid];
  1767. }
  1768. }
  1769. $supplierText = $buckets !== []
  1770. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1771. : '';
  1772. if ($wffTab === 'confirm') {
  1773. $picked = trim((string)($rw['pick_company_name'] ?? $rw['picked_supplier_name'] ?? ''));
  1774. if ($picked === '') {
  1775. // 兜底:从合并工序行取
  1776. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1777. foreach ($rw['_order_merge_rows'] as $mr) {
  1778. if (!is_array($mr)) {
  1779. continue;
  1780. }
  1781. $pn = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  1782. if ($pn !== '') {
  1783. $picked = $pn;
  1784. break;
  1785. }
  1786. }
  1787. }
  1788. }
  1789. $rw['picked_supplier_name'] = $picked;
  1790. } else {
  1791. $rw['notify_supplier_text'] = $supplierText;
  1792. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1793. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1794. $manualPicked = ($ccydh !== '' && isset($manualPickSet[$ccydh]));
  1795. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1796. $rw['manual_picked'] = $manualPicked ? 1 : 0;
  1797. if ($verified) {
  1798. $rw['bid_open_status_text'] = '已开标';
  1799. } elseif ($manualPicked) {
  1800. $rw['bid_open_status_text'] = '已指定供应商';
  1801. } else {
  1802. $rw['bid_open_status_text'] = '待开标';
  1803. }
  1804. }
  1805. }
  1806. unset($rw);
  1807. }
  1808. if (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
  1809. $this->enrichProcuremenListMilestoneTimes($rows);
  1810. $this->syncCollapsedOrderQtyPriceForList($rows);
  1811. }
  1812. if ($wffTab === 'all' && count($rows) > 0) {
  1813. $this->mergePurchaseOrder($rows);
  1814. }
  1815. if ($wffTab === 'pick' && count($rows) > 0) {
  1816. $this->mergePurchaseOrder($rows);
  1817. }
  1818. foreach ($rows as &$rwClean) {
  1819. if (is_array($rwClean)) {
  1820. unset($rwClean['_order_merge_rows']);
  1821. if (array_key_exists('NGZL', $rwClean)) {
  1822. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1823. }
  1824. }
  1825. }
  1826. unset($rwClean);
  1827. return json([
  1828. 'total' => count($filtered),
  1829. 'rows' => $rows,
  1830. 'activeYm' => $ym,
  1831. // 初选:把有数据的月份带回,替换「空月份日历」侧栏
  1832. 'sidebarYms' => ($wffTab === 'pick' && (int)$offset === 0)
  1833. ? $this->ensureProcuremenPickSidebarYmList()
  1834. : [],
  1835. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1836. 'filterOptions' => (
  1837. (int)$offset === 0
  1838. && !$hasActiveSearch
  1839. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1840. )
  1841. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1842. : new \stdClass(),
  1843. ]);
  1844. } catch (\Throwable $e) {
  1845. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1846. return json([
  1847. 'total' => 0,
  1848. 'rows' => [],
  1849. ]);
  1850. }
  1851. }
  1852. /**
  1853. * @param array<int, array<string, mixed>> $pool
  1854. * @return int[]
  1855. */
  1856. protected function extractScydgyIdsFromPool(array $pool): array
  1857. {
  1858. $ids = [];
  1859. foreach ($pool as $r) {
  1860. if (!is_array($r)) {
  1861. continue;
  1862. }
  1863. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1864. if ($id > 0) {
  1865. $ids[$id] = $id;
  1866. }
  1867. }
  1868. return array_values($ids);
  1869. }
  1870. /**
  1871. * 仅查询指定工序 ID 是否已下发/进入后续流程(初选列表加速)
  1872. *
  1873. * @param int[] $scydgyIds
  1874. * @return array<int, true>
  1875. */
  1876. protected function loadPickHiddenScydgySetForIds(array $scydgyIds): array
  1877. {
  1878. $hideSet = [];
  1879. $scydgyIds = array_values(array_filter(array_map('intval', $scydgyIds), function ($id) {
  1880. return $id > 0;
  1881. }));
  1882. if ($scydgyIds === []) {
  1883. return $hideSet;
  1884. }
  1885. // 分批,避免 whereIn 过长
  1886. foreach (array_chunk($scydgyIds, 500) as $chunk) {
  1887. try {
  1888. $poIds = Db::table('purchase_order')
  1889. ->where('scydgy_id', 'in', $chunk)
  1890. ->where(function ($q) {
  1891. $q->whereIn('wflow_status', array_merge(
  1892. ProcuremenStatus::wflowPendingConfirmValues(),
  1893. ProcuremenStatus::wflowPendingApprovalValues()
  1894. ))
  1895. ->whereOr(function ($q1) {
  1896. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1897. })
  1898. ->whereOr(function ($q2) {
  1899. $q2->whereNotNull('pick_time')
  1900. ->where('pick_time', '<>', '')
  1901. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1902. })
  1903. ->whereOr(function ($q3) {
  1904. $q3->whereNotNull('mod_rq')
  1905. ->where('mod_rq', '<>', '')
  1906. ->where('mod_rq', 'not like', '0000-00-00%');
  1907. });
  1908. })
  1909. ->column('scydgy_id');
  1910. if (is_array($poIds)) {
  1911. foreach ($poIds as $pid) {
  1912. $k = (int)$pid;
  1913. if ($k !== 0) {
  1914. $hideSet[$k] = true;
  1915. }
  1916. }
  1917. }
  1918. } catch (\Throwable $e) {
  1919. }
  1920. try {
  1921. $detIdsQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $chunk);
  1922. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1923. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1924. if (is_array($detIds)) {
  1925. foreach ($detIds as $pid) {
  1926. $k = (int)$pid;
  1927. if ($this->isValidScydgyRowId($k)) {
  1928. $hideSet[$k] = true;
  1929. }
  1930. }
  1931. }
  1932. } catch (\Throwable $e) {
  1933. }
  1934. }
  1935. return $hideSet;
  1936. }
  1937. /**
  1938. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1939. *
  1940. * @return array<int, true>
  1941. */
  1942. protected function loadPickHiddenScydgySet(): array
  1943. {
  1944. if ($this->pickHiddenScydgySetCache !== null) {
  1945. return $this->pickHiddenScydgySetCache;
  1946. }
  1947. $cacheKey = 'procuremen_pick_hidden_scydgy_v1';
  1948. try {
  1949. $raw = redis()->get($cacheKey);
  1950. if ($raw !== false && $raw !== null && $raw !== '') {
  1951. $ids = json_decode((string)$raw, true);
  1952. if (is_array($ids)) {
  1953. $hideSet = [];
  1954. foreach ($ids as $pid) {
  1955. $k = (int)$pid;
  1956. if ($k !== 0) {
  1957. $hideSet[$k] = true;
  1958. }
  1959. }
  1960. $this->pickHiddenScydgySetCache = $hideSet;
  1961. return $hideSet;
  1962. }
  1963. }
  1964. } catch (\Throwable $e) {
  1965. }
  1966. $hideSet = [];
  1967. try {
  1968. $poIds = Db::table('purchase_order')
  1969. ->where(function ($q) {
  1970. $q->whereIn('wflow_status', array_merge(
  1971. ProcuremenStatus::wflowPendingConfirmValues(),
  1972. ProcuremenStatus::wflowPendingApprovalValues()
  1973. ))
  1974. ->whereOr(function ($q1) {
  1975. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1976. })
  1977. ->whereOr(function ($q2) {
  1978. $q2->whereNotNull('pick_time')
  1979. ->where('pick_time', '<>', '')
  1980. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1981. })
  1982. ->whereOr(function ($q3) {
  1983. $q3->whereNotNull('mod_rq')
  1984. ->where('mod_rq', '<>', '')
  1985. ->where('mod_rq', 'not like', '0000-00-00%');
  1986. });
  1987. })
  1988. ->column('scydgy_id');
  1989. if (is_array($poIds)) {
  1990. foreach ($poIds as $pid) {
  1991. $k = (int)$pid;
  1992. if ($k !== 0) {
  1993. $hideSet[$k] = true;
  1994. }
  1995. }
  1996. }
  1997. } catch (\Throwable $e) {
  1998. }
  1999. try {
  2000. $detIdsQuery = Db::table('purchase_order_detail');
  2001. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  2002. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  2003. if (is_array($detIds)) {
  2004. foreach ($detIds as $pid) {
  2005. $k = (int)$pid;
  2006. if ($this->isValidScydgyRowId($k)) {
  2007. $hideSet[$k] = true;
  2008. }
  2009. }
  2010. }
  2011. } catch (\Throwable $e) {
  2012. }
  2013. $this->pickHiddenScydgySetCache = $hideSet;
  2014. try {
  2015. redis()->setex($cacheKey, 90, json_encode(array_map('intval', array_keys($hideSet))));
  2016. } catch (\Throwable $e) {
  2017. }
  2018. return $hideSet;
  2019. }
  2020. /**
  2021. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  2022. *
  2023. * @return array<int, array<string, mixed>>
  2024. */
  2025. protected function loadPickManualOrderRows(): array
  2026. {
  2027. try {
  2028. $dbRows = Db::table('purchase_order')
  2029. ->where('scydgy_id', '<', 0)
  2030. ->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%\')')
  2031. ->order('scydgy_id', 'asc')
  2032. ->select();
  2033. } catch (\Throwable $e) {
  2034. try {
  2035. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  2036. } catch (\Throwable $e2) {
  2037. return [];
  2038. }
  2039. }
  2040. if (!is_array($dbRows) || $dbRows === []) {
  2041. return [];
  2042. }
  2043. $detailSidSet = [];
  2044. try {
  2045. $negIds = [];
  2046. foreach ($dbRows as $dbRow) {
  2047. if (!is_array($dbRow)) {
  2048. continue;
  2049. }
  2050. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2051. if ($sid < 0) {
  2052. $negIds[$sid] = true;
  2053. }
  2054. }
  2055. if ($negIds !== []) {
  2056. $detQuery = Db::table('purchase_order_detail')
  2057. ->where('scydgy_id', 'in', array_keys($negIds));
  2058. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  2059. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  2060. if (is_array($detRows)) {
  2061. foreach ($detRows as $did) {
  2062. $detailSidSet[(int)$did] = true;
  2063. }
  2064. }
  2065. }
  2066. } catch (\Throwable $e) {
  2067. }
  2068. $pool = [];
  2069. foreach ($dbRows as $dbRow) {
  2070. if (!is_array($dbRow)) {
  2071. continue;
  2072. }
  2073. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2074. if ($sid >= 0) {
  2075. continue;
  2076. }
  2077. // 已进入确认/审批的不进初选;仅废弃明细残留的仍算可下发
  2078. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  2079. continue;
  2080. }
  2081. // 仅排除已完结;空 status / 「进行中」/ 0 均保留(新建手工单)
  2082. if (ProcuremenStatus::isPoCompleted($dbRow['status'] ?? '')) {
  2083. continue;
  2084. }
  2085. if (isset($detailSidSet[$sid])) {
  2086. continue;
  2087. }
  2088. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  2089. $r['_is_manual'] = 1;
  2090. $pool[] = $r;
  2091. }
  2092. return $pool;
  2093. }
  2094. /**
  2095. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  2096. */
  2097. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  2098. {
  2099. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  2100. foreach ($keys as $k) {
  2101. $t = trim((string)($row[$k] ?? ''));
  2102. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2103. return $t;
  2104. }
  2105. }
  2106. return '';
  2107. }
  2108. /**
  2109. * 分配手工新增工序行 ID(负数递减)
  2110. * 调用方须在命名锁内执行,避免并发重复
  2111. */
  2112. protected function allocateManualScydgyId(): int
  2113. {
  2114. try {
  2115. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  2116. $min = (int)$min;
  2117. return $min < 0 ? $min - 1 : -1;
  2118. } catch (\Throwable $e) {
  2119. return -1;
  2120. }
  2121. }
  2122. /**
  2123. * 手工新增订单号:YW + 年月日 + 当日序号(如 YW20260618001)
  2124. * 调用方须在命名锁内执行,避免并发重复
  2125. */
  2126. protected function allocateManualOrderCcydh(): string
  2127. {
  2128. $prefix = 'YW' . date('Ymd');
  2129. $maxSeq = 0;
  2130. try {
  2131. $rows = Db::table('purchase_order')
  2132. ->where('CCYDH', 'like', $prefix . '%')
  2133. ->column('CCYDH');
  2134. if (is_array($rows)) {
  2135. foreach ($rows as $ccydh) {
  2136. $ccydh = trim((string)$ccydh);
  2137. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3,})$/', $ccydh, $m)) {
  2138. $maxSeq = max($maxSeq, (int)$m[1]);
  2139. }
  2140. }
  2141. }
  2142. } catch (\Throwable $e) {
  2143. }
  2144. $next = $maxSeq + 1;
  2145. $width = $next > 999 ? strlen((string)$next) : 3;
  2146. return $prefix . str_pad((string)$next, $width, '0', STR_PAD_LEFT);
  2147. }
  2148. /**
  2149. * MySQL 命名锁(跨连接防并发撞号)
  2150. */
  2151. protected function acquireProcuremenNamedLock(string $name, int $timeoutSec = 10): bool
  2152. {
  2153. $name = trim($name);
  2154. if ($name === '') {
  2155. return false;
  2156. }
  2157. try {
  2158. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2159. $rows = Db::query('SELECT GET_LOCK(\'' . $nameSql . '\', ' . max(1, $timeoutSec) . ') AS locked');
  2160. if (!is_array($rows) || $rows === []) {
  2161. return false;
  2162. }
  2163. $v = $rows[0]['locked'] ?? $rows[0]['LOCKED'] ?? null;
  2164. return (int)$v === 1;
  2165. } catch (\Throwable $e) {
  2166. return false;
  2167. }
  2168. }
  2169. protected function releaseProcuremenNamedLock(string $name): void
  2170. {
  2171. $name = trim($name);
  2172. if ($name === '') {
  2173. return;
  2174. }
  2175. try {
  2176. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2177. Db::query('SELECT RELEASE_LOCK(\'' . $nameSql . '\')');
  2178. } catch (\Throwable $e) {
  2179. }
  2180. }
  2181. /**
  2182. * purchase_order.mod_rq 是否有有效软删除时间
  2183. */
  2184. protected function isPurchaseOrderSoftDeleted($modRq): bool
  2185. {
  2186. $t = trim((string)$modRq);
  2187. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  2188. }
  2189. /**
  2190. * 列表行 → purchase_order 写入字段
  2191. *
  2192. * @return array<string, mixed>
  2193. */
  2194. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  2195. {
  2196. return $this->normalizePurchaseOrderWritePayload([
  2197. 'scydgy_id' => $scydgyId,
  2198. 'CCYDH' => $row['CCYDH'] ?? null,
  2199. 'CYJMC' => $row['CYJMC'] ?? null,
  2200. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2201. 'CDXMC' => $row['CDXMC'] ?? null,
  2202. 'CGYBH' => $row['CGYBH'] ?? null,
  2203. 'CGYMC' => $row['CGYMC'] ?? null,
  2204. 'CDW' => $row['CDW'] ?? null,
  2205. 'czlyq' => $row['czlyq'] ?? null,
  2206. 'NGZL' => $row['NGZL'] ?? null,
  2207. 'CDF' => $row['CDF'] ?? null,
  2208. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2209. 'MBZ' => $row['MBZ'] ?? null,
  2210. 'bwjg' => $row['bwjg'] ?? null,
  2211. 'iStatus' => $row['iStatus'] ?? null,
  2212. 'dStamp' => $row['dStamp'] ?? null,
  2213. 'dputrecord' => $row['dputrecord'] ?? null,
  2214. 'cywyxm' => $row['cywyxm'] ?? null,
  2215. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2216. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2217. ], $row);
  2218. }
  2219. /**
  2220. * purchase_order 写入前规范化:NOT NULL 列勿显式传 null(会绕过 DEFAULT 触发 1048)
  2221. *
  2222. * @param array<string, mixed> $data
  2223. * @param array<string, mixed> $row 原始列表行(可用于补齐 czlyq)
  2224. * @return array<string, mixed>
  2225. */
  2226. protected function normalizePurchaseOrderWritePayload(array $data, array $row = []): array
  2227. {
  2228. $this->ensurePurchaseOrderCzlyqColumn();
  2229. $cz = '';
  2230. foreach (['czlyq', 'CZLYQ'] as $k) {
  2231. if (isset($data[$k]) && trim((string)$data[$k]) !== '') {
  2232. $cz = trim((string)$data[$k]);
  2233. break;
  2234. }
  2235. if (isset($row[$k]) && trim((string)$row[$k]) !== '') {
  2236. $cz = trim((string)$row[$k]);
  2237. break;
  2238. }
  2239. }
  2240. if ($cz === '') {
  2241. $ccydh = trim((string)($data['CCYDH'] ?? $row['CCYDH'] ?? ''));
  2242. if ($ccydh !== '') {
  2243. try {
  2244. $fromMcyd = Db::table('mcyd')->where('CCYDH', $ccydh)->value('czlyq');
  2245. $cz = trim((string)$fromMcyd);
  2246. } catch (\Throwable $e) {
  2247. $cz = '';
  2248. }
  2249. }
  2250. }
  2251. $data['czlyq'] = $cz;
  2252. // 显式 NULL 的字符串 NOT NULL 列改为空串
  2253. foreach (['czlyq', 'notify_salesman', 'manual_pick_reason', 'score_rule_name'] as $col) {
  2254. if (!array_key_exists($col, $data)) {
  2255. continue;
  2256. }
  2257. if ($data[$col] === null || !is_scalar($data[$col])) {
  2258. $data[$col] = '';
  2259. } else {
  2260. $data[$col] = (string)$data[$col];
  2261. }
  2262. }
  2263. foreach (['rfq_salesman_notified', 'manual_pick', 'score_rule_id', 'score_quality_weight', 'score_price_weight', 'score_lead_weight'] as $col) {
  2264. if (array_key_exists($col, $data) && $data[$col] === null) {
  2265. $data[$col] = 0;
  2266. }
  2267. }
  2268. return $data;
  2269. }
  2270. /**
  2271. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  2272. *
  2273. * @return array{po:?array<string,mixed>, hidden:bool}
  2274. */
  2275. protected function resolvePickRowPoContext(int $sid): array
  2276. {
  2277. $po = null;
  2278. try {
  2279. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2280. if (is_array($found)) {
  2281. $po = $found;
  2282. }
  2283. } catch (\Throwable $e) {
  2284. }
  2285. $hideSet = $this->loadPickHiddenScydgySet();
  2286. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  2287. }
  2288. /**
  2289. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  2290. */
  2291. protected function assertPickRowCanDelete(int $sid, array $row): void
  2292. {
  2293. $ctx = $this->resolvePickRowPoContext($sid);
  2294. $po = $ctx['po'];
  2295. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2296. return;
  2297. }
  2298. if (is_array($po)) {
  2299. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2300. throw new \InvalidArgumentException('该工序已完结,无法删除');
  2301. }
  2302. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2303. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  2304. }
  2305. }
  2306. if ($ctx['hidden']) {
  2307. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2308. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  2309. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  2310. }
  2311. }
  2312. /**
  2313. * 初选直接完结前校验
  2314. */
  2315. protected function assertPickRowCanComplete(int $sid, array $row): void
  2316. {
  2317. $ctx = $this->resolvePickRowPoContext($sid);
  2318. $po = $ctx['po'];
  2319. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2320. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  2321. }
  2322. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2323. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  2324. }
  2325. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  2326. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  2327. }
  2328. }
  2329. /**
  2330. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  2331. */
  2332. protected function softDeleteProcuremenPickRow(array $row): void
  2333. {
  2334. $sid = $this->extractScydgyRowId($row);
  2335. if (!$this->isValidScydgyRowId($sid)) {
  2336. throw new \InvalidArgumentException('无效的行主键');
  2337. }
  2338. $this->assertPickRowCanDelete($sid, $row);
  2339. $po = $this->resolvePickRowPoContext($sid)['po'];
  2340. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2341. return;
  2342. }
  2343. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2344. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  2345. }
  2346. $now = date('Y-m-d H:i:s');
  2347. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2348. if (is_array($exists)) {
  2349. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  2350. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  2351. } else {
  2352. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  2353. $data['mod_rq'] = $now;
  2354. $data['createtime'] = $now;
  2355. Db::table('purchase_order')->insert($data);
  2356. $poIdLog = (int)Db::getLastInsID();
  2357. }
  2358. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  2359. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  2360. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  2361. if ($gymcLog !== '') {
  2362. $logTail .= ' / ' . $gymcLog;
  2363. }
  2364. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  2365. }
  2366. /**
  2367. * 手工新增协助工序(写入 purchase_order)
  2368. *
  2369. * @param array<string, mixed> $params
  2370. * @return int scydgy_id
  2371. */
  2372. protected function saveManualPickOrder(array $params): int
  2373. {
  2374. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  2375. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  2376. $ccydhIn = trim((string)($params['CCYDH'] ?? ''));
  2377. $lockName = 'procuremen_manual_order_alloc';
  2378. if (!$this->acquireProcuremenNamedLock($lockName, 10)) {
  2379. throw new \RuntimeException('系统繁忙,请稍后重试');
  2380. }
  2381. try {
  2382. $ccydh = $ccydhIn !== '' ? $ccydhIn : $this->allocateManualOrderCcydh();
  2383. $now = date('Y-m-d H:i:s');
  2384. $sid = $this->allocateManualScydgyId();
  2385. $this->ensurePurchaseOrderNotifySalesmanColumn();
  2386. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  2387. // 选择供应商 / 通知业务员:支持多选,落库用顿号拼接
  2388. $supplierName = $this->joinRfqMultiSelectValues($params['cGzzxMc'] ?? ($params['pick_company_name'] ?? ''));
  2389. $notifySalesman = $this->joinRfqMultiSelectValues($params['notify_salesman'] ?? '');
  2390. $data = [
  2391. 'scydgy_id' => $sid,
  2392. 'CCYDH' => $ccydh,
  2393. 'CYJMC' => $cyjmc,
  2394. 'CGYMC' => $cgymc,
  2395. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  2396. 'CDW' => trim((string)($params['CDW'] ?? '')),
  2397. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  2398. 'CDF' => trim((string)($params['CDF'] ?? '')),
  2399. 'cGzzxMc' => $supplierName,
  2400. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  2401. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  2402. 'notify_salesman' => $notifySalesman,
  2403. 'rfq_salesman_notified' => 0,
  2404. 'rfq_salesman_notify_time' => null,
  2405. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  2406. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  2407. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  2408. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  2409. 'createtime' => $now,
  2410. 'dStamp' => $now,
  2411. 'dputrecord' => $now,
  2412. ];
  2413. Db::table('purchase_order')->insert($data);
  2414. $poId = (int)Db::getLastInsID();
  2415. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  2416. return $sid;
  2417. } finally {
  2418. $this->releaseProcuremenNamedLock($lockName);
  2419. }
  2420. }
  2421. protected function formatProcuremenRowLabel(array $row): string
  2422. {
  2423. $dh = trim((string)($row['CCYDH'] ?? ''));
  2424. $gymc = trim((string)($row['CGYMC'] ?? ''));
  2425. if ($dh !== '' && $gymc !== '') {
  2426. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  2427. }
  2428. if ($dh !== '') {
  2429. return '订单「' . $dh . '」';
  2430. }
  2431. if ($gymc !== '') {
  2432. return '工序「' . $gymc . '」';
  2433. }
  2434. $id = $this->extractScydgyRowId($row);
  2435. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  2436. }
  2437. /**
  2438. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  2439. */
  2440. protected function extractScydgyRowId(array $row): int
  2441. {
  2442. // 优先 scydgy_id,避免明细行 ID(自增主键)被误当成工序主键;手工单为负数
  2443. if (array_key_exists('scydgy_id', $row) && $row['scydgy_id'] !== null && $row['scydgy_id'] !== '') {
  2444. return (int)$row['scydgy_id'];
  2445. }
  2446. if (array_key_exists('SCYDGY_ID', $row) && $row['SCYDGY_ID'] !== null && $row['SCYDGY_ID'] !== '') {
  2447. return (int)$row['SCYDGY_ID'];
  2448. }
  2449. return (int)($row['ID'] ?? $row['id'] ?? 0);
  2450. }
  2451. protected function isValidScydgyRowId(int $id): bool
  2452. {
  2453. return ProcuremenGuard::isValidScydgyId($id);
  2454. }
  2455. protected function isManualScydgyRowId(int $id): bool
  2456. {
  2457. return $id < 0;
  2458. }
  2459. /**
  2460. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  2461. *
  2462. * @param int[] $scydgyIds
  2463. * @return array<int, string[]>
  2464. */
  2465. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  2466. {
  2467. $out = [];
  2468. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2469. if ($scydgyIds === []) {
  2470. return $out;
  2471. }
  2472. try {
  2473. $rows = Db::table('purchase_order_detail')
  2474. ->where('scydgy_id', 'in', $scydgyIds)
  2475. ->field('scydgy_id,company_name')
  2476. ->order('company_name', 'asc')
  2477. ->select();
  2478. } catch (\Throwable $e) {
  2479. $rows = [];
  2480. }
  2481. if (!is_array($rows)) {
  2482. return $out;
  2483. }
  2484. foreach ($rows as $r) {
  2485. if (!is_array($r)) {
  2486. continue;
  2487. }
  2488. $sid = (int)($r['scydgy_id'] ?? 0);
  2489. $cn = trim((string)($r['company_name'] ?? ''));
  2490. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2491. continue;
  2492. }
  2493. if (!isset($out[$sid])) {
  2494. $out[$sid] = [];
  2495. }
  2496. if (!in_array($cn, $out[$sid], true)) {
  2497. $out[$sid][] = $cn;
  2498. }
  2499. }
  2500. return $out;
  2501. }
  2502. /**
  2503. * 列表展示通知供应商(完整列表,前端单行省略展开)
  2504. *
  2505. * @param string[] $names
  2506. */
  2507. protected function formatNotifySupplierDisplay(array $names): string
  2508. {
  2509. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  2510. return trim((string)$n);
  2511. }, $names))));
  2512. if ($names === []) {
  2513. return '';
  2514. }
  2515. sort($names, SORT_STRING);
  2516. return implode("\n", $names);
  2517. }
  2518. /**
  2519. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  2520. *
  2521. * @param int[] $scydgyIds
  2522. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  2523. */
  2524. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  2525. {
  2526. $out = [];
  2527. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2528. if ($scydgyIds === []) {
  2529. return $out;
  2530. }
  2531. try {
  2532. $rows = Db::table('purchase_order_detail')
  2533. ->where('scydgy_id', 'in', $scydgyIds)
  2534. ->field('scydgy_id,company_name,amount')
  2535. ->select();
  2536. } catch (\Throwable $e) {
  2537. $rows = [];
  2538. }
  2539. if (!is_array($rows)) {
  2540. return $out;
  2541. }
  2542. foreach ($rows as $r) {
  2543. if (!is_array($r)) {
  2544. continue;
  2545. }
  2546. $sid = (int)($r['scydgy_id'] ?? 0);
  2547. $cn = trim((string)($r['company_name'] ?? ''));
  2548. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2549. continue;
  2550. }
  2551. if (!isset($out[$sid])) {
  2552. $out[$sid] = ['all' => [], 'quoted' => []];
  2553. }
  2554. $out[$sid]['all'][$cn] = true;
  2555. $am = trim((string)($r['amount'] ?? ''));
  2556. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2557. $out[$sid]['quoted'][$cn] = true;
  2558. }
  2559. }
  2560. return $out;
  2561. }
  2562. /**
  2563. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  2564. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  2565. */
  2566. protected function mergeQuotedSupplierBuckets(array $buckets): array
  2567. {
  2568. $merged = ['all' => [], 'quoted' => []];
  2569. foreach ($buckets as $b) {
  2570. if (!is_array($b)) {
  2571. continue;
  2572. }
  2573. foreach ($b['all'] ?? [] as $cn => $_) {
  2574. $merged['all'][$cn] = true;
  2575. }
  2576. foreach ($b['quoted'] ?? [] as $cn => $_) {
  2577. $merged['quoted'][$cn] = true;
  2578. }
  2579. }
  2580. return $merged;
  2581. }
  2582. /**
  2583. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  2584. */
  2585. protected function formatQuotedSupplierLines(array $bucket): string
  2586. {
  2587. $all = array_keys($bucket['all'] ?? []);
  2588. if ($all === []) {
  2589. return '';
  2590. }
  2591. sort($all, SORT_STRING);
  2592. $lines = [];
  2593. foreach ($all as $cn) {
  2594. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  2595. $lines[] = $cn . '(' . $status . ')';
  2596. }
  2597. return implode("\n", $lines);
  2598. }
  2599. /**
  2600. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  2601. */
  2602. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  2603. {
  2604. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2605. $this->view->engine->layout(false);
  2606. try {
  2607. $bodyHtml = $this->view->fetch($view);
  2608. $this->view->assign('dialogBody', $bodyHtml);
  2609. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  2610. return $this->view->fetch('procuremen/dialog_lite_shell');
  2611. } finally {
  2612. if ($restoreLayout) {
  2613. $this->view->engine->layout($restoreLayout);
  2614. }
  2615. }
  2616. }
  2617. /**
  2618. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  2619. */
  2620. protected function resolveBundleSysRq(array $bundle): string
  2621. {
  2622. foreach ($bundle['pos'] ?? [] as $po) {
  2623. if (!is_array($po)) {
  2624. continue;
  2625. }
  2626. $sr = trim((string)($po['sys_rq'] ?? ''));
  2627. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  2628. return $sr;
  2629. }
  2630. }
  2631. return '';
  2632. }
  2633. /**
  2634. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  2635. */
  2636. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  2637. {
  2638. $raw = trim((string)$sysRq);
  2639. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  2640. return true;
  2641. }
  2642. $ts = strtotime(str_replace('T', ' ', $raw));
  2643. if ($ts === false || $ts <= 0) {
  2644. return true;
  2645. }
  2646. return time() >= $ts;
  2647. }
  2648. /**
  2649. * 开标前校验:必须已过报价截止时间
  2650. *
  2651. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2652. */
  2653. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  2654. {
  2655. $sysRq = $this->resolveBundleSysRq($bundle);
  2656. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  2657. $this->error('未到招标截止日期');
  2658. }
  2659. }
  2660. /**
  2661. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  2662. *
  2663. * @param array<string, mixed> $d
  2664. * @param string $deliveryYmd
  2665. */
  2666. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  2667. {
  2668. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  2669. return max(0, (int)$d['lead_days']);
  2670. }
  2671. if ($deliveryYmd === '') {
  2672. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  2673. }
  2674. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  2675. return null;
  2676. }
  2677. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2678. $t2 = strtotime($m[1] . ' 00:00:00');
  2679. if ($t1 === false || $t2 === false) {
  2680. return null;
  2681. }
  2682. return max(0, (int)round(($t2 - $t1) / 86400));
  2683. }
  2684. /**
  2685. * @param int|null $days
  2686. */
  2687. protected function formatProcuremenLeadDaysText($days): string
  2688. {
  2689. if ($days === null || $days === '') {
  2690. return '未填写';
  2691. }
  2692. if (!is_numeric($days)) {
  2693. return '未填写';
  2694. }
  2695. return ((int)$days) . '天';
  2696. }
  2697. /**
  2698. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2699. *
  2700. * @param array<string, mixed> $line
  2701. */
  2702. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2703. {
  2704. $amountFilled = !empty($line['amount_filled']);
  2705. $deliveryFilled = !empty($line['delivery_filled']);
  2706. $leadFilled = !empty($line['lead_days_filled']);
  2707. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2708. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2709. $line['amount_show'] = '';
  2710. if (array_key_exists('amount_text', $line)) {
  2711. $line['amount_text'] = $line['unit_price_text'];
  2712. }
  2713. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2714. $line['delivery_show'] = $deliveryText;
  2715. if (array_key_exists('delivery_text', $line)) {
  2716. $line['delivery_text'] = $deliveryText;
  2717. }
  2718. $line['delivery_ymd'] = '';
  2719. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2720. $line['lead_days_show'] = $leadText;
  2721. $line['lead_days_text'] = $leadText;
  2722. $line['lead_days'] = '';
  2723. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2724. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2725. $line['subtotal_num'] = null;
  2726. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2727. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2728. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2729. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2730. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2731. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2732. $line['amount_filled'] = false;
  2733. $line['delivery_filled'] = false;
  2734. $line['lead_days_filled'] = false;
  2735. $line['is_quoted'] = false;
  2736. if (array_key_exists('quote_label', $line)) {
  2737. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2738. }
  2739. }
  2740. protected function ensurePurchaseOrderBidOpenTable(): void
  2741. {
  2742. static $ready = false;
  2743. if ($ready) {
  2744. return;
  2745. }
  2746. $cacheKey = 'procuremen_bid_open_table_ok_v1';
  2747. try {
  2748. if (Cache::get($cacheKey)) {
  2749. $ready = true;
  2750. return;
  2751. }
  2752. } catch (\Throwable $e) {
  2753. }
  2754. try {
  2755. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2756. $ready = true;
  2757. try {
  2758. Cache::set($cacheKey, 1, 86400);
  2759. } catch (\Throwable $e) {
  2760. }
  2761. } catch (\Throwable $e) {
  2762. Db::execute(
  2763. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2764. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2765. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2766. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2767. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2768. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2769. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2770. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2771. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2772. `createtime` datetime DEFAULT NULL,
  2773. PRIMARY KEY (`id`),
  2774. UNIQUE KEY `uk_ccydh` (`ccydh`)
  2775. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2776. );
  2777. $ready = true;
  2778. try {
  2779. Cache::set($cacheKey, 1, 86400);
  2780. } catch (\Throwable $e2) {
  2781. }
  2782. }
  2783. }
  2784. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  2785. {
  2786. $ccydh = trim($ccydh);
  2787. if ($ccydh === '') {
  2788. return false;
  2789. }
  2790. $this->ensurePurchaseOrderBidOpenTable();
  2791. try {
  2792. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2793. return is_array($row);
  2794. } catch (\Throwable $e) {
  2795. return false;
  2796. }
  2797. }
  2798. /**
  2799. * 批量查询订单是否已开标验证
  2800. *
  2801. * @param array<int, string> $ccydhs
  2802. * @return array<string, bool> ccydh => true
  2803. */
  2804. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  2805. {
  2806. $set = [];
  2807. $list = [];
  2808. foreach ($ccydhs as $c) {
  2809. $c = trim((string)$c);
  2810. if ($c !== '') {
  2811. $list[$c] = true;
  2812. }
  2813. }
  2814. if ($list === []) {
  2815. return $set;
  2816. }
  2817. $this->ensurePurchaseOrderBidOpenTable();
  2818. try {
  2819. $rows = Db::table('purchase_order_bid_open')
  2820. ->where('ccydh', 'in', array_keys($list))
  2821. ->field('ccydh')
  2822. ->select();
  2823. foreach ($rows as $row) {
  2824. if (!is_array($row)) {
  2825. continue;
  2826. }
  2827. $c = trim((string)($row['ccydh'] ?? ''));
  2828. if ($c !== '') {
  2829. $set[$c] = true;
  2830. }
  2831. }
  2832. } catch (\Throwable $e) {
  2833. return [];
  2834. }
  2835. return $set;
  2836. }
  2837. /**
  2838. * 批量查询订单是否已指定供应商(免开标)
  2839. *
  2840. * @param array<int, string> $ccydhs
  2841. * @return array<string, bool> ccydh => true
  2842. */
  2843. protected function loadProcuremenManualPickedCcydhSet(array $ccydhs): array
  2844. {
  2845. $set = [];
  2846. $list = [];
  2847. foreach ($ccydhs as $c) {
  2848. $c = trim((string)$c);
  2849. if ($c !== '') {
  2850. $list[$c] = true;
  2851. }
  2852. }
  2853. if ($list === []) {
  2854. return $set;
  2855. }
  2856. $this->ensurePurchaseOrderManualPickColumns();
  2857. try {
  2858. $rows = Db::table('purchase_order')
  2859. ->where('CCYDH', 'in', array_keys($list))
  2860. ->where('manual_pick', 1)
  2861. ->field('CCYDH')
  2862. ->select();
  2863. foreach ($rows as $row) {
  2864. if (!is_array($row)) {
  2865. continue;
  2866. }
  2867. $c = trim((string)($row['CCYDH'] ?? ''));
  2868. if ($c !== '') {
  2869. $set[$c] = true;
  2870. }
  2871. }
  2872. } catch (\Throwable $e) {
  2873. return [];
  2874. }
  2875. return $set;
  2876. }
  2877. /**
  2878. * 确认供应商列表:按开标状态筛选(已开标 / 已指定供应商 / 待开标)
  2879. *
  2880. * @param array<int, array<string, mixed>> $pool
  2881. * @return array<int, array<string, mixed>>
  2882. */
  2883. protected function filterProcuremenPoolByBidOpenStatus(array $pool, string $status): array
  2884. {
  2885. $status = trim($status);
  2886. if ($status === '' || !in_array($status, ['待开标', '已开标', '已指定供应商'], true)) {
  2887. return $pool;
  2888. }
  2889. $ccydhList = [];
  2890. foreach ($pool as $rw) {
  2891. if (!is_array($rw)) {
  2892. continue;
  2893. }
  2894. $c = trim((string)($rw['CCYDH'] ?? ''));
  2895. if ($c !== '') {
  2896. $ccydhList[] = $c;
  2897. }
  2898. }
  2899. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  2900. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  2901. $out = [];
  2902. foreach ($pool as $rw) {
  2903. if (!is_array($rw)) {
  2904. continue;
  2905. }
  2906. $c = trim((string)($rw['CCYDH'] ?? ''));
  2907. if ($c !== '' && isset($bidOpenSet[$c])) {
  2908. $t = '已开标';
  2909. } elseif ($c !== '' && isset($manualPickSet[$c])) {
  2910. $t = '已指定供应商';
  2911. } else {
  2912. $t = '待开标';
  2913. }
  2914. if ($t === $status) {
  2915. $out[] = $rw;
  2916. }
  2917. }
  2918. return $out;
  2919. }
  2920. /**
  2921. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  2922. *
  2923. * @param array<string, mixed> $group
  2924. */
  2925. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  2926. {
  2927. if ($quoteVisible) {
  2928. $group['remark_quote_pending'] = 0;
  2929. return;
  2930. }
  2931. $group['remark'] = '';
  2932. $group['remark_quote_pending'] = 0;
  2933. }
  2934. /**
  2935. * @param array{ccydh?:string} $bundle
  2936. */
  2937. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  2938. {
  2939. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  2940. }
  2941. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  2942. {
  2943. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  2944. return true;
  2945. }
  2946. return $this->isProcuremenManualPickedForBundle($bundle);
  2947. }
  2948. /**
  2949. * 确保 purchase_order 自选供应商字段
  2950. */
  2951. protected function ensurePurchaseOrderManualPickColumns(): void
  2952. {
  2953. static $done = false;
  2954. if ($done) {
  2955. return;
  2956. }
  2957. $done = true;
  2958. $adds = [
  2959. 'manual_pick' => "ADD COLUMN `manual_pick` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=自选供应商(免开标)' AFTER `pick_company_name`",
  2960. 'manual_pick_reason' => "ADD COLUMN `manual_pick_reason` varchar(500) NOT NULL DEFAULT '' COMMENT '自选供应商选择说明' AFTER `manual_pick`",
  2961. ];
  2962. foreach ($adds as $col => $ddl) {
  2963. try {
  2964. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  2965. if (!is_array($cols) || $cols === []) {
  2966. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  2967. }
  2968. } catch (\Throwable $e) {
  2969. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  2970. }
  2971. }
  2972. }
  2973. /**
  2974. * 是否已自选供应商(免开标查看报价)
  2975. *
  2976. * @param array{pos?:array} $bundle
  2977. */
  2978. protected function isProcuremenManualPickedForBundle(array $bundle): bool
  2979. {
  2980. $this->ensurePurchaseOrderManualPickColumns();
  2981. foreach ($bundle['pos'] ?? [] as $poRow) {
  2982. if (!is_array($poRow)) {
  2983. continue;
  2984. }
  2985. if ((int)($poRow['manual_pick'] ?? 0) === 1) {
  2986. return true;
  2987. }
  2988. }
  2989. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2990. if ($ccydh === '') {
  2991. return false;
  2992. }
  2993. try {
  2994. $v = Db::table('purchase_order')->where('CCYDH', $ccydh)->where('manual_pick', 1)->value('id');
  2995. return $v !== null && $v !== false && (int)$v > 0;
  2996. } catch (\Throwable $e) {
  2997. return false;
  2998. }
  2999. }
  3000. /**
  3001. * @param array{pos?:array} $bundle
  3002. * @return array{company:string,reason:string}
  3003. */
  3004. protected function resolveProcuremenManualPickInfo(array $bundle): array
  3005. {
  3006. $this->ensurePurchaseOrderManualPickColumns();
  3007. foreach ($bundle['pos'] ?? [] as $poRow) {
  3008. if (!is_array($poRow)) {
  3009. continue;
  3010. }
  3011. if ((int)($poRow['manual_pick'] ?? 0) !== 1) {
  3012. continue;
  3013. }
  3014. $cn = trim((string)($poRow['pick_company_name'] ?? ''));
  3015. $reason = trim((string)($poRow['manual_pick_reason'] ?? ''));
  3016. return ['company' => $cn, 'reason' => $reason];
  3017. }
  3018. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3019. if ($ccydh === '') {
  3020. return ['company' => '', 'reason' => ''];
  3021. }
  3022. try {
  3023. $row = Db::table('purchase_order')
  3024. ->where('CCYDH', $ccydh)
  3025. ->where('manual_pick', 1)
  3026. ->field('pick_company_name,manual_pick_reason')
  3027. ->order('id', 'asc')
  3028. ->find();
  3029. } catch (\Throwable $e) {
  3030. $row = null;
  3031. }
  3032. if (!is_array($row)) {
  3033. return ['company' => '', 'reason' => ''];
  3034. }
  3035. return [
  3036. 'company' => trim((string)($row['pick_company_name'] ?? '')),
  3037. 'reason' => trim((string)($row['manual_pick_reason'] ?? '')),
  3038. ];
  3039. }
  3040. protected function loadBidOpenAdminUser(int $adminId): ?array
  3041. {
  3042. if ($adminId <= 0) {
  3043. return null;
  3044. }
  3045. try {
  3046. $row = Db::name('admin')->where('id', $adminId)->find();
  3047. } catch (\Throwable $e) {
  3048. return null;
  3049. }
  3050. if (!is_array($row)) {
  3051. return null;
  3052. }
  3053. $status = strtolower(trim((string)($row['status'] ?? '')));
  3054. if ($status !== '' && $status !== 'normal') {
  3055. return null;
  3056. }
  3057. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  3058. return null;
  3059. }
  3060. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  3061. if (!preg_match('/^1\d{10}$/', $phone)) {
  3062. return null;
  3063. }
  3064. $name = trim((string)($row['nickname'] ?? ''));
  3065. if ($name === '') {
  3066. $name = trim((string)($row['username'] ?? ''));
  3067. }
  3068. return [
  3069. 'id' => (int)$row['id'],
  3070. 'username' => trim((string)($row['username'] ?? '')),
  3071. 'nickname' => $name,
  3072. 'mobile' => $phone,
  3073. ];
  3074. }
  3075. /**
  3076. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  3077. */
  3078. protected function bidOpenVerifierAuthGroupRootId(): int
  3079. {
  3080. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  3081. return $id > 0 ? $id : 10;
  3082. }
  3083. /**
  3084. * @return int[]
  3085. */
  3086. protected function loadBidOpenVerifierAuthGroupIds(): array
  3087. {
  3088. static $memo = [];
  3089. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  3090. if (isset($memo[$rootId])) {
  3091. return $memo[$rootId];
  3092. }
  3093. try {
  3094. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  3095. } catch (\Throwable $e) {
  3096. $memo[$rootId] = [$rootId];
  3097. return $memo[$rootId];
  3098. }
  3099. if (!is_array($groups) || $groups === []) {
  3100. $memo[$rootId] = [$rootId];
  3101. return $memo[$rootId];
  3102. }
  3103. $groupList = [];
  3104. foreach ($groups as $g) {
  3105. if (is_array($g)) {
  3106. $groupList[] = $g;
  3107. }
  3108. }
  3109. if ($groupList === []) {
  3110. $memo[$rootId] = [$rootId];
  3111. return $memo[$rootId];
  3112. }
  3113. $tree = \fast\Tree::instance();
  3114. $tree->init($groupList);
  3115. $ids = $tree->getChildrenIds($rootId, true);
  3116. if (!is_array($ids) || $ids === []) {
  3117. $memo[$rootId] = [$rootId];
  3118. return $memo[$rootId];
  3119. }
  3120. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  3121. return $memo[$rootId];
  3122. }
  3123. protected function isBidOpenVerifierAdmin(int $adminId): bool
  3124. {
  3125. if ($adminId <= 0) {
  3126. return false;
  3127. }
  3128. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3129. if ($groupIds === []) {
  3130. return false;
  3131. }
  3132. try {
  3133. return (bool)Db::name('auth_group_access')
  3134. ->where('uid', $adminId)
  3135. ->where('group_id', 'in', $groupIds)
  3136. ->count();
  3137. } catch (\Throwable $e) {
  3138. return false;
  3139. }
  3140. }
  3141. /**
  3142. * @return array<int, array<string, mixed>>
  3143. */
  3144. protected function listBidOpenVerifierCandidates(): array
  3145. {
  3146. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3147. if ($groupIds === []) {
  3148. return [];
  3149. }
  3150. try {
  3151. $adminIds = Db::name('auth_group_access')
  3152. ->where('group_id', 'in', $groupIds)
  3153. ->column('uid');
  3154. } catch (\Throwable $e) {
  3155. $adminIds = [];
  3156. }
  3157. $adminIds = is_array($adminIds)
  3158. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  3159. : [];
  3160. if ($adminIds === []) {
  3161. return [];
  3162. }
  3163. try {
  3164. $rows = Db::name('admin')
  3165. ->where('status', 'normal')
  3166. ->where('id', 'in', $adminIds)
  3167. ->where('mobile', '<>', '')
  3168. ->order('id', 'asc')
  3169. ->select();
  3170. } catch (\Throwable $e) {
  3171. return [];
  3172. }
  3173. if (!is_array($rows)) {
  3174. return [];
  3175. }
  3176. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  3177. $out = [];
  3178. foreach ($rows as $row) {
  3179. if (!is_array($row)) {
  3180. continue;
  3181. }
  3182. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  3183. if ($one === null) {
  3184. continue;
  3185. }
  3186. $out[] = [
  3187. 'id' => $one['id'],
  3188. 'username' => $one['username'],
  3189. 'nickname' => $one['nickname'],
  3190. 'group_name' => $groupNameMap[$one['id']] ?? '',
  3191. 'mobile' => mask_phone($one['mobile']),
  3192. 'mobile_plain' => (string)$one['mobile'],
  3193. ];
  3194. }
  3195. return $out;
  3196. }
  3197. /**
  3198. * @param int[] $adminIds
  3199. * @return array<int, string>
  3200. */
  3201. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  3202. {
  3203. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  3204. if ($adminIds === []) {
  3205. return [];
  3206. }
  3207. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3208. try {
  3209. $rows = Db::name('auth_group_access')
  3210. ->alias('aga')
  3211. ->join('auth_group ag', 'aga.group_id = ag.id')
  3212. ->where('aga.uid', 'in', $adminIds)
  3213. ->where('aga.group_id', 'in', $groupIds)
  3214. ->field('aga.uid,ag.name')
  3215. ->order('aga.uid', 'asc')
  3216. ->order('aga.group_id', 'asc')
  3217. ->select();
  3218. } catch (\Throwable $e) {
  3219. return [];
  3220. }
  3221. if (!is_array($rows)) {
  3222. return [];
  3223. }
  3224. $out = [];
  3225. foreach ($rows as $row) {
  3226. if (!is_array($row)) {
  3227. continue;
  3228. }
  3229. $uid = (int)($row['uid'] ?? 0);
  3230. $name = trim((string)($row['name'] ?? ''));
  3231. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  3232. continue;
  3233. }
  3234. $out[$uid] = $name;
  3235. }
  3236. return $out;
  3237. }
  3238. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  3239. {
  3240. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  3241. }
  3242. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  3243. {
  3244. return 'procuremen_bidopen_wait_' . $adminId;
  3245. }
  3246. protected function renderBidOpenVerifySms(string $code): string
  3247. {
  3248. $tpl = '';
  3249. try {
  3250. $row = $this->loadNotifyTemplateRow('bid_open');
  3251. if (is_array($row)) {
  3252. $tpl = trim((string)($row['content'] ?? ''));
  3253. }
  3254. } catch (\Throwable $e) {
  3255. $tpl = '';
  3256. }
  3257. if ($tpl === '') {
  3258. $tpl = '【可集达】您的短信验证码是{code}';
  3259. }
  3260. return str_replace('{code}', $code, $tpl);
  3261. }
  3262. protected function sendBidOpenVerifySms(string $phone, string $code): void
  3263. {
  3264. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  3265. }
  3266. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  3267. {
  3268. $code = trim($code);
  3269. if (!preg_match('/^\d{6}$/', $code)) {
  3270. return false;
  3271. }
  3272. $mock = Config::get('mproc.mock_sms_code');
  3273. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3274. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3275. return true;
  3276. }
  3277. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3278. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3279. return false;
  3280. }
  3281. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3282. return true;
  3283. }
  3284. /**
  3285. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3286. */
  3287. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  3288. {
  3289. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3290. if ($ccydh === '') {
  3291. throw new \InvalidArgumentException('订单号无效');
  3292. }
  3293. $this->ensurePurchaseOrderBidOpenTable();
  3294. list($operatorId, $operatorName) = $this->GetUseName();
  3295. $now = date('Y-m-d H:i:s');
  3296. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3297. $payload = [
  3298. 'ccydh' => $ccydh,
  3299. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  3300. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  3301. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  3302. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  3303. 'operator_id' => (int)$operatorId,
  3304. 'operator_name' => trim((string)$operatorName),
  3305. 'createtime' => $now,
  3306. ];
  3307. if (is_array($exists)) {
  3308. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  3309. } else {
  3310. Db::table('purchase_order_bid_open')->insert($payload);
  3311. }
  3312. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  3313. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  3314. $labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
  3315. (int)$payload['verifier1_id'],
  3316. (int)$payload['verifier2_id'],
  3317. ]);
  3318. if (isset($labelMap[(int)$payload['verifier1_id']]) && (int)$payload['verifier1_id'] > 0) {
  3319. $name1 = $labelMap[(int)$payload['verifier1_id']];
  3320. }
  3321. if (isset($labelMap[(int)$payload['verifier2_id']]) && (int)$payload['verifier2_id'] > 0) {
  3322. $name2 = $labelMap[(int)$payload['verifier2_id']];
  3323. }
  3324. $logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
  3325. $seenSid = [];
  3326. foreach ($bundle['pos'] ?? [] as $poRow) {
  3327. if (!is_array($poRow)) {
  3328. continue;
  3329. }
  3330. $sid = (int)($poRow['scydgy_id'] ?? 0);
  3331. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  3332. continue;
  3333. }
  3334. $seenSid[$sid] = true;
  3335. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  3336. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  3337. }
  3338. if ($seenSid === []) {
  3339. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  3340. if ($this->isValidScydgyRowId($anchor)) {
  3341. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  3342. }
  3343. }
  3344. // 开标通过后计算并写入供应商服务评分
  3345. try {
  3346. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  3347. ProcuremenSupplierScore::saveForOrder($ccydh, $quoteGroups, date('Y-m', strtotime($now) ?: time()));
  3348. } catch (\Throwable $e) {
  3349. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  3350. }
  3351. }
  3352. /**
  3353. * 报价行展示字段默认值(模板安全访问)
  3354. *
  3355. * @param array<string, mixed> $line
  3356. * @return array<string, mixed>
  3357. */
  3358. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  3359. {
  3360. if (!array_key_exists('amount_quote_pending', $line)) {
  3361. $line['amount_quote_pending'] = 0;
  3362. }
  3363. if (!array_key_exists('delivery_quote_pending', $line)) {
  3364. $line['delivery_quote_pending'] = 0;
  3365. }
  3366. if (!array_key_exists('quote_before_deadline', $line)) {
  3367. $line['quote_before_deadline'] = 0;
  3368. }
  3369. if (!array_key_exists('amount_filled', $line)) {
  3370. $line['amount_filled'] = 0;
  3371. }
  3372. if (!array_key_exists('delivery_filled', $line)) {
  3373. $line['delivery_filled'] = 0;
  3374. }
  3375. if (!array_key_exists('lead_days_filled', $line)) {
  3376. $line['lead_days_filled'] = 0;
  3377. }
  3378. if (!array_key_exists('lead_days_quote_pending', $line)) {
  3379. $line['lead_days_quote_pending'] = 0;
  3380. }
  3381. if (!array_key_exists('lead_days_show', $line)) {
  3382. $line['lead_days_show'] = '未填写';
  3383. }
  3384. if (!array_key_exists('lead_days_text', $line)) {
  3385. $line['lead_days_text'] = $line['lead_days_show'];
  3386. }
  3387. return $line;
  3388. }
  3389. /**
  3390. * 审核弹窗:按供应商汇总报价明细
  3391. *
  3392. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3393. * @return array<int, array<string, mixed>>
  3394. */
  3395. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  3396. {
  3397. $sids = [];
  3398. foreach ($bundle['pos'] ?? [] as $po) {
  3399. if (!is_array($po)) {
  3400. continue;
  3401. }
  3402. $sid = (int)($po['scydgy_id'] ?? 0);
  3403. if ($this->isValidScydgyRowId($sid)) {
  3404. $sids[$sid] = true;
  3405. }
  3406. }
  3407. if ($sids === []) {
  3408. return [];
  3409. }
  3410. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3411. $gymcMap = [];
  3412. $qtyBySid = [];
  3413. $orderedSids = [];
  3414. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3415. if (!is_array($mr)) {
  3416. continue;
  3417. }
  3418. $gid = $this->extractScydgyRowId($mr);
  3419. if ($this->isValidScydgyRowId($gid)) {
  3420. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3421. $orderedSids[] = $gid;
  3422. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3423. if ($qty === '') {
  3424. $qty = trim((string)($mr['NGZL'] ?? ''));
  3425. }
  3426. $qtyBySid[$gid] = $qty;
  3427. }
  3428. }
  3429. foreach ($bundle['pos'] ?? [] as $po) {
  3430. if (!is_array($po)) {
  3431. continue;
  3432. }
  3433. $gid = (int)($po['scydgy_id'] ?? 0);
  3434. if ($this->isValidScydgyRowId($gid)) {
  3435. $nm = trim((string)($po['CGYMC'] ?? ''));
  3436. if ($nm !== '') {
  3437. $gymcMap[$gid] = $nm;
  3438. }
  3439. if (!in_array($gid, $orderedSids, true)) {
  3440. $orderedSids[] = $gid;
  3441. }
  3442. }
  3443. }
  3444. try {
  3445. $detailsQuery = Db::table('purchase_order_detail')
  3446. ->where('scydgy_id', 'in', array_keys($sids));
  3447. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3448. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  3449. } catch (\Throwable $e) {
  3450. try {
  3451. $detailsQuery = Db::table('purchase_order_detail')
  3452. ->where('scydgy_id', 'in', array_keys($sids));
  3453. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3454. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  3455. } catch (\Throwable $e2) {
  3456. $details = [];
  3457. }
  3458. }
  3459. if (!is_array($details)) {
  3460. $details = [];
  3461. }
  3462. $byCompany = [];
  3463. foreach ($details as $d) {
  3464. if (!is_array($d)) {
  3465. continue;
  3466. }
  3467. $cn = trim((string)($d['company_name'] ?? ''));
  3468. if ($cn === '') {
  3469. continue;
  3470. }
  3471. if (!isset($byCompany[$cn])) {
  3472. $ph = trim((string)($d['phone'] ?? ''));
  3473. $username = trim((string)($d['username'] ?? ''));
  3474. if ($username === '') {
  3475. $username = $this->resolveCustomerContactName($ph, $cn);
  3476. }
  3477. $byCompany[$cn] = [
  3478. 'name' => $cn,
  3479. 'email' => trim((string)($d['email'] ?? '')),
  3480. 'phone' => $ph,
  3481. 'username' => $username,
  3482. 'remark' => '',
  3483. 'has_quote' => false,
  3484. 'lines_map' => [],
  3485. ];
  3486. }
  3487. if ($byCompany[$cn]['remark'] === '') {
  3488. $rm = '';
  3489. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3490. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3491. $rm = trim((string)$d[$rk]);
  3492. break;
  3493. }
  3494. }
  3495. if ($rm !== '') {
  3496. $byCompany[$cn]['remark'] = $rm;
  3497. }
  3498. }
  3499. $sid = (int)($d['scydgy_id'] ?? 0);
  3500. $am = trim((string)($d['amount'] ?? ''));
  3501. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3502. if ($gymc === '') {
  3503. $gymc = '工序';
  3504. }
  3505. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3506. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3507. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3508. $deliveryShow = $deliveryRaw;
  3509. }
  3510. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3511. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3512. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3513. $subtotal = null;
  3514. if ($amountNum !== null) {
  3515. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3516. }
  3517. $unitPriceText = $amountFilled
  3518. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3519. : '未填写';
  3520. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3521. $leadFilled = ($leadDays !== null);
  3522. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3523. $lineRow = [
  3524. 'cgymc' => $gymc,
  3525. 'amount' => $am,
  3526. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  3527. 'amount_filled' => $amountFilled,
  3528. 'unit_price_text' => $unitPriceText,
  3529. 'delivery' => $deliveryRaw,
  3530. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  3531. 'delivery_filled' => $deliveryFilled,
  3532. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  3533. 'lead_days' => $leadFilled ? $leadDays : '',
  3534. 'lead_days_filled'=> $leadFilled,
  3535. 'lead_days_show' => $leadText,
  3536. 'lead_days_text' => $leadText,
  3537. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3538. 'subtotal_num' => $subtotal,
  3539. 'status_name' => trim((string)($d['status_name'] ?? '')),
  3540. 'is_quoted' => $amountFilled,
  3541. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  3542. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3543. ];
  3544. if (!$quoteVisible) {
  3545. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  3546. }
  3547. // 按工序 id 暂存,下面再按上方工序表顺序输出
  3548. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  3549. }
  3550. foreach ($byCompany as $cn => $g) {
  3551. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  3552. $lines = [];
  3553. $usedSids = [];
  3554. foreach ($orderedSids as $sid) {
  3555. if (!isset($linesMap[$sid])) {
  3556. continue;
  3557. }
  3558. $lines[] = $linesMap[$sid];
  3559. $usedSids[$sid] = true;
  3560. }
  3561. foreach ($linesMap as $sid => $ln) {
  3562. if (isset($usedSids[$sid])) {
  3563. continue;
  3564. }
  3565. $lines[] = $ln;
  3566. }
  3567. $total = count($lines);
  3568. $quoted = 0;
  3569. $groupTotal = 0.0;
  3570. $groupHasTotal = false;
  3571. if ($quoteVisible) {
  3572. foreach ($lines as $ln) {
  3573. $am = trim((string)($ln['amount'] ?? ''));
  3574. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  3575. $quoted++;
  3576. }
  3577. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3578. $groupTotal += (float)$ln['subtotal_num'];
  3579. $groupHasTotal = true;
  3580. }
  3581. }
  3582. }
  3583. unset($byCompany[$cn]['lines_map']);
  3584. $byCompany[$cn]['lines'] = $lines;
  3585. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  3586. $byCompany[$cn]['line_count'] = $total;
  3587. $byCompany[$cn]['has_total'] = $total > 0;
  3588. $byCompany[$cn]['has_remark'] = $total > 0;
  3589. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  3590. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3591. // 工序行 + 备注行 + 总计行
  3592. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  3593. }
  3594. $groups = array_values($byCompany);
  3595. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3596. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  3597. }
  3598. /**
  3599. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  3600. *
  3601. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3602. * @return array<int, array<string, mixed>>
  3603. */
  3604. protected function loadConfirmSupplierPickGroups(array $bundle): array
  3605. {
  3606. $sids = [];
  3607. $poIdMap = [];
  3608. foreach ($bundle['pos'] ?? [] as $po) {
  3609. if (!is_array($po)) {
  3610. continue;
  3611. }
  3612. $sid = (int)($po['scydgy_id'] ?? 0);
  3613. if ($this->isValidScydgyRowId($sid)) {
  3614. $sids[$sid] = true;
  3615. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  3616. }
  3617. }
  3618. if ($sids === []) {
  3619. return [];
  3620. }
  3621. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3622. $gymcMap = [];
  3623. $qtyBySid = [];
  3624. $orderedSids = [];
  3625. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3626. if (!is_array($mr)) {
  3627. continue;
  3628. }
  3629. $gid = $this->extractScydgyRowId($mr);
  3630. if ($this->isValidScydgyRowId($gid)) {
  3631. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3632. $orderedSids[] = $gid;
  3633. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3634. if ($qty === '') {
  3635. $qty = trim((string)($mr['NGZL'] ?? ''));
  3636. }
  3637. $qtyBySid[$gid] = $qty;
  3638. }
  3639. }
  3640. foreach ($bundle['pos'] ?? [] as $po) {
  3641. if (!is_array($po)) {
  3642. continue;
  3643. }
  3644. $gid = (int)($po['scydgy_id'] ?? 0);
  3645. if ($this->isValidScydgyRowId($gid)) {
  3646. $nm = trim((string)($po['CGYMC'] ?? ''));
  3647. if ($nm !== '') {
  3648. $gymcMap[$gid] = $nm;
  3649. }
  3650. }
  3651. }
  3652. try {
  3653. $details = Db::table('purchase_order_detail')
  3654. ->where('scydgy_id', 'in', array_keys($sids))
  3655. ->order('company_name', 'asc')
  3656. ->order('id', 'asc')
  3657. ->select();
  3658. } catch (\Throwable $e) {
  3659. try {
  3660. $details = Db::table('purchase_order_detail')
  3661. ->where('scydgy_id', 'in', array_keys($sids))
  3662. ->order('company_name', 'asc')
  3663. ->order('ID', 'asc')
  3664. ->select();
  3665. } catch (\Throwable $e2) {
  3666. $details = [];
  3667. }
  3668. }
  3669. if (!is_array($details)) {
  3670. $details = [];
  3671. }
  3672. $byCompany = [];
  3673. foreach ($details as $d) {
  3674. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3675. continue;
  3676. }
  3677. $cn = trim((string)($d['company_name'] ?? ''));
  3678. if ($cn === '') {
  3679. continue;
  3680. }
  3681. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  3682. $sid = (int)($d['scydgy_id'] ?? 0);
  3683. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  3684. continue;
  3685. }
  3686. if (!isset($byCompany[$cn])) {
  3687. $ph = trim((string)($d['phone'] ?? ''));
  3688. $username = trim((string)($d['username'] ?? ''));
  3689. if ($username === '') {
  3690. $username = $this->resolveCustomerContactName($ph, $cn);
  3691. }
  3692. $byCompany[$cn] = [
  3693. 'name' => $cn,
  3694. 'email' => trim((string)($d['email'] ?? '')),
  3695. 'phone' => $ph,
  3696. 'username' => $username,
  3697. 'remark' => '',
  3698. 'pick_lines' => [],
  3699. 'detail_picks' => [],
  3700. ];
  3701. }
  3702. if ($byCompany[$cn]['remark'] === '') {
  3703. $rm = '';
  3704. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3705. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3706. $rm = trim((string)$d[$rk]);
  3707. break;
  3708. }
  3709. }
  3710. if ($rm !== '') {
  3711. $byCompany[$cn]['remark'] = $rm;
  3712. }
  3713. }
  3714. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3715. if ($gymc === '') {
  3716. $gymc = '工序';
  3717. }
  3718. $am = trim((string)($d['amount'] ?? ''));
  3719. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3720. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3721. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3722. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3723. $deliveryShow = $deliveryRaw;
  3724. }
  3725. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3726. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3727. $subtotal = null;
  3728. if ($amountNum !== null) {
  3729. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3730. }
  3731. $unitPriceText = $amountFilled
  3732. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3733. : '未填写';
  3734. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3735. $leadFilled = ($leadDays !== null);
  3736. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3737. $pickLine = [
  3738. 'cgymc' => $gymc,
  3739. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  3740. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  3741. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  3742. 'amount_filled' => $amountFilled,
  3743. 'delivery_filled' => $deliveryFilled,
  3744. 'unit_price_text' => $unitPriceText,
  3745. 'lead_days' => $leadFilled ? $leadDays : '',
  3746. 'lead_days_filled'=> $leadFilled,
  3747. 'lead_days_show' => $leadText,
  3748. 'lead_days_text' => $leadText,
  3749. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3750. 'subtotal_num' => $subtotal,
  3751. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3752. 'is_quoted' => $amountFilled,
  3753. ];
  3754. if (!$quoteVisible) {
  3755. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  3756. }
  3757. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  3758. $byCompany[$cn]['detail_picks'][$sid] = [
  3759. 'scydgy_id' => $sid,
  3760. 'detail_id' => $detailId,
  3761. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  3762. 'cgymc' => $gymc,
  3763. ];
  3764. }
  3765. $out = [];
  3766. foreach ($byCompany as $g) {
  3767. $pickLinesMap = $g['pick_lines'] ?? [];
  3768. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  3769. continue;
  3770. }
  3771. $pickLines = [];
  3772. $usedLineSids = [];
  3773. foreach ($orderedSids as $sid) {
  3774. if (!isset($pickLinesMap[$sid])) {
  3775. continue;
  3776. }
  3777. $pickLines[] = $pickLinesMap[$sid];
  3778. $usedLineSids[$sid] = true;
  3779. }
  3780. foreach ($pickLinesMap as $sid => $ln) {
  3781. if (isset($usedLineSids[$sid])) {
  3782. continue;
  3783. }
  3784. $pickLines[] = $ln;
  3785. }
  3786. $groupTotal = 0.0;
  3787. $groupHasTotal = false;
  3788. if ($quoteVisible) {
  3789. foreach ($pickLines as $ln) {
  3790. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3791. $groupTotal += (float)$ln['subtotal_num'];
  3792. $groupHasTotal = true;
  3793. }
  3794. }
  3795. }
  3796. $lineCount = count($pickLines);
  3797. $g['pick_lines'] = $pickLines;
  3798. $g['line_count'] = $lineCount;
  3799. $g['has_total'] = $lineCount > 0;
  3800. $g['has_remark'] = $lineCount > 0;
  3801. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  3802. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3803. // 工序行 + 备注行 + 总计行
  3804. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  3805. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  3806. $detailPicks = [];
  3807. $usedPickSids = [];
  3808. foreach ($orderedSids as $sid) {
  3809. if (!isset($detailPicksMap[$sid])) {
  3810. continue;
  3811. }
  3812. $detailPicks[] = $detailPicksMap[$sid];
  3813. $usedPickSids[$sid] = true;
  3814. }
  3815. foreach ($detailPicksMap as $sid => $dp) {
  3816. if (isset($usedPickSids[$sid])) {
  3817. continue;
  3818. }
  3819. $detailPicks[] = $dp;
  3820. }
  3821. $g['detail_picks'] = $detailPicks;
  3822. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  3823. unset($g['detail_picks']);
  3824. $out[] = $g;
  3825. }
  3826. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3827. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  3828. }
  3829. /**
  3830. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  3831. * @return array<int, int[]> scydgy_id => detail_id[]
  3832. */
  3833. protected function mapDetailIdsByScydgyId(array $details): array
  3834. {
  3835. $out = [];
  3836. foreach ($details as $d) {
  3837. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3838. continue;
  3839. }
  3840. $sid = (int)($d['scydgy_id'] ?? 0);
  3841. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  3842. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  3843. continue;
  3844. }
  3845. if (!isset($out[$sid])) {
  3846. $out[$sid] = [];
  3847. }
  3848. $out[$sid][] = $pk;
  3849. }
  3850. foreach ($out as $sid => $ids) {
  3851. $out[$sid] = array_values(array_unique($ids));
  3852. }
  3853. return $out;
  3854. }
  3855. /**
  3856. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  3857. *
  3858. * @param array<string, mixed> $dbRow
  3859. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  3860. */
  3861. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  3862. {
  3863. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  3864. $r = [
  3865. 'ID' => $sid,
  3866. 'scydgy_id' => $sid,
  3867. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  3868. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  3869. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  3870. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  3871. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  3872. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  3873. 'CDW' => $dbRow['CDW'] ?? '',
  3874. 'czlyq' => $dbRow['czlyq'] ?? '',
  3875. 'NGZL' => $dbRow['NGZL'] ?? '',
  3876. 'CDF' => $dbRow['CDF'] ?? '',
  3877. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  3878. 'MBZ' => $dbRow['MBZ'] ?? '',
  3879. 'bwjg' => $dbRow['bwjg'] ?? '',
  3880. 'iStatus' => $dbRow['iStatus'] ?? '',
  3881. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  3882. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  3883. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  3884. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  3885. 'dStamp' => $dbRow['dStamp'] ?? '',
  3886. 'pick_time' => $dbRow['pick_time'] ?? '',
  3887. ];
  3888. $r['This_quantity'] = $this->resolveProcuremenThisQuantity($r);
  3889. $r['ceilingPrice'] = $this->resolveProcuremenCeilingPrice($r);
  3890. if ($sid > 0 && isset($dStampMap[$sid])) {
  3891. $t = trim((string)$dStampMap[$sid]);
  3892. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  3893. $r['dStamp'] = $dStampMap[$sid];
  3894. }
  3895. }
  3896. $dsOut = trim((string)($r['dStamp'] ?? ''));
  3897. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  3898. $ct = $dbRow['createtime'];
  3899. if (is_numeric($ct) && (int)$ct > 946684800) {
  3900. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  3901. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  3902. $r['dStamp'] = trim($ct);
  3903. }
  3904. }
  3905. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  3906. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  3907. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  3908. $fallback = trim((string)($r['dStamp'] ?? ''));
  3909. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  3910. $r['dputrecord'] = $fallback;
  3911. }
  3912. }
  3913. if (array_key_exists('id', $dbRow)) {
  3914. $r['purchase_order_id'] = (int)$dbRow['id'];
  3915. }
  3916. if ($sid < 0) {
  3917. $r['_is_manual'] = 1;
  3918. }
  3919. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  3920. $pickOut = trim((string)($r['pick_time'] ?? ''));
  3921. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  3922. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  3923. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  3924. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  3925. $r['pick_time'] = $pickFallback;
  3926. break;
  3927. }
  3928. }
  3929. }
  3930. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  3931. if ($pickNm !== '') {
  3932. $r['pick_company_name'] = $pickNm;
  3933. $r['picked_supplier_name'] = $pickNm;
  3934. }
  3935. return $r;
  3936. }
  3937. /**
  3938. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  3939. *
  3940. * @return array<int, array<string, mixed>>
  3941. */
  3942. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  3943. {
  3944. $pool = [];
  3945. if (!is_array($dbRows) || $dbRows === []) {
  3946. return $pool;
  3947. }
  3948. $dStampMap = [];
  3949. $sidList = [];
  3950. foreach ($dbRows as $tmpRow) {
  3951. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  3952. $sid = (int)$tmpRow['scydgy_id'];
  3953. if ($sid > 0) {
  3954. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  3955. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3956. $sidList[$sid] = true;
  3957. }
  3958. }
  3959. }
  3960. }
  3961. if ($sidList !== []) {
  3962. try {
  3963. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  3964. } catch (\Throwable $e) {
  3965. $dStampMap = [];
  3966. }
  3967. }
  3968. foreach ($dbRows as $dbRow) {
  3969. if (!is_array($dbRow)) {
  3970. continue;
  3971. }
  3972. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  3973. }
  3974. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  3975. $needCcydh = [];
  3976. foreach ($pool as $row) {
  3977. if (!is_array($row)) {
  3978. continue;
  3979. }
  3980. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3981. continue;
  3982. }
  3983. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3984. if ($ccydh !== '') {
  3985. $needCcydh[$ccydh] = true;
  3986. }
  3987. }
  3988. if ($needCcydh !== []) {
  3989. $czMap = [];
  3990. try {
  3991. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  3992. } catch (\Throwable $e) {
  3993. $czMap = [];
  3994. }
  3995. if (is_array($czMap) && $czMap !== []) {
  3996. foreach ($pool as &$row) {
  3997. if (!is_array($row)) {
  3998. continue;
  3999. }
  4000. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  4001. continue;
  4002. }
  4003. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  4004. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  4005. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  4006. }
  4007. }
  4008. unset($row);
  4009. }
  4010. }
  4011. return $pool;
  4012. }
  4013. /**
  4014. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  4015. *
  4016. * @param int[] $scydgyIds
  4017. * @return array<int, array<string, mixed>>
  4018. */
  4019. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  4020. {
  4021. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4022. if ($scydgyIds === []) {
  4023. return [];
  4024. }
  4025. try {
  4026. $list = Db::table('purchase_order_detail')
  4027. ->where('scydgy_id', 'in', $scydgyIds)
  4028. ->field('scydgy_id,company_name,amount,delivery')
  4029. ->select();
  4030. } catch (\Throwable $e) {
  4031. $list = [];
  4032. }
  4033. return is_array($list) ? $list : [];
  4034. }
  4035. /**
  4036. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  4037. *
  4038. * @param int[] $scydgyIds
  4039. * @param array<int, array<string, mixed>> $allRows
  4040. * @return array{cnt:int, amt:int, deliv:int}
  4041. */
  4042. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  4043. {
  4044. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4045. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4046. if ($scydgyIds === [] || $allRows === []) {
  4047. return $out;
  4048. }
  4049. $idSet = array_flip($scydgyIds);
  4050. $all = [];
  4051. $withAmt = [];
  4052. $withDeliv = [];
  4053. foreach ($allRows as $r) {
  4054. if (!is_array($r)) {
  4055. continue;
  4056. }
  4057. $sid = (int)($r['scydgy_id'] ?? 0);
  4058. if (!isset($idSet[$sid])) {
  4059. continue;
  4060. }
  4061. $cn = trim((string)($r['company_name'] ?? ''));
  4062. if ($cn === '') {
  4063. continue;
  4064. }
  4065. $all[$cn] = true;
  4066. $am = $r['amount'] ?? null;
  4067. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  4068. $withAmt[$cn] = true;
  4069. }
  4070. $dv = $r['delivery'] ?? null;
  4071. if ($dv !== null && trim((string)$dv) !== '') {
  4072. $withDeliv[$cn] = true;
  4073. }
  4074. }
  4075. return [
  4076. 'cnt' => count($all),
  4077. 'amt' => count($withAmt),
  4078. 'deliv' => count($withDeliv),
  4079. ];
  4080. }
  4081. /**
  4082. * 本次数量:优先 This_quantity,空则回退工作量 NGZL(与下发/确认/审批弹窗一致)
  4083. *
  4084. * @param array<string, mixed> $row
  4085. */
  4086. protected function resolveProcuremenThisQuantity(array $row): string
  4087. {
  4088. $q = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  4089. if ($q !== '') {
  4090. return $q;
  4091. }
  4092. $ngzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  4093. if (!is_scalar($ngzl)) {
  4094. return '';
  4095. }
  4096. $s = trim((string)$ngzl);
  4097. if ($s === '') {
  4098. return '';
  4099. }
  4100. if (is_numeric($s) && (float)$s === 0.0) {
  4101. return '';
  4102. }
  4103. return $s;
  4104. }
  4105. /**
  4106. * @param array<string, mixed> $row
  4107. */
  4108. protected function resolveProcuremenCeilingPrice(array $row): string
  4109. {
  4110. return trim((string)($row['ceilingPrice'] ?? $row['ceiling_price'] ?? ''));
  4111. }
  4112. /**
  4113. * 多工序数量/限价拼接:跳过空值,避免出现「、10」「304、」
  4114. *
  4115. * @param array<int, mixed> $parts
  4116. */
  4117. protected function joinProcuremenNonEmpty(array $parts, string $sep = '、'): string
  4118. {
  4119. $out = [];
  4120. foreach ($parts as $p) {
  4121. $s = trim((string)$p);
  4122. if ($s !== '') {
  4123. $out[] = $s;
  4124. }
  4125. }
  4126. return $out === [] ? '' : implode($sep, $out);
  4127. }
  4128. /**
  4129. * 确认/审批列表:合并行按各工序同步本次数量、最高限价(顿号间隔)
  4130. *
  4131. * @param array<int, array<string, mixed>> $rows
  4132. */
  4133. protected function syncCollapsedOrderQtyPriceForList(array &$rows): void
  4134. {
  4135. if ($rows === []) {
  4136. return;
  4137. }
  4138. $idList = [];
  4139. foreach ($rows as $rw) {
  4140. if (!is_array($rw)) {
  4141. continue;
  4142. }
  4143. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4144. foreach ($rw['_order_merge_rows'] as $mr) {
  4145. if (!is_array($mr)) {
  4146. continue;
  4147. }
  4148. $mid = (int)($mr['ID'] ?? 0);
  4149. if ($this->isValidScydgyRowId($mid)) {
  4150. $idList[$mid] = true;
  4151. }
  4152. }
  4153. }
  4154. $id = (int)($rw['ID'] ?? 0);
  4155. if ($this->isValidScydgyRowId($id)) {
  4156. $idList[$id] = true;
  4157. }
  4158. }
  4159. if ($idList === []) {
  4160. return;
  4161. }
  4162. try {
  4163. $list = Db::table('purchase_order')
  4164. ->where('scydgy_id', 'in', array_keys($idList))
  4165. ->field('scydgy_id,This_quantity,ceilingPrice,NGZL,pick_company_name')
  4166. ->select();
  4167. } catch (\Throwable $e) {
  4168. return;
  4169. }
  4170. if (!is_array($list)) {
  4171. return;
  4172. }
  4173. $byId = [];
  4174. foreach ($list as $dbRow) {
  4175. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4176. continue;
  4177. }
  4178. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4179. }
  4180. foreach ($rows as &$rw) {
  4181. if (!is_array($rw)) {
  4182. continue;
  4183. }
  4184. $mergeRows = [];
  4185. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4186. $mergeRows = $rw['_order_merge_rows'];
  4187. } else {
  4188. $mergeRows = [$rw];
  4189. }
  4190. $qtyList = [];
  4191. $priceList = [];
  4192. $picked = '';
  4193. foreach ($mergeRows as $mr) {
  4194. if (!is_array($mr)) {
  4195. continue;
  4196. }
  4197. $sid = (int)($mr['ID'] ?? 0);
  4198. $db = ($sid !== 0 && isset($byId[$sid])) ? $byId[$sid] : null;
  4199. $src = $mr;
  4200. if (is_array($db)) {
  4201. $qDb = trim((string)($db['This_quantity'] ?? $db['this_quantity'] ?? ''));
  4202. $pDb = trim((string)($db['ceilingPrice'] ?? $db['ceiling_price'] ?? ''));
  4203. $ngzlDb = $db['NGZL'] ?? $db['ngzl'] ?? null;
  4204. if ($qDb !== '') {
  4205. $src['This_quantity'] = $qDb;
  4206. }
  4207. if ($pDb !== '') {
  4208. $src['ceilingPrice'] = $pDb;
  4209. }
  4210. if ($ngzlDb !== null && trim((string)$ngzlDb) !== '') {
  4211. $src['NGZL'] = $ngzlDb;
  4212. }
  4213. if ($picked === '') {
  4214. $picked = trim((string)($db['pick_company_name'] ?? ''));
  4215. }
  4216. }
  4217. if ($picked === '') {
  4218. $picked = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  4219. }
  4220. $qtyList[] = $this->resolveProcuremenThisQuantity($src);
  4221. $priceList[] = $this->resolveProcuremenCeilingPrice($src);
  4222. }
  4223. $rw['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  4224. $rw['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  4225. if ($picked !== '') {
  4226. $rw['pick_company_name'] = $picked;
  4227. $rw['picked_supplier_name'] = $picked;
  4228. }
  4229. }
  4230. unset($rw);
  4231. }
  4232. /**
  4233. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  4234. *
  4235. * @param int[] $scydgyIds
  4236. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  4237. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  4238. */
  4239. protected function OrderDetailSummary(array $scydgyIds)
  4240. {
  4241. $out = [];
  4242. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4243. if ($scydgyIds === []) {
  4244. return $out;
  4245. }
  4246. $list = [];
  4247. try {
  4248. $list = Db::table('purchase_order_detail')
  4249. ->where('scydgy_id', 'in', $scydgyIds)
  4250. ->field('id,scydgy_id,amount,delivery')
  4251. ->select();
  4252. } catch (\Throwable $e) {
  4253. $list = [];
  4254. }
  4255. if (!is_array($list)) {
  4256. return $out;
  4257. }
  4258. foreach ($list as $r) {
  4259. if (!is_array($r)) {
  4260. continue;
  4261. }
  4262. $ids = (int)($r['scydgy_id'] ?? 0);
  4263. if (!$this->isValidScydgyRowId($ids)) {
  4264. continue;
  4265. }
  4266. if (!isset($out[$ids])) {
  4267. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4268. }
  4269. $out[$ids]['cnt']++;
  4270. $am = $r['amount'] ?? null;
  4271. if ($am !== null && $am !== '') {
  4272. if (!(is_string($am) && trim($am) === '')) {
  4273. $out[$ids]['amt']++;
  4274. }
  4275. }
  4276. $dv = $r['delivery'] ?? null;
  4277. if ($dv !== null && trim((string)$dv) !== '') {
  4278. $out[$ids]['deliv']++;
  4279. }
  4280. }
  4281. return $out;
  4282. }
  4283. /**
  4284. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  4285. *
  4286. * @return array
  4287. */
  4288. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  4289. {
  4290. $strContains = function ($haystack, $needle) {
  4291. if ($needle === '') {
  4292. return false;
  4293. }
  4294. $haystack = (string)$haystack;
  4295. if (function_exists('mb_stripos')) {
  4296. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  4297. }
  4298. return stripos($haystack, $needle) !== false;
  4299. };
  4300. $stripAlias = function ($f) {
  4301. return preg_replace('/^[ab]\./i', '', (string)$f);
  4302. };
  4303. $searchColNames = [];
  4304. foreach (explode(',', $this->searchFields) as $colRaw) {
  4305. $c = $stripAlias(trim($colRaw));
  4306. if ($c !== '') {
  4307. $searchColNames[] = $c;
  4308. }
  4309. }
  4310. // 等值条件先行(表头下拉),减少后续日期解析量
  4311. $eqFilters = [];
  4312. $otherFilters = [];
  4313. foreach ($filterArr as $fk => $fv) {
  4314. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  4315. continue;
  4316. }
  4317. if (is_array($fv)) {
  4318. continue;
  4319. }
  4320. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  4321. continue;
  4322. }
  4323. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  4324. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  4325. $field = $stripAlias($fk);
  4326. if ($sym === '=' || $sym === '') {
  4327. $eqFilters[$field] = trim((string)$fv);
  4328. } else {
  4329. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  4330. }
  4331. }
  4332. $ymTarget = '';
  4333. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  4334. $ymTarget = $ymM[1];
  4335. }
  4336. $filtered = [];
  4337. foreach ($pool as $r) {
  4338. if (!is_array($r)) {
  4339. continue;
  4340. }
  4341. foreach ($eqFilters as $field => $fv) {
  4342. if (trim((string)($r[$field] ?? '')) !== $fv) {
  4343. continue 2;
  4344. }
  4345. }
  4346. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  4347. // 初选池不应含手工单;若混入则直接剔除
  4348. if ($isManual) {
  4349. continue;
  4350. }
  4351. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  4352. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  4353. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  4354. continue;
  4355. }
  4356. if ($applyMonthRange) {
  4357. $mo = (int)$m[2];
  4358. if ($mo < 1 || $mo > 12) {
  4359. continue;
  4360. }
  4361. if ($ymTarget !== '') {
  4362. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4363. if ($ymRow !== $ymTarget) {
  4364. continue;
  4365. }
  4366. } else {
  4367. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4368. $rowMonthStart = $ymRow . '-01 00:00:00';
  4369. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  4370. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  4371. continue;
  4372. }
  4373. }
  4374. }
  4375. if ($search !== '') {
  4376. $hitSearch = false;
  4377. foreach ($searchColNames as $c) {
  4378. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  4379. if ($cell !== '' && $strContains($cell, $search)) {
  4380. $hitSearch = true;
  4381. break;
  4382. }
  4383. }
  4384. if (!$hitSearch) {
  4385. continue;
  4386. }
  4387. }
  4388. foreach ($otherFilters as $item) {
  4389. $fv = $item['fv'];
  4390. $sym = $item['sym'];
  4391. $field = $item['field'];
  4392. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  4393. $cellStr = trim((string)$cell);
  4394. switch ($sym) {
  4395. case '<>':
  4396. if ((string)$cell === (string)$fv) {
  4397. continue 3;
  4398. }
  4399. break;
  4400. case 'LIKE':
  4401. case 'NOT LIKE':
  4402. $needle = trim((string)$fv);
  4403. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  4404. if ($sym === 'LIKE' && !$hit) {
  4405. continue 3;
  4406. }
  4407. if ($sym === 'NOT LIKE' && $hit) {
  4408. continue 3;
  4409. }
  4410. break;
  4411. case 'BETWEEN':
  4412. case 'RANGE':
  4413. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  4414. if (count($parts) < 2) {
  4415. $parts = is_string($fv) ? explode(',', $fv) : [];
  4416. }
  4417. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  4418. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  4419. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  4420. continue 3;
  4421. }
  4422. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  4423. continue 3;
  4424. }
  4425. break;
  4426. case '>':
  4427. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  4428. continue 3;
  4429. }
  4430. break;
  4431. case '>=':
  4432. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  4433. continue 3;
  4434. }
  4435. break;
  4436. case '<':
  4437. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  4438. continue 3;
  4439. }
  4440. break;
  4441. case '<=':
  4442. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  4443. continue 3;
  4444. }
  4445. break;
  4446. default:
  4447. if ((string)$cell !== (string)$fv) {
  4448. continue 3;
  4449. }
  4450. break;
  4451. }
  4452. }
  4453. $filtered[] = $r;
  4454. }
  4455. return $filtered;
  4456. }
  4457. /**
  4458. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  4459. */
  4460. public function snapshotToProcure()
  4461. {
  4462. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4463. $this->error(__('Invalid parameters'));
  4464. }
  4465. $row = json_decode($this->request->post('row_json', ''), true);
  4466. if (!is_array($row)) {
  4467. $this->error(__('Invalid parameters'));
  4468. }
  4469. try {
  4470. $ids = $this->extractScydgyRowId($row);
  4471. if (!$this->isValidScydgyRowId($ids)) {
  4472. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4473. }
  4474. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4475. $data = $this->normalizePurchaseOrderWritePayload([
  4476. 'scydgy_id' => $ids,
  4477. 'CCYDH' => $row['CCYDH'] ?? null,
  4478. 'CYJMC' => $row['CYJMC'] ?? null,
  4479. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4480. 'CDXMC' => $row['CDXMC'] ?? null,
  4481. 'CGYBH' => $row['CGYBH'] ?? null,
  4482. 'CGYMC' => $row['CGYMC'] ?? null,
  4483. 'CDW' => $row['CDW'] ?? null,
  4484. 'czlyq' => $row['czlyq'] ?? null,
  4485. 'NGZL' => $row['NGZL'] ?? null,
  4486. 'CDF' => $row['CDF'] ?? null,
  4487. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4488. 'MBZ' => $row['MBZ'] ?? null,
  4489. 'bwjg' => $row['bwjg'] ?? null,
  4490. 'iStatus' => $row['iStatus'] ?? null,
  4491. 'dStamp' => $row['dStamp'] ?? null,
  4492. 'dputrecord' => $row['dputrecord'] ?? null,
  4493. 'cywyxm' => $row['cywyxm'] ?? null,
  4494. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4495. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4496. ], $row);
  4497. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  4498. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  4499. $mbzSnap = trim((string)($data['MBZ'] ?? ''));
  4500. if (!$exists && $qtySnap === '' && $priceSnap === '' && $mbzSnap === '') {
  4501. $this->success('操作成功');
  4502. return;
  4503. }
  4504. if ($exists) {
  4505. $upd = $data;
  4506. unset($upd['scydgy_id'], $upd['status']);
  4507. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4508. } else {
  4509. // 新增:不写 status(空/走库默认);仅写创建时间
  4510. $data['createtime'] = date('Y-m-d H:i:s');
  4511. Db::table('purchase_order')->insert($data);
  4512. }
  4513. } catch (\Throwable $e) {
  4514. $this->error($e->getMessage());
  4515. }
  4516. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  4517. $this->success('操作成功');
  4518. }
  4519. /**
  4520. * 未发列表
  4521. * 「完结」或「仅保存本次数量/最高限价/备注」:有则改、无则插
  4522. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  4523. */
  4524. public function completeDirectly()
  4525. {
  4526. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4527. $this->error(__('参数错误'));
  4528. }
  4529. if (!$this->procuremenCanComplete()) {
  4530. $this->error(__('You have no permission'));
  4531. }
  4532. $row = json_decode($this->request->post('row_json', ''), true);
  4533. if (!is_array($row)) {
  4534. $this->error(__('Invalid parameters'));
  4535. }
  4536. $finishRaw = $this->request->post('finish', '1');
  4537. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  4538. $poIdLog = null;
  4539. try {
  4540. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  4541. $ids = $this->extractScydgyRowId($row);
  4542. if (!$this->isValidScydgyRowId($ids)) {
  4543. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4544. }
  4545. if ($asComplete) {
  4546. $this->assertPickRowCanComplete($ids, $row);
  4547. }
  4548. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4549. $data = $this->normalizePurchaseOrderWritePayload([
  4550. 'scydgy_id' => $ids,
  4551. 'CCYDH' => $row['CCYDH'] ?? null,
  4552. 'CYJMC' => $row['CYJMC'] ?? null,
  4553. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4554. 'CDXMC' => $row['CDXMC'] ?? null,
  4555. 'CGYBH' => $row['CGYBH'] ?? null,
  4556. 'CGYMC' => $row['CGYMC'] ?? null,
  4557. 'CDW' => $row['CDW'] ?? null,
  4558. 'czlyq' => $row['czlyq'] ?? null,
  4559. 'NGZL' => $row['NGZL'] ?? null,
  4560. 'CDF' => $row['CDF'] ?? null,
  4561. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4562. 'MBZ' => $row['MBZ'] ?? null,
  4563. 'bwjg' => $row['bwjg'] ?? null,
  4564. 'iStatus' => $row['iStatus'] ?? null,
  4565. 'dStamp' => $row['dStamp'] ?? null,
  4566. 'dputrecord' => $row['dputrecord'] ?? null,
  4567. 'cywyxm' => $row['cywyxm'] ?? null,
  4568. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4569. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4570. ], $row);
  4571. if ($asComplete) {
  4572. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  4573. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  4574. }
  4575. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  4576. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  4577. $mbzCd = trim((string)($data['MBZ'] ?? ''));
  4578. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '' && $mbzCd === '') {
  4579. $this->success('操作成功');
  4580. return;
  4581. }
  4582. if ($exists) {
  4583. $upd = $data;
  4584. unset($upd['scydgy_id']);
  4585. if (!$asComplete) {
  4586. unset($upd['status']);
  4587. }
  4588. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4589. } else {
  4590. // 新增:不写 status;完结时 $data 已含 status=1
  4591. $data['createtime'] = date('Y-m-d H:i:s');
  4592. Db::table('purchase_order')->insert($data);
  4593. }
  4594. } catch (\Throwable $e) {
  4595. $this->error($e->getMessage());
  4596. }
  4597. try {
  4598. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4599. if (is_array($rpo)) {
  4600. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4601. $poIdLog = $tid > 0 ? $tid : null;
  4602. }
  4603. } catch (\Throwable $e) {
  4604. $poIdLog = null;
  4605. }
  4606. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  4607. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  4608. if ($asComplete) {
  4609. $this->addOrderLog(
  4610. $ids,
  4611. 'mark_complete',
  4612. '点击「完结」,已标记为已完结',
  4613. $poIdLog
  4614. );
  4615. try {
  4616. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  4617. if ($pdfPublicPath === '') {
  4618. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  4619. }
  4620. } catch (\Throwable $e) {
  4621. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  4622. }
  4623. } else {
  4624. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  4625. $mbz = isset($data['MBZ']) ? trim((string)$data['MBZ']) : '';
  4626. $qtyPart = '本次数量「' . ($q !== '' ? $q : '') . '」';
  4627. $pricePart = '最高限价「' . ($p !== '' ? $p : '') . '」';
  4628. $mbzPart = '备注「' . ($mbz !== '' ? $mbz : '') . '」';
  4629. $detail = ($gymc !== '' ? ($gymc . $qtyPart) : $qtyPart) . ',' . $pricePart . ',' . $mbzPart;
  4630. $this->addOrderLog(
  4631. $ids,
  4632. 'save_qty_price',
  4633. '保存本次数量、最高限价、备注:' . $detail,
  4634. $poIdLog
  4635. );
  4636. }
  4637. $this->pickHiddenScydgySetCache = null;
  4638. $this->success("操作成功");
  4639. }
  4640. /**
  4641. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价、备注(若表中有对应列)
  4642. *
  4643. * @param array<int, array> $rows 引用传递当前页行
  4644. */
  4645. protected function mergePurchaseOrder(array &$rows)
  4646. {
  4647. if ($rows === []) {
  4648. return;
  4649. }
  4650. $ids = [];
  4651. foreach ($rows as $rw) {
  4652. if (!is_array($rw)) {
  4653. continue;
  4654. }
  4655. $id = (int)($rw['ID'] ?? 0);
  4656. // 含手工新增负数 scydgy_id,避免限价/数量不同步
  4657. if ($this->isValidScydgyRowId($id)) {
  4658. $ids[$id] = true;
  4659. }
  4660. }
  4661. $idList = array_keys($ids);
  4662. if ($idList === []) {
  4663. return;
  4664. }
  4665. try {
  4666. $list = Db::table('purchase_order')
  4667. ->where('scydgy_id', 'in', $idList)
  4668. ->field('scydgy_id,This_quantity,ceilingPrice,MBZ')
  4669. ->select();
  4670. } catch (\Throwable $e) {
  4671. return;
  4672. }
  4673. if (!is_array($list)) {
  4674. return;
  4675. }
  4676. $byId = [];
  4677. foreach ($list as $dbRow) {
  4678. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4679. continue;
  4680. }
  4681. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4682. }
  4683. foreach ($rows as &$rw) {
  4684. if (!is_array($rw)) {
  4685. continue;
  4686. }
  4687. $sid = (int)($rw['ID'] ?? 0);
  4688. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  4689. continue;
  4690. }
  4691. $db = $byId[$sid];
  4692. // 有 purchase_order 记录时同步数量/限价/备注(含清空后的空串,避免刷新后又冒出来)
  4693. if (array_key_exists('This_quantity', $db)) {
  4694. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  4695. }
  4696. if (array_key_exists('ceilingPrice', $db)) {
  4697. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  4698. } elseif (array_key_exists('ceiling_price', $db)) {
  4699. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  4700. }
  4701. if (array_key_exists('MBZ', $db)) {
  4702. $rw['MBZ'] = $db['MBZ'] === null ? '' : $db['MBZ'];
  4703. }
  4704. }
  4705. unset($rw);
  4706. }
  4707. /**
  4708. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  4709. */
  4710. public function purchaseConfirmPick()
  4711. {
  4712. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4713. $this->error(__('Invalid parameters'));
  4714. }
  4715. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  4716. $this->error(__('You have no permission'));
  4717. }
  4718. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  4719. if ($batchRaw !== '') {
  4720. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  4721. return;
  4722. }
  4723. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  4724. $sid = (int)$scydgyId;
  4725. if (!$this->isValidScydgyRowId($sid)) {
  4726. $this->error('参数无效');
  4727. }
  4728. $parseIdList = function ($raw) {
  4729. if (is_array($raw)) {
  4730. $arr = $raw;
  4731. } else {
  4732. $decoded = json_decode((string)$raw, true);
  4733. $arr = is_array($decoded) ? $decoded : [];
  4734. }
  4735. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  4736. };
  4737. $selectedRaw = $this->request->post('selected_ids', null);
  4738. if ($selectedRaw === null || $selectedRaw === '') {
  4739. $legacy = (int)$this->request->post('selected_id', 0);
  4740. $selectedIds = $legacy > 0 ? [$legacy] : [];
  4741. } else {
  4742. $selectedIds = $parseIdList($selectedRaw);
  4743. }
  4744. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  4745. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  4746. try {
  4747. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  4748. } catch (\InvalidArgumentException $e) {
  4749. $this->error($e->getMessage());
  4750. } catch (\Throwable $e) {
  4751. $this->error($e->getMessage());
  4752. }
  4753. $this->pickHiddenScydgySetCache = null;
  4754. $this->success('操作成功', '', $result);
  4755. }
  4756. /**
  4757. * 整单采购确认(多道工序一次提交)
  4758. */
  4759. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  4760. {
  4761. $decoded = json_decode($batchRaw, true);
  4762. if (!is_array($decoded) || $decoded === []) {
  4763. $this->error('提交数据无效');
  4764. }
  4765. $picks = [];
  4766. foreach ($decoded as $item) {
  4767. if (!is_array($item)) {
  4768. continue;
  4769. }
  4770. $sid = (int)($item['scydgy_id'] ?? 0);
  4771. if (!$this->isValidScydgyRowId($sid)) {
  4772. continue;
  4773. }
  4774. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  4775. if (!is_array($sel)) {
  4776. $sel = [(int)$sel];
  4777. }
  4778. $unsel = $item['unselected_ids'] ?? [];
  4779. if (!is_array($unsel)) {
  4780. $unsel = json_decode((string)$unsel, true);
  4781. $unsel = is_array($unsel) ? $unsel : [];
  4782. }
  4783. $picks[] = [
  4784. 'scydgy_id' => $sid,
  4785. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  4786. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  4787. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  4788. ];
  4789. }
  4790. if ($picks === []) {
  4791. $this->error('提交数据无效');
  4792. }
  4793. Db::startTrans();
  4794. $results = [];
  4795. try {
  4796. foreach ($picks as $pick) {
  4797. $results[] = $this->runPurchaseConfirmPick(
  4798. (int)$pick['scydgy_id'],
  4799. $pick['selected_ids'],
  4800. $pick['unselected_ids'],
  4801. (int)$pick['purchase_order_id'],
  4802. false,
  4803. false
  4804. );
  4805. }
  4806. Db::commit();
  4807. } catch (\Throwable $e) {
  4808. Db::rollback();
  4809. $msg = $e->getMessage();
  4810. $this->error($msg !== '' ? $msg : '提交失败');
  4811. }
  4812. try {
  4813. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  4814. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  4815. } catch (\Throwable $e) {
  4816. Log::write('采购确认通知批量发送异常: ' . $e->getMessage(), 'error');
  4817. }
  4818. $this->pickHiddenScydgySetCache = null;
  4819. $this->success('操作成功', '', ['batch' => $results]);
  4820. }
  4821. /**
  4822. * @return array<string, mixed>
  4823. */
  4824. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  4825. {
  4826. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  4827. ProcuremenGuard::assertWflowPendingApproval($poRow);
  4828. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  4829. $scydgyId = (string)$sid;
  4830. if ($selectedIds === []) {
  4831. throw new \InvalidArgumentException('请至少勾选一条明细');
  4832. }
  4833. $inter = array_intersect($selectedIds, $unselectedIds);
  4834. if ($inter !== []) {
  4835. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  4836. }
  4837. $allIds = $this->purchaseOrderDetail($sid);
  4838. if ($allIds === []) {
  4839. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  4840. }
  4841. foreach ($selectedIds as $id) {
  4842. if (!in_array($id, $allIds, true)) {
  4843. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  4844. }
  4845. }
  4846. foreach ($unselectedIds as $id) {
  4847. if (!in_array($id, $allIds, true)) {
  4848. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  4849. }
  4850. }
  4851. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  4852. sort($union, SORT_NUMERIC);
  4853. $expect = $allIds;
  4854. sort($expect, SORT_NUMERIC);
  4855. if ($union !== $expect) {
  4856. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  4857. }
  4858. if ($manageTransaction) {
  4859. Db::startTrans();
  4860. }
  4861. try {
  4862. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  4863. $aff = 0;
  4864. try {
  4865. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4866. } catch (\Throwable $e) {
  4867. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4868. }
  4869. if ($aff < 1) {
  4870. throw new \Exception('更新选中状态失败');
  4871. }
  4872. $poPayload = [
  4873. // 审核通过后进入「待入库评分」;合格/不合格后才置已完结
  4874. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  4875. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  4876. ];
  4877. if ($purchaseOrderId > 0) {
  4878. $poAff = (int)Db::table('purchase_order')
  4879. ->where('id', $purchaseOrderId)
  4880. ->where('scydgy_id', $sid)
  4881. ->update($poPayload);
  4882. if ($poAff < 1) {
  4883. throw new \Exception('主表订单不存在或与工序行不匹配');
  4884. }
  4885. } else {
  4886. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  4887. if ($poAff < 1) {
  4888. throw new \Exception('未找到');
  4889. }
  4890. }
  4891. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  4892. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  4893. if ($manageTransaction) {
  4894. Db::commit();
  4895. }
  4896. } catch (\Throwable $e) {
  4897. if ($manageTransaction) {
  4898. Db::rollback();
  4899. }
  4900. throw $e;
  4901. }
  4902. $poIdFinal = $purchaseOrderId;
  4903. if ($poIdFinal <= 0) {
  4904. try {
  4905. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4906. if (is_array($rpo)) {
  4907. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4908. }
  4909. } catch (\Throwable $e) {
  4910. $poIdFinal = 0;
  4911. }
  4912. }
  4913. $pickNames = [];
  4914. foreach ($selectedIds as $pid) {
  4915. $dr = $this->purchaseOrderDetai($sid, $pid);
  4916. $nm = trim((string)($dr['company_name'] ?? ''));
  4917. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  4918. }
  4919. $this->addOrderLog(
  4920. $sid,
  4921. 'purchase_confirm',
  4922. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  4923. $poIdFinal > 0 ? $poIdFinal : null
  4924. );
  4925. if ($sendNotifications) {
  4926. try {
  4927. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  4928. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  4929. 'scydgy_id' => $sid,
  4930. 'selected_ids' => $selectedIds,
  4931. 'unselected_ids' => $unselectedIds,
  4932. 'purchase_order_id' => $purchaseOrderId,
  4933. ]]);
  4934. } catch (\Throwable $e) {
  4935. Log::write('采购确认通知发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  4936. }
  4937. }
  4938. Log::write(sprintf(
  4939. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  4940. $scydgyId,
  4941. $purchaseOrderId,
  4942. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  4943. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  4944. ), 'notice');
  4945. $pdfPublicPath = '';
  4946. try {
  4947. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  4948. } catch (\Throwable $e) {
  4949. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  4950. }
  4951. return [
  4952. 'scydgy_id' => $scydgyId,
  4953. 'purchase_order_id' => $purchaseOrderId,
  4954. 'selected_ids' => $selectedIds,
  4955. 'unselected_ids' => $unselectedIds,
  4956. 'purchase_confirm_pdf' => $pdfPublicPath,
  4957. ];
  4958. }
  4959. /**
  4960. * 审批通过短信:按本次涉及的工序汇总 process_lines
  4961. *
  4962. * @param int[]|string[] $scydgyIds
  4963. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4964. */
  4965. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  4966. {
  4967. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4968. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4969. if ($scydgyIds === []) {
  4970. return $empty;
  4971. }
  4972. $pos = [];
  4973. try {
  4974. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  4975. } catch (\Throwable $e) {
  4976. $rows = [];
  4977. }
  4978. if (is_array($rows)) {
  4979. foreach ($rows as $po) {
  4980. if (is_array($po)) {
  4981. $pos[] = $po;
  4982. }
  4983. }
  4984. }
  4985. if ($pos === []) {
  4986. return $empty;
  4987. }
  4988. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  4989. return [
  4990. 'ccydh' => $ccydh,
  4991. 'pos' => $pos,
  4992. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4993. ];
  4994. }
  4995. /**
  4996. * 审批通过/未通过:短信 + 邮件(同一供应商只发一条;邮件含平台链接)
  4997. *
  4998. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  4999. * @param array<int, array<string, mixed>> $picks
  5000. */
  5001. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  5002. {
  5003. if ($picks === []) {
  5004. return;
  5005. }
  5006. $this->ensureConfirmResultEmailTemplates();
  5007. $fallbackDetailId = 0;
  5008. $winners = [];
  5009. $losers = [];
  5010. foreach ($picks as $pick) {
  5011. if (!is_array($pick)) {
  5012. continue;
  5013. }
  5014. $sid = (int)($pick['scydgy_id'] ?? 0);
  5015. if (!$this->isValidScydgyRowId($sid)) {
  5016. continue;
  5017. }
  5018. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  5019. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  5020. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  5021. $fallbackDetailId = (int)$selectedIds[0];
  5022. }
  5023. foreach ($selectedIds as $pid) {
  5024. $dr = $this->purchaseOrderDetai($sid, $pid);
  5025. if (!is_array($dr)) {
  5026. continue;
  5027. }
  5028. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  5029. }
  5030. foreach ($unselectedIds as $pid) {
  5031. $dr = $this->purchaseOrderDetai($sid, $pid);
  5032. if (!is_array($dr)) {
  5033. continue;
  5034. }
  5035. $key = $this->notifySupplierDedupeKey($dr);
  5036. if (!isset($winners[$key])) {
  5037. $losers[$key] = $dr;
  5038. }
  5039. }
  5040. }
  5041. if ($winners === [] && $losers === []) {
  5042. return;
  5043. }
  5044. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  5045. $poIdLog = 0;
  5046. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5047. if (isset($pos[0]) && is_array($pos[0])) {
  5048. $poIdLog = (int)($pos[0]['id'] ?? 0);
  5049. }
  5050. $sendSmsSafe = function ($phone, $content) {
  5051. $phone = trim((string)$phone);
  5052. if ($phone === '') {
  5053. return;
  5054. }
  5055. try {
  5056. $this->smsbao($phone, $content);
  5057. } catch (\Throwable $e) {
  5058. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  5059. }
  5060. };
  5061. $sendConfirmEmailSafe = function (array $dr, string $emailScene) use ($confirmNotifyVars, $poIdLog) {
  5062. $cname = trim((string)($dr['company_name'] ?? ''));
  5063. $ph = trim((string)($dr['phone'] ?? ''));
  5064. $toEmail = trim((string)($dr['email'] ?? ''));
  5065. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5066. Log::write('采购确认邮件跳过:无有效邮箱 company=' . $cname, 'error');
  5067. return;
  5068. }
  5069. $detailId = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5070. if ($detailId <= 0) {
  5071. $detailId = (int)($confirmNotifyVars['_fallback_detail_id'] ?? 0);
  5072. }
  5073. try {
  5074. $platformUrl = $this->buildMprocMobileOrderUrl($detailId);
  5075. } catch (\Throwable $e) {
  5076. Log::write('采购确认邮件链接失败: ' . $e->getMessage(), 'error');
  5077. $platformUrl = '';
  5078. }
  5079. $vars = array_merge($confirmNotifyVars, [
  5080. 'company_name' => $cname,
  5081. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5082. 'phone' => $ph,
  5083. 'email' => $toEmail,
  5084. 'platform_url' => $platformUrl,
  5085. ]);
  5086. unset($vars['_fallback_detail_id']);
  5087. try {
  5088. $mailPlain = $this->renderNotifyTemplate($emailScene, $vars);
  5089. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  5090. $mailSubject = $this->resolveProcuremenEmailSubject($emailScene);
  5091. $mailConfig = $this->loadMailerConfig();
  5092. $this->issueSendSupplierEmail([
  5093. 'company_name' => $cname,
  5094. 'email' => $toEmail,
  5095. 'mail_plain' => $mailPlain,
  5096. 'mail_body' => $mailBody,
  5097. 'notify_vars' => $vars,
  5098. 'sms_content' => '',
  5099. 'detail_links' => $platformUrl !== '' ? [['url' => $platformUrl, 'cgymc' => '']] : [],
  5100. 'email_log_scene' => 'confirm_result',
  5101. 'email_log_scydgy_id' => (int)($dr['scydgy_id'] ?? 0),
  5102. 'email_log_purchase_order_id' => $poIdLog,
  5103. ], $mailConfig, $mailSubject);
  5104. } catch (\Throwable $e) {
  5105. Log::write('采购确认邮件失败 company=' . $cname . ' email=' . $toEmail . ' ' . $e->getMessage(), 'error');
  5106. }
  5107. };
  5108. $confirmNotifyVars['_fallback_detail_id'] = $fallbackDetailId;
  5109. foreach ($winners as $dr) {
  5110. $cname = trim((string)($dr['company_name'] ?? ''));
  5111. $ph = trim((string)($dr['phone'] ?? ''));
  5112. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  5113. 'company_name' => $cname,
  5114. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5115. 'phone' => $ph,
  5116. ]));
  5117. $sendSmsSafe($ph, $sms);
  5118. $sendConfirmEmailSafe($dr, 'confirm_ok_email');
  5119. }
  5120. foreach ($losers as $dr) {
  5121. $cname = trim((string)($dr['company_name'] ?? ''));
  5122. $ph = trim((string)($dr['phone'] ?? ''));
  5123. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  5124. 'company_name' => $cname,
  5125. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5126. 'phone' => $ph,
  5127. ]));
  5128. $sendSmsSafe($ph, $sms);
  5129. $sendConfirmEmailSafe($dr, 'confirm_fail_email');
  5130. }
  5131. }
  5132. /**
  5133. * 短信去重键:优先手机号,否则公司名
  5134. */
  5135. protected function notifySupplierDedupeKey(array $detailRow): string
  5136. {
  5137. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  5138. if ($ph !== '') {
  5139. return 'p:' . $ph;
  5140. }
  5141. $cn = trim((string)($detailRow['company_name'] ?? ''));
  5142. return 'c:' . $cn;
  5143. }
  5144. /**
  5145. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  5146. *
  5147. * @param int[] $detailIds
  5148. */
  5149. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  5150. {
  5151. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  5152. if ($detailIds === []) {
  5153. return;
  5154. }
  5155. $payload = ['status_name' => $statusName];
  5156. try {
  5157. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  5158. } catch (\Throwable $e) {
  5159. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  5160. }
  5161. }
  5162. /**
  5163. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  5164. */
  5165. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  5166. {
  5167. try {
  5168. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  5169. } catch (\Throwable $e) {
  5170. return;
  5171. }
  5172. if (!is_array($rows)) {
  5173. return;
  5174. }
  5175. foreach ($rows as $dr) {
  5176. if (!is_array($dr)) {
  5177. continue;
  5178. }
  5179. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5180. if ($id <= 0) {
  5181. continue;
  5182. }
  5183. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  5184. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  5185. try {
  5186. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  5187. } catch (\Throwable $e) {
  5188. }
  5189. }
  5190. }
  5191. /**
  5192. * @param array<string, mixed> $detailRow
  5193. */
  5194. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  5195. {
  5196. $am = $detailRow['amount'] ?? null;
  5197. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  5198. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  5199. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  5200. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  5201. }
  5202. /**
  5203. * @return int[]
  5204. */
  5205. protected function purchaseOrderDetail(int $scydgyId): array
  5206. {
  5207. if (!$this->isValidScydgyRowId($scydgyId)) {
  5208. return [];
  5209. }
  5210. try {
  5211. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  5212. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  5213. $list = $listQuery->select();
  5214. } catch (\Throwable $e) {
  5215. return [];
  5216. }
  5217. if (!is_array($list)) {
  5218. return [];
  5219. }
  5220. $ids = [];
  5221. foreach ($list as $r) {
  5222. if (!is_array($r)) {
  5223. continue;
  5224. }
  5225. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  5226. if ($pk > 0) {
  5227. $ids[] = $pk;
  5228. }
  5229. }
  5230. return array_values(array_unique($ids));
  5231. }
  5232. /**
  5233. * 获取当前登录用户信息 [id, 展示名]
  5234. * admin_name 一律记「名称」(昵称),无昵称再回退账号
  5235. */
  5236. protected function GetUseName(): array
  5237. {
  5238. $id = 0;
  5239. $name = '';
  5240. try {
  5241. if ($this->auth && $this->auth->isLogin()) {
  5242. $u = $this->auth->getUserInfo();
  5243. if (is_array($u)) {
  5244. $id = (int)($u['id'] ?? 0);
  5245. $name = trim((string)($u['nickname'] ?? ''));
  5246. // 会话昵称缺失或等于登录账号时,再查库取正式昵称
  5247. $sessionUser = trim((string)($u['username'] ?? ''));
  5248. if ($id > 0 && ($name === '' || ($sessionUser !== '' && strcasecmp($name, $sessionUser) === 0))) {
  5249. try {
  5250. $row = Db::name('admin')->where('id', $id)->field('nickname,username')->find();
  5251. if (is_array($row)) {
  5252. $nick = trim((string)($row['nickname'] ?? ''));
  5253. if ($nick !== '') {
  5254. $name = $nick;
  5255. } elseif ($name === '') {
  5256. $name = trim((string)($row['username'] ?? ''));
  5257. }
  5258. }
  5259. } catch (\Throwable $e) {
  5260. }
  5261. }
  5262. if ($name === '') {
  5263. $name = $sessionUser;
  5264. }
  5265. }
  5266. }
  5267. } catch (\Throwable $e) {
  5268. }
  5269. if ($name === '') {
  5270. $name = '未知用户';
  5271. }
  5272. return [$id, $name];
  5273. }
  5274. /**
  5275. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  5276. */
  5277. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  5278. {
  5279. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  5280. }
  5281. /**
  5282. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  5283. *
  5284. * @param array<int, array<string, mixed>> $rows
  5285. */
  5286. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  5287. {
  5288. $sidList = [];
  5289. foreach ($rows as $rw) {
  5290. if (!is_array($rw)) {
  5291. continue;
  5292. }
  5293. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5294. foreach ($rw['_order_merge_rows'] as $mr) {
  5295. $mid = (int)($mr['ID'] ?? 0);
  5296. if ($this->isValidScydgyRowId($mid)) {
  5297. $sidList[$mid] = true;
  5298. }
  5299. }
  5300. }
  5301. $id = (int)($rw['ID'] ?? 0);
  5302. if ($this->isValidScydgyRowId($id)) {
  5303. $sidList[$id] = true;
  5304. }
  5305. }
  5306. $sids = array_keys($sidList);
  5307. $issueBySid = [];
  5308. $confirmBySid = [];
  5309. $approveBySid = [];
  5310. if ($sids !== []) {
  5311. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  5312. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  5313. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  5314. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  5315. try {
  5316. $logs = Db::table('purchase_order_oper_log')
  5317. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  5318. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  5319. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  5320. ->order('id', 'asc')
  5321. ->select();
  5322. } catch (\Throwable $e) {
  5323. $logs = [];
  5324. }
  5325. if (is_array($logs)) {
  5326. $issueSet = array_fill_keys($issueActs, true);
  5327. $confirmSet = array_fill_keys($confirmActs, true);
  5328. $approveSet = array_fill_keys($approveActs, true);
  5329. foreach ($logs as $lg) {
  5330. if (!is_array($lg)) {
  5331. continue;
  5332. }
  5333. $lg = ProcuremenOperLog::normalizeRow($lg);
  5334. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  5335. if ($sid === 0) {
  5336. continue;
  5337. }
  5338. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  5339. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  5340. if ($t === '') {
  5341. continue;
  5342. }
  5343. if (isset($issueSet[$action])) {
  5344. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  5345. $issueBySid[$sid] = $t;
  5346. }
  5347. }
  5348. if (isset($confirmSet[$action])) {
  5349. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  5350. $confirmBySid[$sid] = $t;
  5351. }
  5352. }
  5353. if (isset($approveSet[$action])) {
  5354. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  5355. $approveBySid[$sid] = $t;
  5356. }
  5357. }
  5358. }
  5359. }
  5360. }
  5361. foreach ($rows as &$rw) {
  5362. if (!is_array($rw)) {
  5363. continue;
  5364. }
  5365. $mergeSids = [];
  5366. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5367. foreach ($rw['_order_merge_rows'] as $mr) {
  5368. $mid = (int)($mr['ID'] ?? 0);
  5369. if ($this->isValidScydgyRowId($mid)) {
  5370. $mergeSids[] = $mid;
  5371. }
  5372. }
  5373. }
  5374. $rid = (int)($rw['ID'] ?? 0);
  5375. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  5376. $mergeSids[] = $rid;
  5377. }
  5378. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  5379. $issue = $pick;
  5380. $confirm = '';
  5381. $approve = '';
  5382. foreach ($mergeSids as $sid) {
  5383. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  5384. $issue = $issueBySid[$sid];
  5385. }
  5386. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  5387. $confirm = $confirmBySid[$sid];
  5388. }
  5389. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  5390. $approve = $approveBySid[$sid];
  5391. }
  5392. }
  5393. if ($issue === '' && $pick !== '') {
  5394. $issue = $pick;
  5395. }
  5396. $rw['issue_time'] = $issue;
  5397. $rw['confirm_time'] = $confirm;
  5398. $rw['approve_time'] = $approve;
  5399. }
  5400. unset($rw);
  5401. }
  5402. /**
  5403. * 按主键取一条
  5404. */
  5405. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  5406. {
  5407. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  5408. return [];
  5409. }
  5410. try {
  5411. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  5412. if (is_array($one)) {
  5413. return $one;
  5414. }
  5415. } catch (\Throwable $e) {
  5416. }
  5417. try {
  5418. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  5419. if (is_array($one)) {
  5420. return $one;
  5421. }
  5422. } catch (\Throwable $e) {
  5423. }
  5424. return [];
  5425. }
  5426. /**
  5427. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  5428. */
  5429. protected function formatProcuremenDetailTime($v): string
  5430. {
  5431. if ($v === null || $v === '') {
  5432. return '';
  5433. }
  5434. if (is_numeric($v) && (int)$v > 946684800) {
  5435. return date('Y-m-d H:i:s', (int)$v);
  5436. }
  5437. return ProcuremenTime::formatDisplayDateTime($v);
  5438. }
  5439. /**
  5440. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  5441. */
  5442. protected function formatDeliveryYmd($v): string
  5443. {
  5444. if ($v === null || $v === '') {
  5445. return '';
  5446. }
  5447. $s = trim((string)$v);
  5448. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  5449. return '';
  5450. }
  5451. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5452. return $m[1];
  5453. }
  5454. $ts = strtotime($s);
  5455. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  5456. }
  5457. /**
  5458. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  5459. */
  5460. protected function detailRowSupplierOperated(array $r): bool
  5461. {
  5462. $am = $r['amount'] ?? null;
  5463. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5464. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5465. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5466. return $okAmt || $okDel;
  5467. }
  5468. /**
  5469. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  5470. */
  5471. protected function resolveDetailSupplierOperTime(array $r): string
  5472. {
  5473. if (!$this->detailRowSupplierOperated($r)) {
  5474. return '';
  5475. }
  5476. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  5477. if ($t !== '') {
  5478. return $t;
  5479. }
  5480. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  5481. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  5482. continue;
  5483. }
  5484. $t = $this->formatProcuremenDetailTime($r[$col]);
  5485. if ($t !== '') {
  5486. return $t;
  5487. }
  5488. }
  5489. return '';
  5490. }
  5491. /**
  5492. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  5493. */
  5494. protected function detailRowSupplierAccepted(array $r): bool
  5495. {
  5496. $am = $r['amount'] ?? null;
  5497. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5498. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5499. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5500. return $okAmt && $okDel;
  5501. }
  5502. /**
  5503. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  5504. */
  5505. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  5506. {
  5507. if ($detailCount > 0) {
  5508. return true;
  5509. }
  5510. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  5511. return true;
  5512. }
  5513. $pickTime = trim((string)($main['pick_time'] ?? ''));
  5514. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  5515. return true;
  5516. }
  5517. return false;
  5518. }
  5519. /**
  5520. * 下发时间:优先 pick_time,其次首条下发明细时间
  5521. */
  5522. protected function resolveProcuremenIssueTime(array $main, array $details): string
  5523. {
  5524. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  5525. if ($issueTime !== '') {
  5526. return $issueTime;
  5527. }
  5528. foreach ($details as $dr) {
  5529. if (!is_array($dr)) {
  5530. continue;
  5531. }
  5532. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5533. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  5534. $issueTime = $t;
  5535. }
  5536. }
  5537. if ($issueTime !== '') {
  5538. return $issueTime;
  5539. }
  5540. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5541. }
  5542. /**
  5543. * 直接点「完结」时间:优先操作记录 mark_complete
  5544. */
  5545. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  5546. {
  5547. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  5548. }
  5549. /**
  5550. * 操作记录时间(取指定 action 最近一条)
  5551. *
  5552. * @param string|array<int, string> $actions
  5553. */
  5554. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  5555. {
  5556. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  5557. }
  5558. /**
  5559. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  5560. *
  5561. * @param array $main purchase_order 一行
  5562. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  5563. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  5564. */
  5565. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  5566. {
  5567. $issueCnt = count($details);
  5568. $acceptCnt = 0;
  5569. $pickedName = '';
  5570. $pickedTime = '';
  5571. foreach ($details as $dr) {
  5572. if (!is_array($dr)) {
  5573. continue;
  5574. }
  5575. if ($this->detailRowSupplierAccepted($dr)) {
  5576. $acceptCnt++;
  5577. }
  5578. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5579. if ($pickedName === '') {
  5580. $pickedName = trim((string)($dr['company_name'] ?? ''));
  5581. }
  5582. if ($pickedTime === '') {
  5583. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  5584. if ($pickedTime === '') {
  5585. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5586. }
  5587. }
  5588. }
  5589. }
  5590. $hasMain = $main !== [];
  5591. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  5592. if ($poTime === '') {
  5593. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  5594. }
  5595. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  5596. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  5597. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  5598. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  5599. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  5600. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  5601. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  5602. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  5603. $inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
  5604. $inboundResult = '';
  5605. if ($scydgyId > 0) {
  5606. try {
  5607. $inRow = Db::table('purchase_order_inbound_score')
  5608. ->where('scydgy_id', $scydgyId)
  5609. ->field('result,updatetime,createtime')
  5610. ->find();
  5611. } catch (\Throwable $e) {
  5612. $inRow = null;
  5613. }
  5614. if (is_array($inRow) && $inRow !== []) {
  5615. $inboundResult = trim((string)($inRow['result'] ?? ''));
  5616. if ($inboundScoreTime === '') {
  5617. $inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
  5618. }
  5619. }
  5620. }
  5621. $inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
  5622. $supplierTime = '';
  5623. if ($acceptCnt > 0) {
  5624. foreach ($details as $dr) {
  5625. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  5626. continue;
  5627. }
  5628. $t = $this->resolveDetailSupplierOperTime($dr);
  5629. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  5630. $supplierTime = $t;
  5631. }
  5632. }
  5633. }
  5634. $directComplete = ($mainCompleted && !$issued);
  5635. $doneTime = '';
  5636. if ($mainCompleted) {
  5637. if ($directComplete) {
  5638. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  5639. }
  5640. if ($doneTime === '' && $inboundScoreTime !== '') {
  5641. $doneTime = $inboundScoreTime;
  5642. }
  5643. if ($doneTime === '') {
  5644. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5645. }
  5646. if ($doneTime === '') {
  5647. foreach ($details as $dr) {
  5648. if (!is_array($dr)) {
  5649. continue;
  5650. }
  5651. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  5652. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  5653. $doneTime = $t;
  5654. }
  5655. }
  5656. }
  5657. if ($doneTime === '') {
  5658. $doneTime = $poTime;
  5659. }
  5660. // 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
  5661. if ($doneTime === '' && $confirmApproveTime !== '') {
  5662. $doneTime = $confirmApproveTime;
  5663. }
  5664. }
  5665. if ($directComplete) {
  5666. // 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
  5667. $step1Done = $hasMain;
  5668. $step2Done = false;
  5669. $step3Done = false;
  5670. $step4Done = false;
  5671. $step5Done = false;
  5672. $stepInboundDone = $inboundScored;
  5673. $step6Done = $mainCompleted && $inboundScored;
  5674. } else {
  5675. $step1Done = $issued;
  5676. $step2Done = $issued;
  5677. $step3Done = $acceptCnt > 0;
  5678. $step4Done = $wflowPendingApproval;
  5679. if (!$step4Done) {
  5680. foreach ($details as $dr) {
  5681. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5682. $step4Done = true;
  5683. break;
  5684. }
  5685. }
  5686. }
  5687. $step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
  5688. $stepInboundDone = $inboundScored;
  5689. // 未确认合格/不合格时,「已完结」保持未点亮(灰色)
  5690. $step6Done = $mainCompleted && $inboundScored;
  5691. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  5692. if ($mainCompleted && $issued) {
  5693. $step3Done = true;
  5694. $step4Done = true;
  5695. $step5Done = true;
  5696. // 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
  5697. if ($supplierTime === '') {
  5698. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5699. if ($fillT !== '') {
  5700. $supplierTime = $fillT;
  5701. }
  5702. }
  5703. if ($pickedTime === '') {
  5704. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5705. if ($fillT !== '') {
  5706. $pickedTime = $fillT;
  5707. }
  5708. }
  5709. if ($auditSelectTime === '') {
  5710. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5711. if ($fillT !== '') {
  5712. $auditSelectTime = $fillT;
  5713. }
  5714. }
  5715. if ($confirmApproveTime === '') {
  5716. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5717. if ($fillT !== '') {
  5718. $confirmApproveTime = $fillT;
  5719. }
  5720. }
  5721. }
  5722. }
  5723. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  5724. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  5725. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  5726. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  5727. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  5728. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  5729. $inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
  5730. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  5731. $deadlineLines = [];
  5732. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  5733. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  5734. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  5735. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  5736. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  5737. }
  5738. }
  5739. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  5740. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  5741. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  5742. if ($deliveryDisp === '') {
  5743. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  5744. }
  5745. if ($deliveryDisp !== '') {
  5746. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  5747. }
  5748. }
  5749. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  5750. $deadlineText = implode("\n", $deadlineLines);
  5751. $prefixOperTime = static function (string $t): string {
  5752. $t = trim($t);
  5753. if ($t === '' || $t === '—') {
  5754. return $t;
  5755. }
  5756. if (strpos($t, '操作时间') === 0) {
  5757. return $t;
  5758. }
  5759. return '操作时间:' . $t;
  5760. };
  5761. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  5762. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  5763. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
  5764. $stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5765. $step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5766. $steps = [
  5767. [
  5768. 'title' => '未发',
  5769. 'subtitle' => '',
  5770. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  5771. 'done' => $step1Done,
  5772. ],
  5773. [
  5774. 'title' => '下发',
  5775. 'subtitle' => $deadlineText,
  5776. 'time' => $prefixOperTime($step2Time),
  5777. 'done' => $step2Done,
  5778. ],
  5779. [
  5780. 'title' => '供应商接单',
  5781. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  5782. 'time' => '',
  5783. 'done' => $step3Done,
  5784. ],
  5785. [
  5786. 'title' => '待确认',
  5787. 'subtitle' => $step4Done
  5788. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  5789. : ($issued ? '待选供应商' : ''),
  5790. 'time' => $prefixOperTime($step4Time),
  5791. 'done' => $step4Done,
  5792. ],
  5793. [
  5794. 'title' => '待审批',
  5795. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  5796. 'time' => $prefixOperTime($step5Time),
  5797. 'done' => $step5Done,
  5798. ],
  5799. [
  5800. 'title' => '是否合格',
  5801. 'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
  5802. 'time' => $prefixOperTime($stepInboundTime),
  5803. 'done' => $stepInboundDone,
  5804. ],
  5805. [
  5806. 'title' => '已完结',
  5807. 'subtitle' => '',
  5808. 'time' => $prefixOperTime($step6Time),
  5809. 'done' => $step6Done,
  5810. ],
  5811. ];
  5812. $currentIdx = count($steps) - 1;
  5813. if ($directComplete) {
  5814. // 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
  5815. if (!$step6Done) {
  5816. foreach ($steps as $i => $s) {
  5817. if (($s['title'] ?? '') === '是否合格') {
  5818. $currentIdx = $i;
  5819. break;
  5820. }
  5821. }
  5822. }
  5823. } else {
  5824. foreach ($steps as $i => $s) {
  5825. if (!$s['done']) {
  5826. $currentIdx = $i;
  5827. break;
  5828. }
  5829. }
  5830. }
  5831. $nSteps = count($steps);
  5832. foreach ($steps as $idx => &$s) {
  5833. $s['current'] = ($idx === $currentIdx);
  5834. if ($idx === 0) {
  5835. $s['pdf_left_bg'] = '';
  5836. } else {
  5837. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  5838. }
  5839. if ($idx >= $nSteps - 1) {
  5840. $s['pdf_right_bg'] = '';
  5841. } else {
  5842. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  5843. }
  5844. }
  5845. unset($s);
  5846. $labelMap = [
  5847. 'CCYDH' => '订单号',
  5848. 'CYJMC' => '印件名称',
  5849. 'CCLBMMC' => '承揽部门',
  5850. 'CGYMC' => '工序名称',
  5851. 'CDW' => '单位',
  5852. 'czlyq' => '类型',
  5853. 'NGZL' => '工作量',
  5854. 'CDF' => '单价',
  5855. 'cGzzxMc' => '工作中心',
  5856. 'MBZ' => '备注',
  5857. 'This_quantity' => '本次数量',
  5858. 'ceilingPrice' => '最高限价',
  5859. ];
  5860. $orderSummary = [];
  5861. foreach ($labelMap as $key => $lab) {
  5862. if (!array_key_exists($key, $main)) {
  5863. continue;
  5864. }
  5865. $val = $main[$key];
  5866. if ($val === null) {
  5867. $val = '';
  5868. } elseif (!is_scalar($val)) {
  5869. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  5870. } else {
  5871. $val = (string)$val;
  5872. }
  5873. $orderSummary[] = ['label' => $lab, 'value' => $val];
  5874. }
  5875. $orderSummary[] = [
  5876. 'label' => '是否合格',
  5877. 'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
  5878. ];
  5879. $orderSummaryGrid = [];
  5880. $n = count($orderSummary);
  5881. for ($i = 0; $i < $n; $i += 2) {
  5882. $left = $orderSummary[$i];
  5883. $hasRight = ($i + 1) < $n;
  5884. $orderSummaryGrid[] = [
  5885. 'l1' => $left['label'],
  5886. 'v1' => $left['value'],
  5887. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  5888. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  5889. ];
  5890. }
  5891. return [
  5892. 'steps' => $steps,
  5893. 'orderSummary' => $orderSummary,
  5894. 'orderSummaryGrid' => $orderSummaryGrid,
  5895. 'inbound_result' => $inboundResult,
  5896. 'inbound_score_time'=> $inboundScoreTime,
  5897. 'detailRows' => $details,
  5898. ];
  5899. }
  5900. /**
  5901. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  5902. *
  5903. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  5904. */
  5905. protected function prepareProcuremenDetailsView(string $ids): array
  5906. {
  5907. $main = [];
  5908. try {
  5909. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5910. $main = is_array($one) ? $one : [];
  5911. } catch (\Throwable $e) {
  5912. $main = [];
  5913. }
  5914. $details = [];
  5915. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  5916. if ($mergeRows === []) {
  5917. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  5918. if ($mergeRows === [] && $main !== []) {
  5919. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  5920. }
  5921. }
  5922. $detailSidList = [];
  5923. $anchorSid = (int)$ids;
  5924. if ($anchorSid !== 0) {
  5925. $detailSidList[$anchorSid] = true;
  5926. }
  5927. foreach ($mergeRows as $mr) {
  5928. if (!is_array($mr)) {
  5929. continue;
  5930. }
  5931. $sid = $this->extractScydgyRowId($mr);
  5932. if ($sid !== 0) {
  5933. $detailSidList[$sid] = true;
  5934. }
  5935. }
  5936. try {
  5937. if ($detailSidList !== []) {
  5938. $details = Db::table('purchase_order_detail')
  5939. ->where('scydgy_id', 'in', array_keys($detailSidList))
  5940. ->order('id', 'asc')
  5941. ->select();
  5942. }
  5943. } catch (\Throwable $e) {
  5944. $details = [];
  5945. }
  5946. if (!is_array($details)) {
  5947. $details = [];
  5948. }
  5949. foreach ($details as &$r) {
  5950. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  5951. $r['id'] = $r['ID'];
  5952. }
  5953. if (isset($r['createtime'])) {
  5954. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  5955. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  5956. } else {
  5957. $r['createtime_text'] = (string)$r['createtime'];
  5958. }
  5959. } else {
  5960. $r['createtime_text'] = '';
  5961. }
  5962. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  5963. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  5964. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  5965. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  5966. if (is_array($r)) {
  5967. $r = $this->maskSupplierContactFields($r);
  5968. }
  5969. }
  5970. unset($r);
  5971. $activeDetails = [];
  5972. foreach ($details as $r) {
  5973. if (is_array($r) && empty($r['is_void'])) {
  5974. $activeDetails[] = $r;
  5975. }
  5976. }
  5977. $operLogs = [];
  5978. try {
  5979. $operSidList = array_keys($detailSidList);
  5980. if ($operSidList === [] && (int)$ids !== 0) {
  5981. $operSidList = [(int)$ids];
  5982. }
  5983. if ($operSidList !== []) {
  5984. $operLogs = Db::table('purchase_order_oper_log')
  5985. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  5986. ->order('id', 'asc')
  5987. ->select();
  5988. }
  5989. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  5990. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  5991. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  5992. if ($poId > 0) {
  5993. $operLogs = Db::table('purchase_order_oper_log')
  5994. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  5995. ->order('id', 'asc')
  5996. ->select();
  5997. }
  5998. }
  5999. } catch (\Throwable $e) {
  6000. $operLogs = [];
  6001. }
  6002. if (!is_array($operLogs)) {
  6003. $operLogs = [];
  6004. }
  6005. $operLogsRaw = $operLogs;
  6006. $processNameBySid = [];
  6007. foreach ($mergeRows as $mr) {
  6008. if (!is_array($mr)) {
  6009. continue;
  6010. }
  6011. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  6012. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  6013. if ($psid !== 0 && $gymc !== '') {
  6014. $processNameBySid[$psid] = $gymc;
  6015. }
  6016. }
  6017. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  6018. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
  6019. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  6020. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  6021. if ($ccydh === '') {
  6022. foreach ($details as $r) {
  6023. if (!is_array($r)) {
  6024. continue;
  6025. }
  6026. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  6027. if ($ccydh !== '') {
  6028. break;
  6029. }
  6030. }
  6031. }
  6032. $this->view->assign('ccydh', $ccydh);
  6033. $this->view->assign('steps', $bundle['steps']);
  6034. $this->view->assign('orderSummary', $bundle['orderSummary']);
  6035. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  6036. $this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
  6037. $this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
  6038. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  6039. $this->view->assign('processCount', count($mergeRows));
  6040. $this->view->assign('detailRows', $details);
  6041. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  6042. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  6043. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  6044. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  6045. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  6046. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  6047. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  6048. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  6049. $this->view->assign('operLogs', $operLogs);
  6050. $sg = $quoteView['supplier_groups'] ?? [];
  6051. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
  6052. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  6053. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
  6054. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
  6055. return [
  6056. 'ok' => $main !== [] || $details !== [],
  6057. 'ccydh' => $ccydh,
  6058. 'steps' => $bundle['steps'],
  6059. ];
  6060. }
  6061. /**
  6062. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  6063. */
  6064. public function details()
  6065. {
  6066. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6067. if (is_array($ids)) {
  6068. $ids = isset($ids[0]) ? $ids[0] : '';
  6069. }
  6070. $ids = trim((string)$ids);
  6071. if ($ids === '') {
  6072. $this->error(__('Invalid parameters'));
  6073. }
  6074. $this->assertManualOrderDetailsViewable((int)$ids);
  6075. // 已完结:打开详情时按最新进度/操作记录重存存证 PDF(含质量/交货评分)
  6076. $sid = (int)$ids;
  6077. if ($this->isValidScydgyRowId($sid)) {
  6078. try {
  6079. $poCheck = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  6080. if (is_array($poCheck) && ProcuremenStatus::isPoCompleted($poCheck['status'] ?? '')) {
  6081. $this->refreshCompletedOrderArchivePdf($sid, true);
  6082. }
  6083. } catch (\Throwable $e) {
  6084. Log::write('详情页刷新完结存证PDF失败 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'notice');
  6085. }
  6086. }
  6087. $this->prepareProcuremenDetailsView($ids);
  6088. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  6089. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  6090. $this->view->engine->layout(false);
  6091. try {
  6092. return $this->view->fetch('procuremen/details_dialog_shell');
  6093. } finally {
  6094. if ($restoreLayout) {
  6095. $this->view->engine->layout($restoreLayout);
  6096. }
  6097. }
  6098. }
  6099. /**
  6100. * 已完结订单重生成存证 PDF(与详情页一致,含质量/交货评分与「已完结」节点)
  6101. *
  6102. * @param bool $requireCompleted true 时仅已完结才重生成;false 强制按当前详情重存
  6103. * @return string 本地 web 路径或 OSS URL,失败为空串
  6104. */
  6105. protected function refreshCompletedOrderArchivePdf(int $scydgyId, bool $requireCompleted = true): string
  6106. {
  6107. if (!$this->isValidScydgyRowId($scydgyId)) {
  6108. return '';
  6109. }
  6110. try {
  6111. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6112. } catch (\Throwable $e) {
  6113. $po = null;
  6114. }
  6115. if (!is_array($po) || $po === []) {
  6116. return '';
  6117. }
  6118. if ($requireCompleted && !ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6119. return trim((string)($po['pdf_url'] ?? ''));
  6120. }
  6121. $poId = (int)($po['id'] ?? 0);
  6122. return $this->savePurchaseConfirmDetailPdf($scydgyId, $poId);
  6123. }
  6124. /**
  6125. * CLI / 手机端评分完结后调用:无后台登录态重生成存证 PDF
  6126. */
  6127. public static function regenerateArchivePdfWithoutAuth(int $scydgyId, bool $requireCompleted = true): string
  6128. {
  6129. if ((int)$scydgyId === 0) {
  6130. return '';
  6131. }
  6132. try {
  6133. $ctl = new class extends Procuremen {
  6134. public function _initialize()
  6135. {
  6136. $this->request = \think\Request::instance();
  6137. $tpl = \think\Config::get('template');
  6138. if (!is_array($tpl)) {
  6139. $tpl = [];
  6140. }
  6141. // CLI / 跨模块调用时无 admin 视图目录
  6142. $tpl['view_path'] = APP_PATH . 'admin' . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR;
  6143. $this->view = new \think\View($tpl, \think\Config::get('view_replace_str'));
  6144. $this->model = new \app\admin\model\Procuremen();
  6145. try {
  6146. ProcuremenSchema::ensureAll();
  6147. } catch (\Throwable $e) {
  6148. }
  6149. }
  6150. public function runRegen(int $sid, bool $requireCompleted): string
  6151. {
  6152. return $this->refreshCompletedOrderArchivePdf($sid, $requireCompleted);
  6153. }
  6154. };
  6155. return $ctl->runRegen($scydgyId, $requireCompleted);
  6156. } catch (\Throwable $e) {
  6157. Log::write('regenerateArchivePdfWithoutAuth 失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'error');
  6158. return '';
  6159. }
  6160. }
  6161. /**
  6162. * 解析合并审核工序行(订单号须一致,且均未协助)
  6163. *
  6164. * @return array<int, array<string, mixed>>
  6165. */
  6166. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  6167. {
  6168. $primary = json_decode($rowJson, true);
  6169. if (!is_array($primary)) {
  6170. $this->error(__('Invalid parameters'));
  6171. }
  6172. $merge = json_decode($mergeRowsJson, true);
  6173. if (!is_array($merge) || $merge === []) {
  6174. $merge = [$primary];
  6175. }
  6176. $seen = [];
  6177. $out = [];
  6178. foreach ($merge as $r) {
  6179. if (!is_array($r)) {
  6180. continue;
  6181. }
  6182. $id = $this->extractScydgyRowId($r);
  6183. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  6184. continue;
  6185. }
  6186. $seen[$id] = true;
  6187. $out[] = $r;
  6188. }
  6189. if ($out === []) {
  6190. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  6191. }
  6192. $ccydh = null;
  6193. foreach ($out as $r) {
  6194. $dh = trim((string)($r['CCYDH'] ?? ''));
  6195. if ($ccydh === null) {
  6196. $ccydh = $dh;
  6197. } elseif ($dh !== $ccydh) {
  6198. $this->error('合并审核要求所选行的订单号一致');
  6199. }
  6200. }
  6201. $ids = [];
  6202. foreach ($out as $r) {
  6203. $id = $this->extractScydgyRowId($r);
  6204. if ($this->isValidScydgyRowId($id)) {
  6205. $ids[$id] = true;
  6206. }
  6207. }
  6208. $poBySid = [];
  6209. $detCntBySid = [];
  6210. if ($ids !== []) {
  6211. $idList = array_keys($ids);
  6212. try {
  6213. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  6214. if (is_array($poList)) {
  6215. foreach ($poList as $po) {
  6216. if (!is_array($po)) {
  6217. continue;
  6218. }
  6219. $sid = (int)($po['scydgy_id'] ?? 0);
  6220. if ($this->isValidScydgyRowId($sid)) {
  6221. $poBySid[$sid] = $po;
  6222. }
  6223. }
  6224. }
  6225. } catch (\Throwable $e) {
  6226. }
  6227. try {
  6228. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  6229. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  6230. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  6231. if (is_array($detRows)) {
  6232. foreach ($detRows as $dr) {
  6233. if (!is_array($dr)) {
  6234. continue;
  6235. }
  6236. $sid = (int)($dr['scydgy_id'] ?? 0);
  6237. if ($this->isValidScydgyRowId($sid)) {
  6238. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  6239. }
  6240. }
  6241. }
  6242. } catch (\Throwable $e) {
  6243. }
  6244. }
  6245. foreach ($out as $r) {
  6246. $id = $this->extractScydgyRowId($r);
  6247. if (!$this->isValidScydgyRowId($id)) {
  6248. continue;
  6249. }
  6250. $po = $poBySid[$id] ?? null;
  6251. if (!is_array($po)) {
  6252. continue;
  6253. }
  6254. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6255. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6256. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  6257. }
  6258. $detCnt = (int)($detCntBySid[$id] ?? 0);
  6259. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  6260. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6261. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  6262. }
  6263. }
  6264. return $out;
  6265. }
  6266. /**
  6267. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  6268. */
  6269. protected function maskSupplierContactFields(array $item): array
  6270. {
  6271. if (array_key_exists('email', $item)) {
  6272. $item['email'] = mask_email((string)$item['email']);
  6273. }
  6274. if (array_key_exists('phone', $item)) {
  6275. $item['phone'] = mask_phone((string)$item['phone']);
  6276. }
  6277. return $item;
  6278. }
  6279. /**
  6280. * @param array<int, array<string, mixed>> $list
  6281. * @return array<int, array<string, mixed>>
  6282. */
  6283. protected function maskSupplierContactList(array $list): array
  6284. {
  6285. $out = [];
  6286. foreach ($list as $item) {
  6287. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  6288. }
  6289. return $out;
  6290. }
  6291. /**
  6292. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  6293. *
  6294. * @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
  6295. * @return array<string, string>|null
  6296. */
  6297. protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
  6298. {
  6299. if (!is_array($row)) {
  6300. return null;
  6301. }
  6302. $norm = [];
  6303. foreach ($row as $k => $v) {
  6304. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  6305. }
  6306. $row = $norm;
  6307. $st = $row['status'] ?? '';
  6308. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  6309. return null;
  6310. }
  6311. $companyName = '';
  6312. foreach (['company_name', 'name'] as $nk) {
  6313. if (!empty($row[$nk])) {
  6314. $companyName = trim((string)$row[$nk]);
  6315. break;
  6316. }
  6317. }
  6318. if ($companyName === '') {
  6319. return null;
  6320. }
  6321. $username = '';
  6322. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  6323. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  6324. $username = trim((string)$row[$uk]);
  6325. break;
  6326. }
  6327. }
  6328. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  6329. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  6330. if ($phone === '' && isset($row['account'])) {
  6331. $phone = trim((string)$row['account']);
  6332. }
  6333. if ($phone === '' && isset($row['mobile'])) {
  6334. $phone = trim((string)$row['mobile']);
  6335. }
  6336. if ($requireContactChannels && $email === '' && $phone === '') {
  6337. return null;
  6338. }
  6339. $category = '';
  6340. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6341. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6342. $category = trim((string)$row[$ck]);
  6343. break;
  6344. }
  6345. }
  6346. return [
  6347. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  6348. 'name' => $companyName,
  6349. 'company_name' => $companyName,
  6350. 'username' => $username,
  6351. 'email' => $email,
  6352. 'phone' => $phone,
  6353. 'category' => $category,
  6354. 'company_type' => $category,
  6355. ];
  6356. }
  6357. /**
  6358. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  6359. */
  6360. protected function resolveCustomerContactById(string $id): ?array
  6361. {
  6362. $id = trim($id);
  6363. if ($id === '' || !ctype_digit($id)) {
  6364. return null;
  6365. }
  6366. try {
  6367. $row = Db::table('customer')->where('id', (int)$id)->find();
  6368. } catch (\Throwable $e) {
  6369. return null;
  6370. }
  6371. return $this->buildCustomerContactPayloadFromRow($row);
  6372. }
  6373. /**
  6374. * 按供应商名称解析联系信息(兼容旧提交数据)
  6375. *
  6376. * @param bool $requireContactChannels true 时须有邮箱或手机
  6377. */
  6378. protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
  6379. {
  6380. $name = trim($name);
  6381. if ($name === '') {
  6382. return null;
  6383. }
  6384. try {
  6385. // customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
  6386. $row = Db::table('customer')
  6387. ->where('company_name', $name)
  6388. ->order('id', 'desc')
  6389. ->find();
  6390. } catch (\Throwable $e) {
  6391. return null;
  6392. }
  6393. return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
  6394. }
  6395. /**
  6396. * 规范化下发/确认时勾选的供应商
  6397. *
  6398. * @param array<int, mixed> $companies
  6399. * @return array<int, array<string, string>>
  6400. */
  6401. protected function normalizePickCompanies(array $companies): array
  6402. {
  6403. $out = [];
  6404. foreach ($companies as $c) {
  6405. if (!is_array($c)) {
  6406. continue;
  6407. }
  6408. $resolved = null;
  6409. $cid = trim((string)($c['id'] ?? ''));
  6410. if ($cid !== '') {
  6411. $resolved = $this->resolveCustomerContactById($cid);
  6412. }
  6413. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  6414. if ($resolved === null && $name !== '') {
  6415. $resolved = $this->resolveCustomerContactByCompanyName($name);
  6416. }
  6417. if ($resolved === null) {
  6418. continue;
  6419. }
  6420. $out[] = $resolved;
  6421. }
  6422. return $out;
  6423. }
  6424. /**
  6425. * 同一次下发批次的时间(优先 pick_time,空则 createtime)
  6426. */
  6427. protected function procuremenIssueBatchTime(array $row): string
  6428. {
  6429. $t = $this->procuremenRowListSortTime($row, 'pick_time');
  6430. if ($t !== '') {
  6431. return $t;
  6432. }
  6433. $t = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  6434. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  6435. return $t;
  6436. }
  6437. return '';
  6438. }
  6439. /**
  6440. * 列表/弹窗合并键:同一订单号 + 同一次下发才合成一行。
  6441. * 避免 202606213S 8-06 下发封面覆膜、8-18 再下发书签模切被并到确认页同一行。
  6442. */
  6443. protected function procuremenIssueBatchGroupKey(array $row): string
  6444. {
  6445. $dh = trim((string)($row['CCYDH'] ?? ''));
  6446. $sid = (int)($row['scydgy_id'] ?? $row['ID'] ?? $row['id'] ?? 0);
  6447. if ($dh === '') {
  6448. return '_id_' . $sid;
  6449. }
  6450. $batch = $this->procuremenIssueBatchTime($row);
  6451. return $batch !== '' ? ($dh . '|' . $batch) : ($dh . '|sid:' . $sid);
  6452. }
  6453. /**
  6454. * 是否同一次下发(同一订单号且下发时间一致)
  6455. */
  6456. protected function isSameProcuremenIssueBatch(array $anchor, array $po): bool
  6457. {
  6458. return $this->procuremenIssueBatchGroupKey($anchor) === $this->procuremenIssueBatchGroupKey($po);
  6459. }
  6460. /**
  6461. * @param array<int, mixed> $pos
  6462. * @return array<int, array<string, mixed>>
  6463. */
  6464. protected function filterPurchaseOrdersSameIssueBatch(array $pos, array $anchor): array
  6465. {
  6466. $out = [];
  6467. foreach ($pos as $po) {
  6468. if (is_array($po) && $this->isSameProcuremenIssueBatch($anchor, $po)) {
  6469. $out[] = $po;
  6470. }
  6471. }
  6472. return $out !== [] ? $out : [$anchor];
  6473. }
  6474. /**
  6475. * 确认供应商列表:同一订单号且同一次下发才合并为一行
  6476. *
  6477. * @param array<int, array<string, mixed>> $pool
  6478. * @return array<int, array<string, mixed>>
  6479. */
  6480. protected function collapseProcuremenPoolByOrder(array $pool): array
  6481. {
  6482. if ($pool === []) {
  6483. return [];
  6484. }
  6485. $groups = [];
  6486. foreach ($pool as $row) {
  6487. if (!is_array($row)) {
  6488. continue;
  6489. }
  6490. $key = $this->procuremenIssueBatchGroupKey($row);
  6491. if (!isset($groups[$key])) {
  6492. $groups[$key] = [];
  6493. }
  6494. $groups[$key][] = $row;
  6495. }
  6496. $out = [];
  6497. foreach ($groups as $ccydh => $rows) {
  6498. if ($rows === []) {
  6499. continue;
  6500. }
  6501. usort($rows, function ($a, $b) {
  6502. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  6503. });
  6504. $head = $rows[0];
  6505. $gymcList = [];
  6506. foreach ($rows as $r) {
  6507. $g = trim((string)($r['CGYMC'] ?? ''));
  6508. if ($g !== '' && !in_array($g, $gymcList, true)) {
  6509. $gymcList[] = $g;
  6510. }
  6511. }
  6512. $merged = $head;
  6513. $orderDh = trim((string)($head['CCYDH'] ?? ''));
  6514. $merged['order_key'] = $orderDh;
  6515. $merged['process_count'] = count($rows);
  6516. $merged['_order_merge_rows'] = $rows;
  6517. $qtyList = [];
  6518. $priceList = [];
  6519. foreach ($rows as $r) {
  6520. if (!is_array($r)) {
  6521. continue;
  6522. }
  6523. $qtyList[] = $this->resolveProcuremenThisQuantity($r);
  6524. $priceList[] = $this->resolveProcuremenCeilingPrice($r);
  6525. }
  6526. if (count($rows) > 1) {
  6527. $merged['CGYMC'] = implode('、', $gymcList);
  6528. // 多工序:数量/限价按有值项顿号间隔(空值不占位)
  6529. $merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  6530. $merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  6531. } else {
  6532. $merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
  6533. $merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
  6534. }
  6535. // 已选供应商:取合并行中首个非空 pick_company_name
  6536. $pickedName = '';
  6537. foreach ($rows as $r) {
  6538. if (!is_array($r)) {
  6539. continue;
  6540. }
  6541. $pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
  6542. if ($pn !== '') {
  6543. $pickedName = $pn;
  6544. break;
  6545. }
  6546. }
  6547. if ($pickedName !== '') {
  6548. $merged['pick_company_name'] = $pickedName;
  6549. $merged['picked_supplier_name'] = $pickedName;
  6550. }
  6551. $mergedPickTime = '';
  6552. foreach ($rows as $r) {
  6553. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  6554. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  6555. $mergedPickTime = $t;
  6556. }
  6557. }
  6558. if ($mergedPickTime !== '') {
  6559. $merged['pick_time'] = $mergedPickTime;
  6560. }
  6561. $out[] = $merged;
  6562. }
  6563. usort($out, function ($a, $b) {
  6564. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  6565. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  6566. if ($ta === $tb) {
  6567. $ida = (int)($a['purchase_order_id'] ?? 0);
  6568. $idb = (int)($b['purchase_order_id'] ?? 0);
  6569. if ($ida !== $idb) {
  6570. return $idb <=> $ida;
  6571. }
  6572. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  6573. }
  6574. if ($ta === '') {
  6575. return 1;
  6576. }
  6577. if ($tb === '') {
  6578. return -1;
  6579. }
  6580. return strcmp($tb, $ta);
  6581. });
  6582. return $out;
  6583. }
  6584. /**
  6585. * 待确认供应商:同一订单号且同一次下发的工序(wflow_status=待确认)
  6586. *
  6587. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6588. */
  6589. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  6590. {
  6591. $scydgyId = trim($scydgyId);
  6592. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6593. if ($scydgyId === '') {
  6594. return $empty;
  6595. }
  6596. try {
  6597. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6598. } catch (\Throwable $e) {
  6599. $anchor = null;
  6600. }
  6601. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  6602. return $empty;
  6603. }
  6604. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6605. if ($ccydh === '') {
  6606. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  6607. }
  6608. try {
  6609. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  6610. } catch (\Throwable $e) {
  6611. $pos = [$anchor];
  6612. }
  6613. if (!is_array($pos) || $pos === []) {
  6614. $pos = [$anchor];
  6615. }
  6616. $pos = $this->filterPurchaseOrdersSameIssueBatch($pos, $anchor);
  6617. return [
  6618. 'ccydh' => $ccydh,
  6619. 'pos' => $pos,
  6620. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6621. ];
  6622. }
  6623. /**
  6624. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  6625. */
  6626. protected function purchaseOrderRowInConfirmStage(array $po): bool
  6627. {
  6628. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6629. return false;
  6630. }
  6631. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  6632. return false;
  6633. }
  6634. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  6635. return true;
  6636. }
  6637. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  6638. $sid = (int)($po['scydgy_id'] ?? 0);
  6639. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  6640. }
  6641. return false;
  6642. }
  6643. /**
  6644. * 采购确认:同一订单号且同一次下发的待审批工序(与列表合并规则一致)
  6645. *
  6646. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6647. */
  6648. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  6649. {
  6650. $scydgyId = trim($scydgyId);
  6651. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6652. if ($scydgyId === '') {
  6653. return $empty;
  6654. }
  6655. try {
  6656. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6657. } catch (\Throwable $e) {
  6658. $anchor = null;
  6659. }
  6660. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  6661. return $empty;
  6662. }
  6663. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6664. if ($ccydh === '') {
  6665. return [
  6666. 'ccydh' => '',
  6667. 'pos' => [$anchor],
  6668. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  6669. ];
  6670. }
  6671. try {
  6672. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  6673. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  6674. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  6675. } catch (\Throwable $e) {
  6676. $pos = [$anchor];
  6677. }
  6678. if (!is_array($pos) || $pos === []) {
  6679. $pos = [$anchor];
  6680. }
  6681. $pos = array_values(array_filter($pos, function ($po) {
  6682. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  6683. }));
  6684. if ($pos === []) {
  6685. $pos = [$anchor];
  6686. }
  6687. $pos = $this->filterPurchaseOrdersSameIssueBatch($pos, $anchor);
  6688. return [
  6689. 'ccydh' => $ccydh,
  6690. 'pos' => $pos,
  6691. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6692. ];
  6693. }
  6694. /**
  6695. * @param array<int, array<string, mixed>> $purchaseOrders
  6696. * @return array<int, array<string, mixed>>
  6697. */
  6698. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  6699. {
  6700. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  6701. $byId = [];
  6702. foreach ($pool as $r) {
  6703. if (!is_array($r)) {
  6704. continue;
  6705. }
  6706. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  6707. if ($this->isValidScydgyRowId($sid)) {
  6708. $byId[$sid] = $r;
  6709. }
  6710. }
  6711. $out = [];
  6712. foreach ($purchaseOrders as $po) {
  6713. if (!is_array($po)) {
  6714. continue;
  6715. }
  6716. $sid = (int)($po['scydgy_id'] ?? 0);
  6717. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  6718. $out[] = $byId[$sid];
  6719. }
  6720. }
  6721. return $out;
  6722. }
  6723. /**
  6724. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  6725. *
  6726. * @return array<int, array<string, mixed>>
  6727. */
  6728. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  6729. {
  6730. $scydgyId = trim($scydgyId);
  6731. if ($scydgyId === '') {
  6732. return [];
  6733. }
  6734. try {
  6735. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6736. } catch (\Throwable $e) {
  6737. $anchor = null;
  6738. }
  6739. if (!is_array($anchor)) {
  6740. return [];
  6741. }
  6742. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  6743. return [];
  6744. }
  6745. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6746. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  6747. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  6748. try {
  6749. $q = Db::table('purchase_order');
  6750. if ($ccydh !== '' && $isValidPick) {
  6751. $q->where('CCYDH', $ccydh)->where('pick_time', $pickTime);
  6752. } else {
  6753. $q->where('scydgy_id', $scydgyId);
  6754. }
  6755. $pos = $q->order('scydgy_id', 'asc')->select();
  6756. } catch (\Throwable $e) {
  6757. $pos = [$anchor];
  6758. }
  6759. if (!is_array($pos) || $pos === []) {
  6760. $pos = [$anchor];
  6761. }
  6762. $pos = array_values(array_filter($pos, function ($po) {
  6763. if (!is_array($po)) {
  6764. return false;
  6765. }
  6766. $mr = $po['mod_rq'] ?? null;
  6767. if ($mr === null || $mr === '') {
  6768. return true;
  6769. }
  6770. $mrs = trim((string)$mr);
  6771. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  6772. }));
  6773. if ($pos === []) {
  6774. $pos = [$anchor];
  6775. }
  6776. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  6777. if ($rows === []) {
  6778. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  6779. }
  6780. return $rows;
  6781. }
  6782. /**
  6783. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  6784. *
  6785. * @param array<int, array<string, mixed>> $mergeRows
  6786. * @return array<int, array<string, mixed>>
  6787. */
  6788. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  6789. {
  6790. $list = array_values($mergeRows);
  6791. $n = count($list);
  6792. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  6793. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  6794. $mergeSame = $n > 1 && $orderKey0 !== '';
  6795. if ($mergeSame) {
  6796. foreach ($list as $rr) {
  6797. if (!is_array($rr)) {
  6798. $mergeSame = false;
  6799. break;
  6800. }
  6801. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  6802. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  6803. $mergeSame = false;
  6804. break;
  6805. }
  6806. }
  6807. }
  6808. $out = [];
  6809. foreach ($list as $idx => $r) {
  6810. if (!is_array($r)) {
  6811. continue;
  6812. }
  6813. $qty = $this->resolveProcuremenThisQuantity($r);
  6814. $price = $this->resolveProcuremenCeilingPrice($r);
  6815. $sid = $this->extractScydgyRowId($r);
  6816. $out[] = [
  6817. 'seq' => $idx + 1,
  6818. 'scydgy_id' => $sid,
  6819. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6820. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6821. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6822. 'CDW' => trim((string)($r['CDW'] ?? '')),
  6823. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  6824. 'NGZL' => $r['NGZL'] ?? '',
  6825. 'This_quantity' => $qty,
  6826. 'ceilingPrice' => $price,
  6827. 'CDF' => trim((string)($r['CDF'] ?? '')),
  6828. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  6829. 'show_order_cells' => !$mergeSame || $idx === 0,
  6830. 'order_rowspan' => $mergeSame ? $n : 1,
  6831. ];
  6832. }
  6833. return $out;
  6834. }
  6835. /**
  6836. * 解析金额/数量(去千分位等非数字字符)
  6837. */
  6838. protected function parseProcuremenMoneyNumber($value): ?float
  6839. {
  6840. if ($value === null || $value === '') {
  6841. return null;
  6842. }
  6843. if (is_numeric($value)) {
  6844. return (float)$value;
  6845. }
  6846. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  6847. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  6848. }
  6849. protected function formatProcuremenMoneyDisplay(?float $amount): string
  6850. {
  6851. if ($amount === null) {
  6852. return '';
  6853. }
  6854. // 保留小数(最多 5 位),去掉末尾无意义的 0,避免 0.25 被显示成 0
  6855. $s = rtrim(rtrim(sprintf('%.5F', (float)$amount), '0'), '.');
  6856. return $s === '' ? '0' : $s;
  6857. }
  6858. /**
  6859. * 列表/详情展示:工作量为 0 时显示空
  6860. */
  6861. protected function formatProcuremenWorkloadDisplay($value): string
  6862. {
  6863. if ($value === null || $value === '') {
  6864. return '';
  6865. }
  6866. $s = trim((string)$value);
  6867. if ($s === '') {
  6868. return '';
  6869. }
  6870. if (is_numeric($s) && (float)$s == 0) {
  6871. return '';
  6872. }
  6873. return $s;
  6874. }
  6875. /**
  6876. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  6877. */
  6878. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  6879. {
  6880. foreach ($details as $d) {
  6881. if (!is_array($d)) {
  6882. continue;
  6883. }
  6884. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  6885. $cn = trim((string)($d['company_name'] ?? ''));
  6886. if ($cn !== '') {
  6887. return $cn;
  6888. }
  6889. }
  6890. }
  6891. return trim((string)($main['pick_company_name'] ?? ''));
  6892. }
  6893. /**
  6894. * 详情报价小计:单价 × 本工序本次数量
  6895. */
  6896. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  6897. {
  6898. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  6899. if ($unit === null) {
  6900. return null;
  6901. }
  6902. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  6903. if ($qty === null || $qty <= 0) {
  6904. return null;
  6905. }
  6906. return $unit * $qty;
  6907. }
  6908. /**
  6909. * 详情页:工序小计 + 供应商分组报价与总计
  6910. *
  6911. * @param array<int, array<string, mixed>> $mergeRows
  6912. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  6913. * @return array{
  6914. * process_rows: array,
  6915. * supplier_groups: array,
  6916. * order_total_text: string,
  6917. * order_total_has: bool,
  6918. * selected_company: string
  6919. * }
  6920. */
  6921. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  6922. {
  6923. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  6924. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  6925. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
  6926. || ((int)($main['manual_pick'] ?? 0) === 1);
  6927. $qtyBySid = [];
  6928. $gymcBySid = [];
  6929. $orderedSids = [];
  6930. foreach ($mergeRows as $mr) {
  6931. if (!is_array($mr)) {
  6932. continue;
  6933. }
  6934. $sid = $this->extractScydgyRowId($mr);
  6935. if ($this->isValidScydgyRowId($sid)) {
  6936. $orderedSids[] = $sid;
  6937. }
  6938. $qty = trim((string)($mr['This_quantity'] ?? ''));
  6939. if ($qty === '') {
  6940. $qty = trim((string)($mr['NGZL'] ?? ''));
  6941. }
  6942. $qtyBySid[$sid] = $qty;
  6943. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  6944. }
  6945. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  6946. $detailByCompanySid = [];
  6947. foreach ($details as $d) {
  6948. if (!is_array($d)) {
  6949. continue;
  6950. }
  6951. $cn = trim((string)($d['company_name'] ?? ''));
  6952. $sid = (int)($d['scydgy_id'] ?? 0);
  6953. if ($cn === '' || $sid === 0) {
  6954. continue;
  6955. }
  6956. if (!isset($detailByCompanySid[$cn])) {
  6957. $detailByCompanySid[$cn] = [];
  6958. }
  6959. $detailByCompanySid[$cn][$sid] = $d;
  6960. }
  6961. $supplierGroups = [];
  6962. foreach ($detailByCompanySid as $cn => $bySid) {
  6963. $lines = [];
  6964. $groupTotal = 0.0;
  6965. $groupHas = false;
  6966. $groupVoid = true;
  6967. $usedSids = [];
  6968. $appendLine = function (int $sid, array $d) use (
  6969. &$lines,
  6970. &$groupTotal,
  6971. &$groupHas,
  6972. &$groupVoid,
  6973. $qtyBySid,
  6974. $gymcBySid,
  6975. $quoteVisible
  6976. ) {
  6977. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  6978. if (!$isVoid) {
  6979. $groupVoid = false;
  6980. }
  6981. $qtyStr = $qtyBySid[$sid] ?? '';
  6982. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  6983. $am = trim((string)($d['amount'] ?? ''));
  6984. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  6985. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  6986. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  6987. $sub = null;
  6988. if (!$isVoid && $amountNum !== null) {
  6989. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  6990. }
  6991. $ct = $this->resolveDetailSupplierOperTime($d);
  6992. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  6993. $leadFilled = ($leadDays !== null);
  6994. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  6995. $line = [
  6996. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  6997. 'amount' => $am,
  6998. 'unit_price_text' => $amountFilled
  6999. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  7000. : '未填写',
  7001. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  7002. 'delivery_ymd' => $deliveryYmd,
  7003. 'amount_filled' => $amountFilled,
  7004. 'delivery_filled' => $deliveryFilled,
  7005. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  7006. 'lead_days' => $leadFilled ? $leadDays : '',
  7007. 'lead_days_filled'=> $leadFilled,
  7008. 'lead_days_show' => $leadText,
  7009. 'lead_days_text' => $leadText,
  7010. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  7011. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  7012. 'is_void' => $isVoid,
  7013. 'oper_time_text' => $ct,
  7014. ];
  7015. if (!$quoteVisible && !$isVoid) {
  7016. $this->maskSupplierQuoteLineBeforeDeadline($line);
  7017. } elseif ($sub !== null) {
  7018. $groupTotal += $sub;
  7019. $groupHas = true;
  7020. }
  7021. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  7022. };
  7023. foreach ($orderedSids as $sid) {
  7024. if (!isset($bySid[$sid])) {
  7025. continue;
  7026. }
  7027. $usedSids[$sid] = true;
  7028. $appendLine($sid, $bySid[$sid]);
  7029. }
  7030. foreach ($bySid as $sid => $d) {
  7031. if (isset($usedSids[$sid])) {
  7032. continue;
  7033. }
  7034. $appendLine((int)$sid, $d);
  7035. }
  7036. $firstDetail = null;
  7037. foreach ($bySid as $d) {
  7038. if (is_array($d)) {
  7039. $firstDetail = $d;
  7040. break;
  7041. }
  7042. }
  7043. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  7044. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  7045. if ($username === '' && $ph !== '') {
  7046. $username = $this->resolveCustomerContactName($ph, $cn);
  7047. }
  7048. $remark = '';
  7049. foreach ($bySid as $d) {
  7050. if (!is_array($d)) {
  7051. continue;
  7052. }
  7053. $rm = '';
  7054. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  7055. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  7056. $rm = trim((string)$d[$rk]);
  7057. break;
  7058. }
  7059. }
  7060. if ($rm !== '') {
  7061. $remark = $rm;
  7062. break;
  7063. }
  7064. }
  7065. $lineCount = count($lines);
  7066. $hasRemark = $lineCount > 0;
  7067. $supplierGroup = [
  7068. 'company_name' => $cn,
  7069. 'username' => $username,
  7070. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  7071. 'phone' => $ph,
  7072. 'remark' => $remark,
  7073. 'has_remark' => $hasRemark,
  7074. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  7075. 'is_void' => $groupVoid,
  7076. 'lines' => $lines,
  7077. 'line_count' => $lineCount,
  7078. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  7079. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  7080. 'has_total' => $lineCount > 0,
  7081. ];
  7082. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  7083. $supplierGroups[] = $supplierGroup;
  7084. }
  7085. usort($supplierGroups, function ($a, $b) {
  7086. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  7087. return ($a['is_void'] ?? false) ? 1 : -1;
  7088. }
  7089. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  7090. return ($a['is_selected'] ?? false) ? -1 : 1;
  7091. }
  7092. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  7093. });
  7094. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  7095. return [
  7096. 'process_rows' => $processRows,
  7097. 'supplier_groups' => $supplierGroups,
  7098. 'order_total_text' => '',
  7099. 'order_total_has' => false,
  7100. 'selected_company' => $selectedCompany,
  7101. ];
  7102. }
  7103. /**
  7104. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  7105. */
  7106. protected function buildProcessLinesPlain(array $mergeRows): string
  7107. {
  7108. $lines = [];
  7109. $i = 1;
  7110. foreach ($mergeRows as $r) {
  7111. if (!is_array($r)) {
  7112. continue;
  7113. }
  7114. $gymc = trim((string)($r['CGYMC'] ?? ''));
  7115. $dw = trim((string)($r['CDW'] ?? ''));
  7116. $gzl = trim((string)($r['NGZL'] ?? ''));
  7117. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  7118. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  7119. if ($dw !== '') {
  7120. $parts[] = '单位:' . $dw;
  7121. }
  7122. if ($gzl !== '') {
  7123. $parts[] = '工作量:' . $gzl;
  7124. }
  7125. if ($qty !== '') {
  7126. $parts[] = '本次数量:' . $qty;
  7127. }
  7128. $lines[] = implode(' ', $parts);
  7129. $i++;
  7130. }
  7131. return implode("\n", $lines);
  7132. }
  7133. /**
  7134. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  7135. *
  7136. * @return array<string, string>
  7137. */
  7138. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  7139. {
  7140. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  7141. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  7142. }
  7143. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  7144. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  7145. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7146. $cyjmc = '';
  7147. foreach ($mergeRows as $mr) {
  7148. if (!is_array($mr)) {
  7149. continue;
  7150. }
  7151. if ($ccydh === '') {
  7152. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  7153. }
  7154. if ($cyjmc === '') {
  7155. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  7156. }
  7157. }
  7158. if ($pos !== []) {
  7159. $firstPo = $pos[0];
  7160. if (is_array($firstPo)) {
  7161. if ($ccydh === '') {
  7162. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  7163. }
  7164. if ($cyjmc === '') {
  7165. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  7166. }
  7167. }
  7168. }
  7169. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  7170. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  7171. if (is_array($any)) {
  7172. if ($ccydh === '') {
  7173. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  7174. }
  7175. if ($cyjmc === '') {
  7176. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  7177. }
  7178. }
  7179. }
  7180. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  7181. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  7182. $cgymc = '';
  7183. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  7184. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  7185. }
  7186. return [
  7187. 'ccydh' => $ccydh,
  7188. 'cyjmc' => $cyjmc,
  7189. 'cgymc' => $cgymc,
  7190. 'process_lines' => $processLines,
  7191. 'process_lines_html' => '',
  7192. ];
  7193. }
  7194. /**
  7195. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  7196. */
  7197. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  7198. {
  7199. $lines = [];
  7200. if ($ccydh !== '') {
  7201. $lines[] = '订单号:' . $ccydh;
  7202. }
  7203. if ($cyjmc !== '') {
  7204. $lines[] = '印件名称:' . $cyjmc;
  7205. }
  7206. if ($processPlain !== '') {
  7207. $lines[] = $processPlain;
  7208. }
  7209. return implode("\n", $lines);
  7210. }
  7211. /**
  7212. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  7213. *
  7214. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  7215. */
  7216. protected function buildPlatformLinksPlain(array $detailLinks): string
  7217. {
  7218. $lines = [];
  7219. $i = 1;
  7220. foreach ($detailLinks as $lk) {
  7221. if (!is_array($lk)) {
  7222. continue;
  7223. }
  7224. $url = trim((string)($lk['url'] ?? ''));
  7225. if ($url === '') {
  7226. continue;
  7227. }
  7228. $label = trim((string)($lk['cgymc'] ?? ''));
  7229. if ($label === '') {
  7230. $label = '工序' . $i;
  7231. }
  7232. $lines[] = $label . ':' . $url;
  7233. $i++;
  7234. }
  7235. return implode("\n", $lines);
  7236. }
  7237. /**
  7238. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  7239. *
  7240. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  7241. */
  7242. protected function buildPlatformLinksHtml(array $detailLinks): string
  7243. {
  7244. $parts = [];
  7245. $i = 1;
  7246. foreach ($detailLinks as $lk) {
  7247. if (!is_array($lk)) {
  7248. continue;
  7249. }
  7250. $url = trim((string)($lk['url'] ?? ''));
  7251. if ($url === '') {
  7252. continue;
  7253. }
  7254. $label = trim((string)($lk['cgymc'] ?? ''));
  7255. if ($label === '') {
  7256. $label = '工序' . $i;
  7257. }
  7258. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  7259. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  7260. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  7261. $i++;
  7262. }
  7263. return implode("<br>\n", $parts);
  7264. }
  7265. /**
  7266. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  7267. *
  7268. * @return array<string, mixed>
  7269. */
  7270. protected function loadMailerConfig(): array
  7271. {
  7272. try {
  7273. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  7274. } catch (\Throwable $e) {
  7275. $cfg = [];
  7276. }
  7277. return is_array($cfg) ? $cfg : [];
  7278. }
  7279. protected function loadNotifyTemplateRow(string $scene): ?array
  7280. {
  7281. try {
  7282. $row = Db::table('purchase_sms_template')
  7283. ->where('scene', $scene)
  7284. ->where(function ($q) {
  7285. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  7286. })
  7287. ->order('id', 'asc')
  7288. ->find();
  7289. } catch (\Throwable $e) {
  7290. return null;
  7291. }
  7292. if (!is_array($row) || $row === []) {
  7293. return null;
  7294. }
  7295. return [
  7296. 'title' => trim((string)($row['title'] ?? '')),
  7297. 'content' => trim((string)($row['content'] ?? '')),
  7298. ];
  7299. }
  7300. /**
  7301. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  7302. */
  7303. protected function buildProcessLinesHtml(array $mergeRows): string
  7304. {
  7305. if (count($mergeRows) <= 1) {
  7306. $r = $mergeRows[0] ?? [];
  7307. if (!is_array($r)) {
  7308. return '';
  7309. }
  7310. $gymc = trim((string)($r['CGYMC'] ?? ''));
  7311. $dw = trim((string)($r['CDW'] ?? ''));
  7312. $gzl = trim((string)($r['NGZL'] ?? ''));
  7313. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  7314. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  7315. if ($dw !== '') {
  7316. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  7317. }
  7318. if ($gzl !== '') {
  7319. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  7320. }
  7321. if ($qty !== '') {
  7322. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  7323. }
  7324. return $html;
  7325. }
  7326. $rows = '';
  7327. $i = 1;
  7328. foreach ($mergeRows as $r) {
  7329. if (!is_array($r)) {
  7330. continue;
  7331. }
  7332. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  7333. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  7334. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  7335. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  7336. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  7337. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  7338. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  7339. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  7340. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  7341. $i++;
  7342. }
  7343. if ($rows === '') {
  7344. return '';
  7345. }
  7346. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  7347. . '<thead><tr style="background:#f5f5f5;">'
  7348. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  7349. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  7350. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  7351. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  7352. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  7353. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  7354. }
  7355. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  7356. {
  7357. $sysRq = trim($sysRq);
  7358. if ($sysRq === '') {
  7359. if ($required) {
  7360. $this->error('请选择招标截止日期');
  7361. }
  7362. return '';
  7363. }
  7364. $ts = strtotime($sysRq);
  7365. if ($ts === false || $ts <= 0) {
  7366. $this->error('招标截止日期格式无效');
  7367. }
  7368. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  7369. if (!$allowPast) {
  7370. $ymd = date('Y-m-d', $ts);
  7371. if ($ymd < date('Y-m-d')) {
  7372. $this->error('招标截止日期不能早于今天');
  7373. }
  7374. if ($ts <= time()) {
  7375. $this->error('招标截止时间不能早于当前时间');
  7376. }
  7377. }
  7378. return date('Y-m-d H:i:s', $ts);
  7379. }
  7380. /**
  7381. * 确保 purchase_order.czlyq(类型)存在
  7382. */
  7383. protected function ensurePurchaseOrderCzlyqColumn(): void
  7384. {
  7385. static $done = false;
  7386. if ($done) {
  7387. return;
  7388. }
  7389. $done = true;
  7390. try {
  7391. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  7392. if (empty($cols)) {
  7393. Db::execute(
  7394. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  7395. );
  7396. }
  7397. } catch (\Throwable $e) {
  7398. // ignore
  7399. }
  7400. }
  7401. /**
  7402. * 确保 purchase_order.delivery_deadline 存在
  7403. */
  7404. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  7405. {
  7406. static $done = false;
  7407. if ($done) {
  7408. return;
  7409. }
  7410. $done = true;
  7411. try {
  7412. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  7413. if (empty($cols)) {
  7414. Db::execute(
  7415. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  7416. );
  7417. }
  7418. } catch (\Throwable $e) {
  7419. // ignore
  7420. }
  7421. }
  7422. /**
  7423. * 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
  7424. */
  7425. protected function ensurePurchaseOrderScoreRuleIdColumn(): void
  7426. {
  7427. static $done = false;
  7428. if ($done) {
  7429. return;
  7430. }
  7431. $done = true;
  7432. // 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
  7433. $adds = [
  7434. 'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
  7435. 'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
  7436. 'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
  7437. 'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
  7438. 'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
  7439. ];
  7440. $changed = false;
  7441. foreach ($adds as $col => $ddl) {
  7442. try {
  7443. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  7444. if (!is_array($cols) || $cols === []) {
  7445. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  7446. $changed = true;
  7447. }
  7448. } catch (\Throwable $e) {
  7449. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  7450. }
  7451. }
  7452. if ($changed) {
  7453. $this->clearPurchaseOrderTableFieldsCache();
  7454. }
  7455. }
  7456. /**
  7457. * ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
  7458. */
  7459. protected function clearPurchaseOrderTableFieldsCache(): void
  7460. {
  7461. try {
  7462. $db = (string)Config::get('database.database');
  7463. $key = $db . '.purchase_order';
  7464. $ref = new \ReflectionProperty(\think\db\Query::class, 'info');
  7465. $ref->setAccessible(true);
  7466. $info = $ref->getValue();
  7467. if (is_array($info) && isset($info[$key])) {
  7468. unset($info[$key]);
  7469. $ref->setValue(null, $info);
  7470. }
  7471. } catch (\Throwable $e) {
  7472. }
  7473. try {
  7474. $db = (string)Config::get('database.database');
  7475. $schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
  7476. if (is_file($schemaFile)) {
  7477. @unlink($schemaFile);
  7478. }
  7479. } catch (\Throwable $e) {
  7480. }
  7481. }
  7482. /**
  7483. * @return array<string, bool>
  7484. */
  7485. protected function loadPurchaseOrderColumnSet(): array
  7486. {
  7487. static $set = null;
  7488. if (is_array($set)) {
  7489. return $set;
  7490. }
  7491. $set = [];
  7492. try {
  7493. $cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
  7494. } catch (\Throwable $e) {
  7495. return $set;
  7496. }
  7497. if (!is_array($cols)) {
  7498. return $set;
  7499. }
  7500. foreach ($cols as $c) {
  7501. if (!is_array($c)) {
  7502. continue;
  7503. }
  7504. $f = (string)($c['Field'] ?? $c['field'] ?? '');
  7505. if ($f !== '') {
  7506. $set[$f] = true;
  7507. }
  7508. }
  7509. return $set;
  7510. }
  7511. /**
  7512. * 解析交货截止日期(仅年月日)
  7513. */
  7514. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  7515. {
  7516. $raw = trim($raw);
  7517. if ($raw === '') {
  7518. if ($required) {
  7519. $this->error('请选择交货截止日期');
  7520. }
  7521. return '';
  7522. }
  7523. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  7524. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  7525. } else {
  7526. $ts = strtotime(str_replace('/', '-', $raw));
  7527. if ($ts === false || $ts <= 0) {
  7528. $this->error('交货截止日期格式无效');
  7529. }
  7530. $ymd = date('Y-m-d', $ts);
  7531. }
  7532. if ($ymd < date('Y-m-d')) {
  7533. $this->error('交货截止日期不能早于今天');
  7534. }
  7535. return $ymd;
  7536. }
  7537. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  7538. {
  7539. $s = trim((string)$value);
  7540. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  7541. return '';
  7542. }
  7543. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  7544. return $m[1];
  7545. }
  7546. $ts = strtotime(str_replace('/', '-', $s));
  7547. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  7548. }
  7549. /**
  7550. * @param array{pos?:array} $bundle
  7551. */
  7552. protected function resolveBundleDeliveryDeadline(array $bundle): string
  7553. {
  7554. foreach ($bundle['pos'] ?? [] as $po) {
  7555. if (!is_array($po)) {
  7556. continue;
  7557. }
  7558. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7559. if ($d !== '') {
  7560. return $d;
  7561. }
  7562. }
  7563. return '';
  7564. }
  7565. protected function formatProcuremenSysRqForInput($sysRq): string
  7566. {
  7567. $sr = trim((string)$sysRq);
  7568. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  7569. return '';
  7570. }
  7571. $ts = strtotime($sr);
  7572. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  7573. }
  7574. protected function formatProcuremenSysRqForDisplay($sysRq): string
  7575. {
  7576. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  7577. if ($sr === '') {
  7578. return '—';
  7579. }
  7580. $ts = strtotime($sr);
  7581. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  7582. }
  7583. /**
  7584. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  7585. *
  7586. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  7587. * @return array{ccydh?:string,pos:array,merge_rows:array}
  7588. */
  7589. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  7590. {
  7591. return $bundle;
  7592. }
  7593. /**
  7594. * 写入/更新 purchase_order(单道工序行)
  7595. *
  7596. * @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
  7597. */
  7598. protected function upsertPurchaseOrderFromRow(
  7599. array $row,
  7600. string $sysRqDb,
  7601. $wflowStatus = null,
  7602. ?string $pickTime = null,
  7603. ?array $exists = null,
  7604. ?string $deliveryDeadline = null,
  7605. $scoreRuleId = null
  7606. ): void {
  7607. $ids = $this->extractScydgyRowId($row);
  7608. if (!$this->isValidScydgyRowId($ids)) {
  7609. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  7610. }
  7611. if ($exists === null) {
  7612. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7613. }
  7614. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  7615. $this->ensurePurchaseOrderScoreRuleIdColumn();
  7616. $this->ensurePurchaseOrderCzlyqColumn();
  7617. $data = $this->normalizePurchaseOrderWritePayload([
  7618. 'scydgy_id' => $ids,
  7619. 'CCYDH' => $row['CCYDH'] ?? null,
  7620. 'CYJMC' => $row['CYJMC'] ?? null,
  7621. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  7622. 'CDXMC' => $row['CDXMC'] ?? null,
  7623. 'CGYBH' => $row['CGYBH'] ?? null,
  7624. 'CGYMC' => $row['CGYMC'] ?? null,
  7625. 'CDW' => $row['CDW'] ?? null,
  7626. 'czlyq' => $row['czlyq'] ?? null,
  7627. 'NGZL' => $row['NGZL'] ?? null,
  7628. 'CDF' => $row['CDF'] ?? null,
  7629. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  7630. 'MBZ' => $row['MBZ'] ?? null,
  7631. 'bwjg' => $row['bwjg'] ?? null,
  7632. 'iStatus' => $row['iStatus'] ?? null,
  7633. 'dStamp' => $row['dStamp'] ?? null,
  7634. 'dputrecord' => $row['dputrecord'] ?? null,
  7635. 'cywyxm' => $row['cywyxm'] ?? null,
  7636. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  7637. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  7638. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7639. 'sys_rq' => $sysRqDb,
  7640. ], $row);
  7641. // 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
  7642. $qtyUp = trim((string)($data['This_quantity'] ?? ''));
  7643. if ($qtyUp === '') {
  7644. $qtyFallback = $this->resolveProcuremenThisQuantity([
  7645. 'This_quantity' => '',
  7646. 'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
  7647. ]);
  7648. if ($qtyFallback !== '') {
  7649. $data['This_quantity'] = $qtyFallback;
  7650. }
  7651. }
  7652. if ($deliveryDeadline !== null) {
  7653. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  7654. }
  7655. // 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
  7656. $scoreRule = null;
  7657. if (is_array($scoreRuleId)) {
  7658. $scoreRule = $scoreRuleId;
  7659. $scoreRuleId = (int)($scoreRule['id'] ?? 0);
  7660. } else {
  7661. $scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
  7662. }
  7663. if ($scoreRuleId !== null && $scoreRuleId > 0) {
  7664. $poCols = $this->loadPurchaseOrderColumnSet();
  7665. if (!empty($poCols['score_rule_id'])) {
  7666. $data['score_rule_id'] = $scoreRuleId;
  7667. if (is_array($scoreRule)) {
  7668. if (!empty($poCols['score_rule_name'])) {
  7669. $data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
  7670. }
  7671. if (!empty($poCols['score_quality_weight'])) {
  7672. $data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
  7673. }
  7674. if (!empty($poCols['score_price_weight'])) {
  7675. $data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
  7676. }
  7677. if (!empty($poCols['score_lead_weight'])) {
  7678. $data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
  7679. }
  7680. }
  7681. }
  7682. }
  7683. if ($wflowStatus !== null && $wflowStatus !== '') {
  7684. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  7685. }
  7686. if ($pickTime !== null && $pickTime !== '') {
  7687. $data['pick_time'] = $pickTime;
  7688. $data['pick_company_name'] = '';
  7689. }
  7690. if ($exists) {
  7691. $upd = $data;
  7692. unset($upd['scydgy_id']);
  7693. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  7694. } else {
  7695. $data['createtime'] = date('Y-m-d H:i:s');
  7696. Db::table('purchase_order')->insert($data);
  7697. }
  7698. }
  7699. /**
  7700. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  7701. *
  7702. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  7703. */
  7704. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
  7705. {
  7706. $toDb = function ($value) {
  7707. if ($value === null) {
  7708. return null;
  7709. }
  7710. if (is_scalar($value)) {
  7711. return $value;
  7712. }
  7713. return json_encode($value, JSON_UNESCAPED_UNICODE);
  7714. };
  7715. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7716. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7717. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7718. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  7719. if ($username === '') {
  7720. $username = $this->resolveCustomerContactName($phone, $companyName);
  7721. }
  7722. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  7723. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  7724. }
  7725. if ($requirePhone && $phone === '') {
  7726. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  7727. }
  7728. $detailLinks = [];
  7729. foreach ($mergeRows as $row) {
  7730. if (!is_array($row)) {
  7731. continue;
  7732. }
  7733. $sid = $this->extractScydgyRowId($row);
  7734. $detailId = 0;
  7735. if ($skipExisting) {
  7736. try {
  7737. $existsQuery = Db::table('purchase_order_detail')
  7738. ->where('scydgy_id', $sid)
  7739. ->where('company_name', $companyName);
  7740. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  7741. $exists = $existsQuery->find();
  7742. } catch (\Throwable $e) {
  7743. $exists = null;
  7744. }
  7745. if (is_array($exists)) {
  7746. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  7747. }
  7748. }
  7749. if ($detailId <= 0) {
  7750. $one = [
  7751. 'scydgy_id' => $toDb($sid),
  7752. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  7753. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  7754. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  7755. 'username' => $username !== '' ? $username : null,
  7756. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  7757. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  7758. 'createtime' => date('Y-m-d H:i:s'),
  7759. 'status' => ProcuremenStatus::POD_UNPICKED,
  7760. 'status_name' => '未提交',
  7761. ];
  7762. Db::table('purchase_order_detail')->insert($one);
  7763. $detailId = (int)Db::getLastInsID();
  7764. }
  7765. $mprocUrl = '';
  7766. if ($buildMobileLinks && $detailId > 0) {
  7767. // 手工询价 → 待报价;协助下发 → 未提交
  7768. $listTab = ($sid < 0) ? 'rfq' : 'draft';
  7769. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId, $listTab);
  7770. }
  7771. $detailLinks[] = [
  7772. 'detail_id' => $detailId,
  7773. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  7774. 'url' => $mprocUrl,
  7775. ];
  7776. }
  7777. $this->invalidatePickHiddenScydgyCache();
  7778. return $detailLinks;
  7779. }
  7780. /**
  7781. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  7782. * @return array<string, mixed>
  7783. */
  7784. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks, string $emailTplScene = 'review_email'): array
  7785. {
  7786. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7787. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7788. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7789. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  7790. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  7791. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  7792. $isMerge = !empty($ctx['is_merge']);
  7793. $contactName = trim((string)($c['username'] ?? ''));
  7794. if ($contactName === '') {
  7795. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  7796. }
  7797. $notifyVars = [
  7798. 'company_name' => $companyName,
  7799. 'contact_name' => $contactName,
  7800. 'phone' => $phone,
  7801. 'email' => $toEmail,
  7802. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  7803. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  7804. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  7805. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  7806. 'deadline' => (string)($ctx['deadline'] ?? ''),
  7807. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  7808. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  7809. 'order_type' => (string)($ctx['order_type'] ?? ''),
  7810. 'score_weights' => (string)($ctx['score_weights'] ?? ''),
  7811. 'platform_url' => $platformUrl,
  7812. 'platform_links' => $platformLinksPlain,
  7813. 'platform_links_html' => $platformLinksHtml,
  7814. ];
  7815. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  7816. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  7817. $mailPlain = $this->renderNotifyTemplate($emailTplScene, $notifyVars);
  7818. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  7819. return [
  7820. 'company_name' => $companyName,
  7821. 'phone' => $phone,
  7822. 'email' => $toEmail,
  7823. 'sms_content' => $smsContent,
  7824. 'mail_plain' => $mailPlain,
  7825. 'mail_body' => $mailBody,
  7826. 'notify_vars' => $notifyVars,
  7827. 'detail_links' => $detailLinks,
  7828. ];
  7829. }
  7830. /**
  7831. * @param array<string, mixed> $chosen
  7832. * @param array<int, array<string, mixed>> $mergeRows
  7833. * @param array{ccydh:string, pos:array} $bundle
  7834. */
  7835. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue', string $emailTplScene = 'review_email'): void
  7836. {
  7837. if (!$sendSms && !$sendEmail) {
  7838. return;
  7839. }
  7840. $companyName = trim((string)($chosen['name'] ?? ''));
  7841. $phone = trim((string)($chosen['phone'] ?? ''));
  7842. $toEmail = trim((string)($chosen['email'] ?? ''));
  7843. if ($companyName === '') {
  7844. throw new \Exception('供应商名称无效');
  7845. }
  7846. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  7847. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  7848. }
  7849. if ($sendSms && $phone === '') {
  7850. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  7851. }
  7852. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  7853. $linkListTab = (strpos($emailTplScene, 'rfq_') === 0) ? 'rfq' : 'draft';
  7854. $sids = [];
  7855. foreach ($mergeRows as $mr) {
  7856. if (!is_array($mr)) {
  7857. continue;
  7858. }
  7859. $sid = $this->extractScydgyRowId($mr);
  7860. if ($this->isValidScydgyRowId($sid)) {
  7861. $sids[$sid] = true;
  7862. }
  7863. }
  7864. if ($sids === []) {
  7865. throw new \Exception('未找到工序行,无法发送通知');
  7866. }
  7867. $sysRqNotify = '';
  7868. $pos = $bundle['pos'] ?? [];
  7869. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7870. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  7871. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  7872. $ts = strtotime($sr);
  7873. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  7874. }
  7875. }
  7876. try {
  7877. $detailsQuery = Db::table('purchase_order_detail')
  7878. ->where('scydgy_id', 'in', array_keys($sids))
  7879. ->where('company_name', $companyName);
  7880. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7881. $details = $detailsQuery->order('id', 'asc')->select();
  7882. } catch (\Throwable $e) {
  7883. $details = [];
  7884. }
  7885. if (!is_array($details) || $details === []) {
  7886. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  7887. try {
  7888. $detailsQuery = Db::table('purchase_order_detail')
  7889. ->where('scydgy_id', 'in', array_keys($sids))
  7890. ->where('company_name', $companyName);
  7891. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7892. $details = $detailsQuery->order('id', 'asc')->select();
  7893. } catch (\Throwable $e) {
  7894. $details = [];
  7895. }
  7896. }
  7897. if (!is_array($details) || $details === []) {
  7898. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  7899. }
  7900. $detailLinks = [];
  7901. foreach ($details as $d) {
  7902. if (!is_array($d)) {
  7903. continue;
  7904. }
  7905. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  7906. if ($detailId <= 0) {
  7907. continue;
  7908. }
  7909. $sid = (int)($d['scydgy_id'] ?? 0);
  7910. $gymc = '';
  7911. foreach ($mergeRows as $mr) {
  7912. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  7913. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  7914. break;
  7915. }
  7916. }
  7917. $detailLinks[] = [
  7918. 'detail_id' => $detailId,
  7919. 'cgymc' => $gymc,
  7920. // 询价邮件 → 待报价;下发报价 → 未提交
  7921. 'url' => $this->buildMprocMobileOrderUrl(
  7922. $detailId,
  7923. ($linkListTab === 'rfq' || $sid < 0) ? 'rfq' : 'draft'
  7924. ),
  7925. ];
  7926. }
  7927. if ($detailLinks === []) {
  7928. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  7929. }
  7930. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  7931. $orderTypeCtx = $this->resolveIssueNotifyOrderTypeFromBundle($bundle);
  7932. $ctx['order_type'] = (string)($orderTypeCtx['order_type'] ?? '');
  7933. $ctx['score_weights'] = (string)($orderTypeCtx['score_weights'] ?? '');
  7934. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks, $emailTplScene);
  7935. $notifyBundle['email_log_scene'] = $emailLogScene;
  7936. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  7937. $poIdLog = 0;
  7938. $pos = $bundle['pos'] ?? [];
  7939. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7940. $poIdLog = (int)($pos[0]['id'] ?? 0);
  7941. }
  7942. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  7943. if ($sendEmail) {
  7944. $mailTplRow = $this->loadNotifyTemplateRow($emailTplScene);
  7945. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  7946. throw new \Exception($this->notifyTemplateMissingMessage($emailTplScene));
  7947. }
  7948. $mailSubject = $this->resolveProcuremenEmailSubject($emailTplScene);
  7949. $mailConfig = $this->loadMailerConfig();
  7950. if (!$this->isProcuremenNotifyDryRun()) {
  7951. if (empty($mailConfig['host'])) {
  7952. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  7953. }
  7954. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  7955. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  7956. }
  7957. }
  7958. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  7959. }
  7960. if ($sendSms) {
  7961. $this->issueSendSupplierSms($notifyBundle);
  7962. }
  7963. }
  7964. /**
  7965. * @param array<int, array<string, mixed>> $quoteGroups
  7966. * @return array<int, array<string, mixed>>
  7967. */
  7968. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  7969. {
  7970. $names = [];
  7971. if (is_string($companiesJson) && $companiesJson !== '') {
  7972. $decoded = json_decode($companiesJson, true);
  7973. if (is_array($decoded)) {
  7974. foreach ($decoded as $nm) {
  7975. $nm = trim((string)$nm);
  7976. if ($nm !== '') {
  7977. $names[] = $nm;
  7978. }
  7979. }
  7980. }
  7981. }
  7982. $names = array_values(array_unique($names));
  7983. if ($names === [] && $selectedCompany !== '') {
  7984. $names = [$selectedCompany];
  7985. }
  7986. if ($names === []) {
  7987. return $quoteGroups;
  7988. }
  7989. $targets = [];
  7990. foreach ($quoteGroups as $g) {
  7991. if (!is_array($g)) {
  7992. continue;
  7993. }
  7994. $cn = trim((string)($g['name'] ?? ''));
  7995. if ($cn !== '' && in_array($cn, $names, true)) {
  7996. $targets[] = $g;
  7997. }
  7998. }
  7999. return $targets;
  8000. }
  8001. /**
  8002. * @return array{pos:array, merge_rows:array, bundle:array}
  8003. */
  8004. protected function loadAuditResendBundle(string $scydgyId): array
  8005. {
  8006. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  8007. $pos = $bundle['pos'];
  8008. $mergeRows = $bundle['merge_rows'];
  8009. if ($pos === [] || $mergeRows === []) {
  8010. $this->error('该订单不在待确认供应商状态');
  8011. }
  8012. $sysRqDb = '';
  8013. if (isset($pos[0]) && is_array($pos[0])) {
  8014. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  8015. }
  8016. foreach ($pos as $i => $poRow) {
  8017. if (is_array($pos[$i]) && $sysRqDb !== '') {
  8018. $pos[$i]['sys_rq'] = $sysRqDb;
  8019. }
  8020. }
  8021. $bundle['pos'] = $pos;
  8022. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  8023. }
  8024. /**
  8025. * @param array<int, array<string, mixed>> $targets
  8026. */
  8027. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  8028. {
  8029. if ($targets === []) {
  8030. $this->error('未找到可通知的供应商');
  8031. }
  8032. $notifyErrors = [];
  8033. try {
  8034. $this->notifyDryRunPreview = [];
  8035. foreach ($targets as $g) {
  8036. if (!is_array($g)) {
  8037. continue;
  8038. }
  8039. $cname = trim((string)($g['name'] ?? ''));
  8040. if ($cname === '') {
  8041. continue;
  8042. }
  8043. $chosen = [
  8044. 'name' => $cname,
  8045. 'company_name' => $cname,
  8046. 'email' => trim((string)($g['email'] ?? '')),
  8047. 'phone' => trim((string)($g['phone'] ?? '')),
  8048. 'username' => trim((string)($g['username'] ?? '')),
  8049. ];
  8050. try {
  8051. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  8052. } catch (\Throwable $e) {
  8053. $notifyErrors[] = $cname . ':' . $e->getMessage();
  8054. }
  8055. }
  8056. } catch (\Throwable $e) {
  8057. $this->error('通知发送失败:' . $e->getMessage());
  8058. }
  8059. if ($notifyErrors !== []) {
  8060. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  8061. }
  8062. if ($this->isProcuremenNotifyDryRun()) {
  8063. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  8064. 'notify_dry_run' => true,
  8065. 'notify_preview' => $this->notifyDryRunPreview,
  8066. ]);
  8067. }
  8068. $nameLabels = [];
  8069. foreach ($targets as $g) {
  8070. if (!is_array($g)) {
  8071. continue;
  8072. }
  8073. $n = trim((string)($g['name'] ?? ''));
  8074. if ($n !== '') {
  8075. $nameLabels[] = $n;
  8076. }
  8077. }
  8078. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  8079. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  8080. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  8081. $seenLogSid = [];
  8082. foreach ($bundle['pos'] ?? [] as $poRow) {
  8083. if (!is_array($poRow)) {
  8084. continue;
  8085. }
  8086. $sid = (int)($poRow['scydgy_id'] ?? 0);
  8087. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  8088. continue;
  8089. }
  8090. $seenLogSid[$sid] = true;
  8091. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  8092. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  8093. }
  8094. if ($seenLogSid === []) {
  8095. foreach ($mergeRows as $mr) {
  8096. if (!is_array($mr)) {
  8097. continue;
  8098. }
  8099. $sid = $this->extractScydgyRowId($mr);
  8100. if ($this->isValidScydgyRowId($sid)) {
  8101. $this->addOrderLog($sid, $logAction, $logMsg, null);
  8102. break;
  8103. }
  8104. }
  8105. }
  8106. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  8107. }
  8108. /**
  8109. * 协助下发 — 发送短信(一家供应商)
  8110. *
  8111. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  8112. */
  8113. protected function issueSendSupplierSms(array $bundle): void
  8114. {
  8115. $companyName = (string)($bundle['company_name'] ?? '');
  8116. $phone = (string)($bundle['phone'] ?? '');
  8117. $smsContent = (string)($bundle['sms_content'] ?? '');
  8118. $this->logIssueNotifyDebug('短信', [
  8119. 'company' => $companyName,
  8120. 'phone' => $phone,
  8121. 'sms_content' => $smsContent,
  8122. ]);
  8123. if ($this->isProcuremenNotifyDryRun()) {
  8124. $this->recordNotifyDryRunPreview([
  8125. 'scene' => 'issue_sms',
  8126. 'company_name' => $companyName,
  8127. 'phone' => $phone,
  8128. 'sms_content' => $smsContent,
  8129. ]);
  8130. return;
  8131. }
  8132. $this->smsbao($phone, $smsContent);
  8133. }
  8134. /**
  8135. * 协助下发 — 发送邮件(一家供应商)
  8136. *
  8137. * @param array<string, mixed> $bundle
  8138. * @param array<string, mixed> $mailConfig
  8139. */
  8140. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  8141. {
  8142. $companyName = (string)($bundle['company_name'] ?? '');
  8143. $toEmail = (string)($bundle['email'] ?? '');
  8144. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  8145. $mailBody = (string)($bundle['mail_body'] ?? '');
  8146. $this->logIssueNotifyDebug('邮件', [
  8147. 'company' => $companyName,
  8148. 'email' => $toEmail,
  8149. 'mail_subject' => $mailSubject,
  8150. 'mail_body' => $mailPlain,
  8151. ]);
  8152. if ($this->isProcuremenNotifyDryRun()) {
  8153. $this->recordNotifyDryRunPreview([
  8154. 'scene' => 'issue_email',
  8155. 'company_name' => $companyName,
  8156. 'email' => $toEmail,
  8157. 'mail_subject' => $mailSubject,
  8158. 'mail_body' => $mailPlain,
  8159. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  8160. 'notify_vars' => $bundle['notify_vars'] ?? [],
  8161. 'detail_links' => $bundle['detail_links'] ?? [],
  8162. ]);
  8163. return;
  8164. }
  8165. $mail = new PHPMailer(true);
  8166. $mail->isSMTP();
  8167. $mail->Host = $mailConfig['host'];
  8168. $mail->SMTPAuth = true;
  8169. $mail->Username = $mailConfig['addr'];
  8170. $mail->Password = $mailConfig['pass'];
  8171. $mail->SMTPSecure = $mailConfig['security'];
  8172. $mail->Port = $mailConfig['port'];
  8173. $mail->CharSet = $mailConfig['charset'];
  8174. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  8175. $mail->addAddress($toEmail, $companyName);
  8176. $mail->isHTML(true);
  8177. $mail->Subject = $mailSubject;
  8178. $mail->Body = $mailBody;
  8179. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  8180. $sendOk = true;
  8181. $failReason = '';
  8182. try {
  8183. $mail->send();
  8184. } catch (\Throwable $e) {
  8185. $sendOk = false;
  8186. $failReason = $e->getMessage();
  8187. $this->persistEmailSendLog([
  8188. 'from_email' => $fromEmail,
  8189. 'to_email' => $toEmail,
  8190. 'send_time' => date('Y-m-d H:i:s'),
  8191. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  8192. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  8193. 'company_name' => $companyName,
  8194. 'mail_subject' => $mailSubject,
  8195. 'status' => 0,
  8196. 'fail_reason' => $failReason,
  8197. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  8198. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  8199. ]);
  8200. throw $e;
  8201. }
  8202. $this->persistEmailSendLog([
  8203. 'from_email' => $fromEmail,
  8204. 'to_email' => $toEmail,
  8205. 'send_time' => date('Y-m-d H:i:s'),
  8206. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  8207. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  8208. 'company_name' => $companyName,
  8209. 'mail_subject' => $mailSubject,
  8210. 'status' => 1,
  8211. 'fail_reason' => '',
  8212. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  8213. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  8214. ]);
  8215. }
  8216. /**
  8217. * 下发通知:解析订单类型名称与评分比例文案
  8218. *
  8219. * @param array<string, mixed> $bundle
  8220. * @return array{order_type:string,score_weights:string}
  8221. */
  8222. protected function resolveIssueNotifyOrderTypeFromBundle(array $bundle): array
  8223. {
  8224. $orderType = '';
  8225. $scoreWeights = '';
  8226. $rule = null;
  8227. if (!empty($bundle['score_rule']) && is_array($bundle['score_rule'])) {
  8228. $rule = $bundle['score_rule'];
  8229. }
  8230. $pos = $bundle['pos'] ?? [];
  8231. $po0 = (is_array($pos) && isset($pos[0]) && is_array($pos[0])) ? $pos[0] : null;
  8232. if ($rule === null && is_array($po0)) {
  8233. $ruleId = (int)($po0['score_rule_id'] ?? 0);
  8234. if ($ruleId > 0) {
  8235. try {
  8236. $rule = ProcuremenSupplierScore::getRuleById($ruleId);
  8237. } catch (\Throwable $e) {
  8238. $rule = null;
  8239. }
  8240. }
  8241. if (!is_array($rule) || (int)($rule['id'] ?? 0) <= 0) {
  8242. $qw = (int)($po0['score_quality_weight'] ?? 0);
  8243. $pw = (int)($po0['score_price_weight'] ?? 0);
  8244. $lw = (int)($po0['score_lead_weight'] ?? 0);
  8245. if ($qw > 0 || $pw > 0 || $lw > 0) {
  8246. $rule = [
  8247. 'name' => trim((string)($po0['score_rule_name'] ?? '')),
  8248. 'quality_weight' => $qw,
  8249. 'price_weight' => $pw,
  8250. 'lead_weight' => $lw,
  8251. ];
  8252. }
  8253. }
  8254. }
  8255. if (is_array($rule)) {
  8256. $orderType = trim((string)($rule['name'] ?? ''));
  8257. $scoreWeights = $this->formatScoreRuleWeightsText($rule);
  8258. }
  8259. if ($orderType === '' && is_array($po0)) {
  8260. $orderType = trim((string)($po0['score_rule_name'] ?? ''));
  8261. }
  8262. return [
  8263. 'order_type' => $orderType,
  8264. 'score_weights' => $scoreWeights,
  8265. ];
  8266. }
  8267. /**
  8268. * 评分比例文案:质量30%、价格50%、交货20%
  8269. *
  8270. * @param array{quality_weight?:mixed,price_weight?:mixed,lead_weight?:mixed} $rule
  8271. */
  8272. protected function formatScoreRuleWeightsText(array $rule): string
  8273. {
  8274. $parts = [];
  8275. $qw = max(0, (float)($rule['quality_weight'] ?? 0));
  8276. $pw = max(0, (float)($rule['price_weight'] ?? 0));
  8277. $lw = max(0, (float)($rule['lead_weight'] ?? 0));
  8278. $fmt = static function ($n) {
  8279. $s = rtrim(rtrim(sprintf('%.2F', (float)$n), '0'), '.');
  8280. return $s === '' ? '0' : $s;
  8281. };
  8282. if ($qw > 0) {
  8283. $parts[] = '质量' . $fmt($qw) . '%';
  8284. }
  8285. if ($pw > 0) {
  8286. $parts[] = '价格' . $fmt($pw) . '%';
  8287. }
  8288. if ($lw > 0) {
  8289. $parts[] = '交货' . $fmt($lw) . '%';
  8290. }
  8291. return implode('、', $parts);
  8292. }
  8293. /**
  8294. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  8295. *
  8296. * @param array<int, array<string, mixed>> $mergeRows
  8297. * @return array<string, mixed>
  8298. */
  8299. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  8300. {
  8301. $head = $mergeRows[0] ?? [];
  8302. $isMerge = count($mergeRows) > 1;
  8303. return [
  8304. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  8305. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  8306. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  8307. 'is_merge' => $isMerge,
  8308. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  8309. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  8310. 'deadline' => $sysRqNotify,
  8311. 'order_type' => '',
  8312. 'score_weights' => '',
  8313. ];
  8314. }
  8315. /**
  8316. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  8317. *
  8318. * @param array<string, mixed> $data
  8319. */
  8320. protected function logIssueNotifyDebug(string $type, array $data): void
  8321. {
  8322. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  8323. return;
  8324. }
  8325. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  8326. }
  8327. protected function ensurePurchaseEmailSendLogTableOnce(): void
  8328. {
  8329. try {
  8330. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  8331. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  8332. return;
  8333. } catch (\Throwable $e) {
  8334. }
  8335. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  8336. if (is_file($sqlFile)) {
  8337. $sql = file_get_contents($sqlFile);
  8338. if (is_string($sql) && $sql !== '') {
  8339. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  8340. $stmt = trim($stmt);
  8341. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  8342. continue;
  8343. }
  8344. try {
  8345. Db::execute($stmt);
  8346. } catch (\Throwable $ignore) {
  8347. }
  8348. }
  8349. }
  8350. }
  8351. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  8352. }
  8353. /**
  8354. * @param array<string, mixed> $row
  8355. */
  8356. protected function persistEmailSendLog(array $row): void
  8357. {
  8358. try {
  8359. $this->ensurePurchaseEmailSendLogTableOnce();
  8360. } catch (\Throwable $e) {
  8361. return;
  8362. }
  8363. list($adminId, $adminName) = $this->GetUseName();
  8364. $cut = function ($s, $max) {
  8365. $s = (string)$s;
  8366. if (function_exists('mb_substr')) {
  8367. return mb_substr($s, 0, $max, 'UTF-8');
  8368. }
  8369. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  8370. };
  8371. $data = [
  8372. 'from_email' => $cut($row['from_email'] ?? '', 128),
  8373. 'to_email' => $cut($row['to_email'] ?? '', 128),
  8374. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  8375. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  8376. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  8377. 'company_name' => $cut($row['company_name'] ?? '', 128),
  8378. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  8379. 'status' => !empty($row['status']) ? 1 : 0,
  8380. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  8381. 'admin_id' => (int)$adminId,
  8382. 'admin_name' => $cut($adminName, 64),
  8383. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  8384. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  8385. 'createtime' => date('Y-m-d H:i:s'),
  8386. ];
  8387. try {
  8388. Db::table('purchase_email_send_log')->insert($data);
  8389. } catch (\Throwable $e) {
  8390. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  8391. }
  8392. }
  8393. protected function formatEmailLogSceneText(string $scene): string
  8394. {
  8395. $map = [
  8396. 'pick_issue' => '初选下发',
  8397. 'audit_resend' => '确认页重发',
  8398. 'rfq_salesman' => '询价通知业务员',
  8399. 'rfq_supplier' => '供应商询价通知',
  8400. ];
  8401. return $map[$scene] ?? $scene;
  8402. }
  8403. /**
  8404. * 邮件发送日志列表
  8405. */
  8406. public function emailLog()
  8407. {
  8408. $this->relationSearch = false;
  8409. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  8410. $this->request->filter(['strip_tags', 'trim']);
  8411. $bakModel = $this->model;
  8412. $this->model = new \app\admin\model\Purchaseemailsendlog;
  8413. if ($this->request->isAjax()) {
  8414. $this->ensurePurchaseEmailSendLogTableOnce();
  8415. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  8416. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  8417. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  8418. $list = $this->model
  8419. ->where($where)
  8420. ->order($sortField, $orderDir)
  8421. ->paginate($limit);
  8422. $rows = [];
  8423. foreach ($list->items() as $item) {
  8424. $row = is_array($item) ? $item : $item->toArray();
  8425. $scene = trim((string)($row['scene'] ?? ''));
  8426. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  8427. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  8428. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  8429. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  8430. $rows[] = $row;
  8431. }
  8432. $this->model = $bakModel;
  8433. return json(['total' => $list->total(), 'rows' => $rows]);
  8434. }
  8435. $this->model = $bakModel;
  8436. return $this->view->fetch('procuremen/emaillog');
  8437. }
  8438. /**
  8439. * 协助下发弹窗(选多家供应商并通知)
  8440. */
  8441. public function pickReview()
  8442. {
  8443. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  8444. $this->error(__('You have no permission'));
  8445. }
  8446. if ($this->request->isPost()) {
  8447. $this->error('请使用弹窗内「确认下发」提交');
  8448. }
  8449. $this->view->assign('pickMode', 1);
  8450. $this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
  8451. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  8452. }
  8453. /**
  8454. * 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
  8455. */
  8456. protected function ensurePurchaseOrderNotifySalesmanColumn(): void
  8457. {
  8458. static $done = false;
  8459. if ($done) {
  8460. return;
  8461. }
  8462. $done = true;
  8463. try {
  8464. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'notify_salesman'");
  8465. if (empty($cols)) {
  8466. Db::execute(
  8467. "ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
  8468. );
  8469. } else {
  8470. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  8471. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
  8472. Db::execute(
  8473. "ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
  8474. );
  8475. }
  8476. }
  8477. } catch (\Throwable $e) {
  8478. // ignore
  8479. }
  8480. }
  8481. /**
  8482. * 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
  8483. */
  8484. protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
  8485. {
  8486. static $done = false;
  8487. if ($done) {
  8488. return;
  8489. }
  8490. $done = true;
  8491. try {
  8492. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
  8493. if (empty($cols)) {
  8494. Db::execute(
  8495. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
  8496. );
  8497. }
  8498. } catch (\Throwable $e) {
  8499. // ignore
  8500. }
  8501. try {
  8502. $cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
  8503. if (empty($cols2)) {
  8504. Db::execute(
  8505. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
  8506. );
  8507. }
  8508. } catch (\Throwable $e) {
  8509. // ignore
  8510. }
  8511. }
  8512. /**
  8513. * 确保「采购确认通过/未通过」邮箱模版存在(正文同短信,末尾加平台链接)
  8514. */
  8515. protected function ensureConfirmResultEmailTemplates(): void
  8516. {
  8517. static $done = false;
  8518. if ($done) {
  8519. return;
  8520. }
  8521. $done = true;
  8522. $now = date('Y-m-d H:i:s');
  8523. $seeds = [
  8524. 'confirm_ok_email' => [
  8525. 'title' => '采购确认结果:已通过',
  8526. 'content' => "【可集达】您好,{company_name}:\n\n您参与的外发加工订单采购确认结果:已通过。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  8527. 'remark' => '审批通过-中标供应商邮箱通知;模版名称作邮件主题',
  8528. ],
  8529. 'confirm_fail_email' => [
  8530. 'title' => '采购确认结果:未通过',
  8531. 'content' => "【可集达】您好,{company_name}:\n\n您参与的外发加工订单采购确认结果:未通过。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  8532. 'remark' => '审批通过-未中标供应商邮箱通知;模版名称作邮件主题',
  8533. ],
  8534. ];
  8535. try {
  8536. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8537. } catch (\Throwable $e) {
  8538. return;
  8539. }
  8540. $colNames = [];
  8541. foreach ($cols as $c) {
  8542. if (!is_array($c)) {
  8543. continue;
  8544. }
  8545. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8546. if ($n !== '') {
  8547. $colNames[$n] = true;
  8548. }
  8549. }
  8550. foreach ($seeds as $scene => $seed) {
  8551. try {
  8552. $row = Db::table('purchase_sms_template')->where('scene', $scene)->find();
  8553. } catch (\Throwable $e) {
  8554. continue;
  8555. }
  8556. if (is_array($row) && $row !== []) {
  8557. continue;
  8558. }
  8559. $data = [
  8560. 'scene' => $scene,
  8561. 'title' => $seed['title'],
  8562. 'content' => $seed['content'],
  8563. 'remark' => $seed['remark'],
  8564. 'status' => 1,
  8565. ];
  8566. if (isset($colNames['updatetime'])) {
  8567. $data['updatetime'] = $now;
  8568. }
  8569. if (isset($colNames['createtime'])) {
  8570. $data['createtime'] = $now;
  8571. }
  8572. try {
  8573. Db::table('purchase_sms_template')->insert($data);
  8574. } catch (\Throwable $e) {
  8575. // ignore
  8576. }
  8577. }
  8578. }
  8579. /**
  8580. * 确保「供应商询价通知」邮箱模版存在(查询询价-询价/发邮件;可在短信模版配置中修改)
  8581. */
  8582. protected function ensureRfqSupplierEmailTemplate(): void
  8583. {
  8584. static $done = false;
  8585. if ($done) {
  8586. return;
  8587. }
  8588. $done = true;
  8589. $content = "您好,{company_name}:\n\n"
  8590. . "您有新的协助采购询价需求,请登录平台查看并处理。\n\n"
  8591. . "需求编号:{ccydh}\n"
  8592. . "印件名称:{cyjmc}\n"
  8593. . "{process_lines}\n\n"
  8594. . "请在 {deadline} 前完成回复。\n\n"
  8595. . "平台链接:{platform_url}\n";
  8596. try {
  8597. $row = Db::table('purchase_sms_template')
  8598. ->where('scene', 'rfq_supplier_email')
  8599. ->find();
  8600. } catch (\Throwable $e) {
  8601. return;
  8602. }
  8603. $now = date('Y-m-d H:i:s');
  8604. if (is_array($row) && $row !== []) {
  8605. return;
  8606. }
  8607. try {
  8608. $data = [
  8609. 'scene' => 'rfq_supplier_email',
  8610. 'title' => '供应商询价通知',
  8611. 'content' => $content,
  8612. 'remark' => '查询询价-询价/发邮件通知供应商;模版名称作邮件主题',
  8613. 'status' => 1,
  8614. ];
  8615. try {
  8616. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8617. } catch (\Throwable $e) {
  8618. $cols = [];
  8619. }
  8620. $colNames = [];
  8621. foreach ($cols as $c) {
  8622. if (!is_array($c)) {
  8623. continue;
  8624. }
  8625. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8626. if ($n !== '') {
  8627. $colNames[$n] = true;
  8628. }
  8629. }
  8630. if (isset($colNames['updatetime'])) {
  8631. $data['updatetime'] = $now;
  8632. }
  8633. if (isset($colNames['createtime'])) {
  8634. $data['createtime'] = $now;
  8635. }
  8636. Db::table('purchase_sms_template')->insert($data);
  8637. } catch (\Throwable $e) {
  8638. // ignore
  8639. }
  8640. }
  8641. /**
  8642. * 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
  8643. */
  8644. protected function ensureRfqSalesmanEmailTemplate(): void
  8645. {
  8646. static $done = false;
  8647. if ($done) {
  8648. return;
  8649. }
  8650. $done = true;
  8651. $content = "您好,{contact_name}:\n\n"
  8652. . "有新的协助采购询价需求,请知悉。\n"
  8653. . "印件名称:{cyjmc}\n"
  8654. . "工序名称:{cgymc}\n"
  8655. . "本次数量:{this_quantity}\n"
  8656. . "供应商报价:\n{supplier_quotes}\n"
  8657. . "平台链接:{platform_url}\n"
  8658. . "需求发起人:{cywyxm}\n";
  8659. try {
  8660. $row = Db::table('purchase_sms_template')
  8661. ->where('scene', 'rfq_salesman_email')
  8662. ->find();
  8663. } catch (\Throwable $e) {
  8664. return;
  8665. }
  8666. $now = date('Y-m-d H:i:s');
  8667. if (is_array($row) && $row !== []) {
  8668. $old = (string)($row['content'] ?? '');
  8669. // 无报价表格 / 无平台链接 / 链接不在「需求发起人」上方时,同步默认文案
  8670. $urlPos = strpos($old, '{platform_url}');
  8671. $cywyPos = strpos($old, '需求发起人');
  8672. $linkNotAboveStarter = ($urlPos === false)
  8673. || ($cywyPos !== false && $urlPos > $cywyPos);
  8674. $needMigrate = (strpos($old, '{supplier_quotes}') === false)
  8675. || (strpos($old, '供应商:{supplier_name}') !== false)
  8676. || $linkNotAboveStarter;
  8677. if ($needMigrate) {
  8678. $data = ['content' => $content];
  8679. if (trim((string)($row['title'] ?? '')) === '' || trim((string)($row['title'] ?? '')) === '询价通知') {
  8680. $data['title'] = '业务员询价通知';
  8681. }
  8682. try {
  8683. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
  8684. if (!empty($cols)) {
  8685. $data['updatetime'] = $now;
  8686. }
  8687. } catch (\Throwable $e) {
  8688. }
  8689. try {
  8690. Db::table('purchase_sms_template')
  8691. ->where('id', (int)($row['id'] ?? 0))
  8692. ->update($data);
  8693. } catch (\Throwable $e) {
  8694. }
  8695. }
  8696. return;
  8697. }
  8698. try {
  8699. $data = [
  8700. 'scene' => 'rfq_salesman_email',
  8701. 'title' => '业务员询价通知',
  8702. 'content' => $content,
  8703. 'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
  8704. 'status' => 1,
  8705. ];
  8706. try {
  8707. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8708. } catch (\Throwable $e) {
  8709. $cols = [];
  8710. }
  8711. $colNames = [];
  8712. foreach ($cols as $c) {
  8713. if (!is_array($c)) {
  8714. continue;
  8715. }
  8716. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8717. if ($n !== '') {
  8718. $colNames[$n] = true;
  8719. }
  8720. }
  8721. if (isset($colNames['updatetime'])) {
  8722. $data['updatetime'] = $now;
  8723. }
  8724. if (isset($colNames['createtime'])) {
  8725. $data['createtime'] = $now;
  8726. }
  8727. Db::table('purchase_sms_template')->insert($data);
  8728. } catch (\Throwable $e) {
  8729. // ignore
  8730. }
  8731. }
  8732. /**
  8733. * 通知业务员邮件:供应商报价明细行(仅名称+单价)
  8734. *
  8735. * @return array<int, array{name:string,amount:string}>
  8736. */
  8737. protected function loadRfqSalesmanSupplierQuoteRows(int $sid, string $supplierRaw = ''): array
  8738. {
  8739. $list = [];
  8740. $seen = [];
  8741. try {
  8742. $rows = Db::table('purchase_order_detail')
  8743. ->where('scydgy_id', $sid)
  8744. ->field('company_name,amount')
  8745. ->order('id', 'asc')
  8746. ->select();
  8747. if (is_array($rows)) {
  8748. foreach ($rows as $r) {
  8749. if (!is_array($r)) {
  8750. continue;
  8751. }
  8752. $cn = trim((string)($r['company_name'] ?? ''));
  8753. if ($cn === '' || isset($seen[$cn])) {
  8754. continue;
  8755. }
  8756. $seen[$cn] = true;
  8757. $amount = trim((string)($r['amount'] ?? ''));
  8758. $list[] = [
  8759. 'name' => $cn,
  8760. 'amount' => $amount !== '' ? $amount : '未报价',
  8761. ];
  8762. }
  8763. }
  8764. } catch (\Throwable $e) {
  8765. }
  8766. if ($list === [] && $supplierRaw !== '') {
  8767. foreach ($this->splitRfqSalesmanNames($supplierRaw) as $cn) {
  8768. if ($cn === '' || isset($seen[$cn])) {
  8769. continue;
  8770. }
  8771. $seen[$cn] = true;
  8772. $list[] = [
  8773. 'name' => $cn,
  8774. 'amount' => '未报价',
  8775. ];
  8776. }
  8777. }
  8778. return $list;
  8779. }
  8780. /**
  8781. * 通知业务员邮件:供应商报价 HTML 表格(名称+单价,不含时间)
  8782. */
  8783. protected function buildRfqSalesmanSupplierQuotesHtml(int $sid, string $supplierRaw = ''): string
  8784. {
  8785. $rows = $this->loadRfqSalesmanSupplierQuoteRows($sid, $supplierRaw);
  8786. if ($rows === []) {
  8787. return '<p style="margin:8px 0;color:#888;">暂无报价</p>';
  8788. }
  8789. $html = '<table cellpadding="0" cellspacing="0" border="1" '
  8790. . 'style="border-collapse:collapse;border-color:#ddd;width:100%;max-width:560px;font-size:14px;margin:8px 0;">'
  8791. . '<thead><tr style="background:#f5f5f5;">'
  8792. . '<th style="padding:8px 10px;text-align:center;width:56px;">序号</th>'
  8793. . '<th style="padding:8px 10px;text-align:left;">供应商名称</th>'
  8794. . '<th style="padding:8px 10px;text-align:center;width:100px;">单价</th>'
  8795. . '</tr></thead><tbody>';
  8796. foreach ($rows as $i => $row) {
  8797. $html .= '<tr>'
  8798. . '<td style="padding:8px 10px;text-align:center;">' . ($i + 1) . '</td>'
  8799. . '<td style="padding:8px 10px;">' . htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8') . '</td>'
  8800. . '<td style="padding:8px 10px;text-align:center;">' . htmlspecialchars($row['amount'], ENT_QUOTES, 'UTF-8') . '</td>'
  8801. . '</tr>';
  8802. }
  8803. $html .= '</tbody></table>';
  8804. return $html;
  8805. }
  8806. /**
  8807. * 询价多选字段:数组或字符串统一为顿号拼接
  8808. *
  8809. * @param mixed $raw
  8810. */
  8811. protected function joinRfqMultiSelectValues($raw): string
  8812. {
  8813. $parts = [];
  8814. if (is_array($raw)) {
  8815. foreach ($raw as $item) {
  8816. if (is_array($item)) {
  8817. continue;
  8818. }
  8819. $v = trim((string)$item);
  8820. if ($v !== '') {
  8821. $parts[] = $v;
  8822. }
  8823. }
  8824. } else {
  8825. $s = trim((string)$raw);
  8826. if ($s !== '') {
  8827. foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
  8828. $v = trim((string)$piece);
  8829. if ($v !== '') {
  8830. $parts[] = $v;
  8831. }
  8832. }
  8833. }
  8834. }
  8835. $parts = array_values(array_unique($parts));
  8836. return implode('、', $parts);
  8837. }
  8838. /**
  8839. * 新增询价:可选供应商名称(仅落库记录,不发通知)
  8840. *
  8841. * @return string[]
  8842. */
  8843. protected function loadRfqSupplierNameOptions(): array
  8844. {
  8845. $out = [];
  8846. try {
  8847. $rows = Db::table('customer')
  8848. ->where(function ($q) {
  8849. $q->where('status', 1)
  8850. ->whereOr('status', '1')
  8851. ->whereOr('status', '')
  8852. ->whereNull('status');
  8853. })
  8854. ->order('id', 'desc')
  8855. ->column('company_name');
  8856. } catch (\Throwable $e) {
  8857. return [];
  8858. }
  8859. if (!is_array($rows)) {
  8860. return [];
  8861. }
  8862. foreach ($rows as $name) {
  8863. $name = trim((string)$name);
  8864. if ($name === '' || isset($out[$name])) {
  8865. continue;
  8866. }
  8867. $out[$name] = $name;
  8868. }
  8869. return array_values($out);
  8870. }
  8871. /**
  8872. * 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
  8873. */
  8874. protected function rfqNotifySalesmanAuthGroupId(): int
  8875. {
  8876. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  8877. if ($id > 0) {
  8878. return $id;
  8879. }
  8880. try {
  8881. $found = Db::name('auth_group')
  8882. ->where('name', '业务员')
  8883. ->where('status', 'normal')
  8884. ->order('id', 'asc')
  8885. ->value('id');
  8886. $id = (int)$found;
  8887. } catch (\Throwable $e) {
  8888. $id = 0;
  8889. }
  8890. return $id > 0 ? $id : 12;
  8891. }
  8892. /**
  8893. * 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
  8894. *
  8895. * @return string[]
  8896. */
  8897. protected function loadRfqSalesmanNameOptions(): array
  8898. {
  8899. $out = [];
  8900. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8901. $name = trim((string)($row['name'] ?? ''));
  8902. if ($name !== '') {
  8903. $out[] = $name;
  8904. }
  8905. }
  8906. return $out;
  8907. }
  8908. /**
  8909. * 业务员角色组下管理员:姓名、邮箱、手机
  8910. *
  8911. * @return array<int, array{name:string,email:string,mobile:string}>
  8912. */
  8913. protected function loadRfqSalesmanContactOptions(): array
  8914. {
  8915. $out = [];
  8916. $seen = [];
  8917. $groupId = $this->rfqNotifySalesmanAuthGroupId();
  8918. if ($groupId <= 0) {
  8919. return [];
  8920. }
  8921. try {
  8922. $adminIds = Db::name('auth_group_access')
  8923. ->where('group_id', $groupId)
  8924. ->column('uid');
  8925. } catch (\Throwable $e) {
  8926. return [];
  8927. }
  8928. $adminIds = is_array($adminIds)
  8929. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  8930. : [];
  8931. if ($adminIds === []) {
  8932. return [];
  8933. }
  8934. try {
  8935. $rows = Db::name('admin')
  8936. ->where('status', 'normal')
  8937. ->where('id', 'in', $adminIds)
  8938. ->order('id', 'asc')
  8939. ->field('id,nickname,username,email,mobile')
  8940. ->select();
  8941. } catch (\Throwable $e) {
  8942. return [];
  8943. }
  8944. if (!is_array($rows)) {
  8945. return [];
  8946. }
  8947. foreach ($rows as $row) {
  8948. if (!is_array($row)) {
  8949. continue;
  8950. }
  8951. $name = trim((string)($row['nickname'] ?? ''));
  8952. if ($name === '') {
  8953. $name = trim((string)($row['username'] ?? ''));
  8954. }
  8955. if ($name === '' || isset($seen[$name])) {
  8956. continue;
  8957. }
  8958. $seen[$name] = true;
  8959. $out[] = [
  8960. 'name' => $name,
  8961. 'email' => trim((string)($row['email'] ?? '')),
  8962. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  8963. ];
  8964. }
  8965. return $out;
  8966. }
  8967. /**
  8968. * 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
  8969. *
  8970. * @return string[]
  8971. */
  8972. protected function loadRfqDeptNameOptions(): array
  8973. {
  8974. $out = [];
  8975. // ERP 承揽部门(主来源)
  8976. try {
  8977. $vals = Db::table('mcyd')
  8978. ->where('CCLBMMC', '<>', '')
  8979. ->whereNotNull('CCLBMMC')
  8980. ->distinct(true)
  8981. ->limit(300)
  8982. ->column('CCLBMMC');
  8983. } catch (\Throwable $e) {
  8984. $vals = [];
  8985. }
  8986. if (is_array($vals)) {
  8987. foreach ($vals as $v) {
  8988. $v = trim((string)$v);
  8989. if ($v === '' || isset($out[$v])) {
  8990. continue;
  8991. }
  8992. $out[$v] = $v;
  8993. }
  8994. }
  8995. // 手工询价历史部门补全
  8996. try {
  8997. $poVals = Db::table('purchase_order')
  8998. ->where('CCLBMMC', '<>', '')
  8999. ->whereNotNull('CCLBMMC')
  9000. ->distinct(true)
  9001. ->limit(200)
  9002. ->column('CCLBMMC');
  9003. } catch (\Throwable $e) {
  9004. $poVals = [];
  9005. }
  9006. if (is_array($poVals)) {
  9007. foreach ($poVals as $v) {
  9008. $v = trim((string)$v);
  9009. if ($v === '' || isset($out[$v])) {
  9010. continue;
  9011. }
  9012. $out[$v] = $v;
  9013. }
  9014. }
  9015. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  9016. if (!isset($out[$preset])) {
  9017. $out[$preset] = $preset;
  9018. }
  9019. }
  9020. $list = array_values($out);
  9021. // 常用部门靠前
  9022. usort($list, static function ($a, $b) {
  9023. $weight = [
  9024. '营销中心' => 1,
  9025. '业务部' => 2,
  9026. '市场部' => 3,
  9027. '外贸部' => 4,
  9028. '新华技术业务部' => 5,
  9029. ];
  9030. $wa = $weight[$a] ?? 100;
  9031. $wb = $weight[$b] ?? 100;
  9032. if ($wa !== $wb) {
  9033. return $wa <=> $wb;
  9034. }
  9035. return strcmp((string)$a, (string)$b);
  9036. });
  9037. return $list;
  9038. }
  9039. /**
  9040. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  9041. */
  9042. public function add()
  9043. {
  9044. if ($this->request->isPost()) {
  9045. $params = $this->request->post('row/a');
  9046. if (!is_array($params)) {
  9047. $this->error(__('Parameter %s can not be empty', ''));
  9048. }
  9049. [, $adminName] = $this->GetUseName();
  9050. $params['cywyxm'] = $adminName;
  9051. try {
  9052. $sid = $this->saveManualPickOrder($params);
  9053. } catch (\InvalidArgumentException $e) {
  9054. $this->error($e->getMessage());
  9055. } catch (\Throwable $e) {
  9056. $this->error($e->getMessage());
  9057. }
  9058. $this->success('新增成功', '', [
  9059. 'scydgy_id' => $sid,
  9060. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  9061. ]);
  9062. }
  9063. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9064. [, $adminName] = $this->GetUseName();
  9065. $this->view->assign('adminNickname', $adminName);
  9066. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  9067. $this->view->assign('defaultCclbmmc', '营销中心');
  9068. $this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
  9069. $this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
  9070. $this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
  9071. return $this->view->fetch();
  9072. }
  9073. /**
  9074. * 业务员新增进度查询(手工询价;有查询权限看全部,含手机端新增且未通知业务员的)
  9075. */
  9076. public function rfqlist()
  9077. {
  9078. $this->relationSearch = false;
  9079. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ';
  9080. $this->request->filter(['strip_tags', 'trim']);
  9081. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9082. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  9083. $this->ensureRfqSalesmanEmailTemplate();
  9084. $this->ensureRfqSupplierEmailTemplate();
  9085. if ($this->request->isAjax()) {
  9086. try {
  9087. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  9088. $limit = max(10, min(500, (int)$limit));
  9089. $filterYm = trim((string)$this->request->param('filter_ym', ''));
  9090. if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
  9091. $filterYm = date('Y-m');
  9092. }
  9093. $applyFilters = function ($query) use ($where, $filterYm) {
  9094. $query->where('scydgy_id', '<', 0);
  9095. $this->applyPurchaseOrderNotDeletedWhere($query);
  9096. // 查询询价:有菜单权限即可看全部手工单(含手机端新增、尚未通知业务员的)
  9097. $this->applyRfqListMonthFilter($query, $filterYm);
  9098. if (!empty($where)) {
  9099. // 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
  9100. $safeWhere = [];
  9101. $skipFields = [
  9102. 'supplier_name' => true,
  9103. 'progress_text' => true,
  9104. 'createtime_text' => true,
  9105. 'notify_time_text' => true,
  9106. 'can_notify_salesman' => true,
  9107. 'has_issued' => true,
  9108. 'has_quoted' => true,
  9109. ];
  9110. foreach ((array)$where as $cond) {
  9111. if (!is_array($cond) || !isset($cond[0])) {
  9112. continue;
  9113. }
  9114. $field = (string)$cond[0];
  9115. $fieldBase = (string)preg_replace('/\|.*$/', '', $field);
  9116. $fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
  9117. if (isset($skipFields[$fieldBase])) {
  9118. continue;
  9119. }
  9120. if ($fieldBase === 'supplier_name') {
  9121. continue;
  9122. }
  9123. $safeWhere[] = $cond;
  9124. }
  9125. if ($safeWhere !== []) {
  9126. $query->where($safeWhere);
  9127. }
  9128. }
  9129. };
  9130. $countQuery = Db::table('purchase_order');
  9131. $applyFilters($countQuery);
  9132. $total = (int)$countQuery->count();
  9133. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  9134. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  9135. $listQuery = Db::table('purchase_order');
  9136. $applyFilters($listQuery);
  9137. $rows = $listQuery
  9138. ->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')
  9139. ->order($sortField, $orderDir)
  9140. ->limit($offset, $limit)
  9141. ->select();
  9142. if (!is_array($rows)) {
  9143. $rows = [];
  9144. }
  9145. $sidList = [];
  9146. foreach ($rows as $r) {
  9147. if (!is_array($r)) {
  9148. continue;
  9149. }
  9150. $sid = (int)($r['scydgy_id'] ?? 0);
  9151. if ($sid < 0) {
  9152. $sidList[$sid] = true;
  9153. }
  9154. }
  9155. $issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
  9156. $quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
  9157. $out = [];
  9158. foreach ($rows as $r) {
  9159. if (!is_array($r)) {
  9160. continue;
  9161. }
  9162. $sid = (int)($r['scydgy_id'] ?? 0);
  9163. if ($sid >= 0) {
  9164. continue;
  9165. }
  9166. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  9167. if ($createdText === '') {
  9168. $createdText = trim((string)($r['dStamp'] ?? ''));
  9169. }
  9170. $notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
  9171. $supplier = trim((string)($r['cGzzxMc'] ?? ''));
  9172. if ($supplier === '') {
  9173. $supplier = trim((string)($r['pick_company_name'] ?? ''));
  9174. }
  9175. $hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
  9176. || isset($issuedSidSet[$sid]);
  9177. $hasQuoted = isset($quotedSidSet[$sid]);
  9178. $salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
  9179. $canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
  9180. $out[] = [
  9181. 'id' => (int)($r['id'] ?? 0),
  9182. 'scydgy_id' => $sid,
  9183. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  9184. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  9185. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  9186. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  9187. 'CDW' => trim((string)($r['CDW'] ?? '')),
  9188. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  9189. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  9190. 'CDF' => trim((string)($r['CDF'] ?? '')),
  9191. 'supplier_name' => $supplier,
  9192. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  9193. 'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
  9194. 'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
  9195. 'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
  9196. 'notify_time_text' => $notifyTimeText,
  9197. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  9198. 'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
  9199. 'has_issued' => $hasIssued ? 1 : 0,
  9200. 'has_quoted' => $hasQuoted ? 1 : 0,
  9201. 'can_notify_salesman' => $canNotifySalesman,
  9202. 'createtime' => $r['createtime'] ?? null,
  9203. 'createtime_text' => $createdText,
  9204. ];
  9205. }
  9206. return json(['total' => $total, 'rows' => $out]);
  9207. } catch (\Throwable $e) {
  9208. Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
  9209. return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
  9210. }
  9211. }
  9212. $sidebar = $this->loadRfqSidebarYearMonths();
  9213. $defaultYm = $this->resolveRfqListDefaultYm($sidebar);
  9214. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  9215. [, $adminName] = $this->GetUseName();
  9216. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  9217. $this->view->assign('adminNickname', $adminName);
  9218. $this->view->assign('defaultYm', $defaultYm);
  9219. $this->view->assign('sidebarYearMonths', $sidebar);
  9220. return $this->view->fetch('procuremen/rfqlist');
  9221. }
  9222. /**
  9223. * 列表默认月份:当月有数据用当月,否则取最近有数据的月份
  9224. *
  9225. * @param array<int, array{year:string, months:array}> $sidebar
  9226. */
  9227. protected function resolveRfqListDefaultYm(array $sidebar): string
  9228. {
  9229. $current = date('Y-m');
  9230. $yms = $this->flattenProcuremenSidebarYms($sidebar);
  9231. if (in_array($current, $yms, true)) {
  9232. return $current;
  9233. }
  9234. if ($yms !== []) {
  9235. rsort($yms, SORT_STRING);
  9236. return (string)$yms[0];
  9237. }
  9238. return $current;
  9239. }
  9240. /**
  9241. * 手工询价列表左侧月份(按 createtime / dStamp)
  9242. *
  9243. * @return array<int, array{year:string, months:array}>
  9244. */
  9245. protected function loadRfqSidebarYearMonths(): array
  9246. {
  9247. $ymSet = [];
  9248. try {
  9249. $q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
  9250. $this->applyPurchaseOrderNotDeletedWhere($q);
  9251. $rows = $q->field('createtime,dStamp')->limit(5000)->select();
  9252. } catch (\Throwable $e) {
  9253. $rows = [];
  9254. }
  9255. if (!is_array($rows)) {
  9256. $rows = [];
  9257. }
  9258. foreach ($rows as $r) {
  9259. if (!is_array($r)) {
  9260. continue;
  9261. }
  9262. $t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  9263. if ($t === '') {
  9264. $t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
  9265. }
  9266. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  9267. $ymSet[$m[1] . '-' . $m[2]] = true;
  9268. }
  9269. }
  9270. return $this->buildYearMonthSidebar(array_keys($ymSet));
  9271. }
  9272. /**
  9273. * 手工询价可见范围(用于详情/操作校验):
  9274. * 超管、具备「查询询价」权限、需求发起人、通知业务员 → 可见
  9275. * 列表页本身不再按发起人/通知过滤,避免手机端新增后后台看不到。
  9276. */
  9277. protected function applyManualRfqViewerWhere($query): void
  9278. {
  9279. if ($this->auth->isSuperAdmin() || $this->hasProcuremenPerm(['rfqlist'])) {
  9280. return;
  9281. }
  9282. [, $adminName] = $this->GetUseName();
  9283. $adminName = trim((string)$adminName);
  9284. if ($adminName === '') {
  9285. $query->whereRaw('1 = 0');
  9286. return;
  9287. }
  9288. // 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
  9289. $query->where(function ($q) use ($adminName) {
  9290. $q->where('cywyxm', $adminName)
  9291. ->whereOr('notify_salesman', $adminName)
  9292. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  9293. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  9294. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  9295. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  9296. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  9297. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  9298. });
  9299. }
  9300. /**
  9301. * 当前用户是否可查看/操作该手工询价单
  9302. */
  9303. protected function canViewManualRfqOrder(array $po): bool
  9304. {
  9305. if ($this->auth->isSuperAdmin()) {
  9306. return true;
  9307. }
  9308. // 有查询询价权限则可操作全部手工询价(询价/查看报价/通知业务员等)
  9309. if ($this->hasProcuremenPerm(['rfqlist'])) {
  9310. return true;
  9311. }
  9312. [, $adminName] = $this->GetUseName();
  9313. $adminName = trim((string)$adminName);
  9314. if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
  9315. return true;
  9316. }
  9317. if ($adminName !== '') {
  9318. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  9319. if ($n === $adminName) {
  9320. return true;
  9321. }
  9322. }
  9323. }
  9324. return false;
  9325. }
  9326. /**
  9327. * 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
  9328. */
  9329. protected function applyRfqListMonthFilter($query, string $ym): void
  9330. {
  9331. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  9332. $ym = date('Y-m');
  9333. }
  9334. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  9335. // 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
  9336. $query->whereRaw(
  9337. "("
  9338. . "CASE "
  9339. . "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  9340. . "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
  9341. . "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
  9342. . "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  9343. . "THEN TRIM(CAST(createtime AS CHAR(32))) "
  9344. . "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
  9345. . "END"
  9346. . ") LIKE '{$ymEsc}-%'"
  9347. );
  9348. }
  9349. /**
  9350. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  9351. */
  9352. public function rfqlistDetails()
  9353. {
  9354. return $this->details();
  9355. }
  9356. /**
  9357. * 查询询价 — 弹窗:可选通知业务员名单(勾选后确认通知)
  9358. */
  9359. public function rfqnotifysalesmen()
  9360. {
  9361. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman'])) {
  9362. $this->error(__('You have no permission'));
  9363. }
  9364. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9365. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  9366. $sid = (int)$this->request->param('scydgy_id', 0);
  9367. if ($sid >= 0) {
  9368. $this->error('仅支持手工新增询价单');
  9369. }
  9370. $po = $this->loadManualRfqOrderForNotify($sid);
  9371. $selectedMap = [];
  9372. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  9373. $selectedMap[$n] = true;
  9374. }
  9375. $list = [];
  9376. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  9377. $name = trim((string)($row['name'] ?? ''));
  9378. if ($name === '') {
  9379. continue;
  9380. }
  9381. $email = trim((string)($row['email'] ?? ''));
  9382. $mobile = trim((string)($row['mobile'] ?? ''));
  9383. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  9384. $list[] = [
  9385. 'name' => $name,
  9386. 'email' => $email,
  9387. 'mobile' => $mobile,
  9388. 'can_select' => $hasEmail ? 1 : 0,
  9389. 'checked' => (!empty($selectedMap[$name]) && $hasEmail) ? 1 : 0,
  9390. ];
  9391. }
  9392. $canNotify = $this->canRfqNotifySalesman($po);
  9393. $this->success('', null, [
  9394. 'scydgy_id' => $sid,
  9395. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9396. 'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
  9397. 'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
  9398. 'can_notify_salesman' => $canNotify ? 1 : 0,
  9399. 'list' => $list,
  9400. ]);
  9401. }
  9402. /**
  9403. * 查询询价 — 补加通知业务员可选名单
  9404. */
  9405. public function rfqsalesmanoptions()
  9406. {
  9407. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen'])) {
  9408. $this->error(__('You have no permission'));
  9409. }
  9410. $out = [];
  9411. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  9412. $email = trim((string)($row['email'] ?? ''));
  9413. $mobile = trim((string)($row['mobile'] ?? ''));
  9414. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  9415. $out[] = [
  9416. 'name' => (string)($row['name'] ?? ''),
  9417. 'email' => $email,
  9418. 'mobile' => $mobile,
  9419. 'can_select' => $hasEmail ? 1 : 0,
  9420. ];
  9421. }
  9422. $this->success('', null, ['list' => $out]);
  9423. }
  9424. /**
  9425. * 查询询价 — 补加通知业务员(合并更新 notify_salesman)
  9426. */
  9427. public function rfqappendsalesmen()
  9428. {
  9429. if (!$this->request->isPost()) {
  9430. $this->error(__('Invalid parameters'));
  9431. }
  9432. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen'])) {
  9433. $this->error(__('You have no permission'));
  9434. }
  9435. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9436. $sid = (int)$this->request->post('scydgy_id', 0);
  9437. if ($sid >= 0) {
  9438. $this->error('仅支持手工新增询价单');
  9439. }
  9440. $po = $this->loadManualRfqOrderForNotify($sid);
  9441. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9442. $this->error('订单已完结,无法添加业务员');
  9443. }
  9444. $raw = $this->request->post('salesmen/a', []);
  9445. if (!is_array($raw) || $raw === []) {
  9446. $salesmenJson = $this->request->post('salesmen_json', '');
  9447. if (is_string($salesmenJson) && $salesmenJson !== '') {
  9448. $decoded = json_decode($salesmenJson, true);
  9449. $raw = is_array($decoded) ? $decoded : [];
  9450. }
  9451. }
  9452. $addNames = [];
  9453. foreach ((array)$raw as $item) {
  9454. if (is_array($item)) {
  9455. $n = trim((string)($item['name'] ?? ''));
  9456. } else {
  9457. $n = trim((string)$item);
  9458. }
  9459. if ($n !== '') {
  9460. $addNames[] = $n;
  9461. }
  9462. }
  9463. $addNames = array_values(array_unique($addNames));
  9464. if ($addNames === []) {
  9465. $this->error('请选择要添加的业务员');
  9466. }
  9467. $allowedOptions = $this->loadRfqSalesmanContactOptions();
  9468. $allowedMap = [];
  9469. foreach ($allowedOptions as $opt) {
  9470. $n = trim((string)($opt['name'] ?? ''));
  9471. if ($n === '') {
  9472. continue;
  9473. }
  9474. $email = trim((string)($opt['email'] ?? ''));
  9475. $allowedMap[$n] = ($email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL));
  9476. }
  9477. foreach ($addNames as $n) {
  9478. if (!array_key_exists($n, $allowedMap)) {
  9479. $this->error('业务员不在可选名单中:' . $n);
  9480. }
  9481. if (!$allowedMap[$n]) {
  9482. $this->error('业务员未填写有效邮箱,无法添加:' . $n);
  9483. }
  9484. }
  9485. $existingRaw = trim((string)($po['notify_salesman'] ?? ''));
  9486. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9487. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9488. try {
  9489. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['notify_salesman' => $mergedStr]);
  9490. } catch (\Throwable $e) {
  9491. $this->error('保存失败:' . $e->getMessage());
  9492. }
  9493. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9494. $this->addOrderLog($sid, 'rfq_append_salesman', '添加通知业务员:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9495. $this->success('已添加业务员', null, [
  9496. 'scydgy_id' => $sid,
  9497. 'notify_salesman' => $mergedStr,
  9498. 'added_count' => count($addNames),
  9499. ]);
  9500. }
  9501. /**
  9502. * 查询询价 — 勾选业务员后邮箱通知(salesmen_json)
  9503. */
  9504. public function rfqnotifysalesman()
  9505. {
  9506. if (!$this->request->isPost()) {
  9507. $this->error(__('Invalid parameters'));
  9508. }
  9509. if (!$this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen'])) {
  9510. $this->error(__('You have no permission'));
  9511. }
  9512. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9513. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  9514. $sid = (int)$this->request->post('scydgy_id', 0);
  9515. if ($sid >= 0) {
  9516. $this->error('仅支持手工新增询价单');
  9517. }
  9518. $po = $this->loadManualRfqOrderForNotify($sid);
  9519. $this->assertRfqCanNotifySalesman($po);
  9520. $raw = $this->request->post('salesmen/a', []);
  9521. if (!is_array($raw) || $raw === []) {
  9522. $salesmenJson = $this->request->post('salesmen_json', '');
  9523. if (is_string($salesmenJson) && $salesmenJson !== '') {
  9524. $decoded = json_decode($salesmenJson, true);
  9525. $raw = is_array($decoded) ? $decoded : [];
  9526. }
  9527. }
  9528. // 兼容旧参数:notify_all / 单人 name
  9529. if ((!is_array($raw) || $raw === []) && (int)$this->request->post('notify_all', 0) === 1) {
  9530. $raw = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  9531. }
  9532. if ((!is_array($raw) || $raw === [])) {
  9533. $oneName = trim((string)$this->request->post('name', ''));
  9534. if ($oneName !== '') {
  9535. $raw = [$oneName];
  9536. }
  9537. }
  9538. $selectedNames = [];
  9539. foreach ((array)$raw as $item) {
  9540. if (is_array($item)) {
  9541. $n = trim((string)($item['name'] ?? ''));
  9542. } else {
  9543. $n = trim((string)$item);
  9544. }
  9545. if ($n !== '') {
  9546. $selectedNames[] = $n;
  9547. }
  9548. }
  9549. $selectedNames = array_values(array_unique($selectedNames));
  9550. if ($selectedNames === []) {
  9551. $this->error('请选择要通知的业务员');
  9552. }
  9553. $optionMap = [];
  9554. foreach ($this->loadRfqSalesmanContactOptions() as $opt) {
  9555. $n = trim((string)($opt['name'] ?? ''));
  9556. if ($n === '') {
  9557. continue;
  9558. }
  9559. $optionMap[$n] = $opt;
  9560. }
  9561. $targets = [];
  9562. foreach ($selectedNames as $n) {
  9563. if (!isset($optionMap[$n])) {
  9564. $this->error('业务员不在可选名单中:' . $n);
  9565. }
  9566. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  9567. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9568. $this->error('业务员未填写有效邮箱,无法通知:' . $n);
  9569. }
  9570. $resolved = $this->resolveRfqSalesmanContactRows([$n]);
  9571. $targets[] = $resolved[0] ?? [
  9572. 'admin_id' => 0,
  9573. 'name' => $n,
  9574. 'email' => $email,
  9575. ];
  9576. }
  9577. $mergedStr = $this->joinRfqMultiSelectValues($selectedNames);
  9578. try {
  9579. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  9580. 'notify_salesman' => $mergedStr,
  9581. ]);
  9582. } catch (\Throwable $e) {
  9583. $this->error('保存通知业务员失败:' . $e->getMessage());
  9584. }
  9585. $po['notify_salesman'] = $mergedStr;
  9586. $mailConfig = $this->loadMailerConfig();
  9587. if (empty($mailConfig['host'])) {
  9588. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9589. }
  9590. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9591. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9592. }
  9593. $this->ensureRfqSalesmanEmailTemplate();
  9594. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  9595. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  9596. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  9597. $cdw = trim((string)($po['CDW'] ?? ''));
  9598. $qty = trim((string)$this->resolveProcuremenThisQuantity($po));
  9599. $ceiling = trim((string)$this->resolveProcuremenCeilingPrice($po));
  9600. $mbz = trim((string)($po['MBZ'] ?? ''));
  9601. $cywyxm = trim((string)($po['cywyxm'] ?? ''));
  9602. $supplier = trim((string)($po['cGzzxMc'] ?? ''));
  9603. if ($supplier === '') {
  9604. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  9605. }
  9606. $supplierQuotesHtml = $this->buildRfqSalesmanSupplierQuotesHtml($sid, $supplier);
  9607. try {
  9608. $platformUrl = $this->buildMprocMobileRfqAddUrl($sid, 'pending');
  9609. } catch (\Throwable $e) {
  9610. $platformUrl = '';
  9611. }
  9612. try {
  9613. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
  9614. } catch (\Throwable $e) {
  9615. $this->error($e->getMessage());
  9616. }
  9617. $okNames = [];
  9618. $failMsgs = [];
  9619. foreach ($targets as $contact) {
  9620. $toEmail = trim((string)($contact['email'] ?? ''));
  9621. $toName = trim((string)($contact['name'] ?? ''));
  9622. $notifyVars = [
  9623. 'contact_name' => $toName,
  9624. 'salesman_name' => $toName,
  9625. 'company_name' => $toName,
  9626. 'email' => $toEmail,
  9627. 'ccydh' => $ccydh,
  9628. 'cyjmc' => $cyjmc,
  9629. 'cgymc' => $cgymc,
  9630. 'cdw' => $cdw,
  9631. 'this_quantity' => $qty,
  9632. 'ceilingPrice' => $ceiling,
  9633. 'MBZ' => $mbz,
  9634. 'supplier_name' => $supplier,
  9635. // 占位符,转 HTML 后再替换成表格,避免被 htmlspecialchars 转义
  9636. 'supplier_quotes' => '__RFQ_SUPPLIER_QUOTES_TABLE__',
  9637. 'cywyxm' => $cywyxm,
  9638. 'platform_url' => $platformUrl,
  9639. ];
  9640. try {
  9641. $mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
  9642. $mailSubject = $mailSubjectTpl;
  9643. foreach ($notifyVars as $k => $v) {
  9644. if ($k === 'supplier_quotes') {
  9645. continue;
  9646. }
  9647. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  9648. }
  9649. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  9650. $mailSubject = trim((string)$mailSubject);
  9651. if ($mailSubject === '') {
  9652. $mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  9653. }
  9654. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  9655. $mailBody = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', $supplierQuotesHtml, $mailBody);
  9656. $mailPlainForLog = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', strip_tags(str_replace(['</tr>', '</p>'], "\n", $supplierQuotesHtml)), $mailPlain);
  9657. $bundle = [
  9658. 'company_name' => $toName,
  9659. 'email' => $toEmail,
  9660. 'mail_plain' => $mailPlainForLog,
  9661. 'mail_body' => $mailBody,
  9662. 'ccydh' => $ccydh,
  9663. 'email_log_scene' => 'rfq_salesman',
  9664. 'email_log_scydgy_id' => $sid,
  9665. 'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
  9666. 'notify_vars' => $notifyVars,
  9667. ];
  9668. $this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
  9669. $okNames[] = $toName . '(' . $toEmail . ')';
  9670. } catch (\Throwable $e) {
  9671. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  9672. }
  9673. }
  9674. if ($okNames === []) {
  9675. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  9676. }
  9677. $now = date('Y-m-d H:i:s');
  9678. try {
  9679. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  9680. 'rfq_salesman_notified' => 1,
  9681. 'rfq_salesman_notify_time' => $now,
  9682. ]);
  9683. } catch (\Throwable $e) {
  9684. // ignore
  9685. }
  9686. $this->addOrderLog(
  9687. $sid,
  9688. 'rfq_notify_salesman',
  9689. '邮箱通知业务员:' . implode('、', $okNames),
  9690. (int)($po['id'] ?? 0)
  9691. );
  9692. $msg = '已通知 ' . count($okNames) . ' 人';
  9693. if ($failMsgs !== []) {
  9694. $msg .= ';部分失败:' . implode(';', $failMsgs);
  9695. }
  9696. $this->success($msg, null, [
  9697. 'scydgy_id' => $sid,
  9698. 'notify_salesman' => $mergedStr,
  9699. 'rfq_salesman_notified' => 1,
  9700. 'rfq_salesman_notify_time' => $now,
  9701. 'notify_time_text' => $now,
  9702. 'ok_count' => count($okNames),
  9703. 'fail_count' => count($failMsgs),
  9704. ]);
  9705. }
  9706. /**
  9707. * 查询询价 — 下发前:返回将通知的供应商表格数据
  9708. */
  9709. public function rfqissuesuppliers()
  9710. {
  9711. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers'])) {
  9712. $this->error(__('You have no permission'));
  9713. }
  9714. $sid = (int)$this->request->param('scydgy_id', 0);
  9715. if ($sid >= 0) {
  9716. $this->error('仅支持手工新增询价单');
  9717. }
  9718. $po = $this->loadManualRfqOrderForNotify($sid);
  9719. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9720. if ($supplierRaw === '') {
  9721. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9722. }
  9723. $names = $this->splitRfqSalesmanNames($supplierRaw);
  9724. // 已成功发过询价邮件的供应商(含历史 pick_issue 场景)
  9725. $notifiedMap = [];
  9726. try {
  9727. $this->ensurePurchaseEmailSendLogTableOnce();
  9728. $logRows = Db::table('purchase_email_send_log')
  9729. ->where('scydgy_id', $sid)
  9730. ->where('status', 1)
  9731. ->where('scene', 'in', ['rfq_supplier', 'pick_issue'])
  9732. ->field('company_name')
  9733. ->select();
  9734. if (is_array($logRows)) {
  9735. foreach ($logRows as $lr) {
  9736. if (!is_array($lr)) {
  9737. continue;
  9738. }
  9739. $cn = trim((string)($lr['company_name'] ?? ''));
  9740. if ($cn !== '') {
  9741. $notifiedMap[$cn] = true;
  9742. }
  9743. }
  9744. }
  9745. } catch (\Throwable $e) {
  9746. }
  9747. // 兼容:明细已生成(曾下发)也视为已通知
  9748. try {
  9749. $detRows = Db::table('purchase_order_detail')
  9750. ->where('scydgy_id', $sid)
  9751. ->field('company_name')
  9752. ->select();
  9753. if (is_array($detRows)) {
  9754. foreach ($detRows as $dr) {
  9755. if (!is_array($dr)) {
  9756. continue;
  9757. }
  9758. $cn = trim((string)($dr['company_name'] ?? ''));
  9759. if ($cn !== '') {
  9760. $notifiedMap[$cn] = true;
  9761. }
  9762. }
  9763. }
  9764. } catch (\Throwable $e) {
  9765. }
  9766. $list = [];
  9767. foreach ($names as $name) {
  9768. // 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
  9769. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9770. $email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
  9771. $phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
  9772. $username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
  9773. $okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
  9774. $notified = !empty($notifiedMap[$name]) ? 1 : 0;
  9775. $list[] = [
  9776. 'name' => $name,
  9777. 'username' => $username,
  9778. 'email' => $email,
  9779. 'phone' => $phone,
  9780. 'can_notify' => $okEmail ? 1 : 0,
  9781. 'found' => is_array($contact) ? 1 : 0,
  9782. 'notified' => $notified,
  9783. 'notify_status_text' => $notified ? '已通知' : '未通知',
  9784. ];
  9785. }
  9786. $this->success('', null, [
  9787. 'scydgy_id' => $sid,
  9788. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9789. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9790. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9791. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9792. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9793. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9794. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9795. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9796. 'list' => $list,
  9797. ]);
  9798. }
  9799. /**
  9800. * 查询询价 — 补加供应商可选名单
  9801. */
  9802. public function rfqsupplieroptions()
  9803. {
  9804. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
  9805. $this->error(__('You have no permission'));
  9806. }
  9807. $names = array_values($this->loadRfqSupplierNameOptions());
  9808. $out = [];
  9809. foreach ($names as $name) {
  9810. $out[] = ['name' => $name];
  9811. }
  9812. $this->success('', null, ['list' => $out]);
  9813. }
  9814. /**
  9815. * 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
  9816. */
  9817. public function rfqappendsuppliers()
  9818. {
  9819. if (!$this->request->isPost()) {
  9820. $this->error(__('Invalid parameters'));
  9821. }
  9822. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers'])) {
  9823. $this->error(__('You have no permission'));
  9824. }
  9825. $sid = (int)$this->request->post('scydgy_id', 0);
  9826. if ($sid >= 0) {
  9827. $this->error('仅支持手工新增询价单');
  9828. }
  9829. $po = $this->loadManualRfqOrderForNotify($sid);
  9830. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9831. $this->error('订单已完结,无法补加供应商');
  9832. }
  9833. $raw = $this->request->post('suppliers/a', []);
  9834. if (!is_array($raw) || $raw === []) {
  9835. $suppliersJson = $this->request->post('suppliers_json', '');
  9836. if (is_string($suppliersJson) && $suppliersJson !== '') {
  9837. $decoded = json_decode($suppliersJson, true);
  9838. $raw = is_array($decoded) ? $decoded : [];
  9839. }
  9840. }
  9841. $addNames = [];
  9842. foreach ((array)$raw as $item) {
  9843. if (is_array($item)) {
  9844. $n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
  9845. } else {
  9846. $n = trim((string)$item);
  9847. }
  9848. if ($n !== '') {
  9849. $addNames[] = $n;
  9850. }
  9851. }
  9852. $addNames = array_values(array_unique($addNames));
  9853. if ($addNames === []) {
  9854. $this->error('请选择要补加的供应商');
  9855. }
  9856. $existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9857. if ($existingRaw === '') {
  9858. $existingRaw = trim((string)($po['pick_company_name'] ?? ''));
  9859. }
  9860. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9861. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9862. try {
  9863. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
  9864. } catch (\Throwable $e) {
  9865. $this->error('保存失败:' . $e->getMessage());
  9866. }
  9867. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9868. $this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9869. $this->success('已补加供应商', null, [
  9870. 'scydgy_id' => $sid,
  9871. 'cGzzxMc' => $mergedStr,
  9872. 'added_count' => count($addNames),
  9873. ]);
  9874. }
  9875. /**
  9876. * 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
  9877. */
  9878. public function rfqissue()
  9879. {
  9880. if (!$this->request->isPost()) {
  9881. $this->error(__('Invalid parameters'));
  9882. }
  9883. if (!$this->hasProcuremenPerm(['rfqissue'])) {
  9884. $this->error(__('You have no permission'));
  9885. }
  9886. $this->ensureRfqSupplierEmailTemplate();
  9887. $sid = (int)$this->request->post('scydgy_id', 0);
  9888. if ($sid >= 0) {
  9889. $this->error('仅支持手工新增询价单');
  9890. }
  9891. $po = $this->loadManualRfqOrderForNotify($sid);
  9892. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9893. $this->error('订单已完结,无法下发');
  9894. }
  9895. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9896. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9897. $this->error('订单已进入后续流程,无法再下发');
  9898. }
  9899. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9900. if ($supplierRaw === '') {
  9901. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9902. }
  9903. $supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
  9904. if ($supplierNames === []) {
  9905. $this->error('请先在新增询价时选择供应商');
  9906. }
  9907. $companies = [];
  9908. $missing = [];
  9909. $noEmail = [];
  9910. foreach ($supplierNames as $name) {
  9911. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9912. if ($contact === null) {
  9913. $missing[] = $name;
  9914. continue;
  9915. }
  9916. $em = trim((string)($contact['email'] ?? ''));
  9917. if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
  9918. $noEmail[] = $name;
  9919. continue;
  9920. }
  9921. $companies[] = $contact;
  9922. }
  9923. if ($missing !== []) {
  9924. $this->error('未找到供应商档案:' . implode('、', $missing));
  9925. }
  9926. if ($noEmail !== []) {
  9927. $this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
  9928. }
  9929. if ($companies === []) {
  9930. $this->error('没有可通知的供应商');
  9931. }
  9932. $mailConfig = $this->loadMailerConfig();
  9933. if (empty($mailConfig['host'])) {
  9934. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9935. }
  9936. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9937. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9938. }
  9939. $mergeRow = $po;
  9940. $mergeRow['ID'] = $sid;
  9941. $mergeRow['id'] = $sid;
  9942. $mergeRows = [$mergeRow];
  9943. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9944. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9945. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9946. }
  9947. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9948. $issueTime = date('Y-m-d H:i:s');
  9949. $nameLabels = [];
  9950. foreach ($companies as $c) {
  9951. $nameLabels[] = trim((string)($c['name'] ?? ''));
  9952. }
  9953. $logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
  9954. Db::startTrans();
  9955. try {
  9956. $this->upsertPurchaseOrderFromRow(
  9957. $mergeRow,
  9958. $sysRqDb,
  9959. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9960. $issueTime,
  9961. $po,
  9962. null,
  9963. $scoreRule
  9964. );
  9965. foreach ($companies as $c) {
  9966. $this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
  9967. }
  9968. Db::commit();
  9969. } catch (\Throwable $e) {
  9970. Db::rollback();
  9971. $this->error($e->getMessage());
  9972. }
  9973. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9974. if ($poId <= 0) {
  9975. try {
  9976. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9977. } catch (\Throwable $e) {
  9978. $poId = 0;
  9979. }
  9980. }
  9981. $this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
  9982. $posNotify = [];
  9983. try {
  9984. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9985. if (is_array($fresh)) {
  9986. $fresh['sys_rq'] = $sysRqDb;
  9987. $posNotify = [$fresh];
  9988. }
  9989. } catch (\Throwable $e) {
  9990. $posNotify = [$po];
  9991. $posNotify[0]['sys_rq'] = $sysRqDb;
  9992. }
  9993. $notifyBundle = [
  9994. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9995. 'pos' => $posNotify,
  9996. 'merge_rows' => $mergeRows,
  9997. ];
  9998. $notifyErrors = [];
  9999. foreach ($companies as $c) {
  10000. $cname = trim((string)($c['name'] ?? ''));
  10001. try {
  10002. // 询价下发:仅邮箱通知供应商
  10003. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  10004. } catch (\Throwable $e) {
  10005. $notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
  10006. }
  10007. }
  10008. if ($notifyErrors !== []) {
  10009. $this->error('下发已保存,但邮件通知失败:' . implode(';', $notifyErrors));
  10010. }
  10011. $this->success('已询价并邮件通知供应商', null, [
  10012. 'scydgy_id' => $sid,
  10013. 'progress_text' => '待报价',
  10014. 'supplier_count' => count($companies),
  10015. ]);
  10016. }
  10017. /**
  10018. * 查询询价 — 弹窗内向单个供应商发送询价邮件
  10019. */
  10020. public function rfqissuesendmail()
  10021. {
  10022. if (!$this->request->isPost()) {
  10023. $this->error(__('Invalid parameters'));
  10024. }
  10025. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail'])) {
  10026. $this->error(__('You have no permission'));
  10027. }
  10028. $this->ensureRfqSupplierEmailTemplate();
  10029. $sid = (int)$this->request->post('scydgy_id', 0);
  10030. $companyName = trim((string)$this->request->post('company_name', ''));
  10031. if ($sid >= 0) {
  10032. $this->error('仅支持手工新增询价单');
  10033. }
  10034. if ($companyName === '') {
  10035. $this->error('请选择供应商');
  10036. }
  10037. $po = $this->loadManualRfqOrderForNotify($sid);
  10038. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  10039. $this->error('订单已完结,无法发送');
  10040. }
  10041. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  10042. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  10043. $this->error('订单已进入后续流程,无法再发送');
  10044. }
  10045. $contact = $this->resolveCustomerContactByCompanyName($companyName, false);
  10046. if ($contact === null) {
  10047. $this->error('未找到供应商档案:' . $companyName);
  10048. }
  10049. $email = trim((string)($contact['email'] ?? ''));
  10050. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  10051. $this->error('该供应商未填写有效邮箱');
  10052. }
  10053. $mailConfig = $this->loadMailerConfig();
  10054. if (empty($mailConfig['host'])) {
  10055. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  10056. }
  10057. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  10058. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  10059. }
  10060. $mergeRow = $po;
  10061. $mergeRow['ID'] = $sid;
  10062. $mergeRow['id'] = $sid;
  10063. $mergeRows = [$mergeRow];
  10064. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  10065. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  10066. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  10067. }
  10068. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  10069. $issueTime = date('Y-m-d H:i:s');
  10070. Db::startTrans();
  10071. try {
  10072. $this->upsertPurchaseOrderFromRow(
  10073. $mergeRow,
  10074. $sysRqDb,
  10075. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  10076. $issueTime,
  10077. $po,
  10078. null,
  10079. $scoreRule
  10080. );
  10081. $this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
  10082. Db::commit();
  10083. } catch (\Throwable $e) {
  10084. Db::rollback();
  10085. $this->error($e->getMessage());
  10086. }
  10087. $posNotify = [];
  10088. try {
  10089. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  10090. if (is_array($fresh)) {
  10091. $fresh['sys_rq'] = $sysRqDb;
  10092. $posNotify = [$fresh];
  10093. }
  10094. } catch (\Throwable $e) {
  10095. $posNotify = [$po];
  10096. $posNotify[0]['sys_rq'] = $sysRqDb;
  10097. }
  10098. $notifyBundle = [
  10099. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  10100. 'pos' => $posNotify,
  10101. 'merge_rows' => $mergeRows,
  10102. ];
  10103. try {
  10104. $this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  10105. } catch (\Throwable $e) {
  10106. $this->error('明细已保存,但邮件发送失败:' . $e->getMessage());
  10107. }
  10108. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  10109. if ($poId <= 0) {
  10110. try {
  10111. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  10112. } catch (\Throwable $e) {
  10113. $poId = 0;
  10114. }
  10115. }
  10116. $this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
  10117. $this->success('已向「' . $companyName . '」发送询价邮件', null, [
  10118. 'scydgy_id' => $sid,
  10119. 'company_name' => $companyName,
  10120. ]);
  10121. }
  10122. /**
  10123. * 查询询价 — 查看各供应商报价(单价)
  10124. */
  10125. public function rfqquotes()
  10126. {
  10127. if (!$this->hasProcuremenPerm(['rfqquotes', 'rfqissue'])) {
  10128. $this->error(__('You have no permission'));
  10129. }
  10130. $sid = (int)$this->request->param('scydgy_id', 0);
  10131. if ($sid >= 0) {
  10132. $this->error('仅支持手工新增询价单');
  10133. }
  10134. $po = $this->loadManualRfqOrderForNotify($sid);
  10135. $rows = [];
  10136. try {
  10137. // 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
  10138. $q = Db::table('purchase_order_detail')
  10139. ->where('scydgy_id', $sid)
  10140. ->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
  10141. ->order('id', 'asc');
  10142. $this->applyActivePurchaseOrderDetailWhere($q);
  10143. $rows = $q->select();
  10144. } catch (\Throwable $e) {
  10145. try {
  10146. $q = Db::table('purchase_order_detail')
  10147. ->where('scydgy_id', $sid)
  10148. ->order('id', 'asc');
  10149. $this->applyActivePurchaseOrderDetailWhere($q);
  10150. $rows = $q->select();
  10151. } catch (\Throwable $e2) {
  10152. $rows = [];
  10153. }
  10154. }
  10155. if (!is_array($rows)) {
  10156. $rows = [];
  10157. }
  10158. $list = [];
  10159. foreach ($rows as $row) {
  10160. if (!is_array($row)) {
  10161. continue;
  10162. }
  10163. $amount = trim((string)($row['amount'] ?? ''));
  10164. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  10165. // 未报价不显示时间(createtime 是下发时间,不是报价时间)
  10166. $oper = '';
  10167. if ($isQuoted) {
  10168. $oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
  10169. if ($oper === '') {
  10170. $oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  10171. }
  10172. }
  10173. $list[] = [
  10174. 'id' => (int)($row['id'] ?? 0),
  10175. 'company_name' => trim((string)($row['company_name'] ?? '')),
  10176. 'amount' => $amount,
  10177. 'amount_text' => $isQuoted ? $amount : '',
  10178. 'is_quoted' => $isQuoted,
  10179. 'quote_label' => $isQuoted ? '已报价' : '未报价',
  10180. 'status_name' => trim((string)($row['status_name'] ?? '')),
  10181. 'oper_time' => $oper,
  10182. ];
  10183. }
  10184. $this->success('', null, [
  10185. 'scydgy_id' => $sid,
  10186. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  10187. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  10188. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  10189. 'CDW' => trim((string)($po['CDW'] ?? '')),
  10190. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  10191. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  10192. 'CDF' => trim((string)($po['CDF'] ?? '')),
  10193. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  10194. 'list' => $list,
  10195. ]);
  10196. }
  10197. /**
  10198. * 手工询价是否已下发(有下发明细或已进入待确认及之后)
  10199. */
  10200. protected function isRfqOrderIssued(array $po): bool
  10201. {
  10202. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  10203. return true;
  10204. }
  10205. $sid = (int)($po['scydgy_id'] ?? 0);
  10206. if ($sid >= 0) {
  10207. return false;
  10208. }
  10209. try {
  10210. $q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  10211. $this->applyActivePurchaseOrderDetailWhere($q);
  10212. return (int)$q->count() > 0;
  10213. } catch (\Throwable $e) {
  10214. return false;
  10215. }
  10216. }
  10217. /**
  10218. * 批量:已有下发明细的手工询价 scydgy_id
  10219. *
  10220. * @param int[] $scydgyIds
  10221. * @return array<int, bool>
  10222. */
  10223. protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
  10224. {
  10225. $set = [];
  10226. $ids = [];
  10227. foreach ($scydgyIds as $sid) {
  10228. $sid = (int)$sid;
  10229. if ($sid < 0) {
  10230. $ids[$sid] = true;
  10231. }
  10232. }
  10233. if ($ids === []) {
  10234. return $set;
  10235. }
  10236. try {
  10237. $q = Db::table('purchase_order_detail')
  10238. ->where('scydgy_id', 'in', array_keys($ids))
  10239. ->field('scydgy_id');
  10240. $this->applyActivePurchaseOrderDetailWhere($q);
  10241. $rows = $q->select();
  10242. } catch (\Throwable $e) {
  10243. return $set;
  10244. }
  10245. if (!is_array($rows)) {
  10246. return $set;
  10247. }
  10248. foreach ($rows as $row) {
  10249. if (!is_array($row)) {
  10250. continue;
  10251. }
  10252. $sid = (int)($row['scydgy_id'] ?? 0);
  10253. if ($sid < 0) {
  10254. $set[$sid] = true;
  10255. }
  10256. }
  10257. return $set;
  10258. }
  10259. /**
  10260. * 批量:已填单价(已报价)的手工询价 scydgy_id
  10261. *
  10262. * @param int[] $scydgyIds
  10263. * @return array<int, bool>
  10264. */
  10265. protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
  10266. {
  10267. $set = [];
  10268. $ids = [];
  10269. foreach ($scydgyIds as $sid) {
  10270. $sid = (int)$sid;
  10271. if ($sid < 0) {
  10272. $ids[$sid] = true;
  10273. }
  10274. }
  10275. if ($ids === []) {
  10276. return $set;
  10277. }
  10278. try {
  10279. $q = Db::table('purchase_order_detail')
  10280. ->where('scydgy_id', 'in', array_keys($ids))
  10281. ->field('scydgy_id,amount');
  10282. $this->applyActivePurchaseOrderDetailWhere($q);
  10283. $rows = $q->select();
  10284. } catch (\Throwable $e) {
  10285. return $set;
  10286. }
  10287. if (!is_array($rows)) {
  10288. return $set;
  10289. }
  10290. foreach ($rows as $row) {
  10291. if (!is_array($row)) {
  10292. continue;
  10293. }
  10294. $amount = trim((string)($row['amount'] ?? ''));
  10295. if ($amount === '' || $amount === '0' || $amount === '0.00') {
  10296. continue;
  10297. }
  10298. $sid = (int)($row['scydgy_id'] ?? 0);
  10299. if ($sid < 0) {
  10300. $set[$sid] = true;
  10301. }
  10302. }
  10303. return $set;
  10304. }
  10305. /**
  10306. * 已下发且至少一家供应商已报价,才允许通知业务员
  10307. */
  10308. protected function canRfqNotifySalesman(array $po): bool
  10309. {
  10310. if (!$this->isRfqOrderIssued($po)) {
  10311. return false;
  10312. }
  10313. $sid = (int)($po['scydgy_id'] ?? 0);
  10314. if ($sid >= 0) {
  10315. return false;
  10316. }
  10317. $quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
  10318. return isset($quoted[$sid]);
  10319. }
  10320. protected function assertRfqCanNotifySalesman(array $po): void
  10321. {
  10322. if (!$this->isRfqOrderIssued($po)) {
  10323. $this->error('请先询价并等待供应商报价后再通知业务员');
  10324. }
  10325. if (!$this->canRfqNotifySalesman($po)) {
  10326. $this->error('供应商尚未报价,暂不能通知业务员');
  10327. }
  10328. }
  10329. /**
  10330. * 加载手工询价单(含可见性校验)
  10331. *
  10332. * @return array<string, mixed>
  10333. */
  10334. protected function loadManualRfqOrderForNotify(int $scydgyId): array
  10335. {
  10336. try {
  10337. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10338. } catch (\Throwable $e) {
  10339. $po = null;
  10340. }
  10341. if (!is_array($po)) {
  10342. $this->error('订单不存在');
  10343. }
  10344. $modRq = trim((string)($po['mod_rq'] ?? ''));
  10345. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  10346. $this->error('订单不存在');
  10347. }
  10348. if ($this->auth->isSuperAdmin()) {
  10349. return $po;
  10350. }
  10351. if ($this->canViewManualRfqOrder($po)) {
  10352. return $po;
  10353. }
  10354. $this->error('无权操作该订单');
  10355. }
  10356. /**
  10357. * @return string[]
  10358. */
  10359. protected function splitRfqSalesmanNames(string $raw): array
  10360. {
  10361. $parts = [];
  10362. $raw = trim($raw);
  10363. if ($raw === '') {
  10364. return [];
  10365. }
  10366. foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
  10367. $v = trim((string)$piece);
  10368. if ($v !== '' && !in_array($v, $parts, true)) {
  10369. $parts[] = $v;
  10370. }
  10371. }
  10372. return $parts;
  10373. }
  10374. /**
  10375. * 按姓名匹配 fa_admin 邮箱
  10376. *
  10377. * @param string[] $names
  10378. * @return array<int, array{admin_id:int,name:string,email:string}>
  10379. */
  10380. protected function resolveRfqSalesmanContactRows(array $names): array
  10381. {
  10382. $out = [];
  10383. foreach ($names as $name) {
  10384. $name = trim((string)$name);
  10385. if ($name === '') {
  10386. continue;
  10387. }
  10388. $adminId = 0;
  10389. $email = '';
  10390. try {
  10391. $row = Db::name('admin')
  10392. ->where(function ($q) use ($name) {
  10393. $q->where('nickname', $name)->whereOr('username', $name);
  10394. })
  10395. ->where('status', 'normal')
  10396. ->order('id', 'asc')
  10397. ->field('id,nickname,username,email')
  10398. ->find();
  10399. } catch (\Throwable $e) {
  10400. $row = null;
  10401. }
  10402. if (is_array($row)) {
  10403. $adminId = (int)($row['id'] ?? 0);
  10404. $email = trim((string)($row['email'] ?? ''));
  10405. $disp = trim((string)($row['nickname'] ?? ''));
  10406. if ($disp === '') {
  10407. $disp = trim((string)($row['username'] ?? ''));
  10408. }
  10409. if ($disp !== '') {
  10410. $name = $disp;
  10411. }
  10412. }
  10413. $out[] = [
  10414. 'admin_id' => $adminId,
  10415. 'name' => $name,
  10416. 'email' => $email,
  10417. ];
  10418. }
  10419. return $out;
  10420. }
  10421. /**
  10422. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  10423. */
  10424. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  10425. {
  10426. if ($scydgyId >= 0) {
  10427. return;
  10428. }
  10429. try {
  10430. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10431. } catch (\Throwable $e) {
  10432. $po = null;
  10433. }
  10434. if (!is_array($po)) {
  10435. $this->error('订单不存在');
  10436. }
  10437. $modRq = trim((string)($po['mod_rq'] ?? ''));
  10438. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  10439. $this->error('订单不存在');
  10440. }
  10441. if ($this->auth->isSuperAdmin()) {
  10442. return;
  10443. }
  10444. [, $adminName] = $this->GetUseName();
  10445. $cywy = trim((string)($po['cywyxm'] ?? ''));
  10446. if ($cywy !== '' && $cywy === $adminName) {
  10447. return;
  10448. }
  10449. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  10450. try {
  10451. if ($this->auth->check($rule)) {
  10452. return;
  10453. }
  10454. } catch (\Throwable $e) {
  10455. }
  10456. }
  10457. $this->error('无权查看该订单');
  10458. }
  10459. /**
  10460. * 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
  10461. */
  10462. protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
  10463. {
  10464. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  10465. return ProcuremenStatus::PO_COMPLETED;
  10466. }
  10467. $sid = (int)($row['scydgy_id'] ?? 0);
  10468. if ($sid < 0) {
  10469. if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
  10470. return '已通知业务员';
  10471. }
  10472. if ($hasQuoted) {
  10473. return '供应商已报价';
  10474. }
  10475. if ($hasIssued
  10476. || ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
  10477. || ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
  10478. return '待报价';
  10479. }
  10480. try {
  10481. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  10482. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  10483. if ((int)$detCntQuery->count() > 0) {
  10484. return '待报价';
  10485. }
  10486. } catch (\Throwable $e) {
  10487. }
  10488. return '待询价';
  10489. }
  10490. if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
  10491. return '待入库评分';
  10492. }
  10493. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  10494. return '待采购确认';
  10495. }
  10496. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  10497. return '待确认供应商';
  10498. }
  10499. return '待协助下发';
  10500. }
  10501. /**
  10502. * 协助初选列表 — 批量软删除
  10503. */
  10504. public function pickDelete()
  10505. {
  10506. if (!$this->request->isPost() || !$this->request->isAjax()) {
  10507. $this->error(__('Invalid parameters'));
  10508. }
  10509. if (!$this->procuremenCanPickDelete()) {
  10510. $this->error(__('You have no permission'));
  10511. }
  10512. $rowsRaw = $this->request->post('rows_json', '[]');
  10513. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  10514. if (!is_array($rows) || $rows === []) {
  10515. $this->error('请至少勾选一条工序');
  10516. }
  10517. $done = 0;
  10518. Db::startTrans();
  10519. try {
  10520. foreach ($rows as $row) {
  10521. if (!is_array($row)) {
  10522. continue;
  10523. }
  10524. $this->softDeleteProcuremenPickRow($row);
  10525. $done++;
  10526. }
  10527. if ($done < 1) {
  10528. throw new \Exception('没有可删除的工序');
  10529. }
  10530. Db::commit();
  10531. } catch (\InvalidArgumentException $e) {
  10532. Db::rollback();
  10533. $this->error($e->getMessage());
  10534. } catch (\Throwable $e) {
  10535. Db::rollback();
  10536. $this->error($e->getMessage());
  10537. }
  10538. $this->pickHiddenScydgySetCache = null;
  10539. $this->success('已删除 ' . $done . ' 条工序');
  10540. }
  10541. /**
  10542. * 下发 — 手工新增工序(弹窗)
  10543. */
  10544. public function pickAdd()
  10545. {
  10546. if ($this->request->isPost()) {
  10547. $params = $this->request->post('row/a');
  10548. if (!is_array($params)) {
  10549. $this->error(__('Parameter %s can not be empty', ''));
  10550. }
  10551. try {
  10552. $sid = $this->saveManualPickOrder($params);
  10553. } catch (\InvalidArgumentException $e) {
  10554. $this->error($e->getMessage());
  10555. } catch (\Throwable $e) {
  10556. $this->error($e->getMessage());
  10557. }
  10558. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  10559. }
  10560. return $this->view->fetch('procuremen/pick_add');
  10561. }
  10562. /**
  10563. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  10564. */
  10565. public function pickSubmit()
  10566. {
  10567. if (!$this->request->isPost()) {
  10568. $this->error(__('Invalid parameters'));
  10569. }
  10570. // ---------- 接口订单数据 ----------
  10571. $rowJson = $this->request->post('row_json', '');
  10572. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  10573. $companiesJson = $this->request->post('companies_json', '[]');
  10574. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  10575. $companies = json_decode($companiesJson, true);
  10576. if (!is_array($companies)) {
  10577. $this->error('供应商数据无效');
  10578. }
  10579. $issueCompanies = $this->normalizePickCompanies($companies);
  10580. if ($issueCompanies === []) {
  10581. $this->error('请至少选择一家合作供应商');
  10582. }
  10583. $issueNameLabels = [];
  10584. foreach ($issueCompanies as $pc) {
  10585. $issueNameLabels[] = $pc['name'];
  10586. }
  10587. $issueNamesSummary = implode('、', $issueNameLabels);
  10588. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  10589. if ($sysRq === '') {
  10590. $this->error('请选择招标截止日期');
  10591. }
  10592. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  10593. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  10594. (string)$this->request->post('delivery_deadline', ''),
  10595. true
  10596. );
  10597. $scoreRuleId = (int)$this->request->post('score_rule_id', 0);
  10598. if ($scoreRuleId <= 0) {
  10599. $this->error('请选择订单类型');
  10600. }
  10601. $scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
  10602. if ((int)($scoreRule['id'] ?? 0) <= 0) {
  10603. $this->error('订单类型无效,请刷新后重选');
  10604. }
  10605. $scoreRuleId = (int)$scoreRule['id'];
  10606. $this->ensurePurchaseOrderScoreRuleIdColumn();
  10607. $isMerge = count($mergeRows) > 1;
  10608. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  10609. $logMsg = '下发' . $procPart
  10610. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  10611. $issueTime = date('Y-m-d H:i:s');
  10612. $logSidList = [];
  10613. foreach ($mergeRows as $row) {
  10614. if (!is_array($row)) {
  10615. continue;
  10616. }
  10617. $sid = $this->extractScydgyRowId($row);
  10618. if ($this->isValidScydgyRowId($sid)) {
  10619. $logSidList[$sid] = true;
  10620. }
  10621. }
  10622. if ($logSidList === []) {
  10623. $this->error('未找到有效工序,无法下发');
  10624. }
  10625. // 防连点/并发:同一批工序加命名锁,已下发则直接拒绝(避免重复短信邮件)
  10626. $sidKeys = array_keys($logSidList);
  10627. sort($sidKeys, SORT_NUMERIC);
  10628. $pickLockName = 'procuremen_pick_submit_' . md5(implode(',', $sidKeys));
  10629. if (!$this->acquireProcuremenNamedLock($pickLockName, 15)) {
  10630. $this->error('下发处理中,请勿重复点击');
  10631. }
  10632. $existingBySid = [];
  10633. try {
  10634. try {
  10635. $existingRows = Db::table('purchase_order')
  10636. ->where('scydgy_id', 'in', $sidKeys)
  10637. ->select();
  10638. if (is_array($existingRows)) {
  10639. foreach ($existingRows as $poRow) {
  10640. if (!is_array($poRow)) {
  10641. continue;
  10642. }
  10643. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10644. if ($this->isValidScydgyRowId($sid)) {
  10645. $existingBySid[$sid] = $poRow;
  10646. }
  10647. }
  10648. }
  10649. } catch (\Throwable $e) {
  10650. $existingBySid = [];
  10651. }
  10652. foreach ($sidKeys as $sid) {
  10653. $poRow = $existingBySid[$sid] ?? null;
  10654. if (!is_array($poRow)) {
  10655. continue;
  10656. }
  10657. if ($this->isPurchaseOrderSoftDeleted($poRow['mod_rq'] ?? null)) {
  10658. continue;
  10659. }
  10660. $label = $this->formatProcuremenRowLabel(['CCYDH' => $poRow['CCYDH'] ?? '', 'CGYMC' => $poRow['CGYMC'] ?? '']);
  10661. if (ProcuremenStatus::isPoCompleted($poRow['status'] ?? '')) {
  10662. $this->error(($label !== '' ? $label : ('工序#' . $sid)) . '已完结,无法再次下发');
  10663. }
  10664. if (!ProcuremenStatus::isWflowPendingIssue($poRow['wflow_status'] ?? '')) {
  10665. $this->error(($label !== '' ? $label : ('工序#' . $sid)) . '已下发或进入后续流程,请勿重复提交');
  10666. }
  10667. }
  10668. Db::startTrans();
  10669. try {
  10670. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  10671. foreach ($mergeRows as $row) {
  10672. if (!is_array($row)) {
  10673. continue;
  10674. }
  10675. $sid = $this->extractScydgyRowId($row);
  10676. $this->upsertPurchaseOrderFromRow(
  10677. $row,
  10678. $sysRqDb,
  10679. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  10680. $issueTime,
  10681. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  10682. $deliveryDeadlineDb,
  10683. $scoreRule
  10684. );
  10685. }
  10686. foreach ($issueCompanies as $c) {
  10687. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10688. }
  10689. Db::commit();
  10690. } catch (\Throwable $e) {
  10691. Db::rollback();
  10692. $this->error($e->getMessage());
  10693. }
  10694. } finally {
  10695. $this->releaseProcuremenNamedLock($pickLockName);
  10696. }
  10697. $poIdBySid = [];
  10698. if ($logSidList !== []) {
  10699. try {
  10700. $poIdBySid = Db::table('purchase_order')
  10701. ->where('scydgy_id', 'in', array_keys($logSidList))
  10702. ->column('id', 'scydgy_id');
  10703. } catch (\Throwable $e) {
  10704. $poIdBySid = [];
  10705. }
  10706. }
  10707. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  10708. if ($logSidList !== []) {
  10709. list($adminId, $adminName) = $this->GetUseName();
  10710. $logRows = [];
  10711. $seenLogSid = [];
  10712. foreach ($mergeRows as $row) {
  10713. if (!is_array($row)) {
  10714. continue;
  10715. }
  10716. $ids = $this->extractScydgyRowId($row);
  10717. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  10718. continue;
  10719. }
  10720. $seenLogSid[$ids] = true;
  10721. $poIdLog = null;
  10722. if (isset($poIdBySid[$ids])) {
  10723. $tid = (int)$poIdBySid[$ids];
  10724. $poIdLog = $tid > 0 ? $tid : null;
  10725. }
  10726. $logRows[] = ProcuremenOperLog::buildInsertRow(
  10727. $ids,
  10728. 'issue_submit',
  10729. $logMsg,
  10730. $poIdLog,
  10731. (int)$adminId,
  10732. (string)$adminName
  10733. );
  10734. }
  10735. if ($logRows !== []) {
  10736. try {
  10737. Db::table('purchase_order_oper_log')->insertAll($logRows);
  10738. } catch (\Throwable $e) {
  10739. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  10740. }
  10741. }
  10742. }
  10743. $notifyErrors = [];
  10744. $posNotify = [];
  10745. if ($logSidList !== []) {
  10746. try {
  10747. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  10748. } catch (\Throwable $e) {
  10749. $posNotify = [];
  10750. }
  10751. }
  10752. if (!is_array($posNotify)) {
  10753. $posNotify = [];
  10754. }
  10755. foreach ($posNotify as $i => $prow) {
  10756. if (is_array($posNotify[$i])) {
  10757. $posNotify[$i]['sys_rq'] = $sysRqDb;
  10758. }
  10759. }
  10760. $ccydhPick = '';
  10761. foreach ($mergeRows as $row) {
  10762. if (!is_array($row)) {
  10763. continue;
  10764. }
  10765. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  10766. if ($ccydhPick !== '') {
  10767. break;
  10768. }
  10769. }
  10770. $notifyBundleBase = [
  10771. 'ccydh' => $ccydhPick,
  10772. 'pos' => $posNotify,
  10773. 'merge_rows' => $mergeRows,
  10774. 'score_rule' => is_array($scoreRule) ? $scoreRule : null,
  10775. ];
  10776. try {
  10777. $this->notifyDryRunPreview = [];
  10778. foreach ($issueCompanies as $c) {
  10779. if (!is_array($c)) {
  10780. continue;
  10781. }
  10782. $cname = trim((string)($c['name'] ?? ''));
  10783. if ($cname === '') {
  10784. continue;
  10785. }
  10786. try {
  10787. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  10788. } catch (\Throwable $e) {
  10789. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10790. }
  10791. }
  10792. } catch (\Throwable $e) {
  10793. $this->error('通知发送失败:' . $e->getMessage());
  10794. }
  10795. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10796. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  10797. }
  10798. if ($this->isProcuremenNotifyDryRun()) {
  10799. $this->success('【演练模式】已保存并生成通知预览', '', [
  10800. 'notify_dry_run' => true,
  10801. 'notify_preview' => $this->notifyDryRunPreview,
  10802. ]);
  10803. }
  10804. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  10805. }
  10806. /**
  10807. * 确认供应商弹窗
  10808. */
  10809. public function auditIssue()
  10810. {
  10811. $ids = $this->request->param('ids', $this->request->param('id', ''));
  10812. if (is_array($ids)) {
  10813. $ids = isset($ids[0]) ? $ids[0] : '';
  10814. }
  10815. $ids = trim((string)$ids);
  10816. if ($ids === '') {
  10817. $this->error(__('Invalid parameters'));
  10818. }
  10819. if ($this->request->isPost()) {
  10820. $this->error('请使用弹窗内「确认」提交');
  10821. }
  10822. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10823. $pos = $bundle['pos'];
  10824. if ($pos === []) {
  10825. $this->error('该订单不在待确认供应商状态');
  10826. }
  10827. $po = $pos[0];
  10828. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10829. if ($quoteGroups === []) {
  10830. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  10831. }
  10832. $pickedName = '';
  10833. foreach ($pos as $poRow) {
  10834. if (!is_array($poRow)) {
  10835. continue;
  10836. }
  10837. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  10838. if ($pn !== '') {
  10839. $pickedName = $pn;
  10840. break;
  10841. }
  10842. }
  10843. $this->view->assign('po', $po);
  10844. $this->view->assign('scydgyId', $ids);
  10845. $this->view->assign('orderCcydh', $bundle['ccydh']);
  10846. $mergeRows = $bundle['merge_rows'];
  10847. $this->view->assign('processRows', $mergeRows);
  10848. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  10849. $this->view->assign('processCount', count($mergeRows));
  10850. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  10851. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  10852. $this->view->assign('pickedCompanyName', $pickedName);
  10853. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10854. if ($sysRqForView === '') {
  10855. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10856. }
  10857. $this->view->assign('sysRq', $sysRqForView);
  10858. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  10859. if ($deliveryDeadlineForView === '') {
  10860. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10861. }
  10862. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10863. $this->ensurePurchaseOrderManualPickColumns();
  10864. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
  10865. $manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
  10866. $manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
  10867. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  10868. if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
  10869. $pickedName = $manualPickInfo['company'];
  10870. $this->view->assign('pickedCompanyName', $pickedName);
  10871. }
  10872. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  10873. $this->view->assign('manualPicked', $manualPicked);
  10874. $this->view->assign('manualPickReason', $manualPickInfo['reason']);
  10875. $this->view->assign('quoteVisible', $quoteVisible);
  10876. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
  10877. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  10878. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
  10879. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
  10880. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  10881. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  10882. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  10883. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  10884. return $this->view->fetch('procuremen/audit_issue');
  10885. }
  10886. /**
  10887. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  10888. *
  10889. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10890. */
  10891. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  10892. {
  10893. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10894. return false;
  10895. }
  10896. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10897. return false;
  10898. }
  10899. return true;
  10900. }
  10901. /**
  10902. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  10903. *
  10904. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10905. */
  10906. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  10907. {
  10908. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10909. return false;
  10910. }
  10911. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10912. return false;
  10913. }
  10914. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  10915. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  10916. return true;
  10917. }
  10918. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  10919. }
  10920. /**
  10921. * 确认页 — 补加供应商弹窗
  10922. */
  10923. public function auditAppend()
  10924. {
  10925. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  10926. $this->error(__('You have no permission'));
  10927. }
  10928. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  10929. if (is_array($ids)) {
  10930. $ids = isset($ids[0]) ? $ids[0] : '';
  10931. }
  10932. $ids = trim((string)$ids);
  10933. if ($ids === '') {
  10934. $this->error(__('Invalid parameters'));
  10935. }
  10936. if ($this->request->isPost()) {
  10937. $this->error('请使用弹窗内「确认」提交');
  10938. }
  10939. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10940. if (($bundle['pos'] ?? []) === []) {
  10941. $this->error('该订单不在待确认供应商状态');
  10942. }
  10943. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10944. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10945. $this->error('已开标验证,不能再补加供应商');
  10946. }
  10947. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10948. $this->error('已指定供应商,不能再补加供应商');
  10949. }
  10950. $this->error('已经超过了招标截止日期,不可操作');
  10951. }
  10952. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10953. $existingNames = [];
  10954. foreach ($quoteGroups as $g) {
  10955. if (!is_array($g)) {
  10956. continue;
  10957. }
  10958. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  10959. if ($n !== '') {
  10960. $existingNames[$n] = true;
  10961. }
  10962. }
  10963. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  10964. $mergeRows = $bundle['merge_rows'] ?? [];
  10965. $this->view->assign('scydgyId', $ids);
  10966. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  10967. $this->view->assign('po', $po);
  10968. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  10969. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  10970. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  10971. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10972. if ($sysRqForView === '') {
  10973. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10974. }
  10975. $this->view->assign('sysRq', $sysRqForView);
  10976. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  10977. if ($deliveryDeadlineForView === '') {
  10978. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10979. }
  10980. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10981. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  10982. }
  10983. /**
  10984. * 确认页 — 补加供应商提交
  10985. */
  10986. public function auditAppendSubmit()
  10987. {
  10988. if (!$this->request->isPost()) {
  10989. $this->error(__('Invalid parameters'));
  10990. }
  10991. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  10992. $this->error(__('You have no permission'));
  10993. }
  10994. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  10995. if ($ids === '') {
  10996. $this->error(__('Invalid parameters'));
  10997. }
  10998. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10999. if (($bundle['pos'] ?? []) === []) {
  11000. $this->error('该订单不在待确认供应商状态');
  11001. }
  11002. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  11003. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  11004. $this->error('已开标验证,不能再补加供应商');
  11005. }
  11006. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  11007. $this->error('已指定供应商,不能再补加供应商');
  11008. }
  11009. $this->error('已经超过了招标截止日期,不可操作');
  11010. }
  11011. $companiesJson = $this->request->post('companies_json', '[]');
  11012. $companies = json_decode((string)$companiesJson, true);
  11013. if (!is_array($companies)) {
  11014. $this->error('供应商数据无效');
  11015. }
  11016. $issueCompanies = $this->normalizePickCompanies($companies);
  11017. if ($issueCompanies === []) {
  11018. $this->error('请至少选择一家合作供应商');
  11019. }
  11020. $mergeRows = $bundle['merge_rows'] ?? [];
  11021. if (!is_array($mergeRows) || $mergeRows === []) {
  11022. $this->error('未找到工序行,无法补加');
  11023. }
  11024. $existingNames = [];
  11025. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  11026. if (!is_array($g)) {
  11027. continue;
  11028. }
  11029. $n = trim((string)($g['company_name'] ?? ''));
  11030. if ($n !== '') {
  11031. $existingNames[$n] = true;
  11032. }
  11033. }
  11034. $toAdd = [];
  11035. foreach ($issueCompanies as $c) {
  11036. if (!is_array($c)) {
  11037. continue;
  11038. }
  11039. $n = trim((string)($c['name'] ?? ''));
  11040. if ($n === '' || isset($existingNames[$n])) {
  11041. continue;
  11042. }
  11043. $toAdd[] = $c;
  11044. }
  11045. if ($toAdd === []) {
  11046. $this->error('所选供应商均已在本单中,请选择新的供应商');
  11047. }
  11048. $addedNames = [];
  11049. Db::startTrans();
  11050. try {
  11051. foreach ($toAdd as $c) {
  11052. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  11053. $addedNames[] = trim((string)($c['name'] ?? ''));
  11054. }
  11055. Db::commit();
  11056. } catch (\Throwable $e) {
  11057. Db::rollback();
  11058. $this->error($e->getMessage());
  11059. }
  11060. $notifyErrors = [];
  11061. $notifyBundleBase = [
  11062. 'ccydh' => $bundle['ccydh'] ?? '',
  11063. 'pos' => $bundle['pos'] ?? [],
  11064. 'merge_rows' => $mergeRows,
  11065. ];
  11066. foreach ($toAdd as $c) {
  11067. if (!is_array($c)) {
  11068. continue;
  11069. }
  11070. $cname = trim((string)($c['name'] ?? ''));
  11071. if ($cname === '') {
  11072. continue;
  11073. }
  11074. try {
  11075. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  11076. } catch (\Throwable $e) {
  11077. $notifyErrors[] = $cname . ':' . $e->getMessage();
  11078. }
  11079. }
  11080. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  11081. $seenLogSid = [];
  11082. foreach ($bundle['pos'] ?? [] as $poRow) {
  11083. if (!is_array($poRow)) {
  11084. continue;
  11085. }
  11086. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11087. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  11088. continue;
  11089. }
  11090. $seenLogSid[$sid] = true;
  11091. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11092. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11093. }
  11094. if ($seenLogSid === []) {
  11095. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  11096. if ($this->isValidScydgyRowId($logSid)) {
  11097. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  11098. }
  11099. }
  11100. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  11101. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  11102. }
  11103. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  11104. }
  11105. /**
  11106. * 开标双重验证 — 可选验证人列表
  11107. */
  11108. public function bidOpenUsers()
  11109. {
  11110. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  11111. $this->error('无权限');
  11112. }
  11113. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  11114. if ($scydgyId !== '') {
  11115. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11116. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  11117. $this->success('已完成开标验证', null, [
  11118. 'verified' => 1,
  11119. 'users' => [],
  11120. ]);
  11121. }
  11122. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  11123. $this->error('本单已指定供应商,无需再开标');
  11124. }
  11125. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  11126. }
  11127. $this->success('', null, [
  11128. 'verified' => 0,
  11129. 'users' => $this->listBidOpenVerifierCandidates(),
  11130. ]);
  11131. }
  11132. /**
  11133. * 开标双重验证 — 向指定管理员发送短信验证码
  11134. */
  11135. public function bidOpenSendCode()
  11136. {
  11137. if (!$this->request->isPost()) {
  11138. $this->error(__('Invalid parameters'));
  11139. }
  11140. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  11141. $this->error('无权限');
  11142. }
  11143. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11144. $adminId = (int)$this->request->post('admin_id', 0);
  11145. if ($scydgyId === '' || $adminId <= 0) {
  11146. $this->error('参数无效');
  11147. }
  11148. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11149. if ($bundle['pos'] === []) {
  11150. $this->error('该订单不在待确认供应商状态');
  11151. }
  11152. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  11153. $this->success('已完成开标验证,无需重复发送');
  11154. }
  11155. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  11156. $this->error('本单已指定供应商,无需再开标');
  11157. }
  11158. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  11159. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11160. if ($ccydh === '') {
  11161. $this->error('订单号无效');
  11162. }
  11163. $admin = $this->loadBidOpenAdminUser($adminId);
  11164. if ($admin === null) {
  11165. $this->error('验证人无效或未绑定手机号');
  11166. }
  11167. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  11168. $cd = max(30, min(120, $cd));
  11169. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  11170. $this->error('发送过于频繁,请稍后再试');
  11171. }
  11172. $code = (string)random_int(100000, 999999);
  11173. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  11174. $ttl = max(60, min(600, $ttl));
  11175. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  11176. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  11177. try {
  11178. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  11179. } catch (\Throwable $e) {
  11180. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  11181. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  11182. $this->error($e->getMessage());
  11183. }
  11184. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  11185. }
  11186. /**
  11187. * 开标双重验证 — 两人验证码校验并记录
  11188. */
  11189. public function bidOpenVerify()
  11190. {
  11191. if (!$this->request->isPost()) {
  11192. $this->error(__('Invalid parameters'));
  11193. }
  11194. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  11195. $this->error('无权限');
  11196. }
  11197. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11198. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  11199. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  11200. $code1 = trim((string)$this->request->post('code1', ''));
  11201. $code2 = trim((string)$this->request->post('code2', ''));
  11202. if ($scydgyId === '') {
  11203. $this->error('参数无效');
  11204. }
  11205. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  11206. $this->error('请选择两位验证人');
  11207. }
  11208. if ($verifier1Id === $verifier2Id) {
  11209. $this->error('两位验证人不能相同');
  11210. }
  11211. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  11212. $this->error('请输入6位短信验证码');
  11213. }
  11214. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11215. if ($bundle['pos'] === []) {
  11216. $this->error('该订单不在待确认供应商状态');
  11217. }
  11218. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11219. if ($ccydh === '') {
  11220. $this->error('订单号无效');
  11221. }
  11222. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  11223. $this->success('已完成开标验证');
  11224. }
  11225. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  11226. $this->error('本单已指定供应商,无需再开标');
  11227. }
  11228. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  11229. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  11230. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  11231. if ($verifier1 === null || $verifier2 === null) {
  11232. $this->error('验证人无效或未绑定手机号');
  11233. }
  11234. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  11235. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  11236. }
  11237. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  11238. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  11239. }
  11240. try {
  11241. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  11242. } catch (\Throwable $e) {
  11243. $this->error($e->getMessage());
  11244. }
  11245. $this->success('开标验证成功,可查看供应商报价与交货日期');
  11246. }
  11247. /**
  11248. * 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
  11249. */
  11250. public function auditManualPick()
  11251. {
  11252. if (!$this->request->isPost()) {
  11253. $this->error(__('Invalid parameters'));
  11254. }
  11255. if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
  11256. $this->error('无权限');
  11257. }
  11258. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11259. if ($scydgyId === '') {
  11260. $this->error('参数无效');
  11261. }
  11262. $companyName = trim((string)$this->request->post('selected_company', ''));
  11263. $reason = trim((string)$this->request->post('pick_reason', ''));
  11264. if ($companyName === '') {
  11265. $this->error('请选择一家供应商');
  11266. }
  11267. if ($reason === '') {
  11268. $this->error('请填写选择说明');
  11269. }
  11270. if (mb_strlen($reason) > 500) {
  11271. $this->error('选择说明不能超过500字');
  11272. }
  11273. $this->ensurePurchaseOrderManualPickColumns();
  11274. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11275. $pos = $bundle['pos'];
  11276. if ($pos === []) {
  11277. $this->error('该订单不在待确认供应商状态');
  11278. }
  11279. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  11280. $this->error('本单已开标验证,请直接在列表中选定供应商后确认');
  11281. }
  11282. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11283. if ($quoteGroups === []) {
  11284. $this->error('暂无供应商,请确认已完成协助初选通知');
  11285. }
  11286. $matched = null;
  11287. foreach ($quoteGroups as $g) {
  11288. if (!is_array($g)) {
  11289. continue;
  11290. }
  11291. if (trim((string)($g['name'] ?? '')) === $companyName) {
  11292. $matched = $g;
  11293. break;
  11294. }
  11295. }
  11296. if ($matched === null) {
  11297. $this->error('所选供应商不在本单报价列表中');
  11298. }
  11299. $logMsg = '指定供应商:已选定「' . $companyName . '」;说明:' . $reason;
  11300. Db::startTrans();
  11301. try {
  11302. foreach ($pos as $poRow) {
  11303. if (!is_array($poRow)) {
  11304. continue;
  11305. }
  11306. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11307. if (!$this->isValidScydgyRowId($sid)) {
  11308. continue;
  11309. }
  11310. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11311. 'pick_company_name' => $companyName,
  11312. 'manual_pick' => 1,
  11313. 'manual_pick_reason' => $reason,
  11314. ]);
  11315. }
  11316. Db::commit();
  11317. } catch (\Throwable $e) {
  11318. Db::rollback();
  11319. $this->error($e->getMessage());
  11320. }
  11321. foreach ($pos as $poRow) {
  11322. if (!is_array($poRow)) {
  11323. continue;
  11324. }
  11325. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11326. if (!$this->isValidScydgyRowId($sid)) {
  11327. continue;
  11328. }
  11329. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11330. $this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11331. }
  11332. // 自选后可见报价:按本单规则计算评分(与开标后一致)
  11333. try {
  11334. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11335. if ($ccydh !== '') {
  11336. // 重新加载以拿到未掩码报价参与计分
  11337. $bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11338. $groupsFresh = $this->loadAuditSupplierQuoteGroups($bundleFresh);
  11339. ProcuremenSupplierScore::saveForOrder($ccydh, $groupsFresh, date('Y-m'));
  11340. }
  11341. } catch (\Throwable $e) {
  11342. Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
  11343. }
  11344. $this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
  11345. }
  11346. /**
  11347. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  11348. */
  11349. public function auditSubmit()
  11350. {
  11351. if (!$this->request->isPost()) {
  11352. $this->error(__('Invalid parameters'));
  11353. }
  11354. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11355. if ($scydgyId === '') {
  11356. $this->error('参数无效');
  11357. }
  11358. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11359. $pos = $bundle['pos'];
  11360. $mergeRows = $bundle['merge_rows'];
  11361. if ($pos === [] || $mergeRows === []) {
  11362. $this->error('该订单不在待确认供应商状态');
  11363. }
  11364. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11365. if ($quoteGroups === []) {
  11366. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  11367. }
  11368. $companyName = trim((string)$this->request->post('selected_company', ''));
  11369. if ($companyName === '') {
  11370. $this->error('请选择一家供应商');
  11371. }
  11372. $matched = null;
  11373. foreach ($quoteGroups as $g) {
  11374. if (!is_array($g)) {
  11375. continue;
  11376. }
  11377. if (trim((string)($g['name'] ?? '')) === $companyName) {
  11378. $matched = $g;
  11379. break;
  11380. }
  11381. }
  11382. if ($matched === null) {
  11383. $this->error('所选供应商不在本单报价列表中');
  11384. }
  11385. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  11386. if ($sysRqDb === '') {
  11387. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  11388. } else {
  11389. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  11390. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  11391. }
  11392. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  11393. $this->error('未到招标截止日期,暂不可确认');
  11394. }
  11395. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
  11396. && !$this->isProcuremenManualPickedForBundle($bundle)
  11397. ) {
  11398. $this->error('请先完成开标双重验证或指定供应商后再确认');
  11399. }
  11400. $procCnt = count($mergeRows);
  11401. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  11402. $logMsg = '确认供应商' . $procPart . ':已选定「' . $companyName . '」';
  11403. Db::startTrans();
  11404. try {
  11405. foreach ($pos as $poRow) {
  11406. if (!is_array($poRow)) {
  11407. continue;
  11408. }
  11409. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11410. if (!$this->isValidScydgyRowId($sid)) {
  11411. continue;
  11412. }
  11413. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11414. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  11415. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11416. 'pick_company_name' => $companyName,
  11417. 'sys_rq' => $sysRqDb,
  11418. ]);
  11419. }
  11420. Db::commit();
  11421. } catch (\Throwable $e) {
  11422. Db::rollback();
  11423. $this->error($e->getMessage());
  11424. }
  11425. foreach ($pos as $poRow) {
  11426. if (!is_array($poRow)) {
  11427. continue;
  11428. }
  11429. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11430. if (!$this->isValidScydgyRowId($sid)) {
  11431. continue;
  11432. }
  11433. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11434. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11435. }
  11436. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  11437. }
  11438. /**
  11439. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  11440. */
  11441. public function auditResendSms()
  11442. {
  11443. if (!$this->request->isPost()) {
  11444. $this->error(__('Invalid parameters'));
  11445. }
  11446. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11447. if ($scydgyId === '') {
  11448. $this->error('参数无效');
  11449. }
  11450. $loaded = $this->loadAuditResendBundle($scydgyId);
  11451. $mergeRows = $loaded['merge_rows'];
  11452. $bundle = $loaded['bundle'];
  11453. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  11454. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11455. if ($quoteGroups === []) {
  11456. $this->error('暂无可通知的供应商');
  11457. }
  11458. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  11459. $companiesJson = (string)$this->request->post('companies_json', '');
  11460. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  11461. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  11462. }
  11463. /**
  11464. * 确认供应商 — 二次发送邮件(可选单家/批量)
  11465. */
  11466. public function auditResendEmail()
  11467. {
  11468. if (!$this->request->isPost()) {
  11469. $this->error(__('Invalid parameters'));
  11470. }
  11471. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11472. if ($scydgyId === '') {
  11473. $this->error('参数无效');
  11474. }
  11475. $loaded = $this->loadAuditResendBundle($scydgyId);
  11476. $mergeRows = $loaded['merge_rows'];
  11477. $bundle = $loaded['bundle'];
  11478. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  11479. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11480. if ($quoteGroups === []) {
  11481. $this->error('暂无可通知的供应商');
  11482. }
  11483. $companiesJson = (string)$this->request->post('companies_json', '');
  11484. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  11485. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  11486. if ($companiesJson === '' && $selectedCompany === '') {
  11487. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  11488. }
  11489. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  11490. }
  11491. /**
  11492. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  11493. *
  11494. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  11495. * @return array<int, true> 已处理的 scydgy_id 集合
  11496. */
  11497. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  11498. {
  11499. $pos = $bundle['pos'] ?? [];
  11500. if (!is_array($pos) || $pos === []) {
  11501. return [];
  11502. }
  11503. $sids = [];
  11504. $poIdBySid = [];
  11505. foreach ($pos as $poRow) {
  11506. if (!is_array($poRow)) {
  11507. continue;
  11508. }
  11509. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11510. if ($this->isValidScydgyRowId($sid)) {
  11511. $sids[$sid] = true;
  11512. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11513. if ($poId > 0) {
  11514. $poIdBySid[$sid] = $poId;
  11515. }
  11516. }
  11517. }
  11518. if ($sids === []) {
  11519. return [];
  11520. }
  11521. $logMsg = '重新下发';
  11522. $suffix = trim((string)$logSuffix, ',, ');
  11523. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  11524. $logMsg .= ':从历史存证退回协助初选';
  11525. } else {
  11526. $logMsg .= ':退回协助初选';
  11527. }
  11528. Db::table('purchase_order')
  11529. ->where('scydgy_id', 'in', array_keys($sids))
  11530. ->update([
  11531. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  11532. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11533. 'pick_company_name' => '',
  11534. 'pick_time' => null,
  11535. 'sys_rq' => null,
  11536. 'mod_rq' => null,
  11537. ]);
  11538. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  11539. foreach (array_keys($sids) as $sid) {
  11540. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  11541. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11542. }
  11543. return $sids;
  11544. }
  11545. /**
  11546. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  11547. *
  11548. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  11549. */
  11550. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  11551. {
  11552. $scydgyId = trim($scydgyId);
  11553. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11554. if ($scydgyId === '') {
  11555. return $empty;
  11556. }
  11557. try {
  11558. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  11559. } catch (\Throwable $e) {
  11560. $anchor = null;
  11561. }
  11562. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  11563. return $empty;
  11564. }
  11565. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  11566. if ($ccydh === '') {
  11567. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  11568. }
  11569. try {
  11570. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  11571. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  11572. $pos = $query->order('scydgy_id', 'asc')->select();
  11573. } catch (\Throwable $e) {
  11574. $pos = [$anchor];
  11575. }
  11576. if (!is_array($pos) || $pos === []) {
  11577. $pos = [$anchor];
  11578. }
  11579. return [
  11580. 'ccydh' => $ccydh,
  11581. 'pos' => $pos,
  11582. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  11583. ];
  11584. }
  11585. protected function purchaseOrderRowIsCompleted(array $po): bool
  11586. {
  11587. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11588. }
  11589. /**
  11590. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  11591. *
  11592. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  11593. */
  11594. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  11595. {
  11596. $scydgyId = trim($scydgyId);
  11597. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11598. if ($scydgyId === '') {
  11599. return $empty;
  11600. }
  11601. try {
  11602. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  11603. } catch (\Throwable $e) {
  11604. $anchor = null;
  11605. }
  11606. if (!is_array($anchor)) {
  11607. return $empty;
  11608. }
  11609. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  11610. if ($ccydh === '') {
  11611. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  11612. }
  11613. try {
  11614. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  11615. } catch (\Throwable $e) {
  11616. $pos = [$anchor];
  11617. }
  11618. if (!is_array($pos) || $pos === []) {
  11619. $pos = [$anchor];
  11620. }
  11621. $pos = $this->filterPurchaseOrdersSameIssueBatch($pos, $anchor);
  11622. return [
  11623. 'ccydh' => $ccydh,
  11624. 'pos' => $pos,
  11625. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  11626. ];
  11627. }
  11628. /**
  11629. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  11630. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  11631. */
  11632. public function auditAbandon()
  11633. {
  11634. if (!$this->request->isPost()) {
  11635. $this->error(__('Invalid parameters'));
  11636. }
  11637. $anchorIds = [];
  11638. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  11639. if ($batchRaw !== '') {
  11640. $decoded = json_decode($batchRaw, true);
  11641. if (is_array($decoded)) {
  11642. foreach ($decoded as $id) {
  11643. $s = trim((string)$id);
  11644. if ($s !== '') {
  11645. $anchorIds[] = $s;
  11646. }
  11647. }
  11648. }
  11649. }
  11650. if ($anchorIds === []) {
  11651. $single = trim((string)$this->request->post('scydgy_id', ''));
  11652. if ($single !== '') {
  11653. $anchorIds[] = $single;
  11654. }
  11655. }
  11656. if ($anchorIds === []) {
  11657. $this->error('请至少选择一条订单');
  11658. }
  11659. $processedCcydh = [];
  11660. $doneOrders = 0;
  11661. $allSids = [];
  11662. Db::startTrans();
  11663. try {
  11664. foreach ($anchorIds as $anchorId) {
  11665. $fromArchive = false;
  11666. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  11667. if (($bundle['pos'] ?? []) === []) {
  11668. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  11669. $fromArchive = ($bundle['pos'] ?? []) !== [];
  11670. }
  11671. if (($bundle['pos'] ?? []) === []) {
  11672. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  11673. $fromArchive = ($bundle['pos'] ?? []) !== [];
  11674. }
  11675. if (($bundle['pos'] ?? []) === []) {
  11676. continue;
  11677. }
  11678. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11679. $batchTime = '';
  11680. if (!empty($bundle['pos'][0]) && is_array($bundle['pos'][0])) {
  11681. $batchTime = $this->procuremenIssueBatchTime($bundle['pos'][0]);
  11682. }
  11683. $dedupeKey = $ccydh !== '' ? ($ccydh . '|' . $batchTime) : ('sid:' . $anchorId);
  11684. if (isset($processedCcydh[$dedupeKey])) {
  11685. continue;
  11686. }
  11687. $processedCcydh[$dedupeKey] = true;
  11688. $sids = $fromArchive
  11689. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回协助初选')
  11690. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  11691. if ($sids === []) {
  11692. continue;
  11693. }
  11694. $doneOrders++;
  11695. foreach (array_keys($sids) as $sid) {
  11696. $allSids[(int)$sid] = true;
  11697. }
  11698. }
  11699. if ($doneOrders < 1) {
  11700. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  11701. }
  11702. Db::commit();
  11703. } catch (\Throwable $e) {
  11704. Db::rollback();
  11705. $this->error($e->getMessage());
  11706. }
  11707. $this->pickHiddenScydgySetCache = null;
  11708. $msg = $doneOrders > 1
  11709. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  11710. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  11711. $this->success($msg);
  11712. }
  11713. /**
  11714. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  11715. */
  11716. public function archiveAbandon()
  11717. {
  11718. return $this->auditAbandon();
  11719. }
  11720. /**
  11721. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  11722. */
  11723. public function purchaseApprovalReject()
  11724. {
  11725. if (!$this->request->isPost() || !$this->request->isAjax()) {
  11726. $this->error(__('Invalid parameters'));
  11727. }
  11728. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  11729. $this->error(__('You have no permission'));
  11730. }
  11731. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  11732. $decoded = json_decode($batchRaw, true);
  11733. if (!is_array($decoded) || $decoded === []) {
  11734. $this->error('提交数据无效');
  11735. }
  11736. $done = 0;
  11737. Db::startTrans();
  11738. try {
  11739. foreach ($decoded as $item) {
  11740. if (!is_array($item)) {
  11741. continue;
  11742. }
  11743. $sid = (int)($item['scydgy_id'] ?? 0);
  11744. if (!$this->isValidScydgyRowId($sid)) {
  11745. continue;
  11746. }
  11747. $this->runPurchaseApprovalRejectForSid($sid);
  11748. $done++;
  11749. }
  11750. if ($done < 1) {
  11751. throw new \Exception('所选订单均不在待审批状态');
  11752. }
  11753. Db::commit();
  11754. } catch (\Throwable $e) {
  11755. Db::rollback();
  11756. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  11757. }
  11758. $this->pickHiddenScydgySetCache = null;
  11759. $this->success('已驳回并退回「协助审批下发」');
  11760. }
  11761. /**
  11762. * @throws \Exception
  11763. */
  11764. protected function runPurchaseApprovalRejectForSid(int $sid): void
  11765. {
  11766. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  11767. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  11768. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  11769. $allIds = $this->purchaseOrderDetail($sid);
  11770. if ($allIds === []) {
  11771. throw new \Exception('未找到下发明细');
  11772. }
  11773. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11774. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  11775. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11776. 'pick_company_name' => '',
  11777. ]);
  11778. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  11779. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  11780. $poId = 0;
  11781. try {
  11782. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  11783. if (is_array($po)) {
  11784. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11785. }
  11786. } catch (\Throwable $e) {
  11787. }
  11788. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  11789. }
  11790. /**
  11791. * 审核弹窗(旧入口,POST 已关闭)
  11792. */
  11793. public function review()
  11794. {
  11795. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  11796. $this->error(__('You have no permission'));
  11797. }
  11798. if ($this->request->isPost()) {
  11799. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  11800. }
  11801. $this->view->assign('pickMode', 0);
  11802. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  11803. }
  11804. /**
  11805. * 审核弹窗获取公司列表
  11806. */
  11807. public function reviewCompanies()
  11808. {
  11809. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  11810. $this->error(__('You have no permission'));
  11811. }
  11812. if (!$this->request->isAjax()) {
  11813. $this->error(__('Invalid parameters'));
  11814. }
  11815. $list = [];
  11816. try {
  11817. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  11818. $rows = Db::table('customer')
  11819. ->where(function ($q) {
  11820. $q->where('status', 1)
  11821. ->whereOr('status', '1')
  11822. ->whereOr('status', '')
  11823. ->whereNull('status');
  11824. })
  11825. ->order('id', 'desc')
  11826. ->select();
  11827. } catch (\Throwable $e) {
  11828. $this->success('', '', []);
  11829. return;
  11830. }
  11831. if (!is_array($rows)) {
  11832. $this->success('', '', []);
  11833. return;
  11834. }
  11835. $detailColCandidates = [
  11836. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  11837. 'company_detail', 'company_desc', 'address',
  11838. ];
  11839. foreach ($rows as $row) {
  11840. if (!is_array($row)) {
  11841. continue;
  11842. }
  11843. $norm = [];
  11844. foreach ($row as $k => $v) {
  11845. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  11846. }
  11847. $row = $norm;
  11848. $st = $row['status'] ?? '';
  11849. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  11850. continue;
  11851. }
  11852. $payload = $this->buildCustomerContactPayloadFromRow($row);
  11853. if ($payload === null) {
  11854. continue;
  11855. }
  11856. $detail = '';
  11857. foreach ($detailColCandidates as $dk) {
  11858. if (!isset($row[$dk])) {
  11859. continue;
  11860. }
  11861. $dv = trim((string)$row[$dk]);
  11862. if ($dv !== '') {
  11863. $detail = $dv;
  11864. break;
  11865. }
  11866. }
  11867. $payload['detail'] = $detail;
  11868. $list[] = $this->maskSupplierContactFields($payload);
  11869. }
  11870. $this->success('', '', $list);
  11871. }
  11872. /**
  11873. * 采购确认-下发明细弹窗:
  11874. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  11875. */
  11876. public function outward_detail()
  11877. {
  11878. $ids = $this->request->param('ids', $this->request->param('id', ''));
  11879. if (is_array($ids)) {
  11880. $ids = isset($ids[0]) ? $ids[0] : '';
  11881. }
  11882. $ids = trim((string)$ids);
  11883. if ($ids === '') {
  11884. $this->error(__('Invalid parameters'));
  11885. }
  11886. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  11887. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  11888. $wffTab = 'all';
  11889. }
  11890. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  11891. $purchaseOrderId = 0;
  11892. $po = null;
  11893. try {
  11894. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  11895. if (is_array($po)) {
  11896. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11897. }
  11898. } catch (\Throwable $e) {
  11899. $purchaseOrderId = 0;
  11900. $po = null;
  11901. }
  11902. if (!$isPurchaseConfirm && is_array($po)) {
  11903. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11904. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  11905. $isPurchaseConfirm = true;
  11906. }
  11907. }
  11908. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  11909. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11910. $confirmProcessCount = 1;
  11911. $confirmPickGroups = [];
  11912. $processDisplayRows = [];
  11913. $allDetailsBySid = [];
  11914. $requiredSidList = [];
  11915. $sidList = [$ids];
  11916. if ($isPurchaseConfirm) {
  11917. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  11918. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  11919. if ($mergeRows !== []) {
  11920. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  11921. }
  11922. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  11923. if ($confirmBundle['pos'] !== []) {
  11924. $sidList = [];
  11925. foreach ($confirmBundle['pos'] as $poRow) {
  11926. if (!is_array($poRow)) {
  11927. continue;
  11928. }
  11929. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11930. if (!$this->isValidScydgyRowId($sid)) {
  11931. continue;
  11932. }
  11933. $sidList[] = (string)$sid;
  11934. $requiredSidList[] = $sid;
  11935. }
  11936. }
  11937. if ($sidList === []) {
  11938. $sidList = [$ids];
  11939. $requiredSidList = [(int)$ids];
  11940. }
  11941. $confirmProcessCount = max(1, count($requiredSidList));
  11942. if (is_array($po) && $purchaseOrderId <= 0) {
  11943. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11944. }
  11945. }
  11946. $rows = [];
  11947. try {
  11948. if (count($sidList) === 1) {
  11949. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  11950. } else {
  11951. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  11952. }
  11953. } catch (\Throwable $e) {
  11954. $rows = [];
  11955. }
  11956. if ($isPurchaseConfirm) {
  11957. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  11958. }
  11959. foreach ($rows as &$r) {
  11960. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  11961. $r['id'] = $r['ID'];
  11962. }
  11963. if (isset($r['createtime'])) {
  11964. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  11965. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  11966. } else {
  11967. $r['createtime_text'] = (string)$r['createtime'];
  11968. }
  11969. } else {
  11970. $r['createtime_text'] = '';
  11971. }
  11972. if (is_array($r)) {
  11973. $r = $this->maskSupplierContactFields($r);
  11974. }
  11975. }
  11976. unset($r);
  11977. $pickedCompanyName = '';
  11978. $manualPicked = 0;
  11979. $manualPickReason = '';
  11980. $quoteVisible = 0;
  11981. $bidOpenVerified = 0;
  11982. if ($isPurchaseConfirm) {
  11983. // 确认包为空时,用当前主单兜底,避免指定说明读不到
  11984. if (($confirmBundle['ccydh'] ?? '') === '' && is_array($po)) {
  11985. $confirmBundle['ccydh'] = trim((string)($po['CCYDH'] ?? ''));
  11986. }
  11987. if (($confirmBundle['pos'] ?? []) === [] && is_array($po)) {
  11988. $confirmBundle['pos'] = [$po];
  11989. }
  11990. $manualPickInfo = $this->resolveProcuremenManualPickInfo($confirmBundle);
  11991. $manualPicked = $this->isProcuremenManualPickedForBundle($confirmBundle) ? 1 : 0;
  11992. $manualPickReason = (string)($manualPickInfo['reason'] ?? '');
  11993. if ($manualPickInfo['company'] !== '') {
  11994. $pickedCompanyName = $manualPickInfo['company'];
  11995. }
  11996. if ($pickedCompanyName === '') {
  11997. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  11998. if (!is_array($poRow)) {
  11999. continue;
  12000. }
  12001. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  12002. if ($pn !== '') {
  12003. $pickedCompanyName = $pn;
  12004. break;
  12005. }
  12006. }
  12007. }
  12008. // 再兜底:直接读当前主单字段
  12009. if (is_array($po) && (int)($po['manual_pick'] ?? 0) === 1) {
  12010. $manualPicked = 1;
  12011. if ($manualPickReason === '') {
  12012. $manualPickReason = trim((string)($po['manual_pick_reason'] ?? ''));
  12013. }
  12014. if ($pickedCompanyName === '') {
  12015. $pickedCompanyName = trim((string)($po['pick_company_name'] ?? ''));
  12016. }
  12017. }
  12018. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle) ? 1 : 0;
  12019. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  12020. }
  12021. $this->view->assign('rows', $rows ?: []);
  12022. $this->view->assign('rowCount', count($rows ?: []));
  12023. $this->view->assign('scydgyId', $ids);
  12024. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  12025. $this->view->assign('headTitle', $headTitle);
  12026. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  12027. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  12028. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  12029. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  12030. $this->view->assign('processDisplayRows', $processDisplayRows);
  12031. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  12032. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  12033. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  12034. $this->view->assign('manualPicked', $manualPicked);
  12035. $this->view->assign('manualPickReason', $manualPickReason);
  12036. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  12037. $this->view->assign('quoteVisible', $quoteVisible);
  12038. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
  12039. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  12040. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
  12041. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
  12042. $sysRqDisplay = '—';
  12043. if ($isPurchaseConfirm) {
  12044. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  12045. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  12046. );
  12047. }
  12048. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  12049. $this->view->assign('sysRq', $isPurchaseConfirm
  12050. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  12051. : '');
  12052. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  12053. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  12054. : '');
  12055. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  12056. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  12057. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  12058. if ($isPurchaseConfirm) {
  12059. return $this->view->fetch();
  12060. }
  12061. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  12062. $this->view->engine->layout(false);
  12063. try {
  12064. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  12065. $this->view->assign('dialogBody', $bodyHtml);
  12066. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  12067. } finally {
  12068. if ($restoreLayout) {
  12069. $this->view->engine->layout($restoreLayout);
  12070. }
  12071. }
  12072. }
  12073. /**
  12074. * 月度导出记录表(不存在时自动创建)
  12075. */
  12076. protected function ensurePurchaseMonthExportLogTable(): void
  12077. {
  12078. try {
  12079. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  12080. } catch (\Throwable $e) {
  12081. Db::execute(
  12082. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  12083. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  12084. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  12085. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  12086. `admin_name` varchar(64) NOT NULL DEFAULT '',
  12087. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  12088. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  12089. `createtime` int(10) unsigned DEFAULT NULL,
  12090. PRIMARY KEY (`id`),
  12091. KEY `idx_ym` (`ym`),
  12092. KEY `idx_ct` (`createtime`)
  12093. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  12094. );
  12095. }
  12096. }
  12097. /**
  12098. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  12099. *
  12100. * @param array<int, mixed> $dbRows
  12101. * @return array<int, array<string, mixed>>
  12102. */
  12103. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  12104. {
  12105. $keyword = trim((string)$this->request->get('search', ''));
  12106. if ($keyword === '') {
  12107. $keyword = trim((string)$this->request->request('search', ''));
  12108. }
  12109. $filter = $this->request->get('filter', '');
  12110. $op = $this->request->get('op', '');
  12111. if (is_string($filter) && $filter !== '') {
  12112. $filterArr = (array)json_decode($filter, true);
  12113. } else {
  12114. $filterArr = is_array($filter) ? $filter : [];
  12115. }
  12116. if (is_string($op) && $op !== '') {
  12117. $opArr = (array)json_decode($op, true);
  12118. } else {
  12119. $opArr = is_array($op) ? $op : [];
  12120. }
  12121. if ($keyword === '' && $filterArr === []) {
  12122. return array_values(array_filter($dbRows, 'is_array'));
  12123. }
  12124. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  12125. $out = [];
  12126. foreach ($dbRows as $row) {
  12127. if (!is_array($row)) {
  12128. continue;
  12129. }
  12130. if ($keyword !== '') {
  12131. $hit = false;
  12132. foreach ($searchFields as $f) {
  12133. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  12134. $hit = true;
  12135. break;
  12136. }
  12137. }
  12138. if (!$hit) {
  12139. continue;
  12140. }
  12141. }
  12142. $passFilter = true;
  12143. foreach ($filterArr as $field => $val) {
  12144. $field = (string)$field;
  12145. $val = trim((string)$val);
  12146. if ($field === '' || $val === '') {
  12147. continue;
  12148. }
  12149. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  12150. continue;
  12151. }
  12152. $cell = (string)($row[$field] ?? '');
  12153. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  12154. if ($mode === '=' || $mode === 'EQUAL') {
  12155. if (strcasecmp($cell, $val) !== 0) {
  12156. $passFilter = false;
  12157. break;
  12158. }
  12159. } elseif (mb_stripos($cell, $val) === false) {
  12160. $passFilter = false;
  12161. break;
  12162. }
  12163. }
  12164. if (!$passFilter) {
  12165. continue;
  12166. }
  12167. $out[] = $row;
  12168. }
  12169. return $out;
  12170. }
  12171. /**
  12172. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  12173. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  12174. */
  12175. public function export_month_outward()
  12176. {
  12177. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  12178. $this->error(__('You have no permission'));
  12179. }
  12180. $bundle = $this->prepareMonthOutwardExportBundle();
  12181. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  12182. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  12183. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  12184. $spreadsheet = new Spreadsheet();
  12185. $sheet = $spreadsheet->getActiveSheet();
  12186. $sheet->setTitle('外协加工明细');
  12187. $mon = (int)substr($ym, 5, 2);
  12188. $sheet->mergeCells('A1:H1');
  12189. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  12190. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  12191. $sheet->getStyle('A1')->getAlignment()
  12192. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12193. ->setVertical(Alignment::VERTICAL_CENTER);
  12194. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  12195. $col = 'A';
  12196. foreach ($headers as $h) {
  12197. $sheet->setCellValue($col . '2', $h);
  12198. $col++;
  12199. }
  12200. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  12201. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12202. $rowNum = 3;
  12203. $sumSubtotalCounts = 0;
  12204. $grandAmount = 0.0;
  12205. $globalSeq = 0;
  12206. if ($groups === []) {
  12207. $sheet->mergeCells('A3:H3');
  12208. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  12209. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12210. $rowNum = 4;
  12211. } else {
  12212. foreach ($groups as $items) {
  12213. if ($items === []) {
  12214. continue;
  12215. }
  12216. $groupLineCount = count($items);
  12217. $subAmount = 0.0;
  12218. foreach ($items as $line) {
  12219. $globalSeq++;
  12220. $dr = $line['detail'];
  12221. $amt = $this->procuremenExportAmount($dr);
  12222. $subAmount += $amt;
  12223. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  12224. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  12225. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  12226. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  12227. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  12228. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  12229. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  12230. $sheet->setCellValue('H' . $rowNum, $amt);
  12231. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  12232. $rowNum++;
  12233. }
  12234. $sumSubtotalCounts += $groupLineCount;
  12235. $grandAmount += $subAmount;
  12236. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  12237. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  12238. $sheet->getStyle('G' . $rowNum)->getAlignment()
  12239. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  12240. ->setVertical(Alignment::VERTICAL_CENTER);
  12241. $rowNum++;
  12242. }
  12243. }
  12244. $sheet->setCellValue('A' . $rowNum, '总计');
  12245. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  12246. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  12247. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  12248. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  12249. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  12250. $lastRow = $rowNum;
  12251. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  12252. 'borders' => [
  12253. 'allBorders' => [
  12254. 'borderStyle' => Border::BORDER_THIN,
  12255. 'color' => ['rgb' => '000000'],
  12256. ],
  12257. ],
  12258. ]);
  12259. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  12260. if ($lastRow >= 3) {
  12261. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12262. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12263. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12264. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12265. }
  12266. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  12267. $sheet->getColumnDimension('A')->setWidth(7);
  12268. $sheet->getColumnDimension('B')->setWidth(16);
  12269. $sheet->getColumnDimension('C')->setWidth(52);
  12270. $sheet->getColumnDimension('D')->setWidth(32);
  12271. $sheet->getColumnDimension('E')->setWidth(12);
  12272. $sheet->getColumnDimension('F')->setWidth(44);
  12273. $sheet->getColumnDimension('G')->setWidth(26);
  12274. $sheet->getColumnDimension('H')->setWidth(13);
  12275. $sheet->getRowDimension(1)->setRowHeight(28);
  12276. $ymCompact = str_replace('-', '', $ym);
  12277. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  12278. $filename = $fileBase . '.xlsx';
  12279. try {
  12280. $this->ensurePurchaseMonthExportLogTable();
  12281. list($adminId, $adminName) = $this->GetUseName();
  12282. Db::table('purchase_month_export_log')->insert([
  12283. 'ym' => $ym,
  12284. 'admin_id' => (int)$adminId,
  12285. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  12286. 'row_count' => count($exportLines),
  12287. 'total_amount' => round($grandAmount, 2),
  12288. 'createtime' => time(),
  12289. ]);
  12290. } catch (\Throwable $e) {
  12291. Log::write('month export log: ' . $e->getMessage(), 'error');
  12292. }
  12293. if (ob_get_length()) {
  12294. ob_end_clean();
  12295. }
  12296. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  12297. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  12298. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  12299. header('Cache-Control: max-age=0');
  12300. $writer = new Xlsx($spreadsheet);
  12301. $writer->save('php://output');
  12302. $spreadsheet->disconnectWorksheets();
  12303. unset($spreadsheet);
  12304. exit;
  12305. }
  12306. /**
  12307. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  12308. */
  12309. public function export_month_quote()
  12310. {
  12311. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  12312. $this->error(__('You have no permission'));
  12313. }
  12314. $bundle = $this->prepareMonthOutwardExportBundle();
  12315. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  12316. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  12317. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  12318. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  12319. $spreadsheet = new Spreadsheet();
  12320. $sheet = $spreadsheet->getActiveSheet();
  12321. $sheet->setTitle('供应商报价明细');
  12322. $mon = (int)substr($ym, 5, 2);
  12323. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  12324. $sheet->getColumnDimension('A')->setWidth(7);
  12325. $sheet->getColumnDimension('B')->setWidth(16);
  12326. $sheet->getColumnDimension('C')->setWidth(52);
  12327. $sheet->getColumnDimension('D')->setWidth(26);
  12328. $sheet->getColumnDimension('E')->setWidth(32);
  12329. $sheet->getColumnDimension('F')->setWidth(12);
  12330. $sheet->getColumnDimension('G')->setWidth(14);
  12331. $sheet->getColumnDimension('H')->setWidth(12);
  12332. if ($quoteLastRow < 1) {
  12333. $quoteLastRow = 3;
  12334. }
  12335. $ymCompact = str_replace('-', '', $ym);
  12336. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  12337. if (ob_get_length()) {
  12338. ob_end_clean();
  12339. }
  12340. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  12341. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  12342. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  12343. header('Cache-Control: max-age=0');
  12344. $writer = new Xlsx($spreadsheet);
  12345. $writer->save('php://output');
  12346. $spreadsheet->disconnectWorksheets();
  12347. unset($spreadsheet);
  12348. exit;
  12349. }
  12350. /**
  12351. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  12352. *
  12353. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  12354. */
  12355. protected function prepareMonthOutwardExportBundle(): array
  12356. {
  12357. $this->request->filter(['strip_tags', 'trim']);
  12358. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  12359. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  12360. $ym = date('Y-m');
  12361. }
  12362. $dbRows = [];
  12363. try {
  12364. $query = Db::table('purchase_order');
  12365. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  12366. $dbRows = $query->select();
  12367. } catch (\Throwable $e) {
  12368. $dbRows = [];
  12369. }
  12370. if (!is_array($dbRows)) {
  12371. $dbRows = [];
  12372. }
  12373. $completeTsMap = [];
  12374. $sidList = [];
  12375. foreach ($dbRows as $dbRow) {
  12376. if (!is_array($dbRow)) {
  12377. continue;
  12378. }
  12379. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  12380. if ($sid > 0) {
  12381. $sidList[$sid] = true;
  12382. }
  12383. }
  12384. if ($sidList !== []) {
  12385. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  12386. }
  12387. // 导出始终按「查看月份」取当月完结单;搜索只在当月内再缩小(勿跨月,否则会与列表不一致)
  12388. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  12389. if (!is_array($dbRow)) {
  12390. return false;
  12391. }
  12392. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  12393. if ($done['ts'] <= 0) {
  12394. return false;
  12395. }
  12396. return date('Y-m', $done['ts']) === $ym;
  12397. }));
  12398. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  12399. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  12400. $mainBySid = [];
  12401. foreach ($pool as $rw) {
  12402. if (!is_array($rw)) {
  12403. continue;
  12404. }
  12405. $rid = (int)($rw['ID'] ?? 0);
  12406. if ($rid > 0) {
  12407. $mainBySid[$rid] = $rw;
  12408. }
  12409. }
  12410. if ($mainBySid === []) {
  12411. $detailRows = [];
  12412. } else {
  12413. try {
  12414. $detailRows = Db::table('purchase_order_detail')
  12415. ->where('scydgy_id', 'in', array_keys($mainBySid))
  12416. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  12417. ->order('status', 'desc')
  12418. ->order('CCYDH', 'asc')
  12419. ->order('company_name', 'asc')
  12420. ->order('id', 'asc')
  12421. ->select();
  12422. } catch (\Throwable $e) {
  12423. try {
  12424. $detailRows = Db::table('purchase_order_detail')
  12425. ->where('scydgy_id', 'in', array_keys($mainBySid))
  12426. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  12427. ->order('status', 'desc')
  12428. ->order('CCYDH', 'asc')
  12429. ->order('company_name', 'asc')
  12430. ->order('ID', 'asc')
  12431. ->select();
  12432. } catch (\Throwable $e2) {
  12433. $detailRows = [];
  12434. }
  12435. }
  12436. }
  12437. if (!is_array($detailRows)) {
  12438. $detailRows = [];
  12439. }
  12440. $exportLines = [];
  12441. $detailSidSeen = [];
  12442. foreach ($detailRows as $dr) {
  12443. if (!is_array($dr)) {
  12444. continue;
  12445. }
  12446. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12447. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  12448. continue;
  12449. }
  12450. if (isset($detailSidSeen[$sid])) {
  12451. continue;
  12452. }
  12453. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  12454. continue;
  12455. }
  12456. $detailSidSeen[$sid] = true;
  12457. $m = $mainBySid[$sid];
  12458. $exportLines[] = [
  12459. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12460. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12461. 'company_name' => (string)($dr['company_name'] ?? ''),
  12462. 'CDF' => (string)($m['CDF'] ?? ''),
  12463. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12464. 'gx' => $this->procuremenExportGxText($m),
  12465. 'detail' => $dr,
  12466. ];
  12467. }
  12468. foreach ($detailRows as $dr) {
  12469. if (!is_array($dr)) {
  12470. continue;
  12471. }
  12472. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12473. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  12474. continue;
  12475. }
  12476. $detailSidSeen[$sid] = true;
  12477. $m = $mainBySid[$sid];
  12478. $exportLines[] = [
  12479. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12480. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12481. 'company_name' => (string)($dr['company_name'] ?? ''),
  12482. 'CDF' => (string)($m['CDF'] ?? ''),
  12483. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12484. 'gx' => $this->procuremenExportGxText($m),
  12485. 'detail' => $dr,
  12486. ];
  12487. }
  12488. foreach ($mainBySid as $sid => $m) {
  12489. if (isset($detailSidSeen[$sid])) {
  12490. continue;
  12491. }
  12492. $company = trim((string)($m['pick_company_name'] ?? ''));
  12493. $exportLines[] = [
  12494. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  12495. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  12496. 'company_name' => $company,
  12497. 'CDF' => (string)($m['CDF'] ?? ''),
  12498. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12499. 'gx' => $this->procuremenExportGxText($m),
  12500. 'detail' => [],
  12501. ];
  12502. }
  12503. $groups = [];
  12504. foreach ($exportLines as $line) {
  12505. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  12506. if (!isset($groups[$k])) {
  12507. $groups[$k] = [];
  12508. }
  12509. $groups[$k][] = $line;
  12510. }
  12511. ksort($groups, SORT_STRING);
  12512. return [
  12513. 'ym' => $ym,
  12514. 'mainBySid' => $mainBySid,
  12515. 'detailRows' => $detailRows,
  12516. 'exportLines' => $exportLines,
  12517. 'groups' => $groups,
  12518. ];
  12519. }
  12520. /**
  12521. * 导出用:工序列文案
  12522. */
  12523. protected function procuremenExportGxText(array $r)
  12524. {
  12525. $a = trim((string)($r['CDXMC'] ?? ''));
  12526. $b = trim((string)($r['CGYMC'] ?? ''));
  12527. if ($a !== '' && $b !== '') {
  12528. return $a . ':' . $b;
  12529. }
  12530. return $a !== '' ? $a : $b;
  12531. }
  12532. /**
  12533. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  12534. */
  12535. protected function procuremenExportAmount(array $r)
  12536. {
  12537. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  12538. if (!array_key_exists($k, $r)) {
  12539. continue;
  12540. }
  12541. $v = $r[$k];
  12542. if ($v === null || $v === '') {
  12543. continue;
  12544. }
  12545. if (is_numeric($v)) {
  12546. return (float)$v;
  12547. }
  12548. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  12549. if ($v !== '' && is_numeric($v)) {
  12550. return (float)$v;
  12551. }
  12552. }
  12553. return 0.0;
  12554. }
  12555. /**
  12556. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  12557. *
  12558. * @param array<int, array<string, mixed>> $detailRows
  12559. * @param array<int, array<string, mixed>> $mainBySid
  12560. * @return array<int, array<string, mixed>>
  12561. */
  12562. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  12563. {
  12564. $lines = [];
  12565. foreach ($detailRows as $dr) {
  12566. if (!is_array($dr)) {
  12567. continue;
  12568. }
  12569. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12570. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  12571. continue;
  12572. }
  12573. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  12574. continue;
  12575. }
  12576. $cn = trim((string)($dr['company_name'] ?? ''));
  12577. if ($cn === '') {
  12578. continue;
  12579. }
  12580. $m = $mainBySid[$sid];
  12581. $am = trim((string)($dr['amount'] ?? ''));
  12582. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  12583. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  12584. $amountText = $amountFilled
  12585. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  12586. : '未填写';
  12587. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  12588. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  12589. if ($deliveryShow === '' && $deliveryRaw !== '') {
  12590. $deliveryShow = $deliveryRaw;
  12591. }
  12592. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  12593. ? $deliveryShow
  12594. : '未填写';
  12595. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  12596. $lines[] = [
  12597. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12598. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12599. 'gx' => $this->procuremenExportGxText($m),
  12600. 'company_name' => $cn,
  12601. 'amount_text' => $amountText,
  12602. 'amount_num' => $amountFilled ? $amountNum : null,
  12603. 'delivery_text' => $deliveryText,
  12604. 'picked_text' => $picked ? '中标' : '未中标',
  12605. 'picked' => $picked,
  12606. ];
  12607. }
  12608. $winnerSupplierByOrder = [];
  12609. foreach ($lines as $line) {
  12610. $dh = trim((string)($line['CCYDH'] ?? ''));
  12611. $cn = trim((string)($line['company_name'] ?? ''));
  12612. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  12613. $winnerSupplierByOrder[$dh][$cn] = true;
  12614. }
  12615. }
  12616. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  12617. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  12618. if ($c !== 0) {
  12619. return $c;
  12620. }
  12621. $dh = trim((string)($a['CCYDH'] ?? ''));
  12622. $aCn = trim((string)($a['company_name'] ?? ''));
  12623. $bCn = trim((string)($b['company_name'] ?? ''));
  12624. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  12625. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  12626. if ($aSupplierWin !== $bSupplierWin) {
  12627. return $aSupplierWin ? -1 : 1;
  12628. }
  12629. $c = strcmp($aCn, $bCn);
  12630. if ($c !== 0) {
  12631. return $c;
  12632. }
  12633. if (!empty($a['picked']) !== !empty($b['picked'])) {
  12634. return !empty($a['picked']) ? -1 : 1;
  12635. }
  12636. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  12637. if ($c !== 0) {
  12638. return $c;
  12639. }
  12640. return 0;
  12641. });
  12642. return $lines;
  12643. }
  12644. /**
  12645. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  12646. *
  12647. * @param array<int, array<string, mixed>> $quoteLines
  12648. */
  12649. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  12650. {
  12651. $mon = (int)substr($ym, 5, 2);
  12652. $titleRow = $startRow;
  12653. $headerRow = $startRow + 1;
  12654. $dataStartRow = $startRow + 2;
  12655. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  12656. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  12657. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  12658. $sheet->getStyle('A' . $titleRow)->getAlignment()
  12659. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12660. ->setVertical(Alignment::VERTICAL_CENTER);
  12661. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  12662. $col = 'A';
  12663. foreach ($headers as $h) {
  12664. $sheet->setCellValue($col . $headerRow, $h);
  12665. $col++;
  12666. }
  12667. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  12668. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12669. $rowNum = $dataStartRow;
  12670. if ($quoteLines === []) {
  12671. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  12672. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  12673. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12674. $rowNum = $dataStartRow + 1;
  12675. } else {
  12676. $i = 0;
  12677. foreach ($quoteLines as $line) {
  12678. $i++;
  12679. $sheet->setCellValue('A' . $rowNum, $i);
  12680. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  12681. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  12682. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  12683. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  12684. if ($line['amount_num'] !== null) {
  12685. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  12686. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  12687. } else {
  12688. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  12689. }
  12690. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  12691. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  12692. if (!empty($line['picked'])) {
  12693. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  12694. }
  12695. $rowNum++;
  12696. }
  12697. }
  12698. $lastRow = $rowNum - 1;
  12699. if ($lastRow >= $headerRow) {
  12700. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  12701. 'borders' => [
  12702. 'allBorders' => [
  12703. 'borderStyle' => Border::BORDER_THIN,
  12704. 'color' => ['rgb' => '000000'],
  12705. ],
  12706. ],
  12707. ]);
  12708. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  12709. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12710. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12711. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12712. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  12713. if ($lastRow >= $dataStartRow) {
  12714. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  12715. }
  12716. }
  12717. return $lastRow;
  12718. }
  12719. /**
  12720. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  12721. */
  12722. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  12723. {
  12724. if ($lastRow < $dataStartRow || $headerRow < 1) {
  12725. return;
  12726. }
  12727. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  12728. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12729. ->setVertical(Alignment::VERTICAL_CENTER);
  12730. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  12731. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12732. ->setVertical(Alignment::VERTICAL_CENTER);
  12733. if ($lastCol > 'B') {
  12734. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  12735. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  12736. ->setVertical(Alignment::VERTICAL_CENTER);
  12737. }
  12738. }
  12739. /**
  12740. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  12741. */
  12742. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  12743. {
  12744. $s = trim($ccydh);
  12745. if ($s === '') {
  12746. return 'ORDER';
  12747. }
  12748. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  12749. $s = trim($s, '._-');
  12750. if ($s === '') {
  12751. return 'ORDER';
  12752. }
  12753. if (function_exists('mb_substr')) {
  12754. return mb_substr($s, 0, 80, 'UTF-8');
  12755. }
  12756. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  12757. }
  12758. /**
  12759. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  12760. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  12761. *
  12762. * @return array{objectKey: string, webPath: string}
  12763. */
  12764. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  12765. {
  12766. $sid = (int)$scydgyId;
  12767. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  12768. $y = date('Y');
  12769. $m = date('m');
  12770. $d = date('d');
  12771. $basename = $safeOrder . '_' . $sid . '.pdf';
  12772. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  12773. return [
  12774. 'objectKey' => $objectKey,
  12775. 'webPath' => '/' . $objectKey,
  12776. ];
  12777. }
  12778. /**
  12779. * 采购确认成功后 / 已完结刷新:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  12780. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  12781. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  12782. * 说明:审批通过时会先存一版;质量+交货评分使订单「已完结」后,详情页打开或评分保存完成时会再重存,以含最终步骤与操作记录。
  12783. *
  12784. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  12785. */
  12786. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  12787. {
  12788. if (!$this->isValidScydgyRowId($scydgyId)) {
  12789. return '';
  12790. }
  12791. $ids = trim((string)$scydgyId);
  12792. $prep = $this->prepareProcuremenDetailsView($ids);
  12793. if (!$prep['ok']) {
  12794. return '';
  12795. }
  12796. $ccydh = $prep['ccydh'];
  12797. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  12798. $objectKey = $paths['objectKey'];
  12799. $webPath = $paths['webPath'];
  12800. $cyjmc = '';
  12801. try {
  12802. $poMeta = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->field('CYJMC')->find();
  12803. if (is_array($poMeta)) {
  12804. $cyjmc = trim((string)($poMeta['CYJMC'] ?? ''));
  12805. }
  12806. } catch (\Throwable $e) {
  12807. $cyjmc = '';
  12808. }
  12809. $genTime = date('Y-m-d H:i:s');
  12810. $metaIds = '工序行ID ' . $ids . ' | 主表订单ID ' . (int)$purchaseOrderId;
  12811. $metaLeft = $metaIds . ($cyjmc !== '' ? ' | ' . $cyjmc : '');
  12812. // PDF 进度:去掉「未发」;节点用纯色圆点(不用图片,避免 mPDF 破图)
  12813. $pdfSteps = [];
  12814. $viewSteps = $prep['steps'] ?? [];
  12815. if (is_array($viewSteps)) {
  12816. foreach ($viewSteps as $st) {
  12817. if (!is_array($st)) {
  12818. continue;
  12819. }
  12820. if (trim((string)($st['title'] ?? '')) === '未发') {
  12821. continue;
  12822. }
  12823. $pdfSteps[] = $st;
  12824. }
  12825. }
  12826. $pdfStepW = count($pdfSteps) > 0 ? (round(100 / count($pdfSteps), 2) . '%') : '16.66%';
  12827. $nPdf = count($pdfSteps);
  12828. foreach ($pdfSteps as $idx => &$pst) {
  12829. if ($idx === 0) {
  12830. $pst['pdf_left_bg'] = '';
  12831. } else {
  12832. $pst['pdf_left_bg'] = !empty($pdfSteps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  12833. }
  12834. if ($idx >= $nPdf - 1) {
  12835. $pst['pdf_right_bg'] = '';
  12836. } else {
  12837. $pst['pdf_right_bg'] = !empty($pst['done']) ? '#1890ff' : '#e0e0e0';
  12838. }
  12839. }
  12840. unset($pst);
  12841. $this->view->assign([
  12842. 'pdf_export' => 1,
  12843. 'pdfMetaLine' => $metaLeft,
  12844. 'pdfMetaLeft' => $metaLeft,
  12845. 'pdfMetaIds' => $metaIds,
  12846. 'pdfMetaTitle' => $cyjmc,
  12847. 'pdfMetaTime' => 'PDF生成时间 ' . $genTime,
  12848. 'pdfSteps' => $pdfSteps,
  12849. 'pdfStepWidth' => $pdfStepW,
  12850. ]);
  12851. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  12852. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  12853. $this->view->engine->layout(false);
  12854. try {
  12855. $html = $this->view->fetch('procuremen/details_pdf_shell');
  12856. } catch (\Throwable $e) {
  12857. if ($restoreLayout) {
  12858. $this->view->engine->layout($restoreLayout);
  12859. }
  12860. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  12861. $this->view->assign([
  12862. 'pdf_export' => '', 'pdfMetaLine' => '', 'pdfMetaLeft' => '',
  12863. 'pdfMetaIds' => '', 'pdfMetaTitle' => '', 'pdfMetaTime' => '',
  12864. 'pdfSteps' => [], 'pdfStepWidth' => '',
  12865. ]);
  12866. return '';
  12867. }
  12868. if ($restoreLayout) {
  12869. $this->view->engine->layout($restoreLayout);
  12870. }
  12871. $this->view->assign([
  12872. 'pdf_export' => '', 'pdfMetaLine' => '', 'pdfMetaLeft' => '',
  12873. 'pdfMetaIds' => '', 'pdfMetaTitle' => '', 'pdfMetaTime' => '',
  12874. 'pdfSteps' => [], 'pdfStepWidth' => '',
  12875. ]);
  12876. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  12877. if (!is_dir($tempDir)) {
  12878. @mkdir($tempDir, 0755, true);
  12879. }
  12880. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  12881. try {
  12882. $mpdf = new \Mpdf\Mpdf([
  12883. 'mode' => 'utf-8',
  12884. 'format' => 'A4',
  12885. 'margin_left' => 12,
  12886. 'margin_right' => 12,
  12887. 'margin_top' => 14,
  12888. 'margin_bottom' => 14,
  12889. 'tempDir' => $tempDir,
  12890. 'autoScriptToLang' => true,
  12891. 'autoLangToFont' => true,
  12892. ]);
  12893. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  12894. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  12895. $mpdf->SetBasePath('http://127.0.0.1/');
  12896. $mpdf->WriteHTML($html);
  12897. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  12898. } catch (\Throwable $e) {
  12899. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  12900. if (is_file($tempPdf)) {
  12901. @unlink($tempPdf);
  12902. }
  12903. return '';
  12904. }
  12905. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  12906. if ($ossUrl !== '') {
  12907. @unlink($tempPdf);
  12908. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12909. return $ossUrl;
  12910. }
  12911. $pi = pathinfo($objectKey);
  12912. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  12913. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  12914. if ($baseFile === '') {
  12915. @unlink($tempPdf);
  12916. return '';
  12917. }
  12918. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  12919. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  12920. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  12921. @unlink($tempPdf);
  12922. return '';
  12923. }
  12924. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  12925. if (!@copy($tempPdf, $fullPath)) {
  12926. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  12927. @unlink($tempPdf);
  12928. return '';
  12929. }
  12930. @unlink($tempPdf);
  12931. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12932. return $webPath;
  12933. }
  12934. /**
  12935. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  12936. */
  12937. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  12938. {
  12939. if ($scydgyId <= 0 || $webPath === '') {
  12940. return;
  12941. }
  12942. try {
  12943. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  12944. } catch (\Throwable $e) {
  12945. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  12946. }
  12947. }
  12948. /**
  12949. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  12950. *
  12951. * @param array<string, string> $vars
  12952. * @return array<string, string>
  12953. */
  12954. protected function normalizeSmsTemplateVars(array $vars): array
  12955. {
  12956. $out = [];
  12957. foreach ($vars as $k => $v) {
  12958. $out[(string)$k] = trim((string)$v);
  12959. }
  12960. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  12961. $out['contact_name'] = $out['company_name'];
  12962. }
  12963. return $out;
  12964. }
  12965. /**
  12966. * 按手机号或公司名称查 customer 表联系人姓名
  12967. */
  12968. protected function resolveCustomerContactName(string $phone, string $companyName): string
  12969. {
  12970. $phone = trim($phone);
  12971. $companyName = trim($companyName);
  12972. try {
  12973. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  12974. $row = Db::table('customer')
  12975. ->where(function ($q) use ($phone) {
  12976. $q->where('phone', $phone)->whereOr('account', $phone);
  12977. })
  12978. ->order('id', 'asc')
  12979. ->find();
  12980. if (is_array($row)) {
  12981. $nm = trim((string)($row['username'] ?? ''));
  12982. if ($nm !== '') {
  12983. return $nm;
  12984. }
  12985. }
  12986. }
  12987. if ($companyName !== '') {
  12988. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  12989. if (is_array($row)) {
  12990. return trim((string)($row['username'] ?? ''));
  12991. }
  12992. }
  12993. } catch (\Throwable $e) {
  12994. }
  12995. return '';
  12996. }
  12997. /**
  12998. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;;http(s) 链接做成可点的 &lt;a&gt;(微信 QQ 邮箱提醒纯文本 URL 常不可点)
  12999. */
  13000. protected function plainTextToHtmlEmailBody(string $text): string
  13001. {
  13002. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  13003. $parts = explode("\n", $text);
  13004. $out = [];
  13005. foreach ($parts as $line) {
  13006. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  13007. $out[] = $line;
  13008. } else {
  13009. $esc = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  13010. $esc = preg_replace(
  13011. '#(https?://[^\s<>"\']+)#iu',
  13012. '<a href="$1" style="color:#1565c0;text-decoration:underline;word-break:break-all;">$1</a>',
  13013. $esc
  13014. );
  13015. $out[] = $esc;
  13016. }
  13017. }
  13018. return implode("<br>\n", $out);
  13019. }
  13020. /**
  13021. * 短信场景:去掉链接类变量,避免误填 URL
  13022. *
  13023. * @param array<string, string> $vars
  13024. * @return array<string, string>
  13025. */
  13026. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  13027. {
  13028. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  13029. return $vars;
  13030. }
  13031. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  13032. $vars[$k] = '';
  13033. }
  13034. return $vars;
  13035. }
  13036. /**
  13037. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  13038. *
  13039. * @param array<string, string> $vars
  13040. */
  13041. protected function renderNotifyTemplate(string $scene, array $vars): string
  13042. {
  13043. $vars = $this->normalizeSmsTemplateVars($vars);
  13044. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  13045. $row = $this->loadNotifyTemplateRow($scene);
  13046. if ($row === null) {
  13047. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  13048. }
  13049. $tpl = trim((string)($row['content'] ?? ''));
  13050. if ($tpl === '') {
  13051. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  13052. }
  13053. foreach ($vars as $k => $v) {
  13054. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  13055. }
  13056. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  13057. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  13058. return $tpl;
  13059. }
  13060. protected function resolveProcuremenEmailSubject(string $scene): string
  13061. {
  13062. // 询价 / 采购确认结果邮箱:模版名称即邮件主题
  13063. if (in_array($scene, ['rfq_salesman_email', 'rfq_supplier_email', 'confirm_ok_email', 'confirm_fail_email'], true)) {
  13064. $row = $this->loadNotifyTemplateRow($scene);
  13065. $title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
  13066. if ($title !== '') {
  13067. return $title;
  13068. }
  13069. $fallback = [
  13070. 'rfq_supplier_email' => '供应商询价通知',
  13071. 'rfq_salesman_email' => '协助采购询价通知',
  13072. 'confirm_ok_email' => '采购确认结果:已通过',
  13073. 'confirm_fail_email' => '采购确认结果:未通过',
  13074. ];
  13075. return $fallback[$scene] ?? '协助采购通知';
  13076. }
  13077. $map = [
  13078. 'review_email' => '您有新的协助加工订单',
  13079. ];
  13080. $subject = trim((string)($map[$scene] ?? ''));
  13081. if ($subject === '') {
  13082. $this->error('未配置邮件主题:' . $scene);
  13083. }
  13084. return $subject;
  13085. }
  13086. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  13087. {
  13088. $map = [
  13089. 'review_email' => '协助下发-邮箱',
  13090. 'review_sms' => '协助下发-短信',
  13091. 'confirm_ok' => '采购确认-通过',
  13092. 'confirm_fail' => '采购确认-未通过',
  13093. 'confirm_ok_email' => '采购确认通过-邮箱',
  13094. 'confirm_fail_email' => '采购确认未通过-邮箱',
  13095. 'bid_open' => '开标双重验证',
  13096. 'rfq_salesman_email' => '询价通知业务员-邮箱',
  13097. 'rfq_supplier_email' => '供应商询价通知',
  13098. ];
  13099. $label = $map[$scene] ?? $scene;
  13100. if ($titleRequired) {
  13101. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  13102. }
  13103. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  13104. }
  13105. /**
  13106. * 是否开启协助通知演练(不发真实短信/邮件)
  13107. */
  13108. protected function isProcuremenNotifyDryRun(): bool
  13109. {
  13110. return (bool)Config::get('procuremen_notify_dry_run');
  13111. }
  13112. /**
  13113. * @param array<string, mixed> $payload
  13114. */
  13115. protected function recordNotifyDryRunPreview(array $payload): void
  13116. {
  13117. $this->notifyDryRunPreview[] = $payload;
  13118. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  13119. }
  13120. /**
  13121. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  13122. * @throws \Exception
  13123. */
  13124. protected function smsbao($phone, $content)
  13125. {
  13126. if ($this->isProcuremenNotifyDryRun()) {
  13127. $this->recordNotifyDryRunPreview([
  13128. 'scene' => 'sms_only',
  13129. 'phone' => $phone,
  13130. 'sms_content' => $content,
  13131. ]);
  13132. return;
  13133. }
  13134. $statusStr = [
  13135. '0' => '短信发送成功',
  13136. '-1' => '参数不全',
  13137. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  13138. '30' => '密码错误',
  13139. '40' => '账号不存在',
  13140. '41' => '余额不足',
  13141. '42' => '帐户已过期',
  13142. '43' => 'IP地址限制',
  13143. '50' => '内容含有敏感词',
  13144. ];
  13145. $smsapi = 'http://api.smsbao.com/';
  13146. $user = 'zhuwei123';
  13147. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  13148. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  13149. $result = @file_get_contents($sendurl);
  13150. if ($result === false) {
  13151. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  13152. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  13153. }
  13154. $result = trim((string)$result);
  13155. if ($result !== '0') {
  13156. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  13157. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  13158. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  13159. }
  13160. }
  13161. }