Procuremen.php 274 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use PHPMailer\PHPMailer\PHPMailer;
  6. use think\Config;
  7. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  8. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  9. use PhpOffice\PhpSpreadsheet\Style\Border;
  10. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  11. use think\Db;
  12. use think\Log;
  13. class Procuremen extends Backend
  14. {
  15. /**
  16. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  17. */
  18. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  19. /**
  20. * Procuremen模型对象
  21. * @var \app\admin\model\Procuremen
  22. */
  23. protected $model = null;
  24. /**
  25. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  26. */
  27. protected $notifyDryRunPreview = [];
  28. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  29. protected $procuremenRedisCache = null;
  30. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  31. protected $pickHiddenScydgySetCache = null;
  32. /**
  33. * @var array
  34. */
  35. protected $noNeedRight = [
  36. 'review', 'reviewCompanies', 'outward_detail', 'export_month_outward', 'snapshotToProcure',
  37. 'pick', 'audit', 'confirm', 'pickreview', 'picksubmit', 'pickadd', 'auditissue', 'auditsubmit',
  38. 'auditresendsms', 'auditabandon', 'archiveabandon', 'auditresendemail', 'purchaseconfirmpick', 'purchaseapprovalreject', 'add', 'pickdelete', 'completeDirectly', 'rfqlist', 'details',
  39. ];
  40. public function _initialize()
  41. {
  42. parent::_initialize();
  43. $this->model = new \app\admin\model\Procuremen;
  44. }
  45. /**
  46. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  47. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  48. *
  49. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  50. */
  51. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  52. {
  53. static $mprocCfgLoaded = false;
  54. if (!$mprocCfgLoaded) {
  55. $mprocCfgLoaded = true;
  56. if (is_file(APP_PATH . 'extra/mproc.php')) {
  57. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  58. }
  59. }
  60. $eid = (int)$purchaseOrderDetailId;
  61. $base = $this->resolveMprocMobilePublicBaseUrl();
  62. if ($base === '') {
  63. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  64. }
  65. $path = trim((string)Config::get('mproc.mobile_index_path'));
  66. if ($path === '') {
  67. $path = '/index.php/index/index/index';
  68. } else {
  69. $path = '/' . ltrim($path, '/');
  70. }
  71. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  72. if ($eid > 0) {
  73. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  74. }
  75. return $base . $path . '?main_tab=orders';
  76. }
  77. /**
  78. * 邮件/短信外链:须为带点的公网域名
  79. */
  80. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  81. {
  82. $u = trim((string)$baseUrl);
  83. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  84. return false;
  85. }
  86. $host = parse_url($u, PHP_URL_HOST);
  87. if (!is_string($host) || $host === '') {
  88. return false;
  89. }
  90. if (strcasecmp($host, 'localhost') === 0) {
  91. return false;
  92. }
  93. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  94. return false;
  95. }
  96. if (strpos($host, '.') === false) {
  97. return false;
  98. }
  99. return true;
  100. }
  101. /**
  102. * 解析用于协助邮件/短信的手机端站点根
  103. */
  104. protected function resolveMprocMobilePublicBaseUrl()
  105. {
  106. $candidates = [];
  107. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  108. $candidates[] = trim((string)Config::get('site.indexurl'));
  109. $cdn = trim((string)Config::get('site.cdnurl'));
  110. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  111. $candidates[] = rtrim($cdn, '/');
  112. }
  113. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  114. $candidates[] = $reqBase;
  115. foreach ($candidates as $c) {
  116. if ($c === '') {
  117. continue;
  118. }
  119. $c = rtrim($c, '/');
  120. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  121. return $c;
  122. }
  123. }
  124. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  125. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  126. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  127. return $reqBase;
  128. }
  129. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  130. return '';
  131. }
  132. /**
  133. * 排除 mcyd.dputrecord 空串、零日期等非法值,避免 MySQL 1525(DATE_FORMAT/BETWEEN 遇 '' 报错)
  134. */
  135. protected function whereMcydDputrecordValid($query, $alias = 'a')
  136. {
  137. $c = $alias . '.dStamp';
  138. // 先转成 CHAR 再判断,避免 DATETIME 列里存 '' / 0000-00-00 时参与日期函数报错
  139. return $query->whereRaw(
  140. $c . ' IS NOT NULL'
  141. . ' AND TRIM(CAST(' . $c . ' AS CHAR(32))) <> \'\''
  142. . ' AND TRIM(CAST(' . $c . ' AS CHAR(32))) NOT LIKE \'0000-00-00%\''
  143. . ' AND TRIM(CAST(' . $c . ' AS CHAR(32))) REGEXP \'^[12][0-9]{3}-[01][0-9]-[0-3][0-9]\''
  144. );
  145. }
  146. /**
  147. * 获取 Redis 中 procuremen_redis
  148. */
  149. protected function ProcuremenRedis(): array
  150. {
  151. if ($this->procuremenRedisCache !== null) {
  152. return $this->procuremenRedisCache;
  153. }
  154. try {
  155. $redis = redis();
  156. $raw = $redis->get('procuremen_redis');
  157. if ($raw === false || $raw === '') {
  158. $this->procuremenRedisCache = [];
  159. return $this->procuremenRedisCache;
  160. }
  161. $decoded = json_decode($raw, true);
  162. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  163. $this->procuremenRedisCache = [];
  164. return $this->procuremenRedisCache;
  165. }
  166. $this->procuremenRedisCache = $decoded['data'];
  167. return $this->procuremenRedisCache;
  168. } catch (\Throwable $e) {
  169. $this->procuremenRedisCache = [];
  170. return $this->procuremenRedisCache;
  171. }
  172. }
  173. /**
  174. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  175. *
  176. * @return array<int, array<string, mixed>>
  177. */
  178. protected function procuremenFetchErpPoolFromDb(): array
  179. {
  180. try {
  181. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  182. $endTime = date('Y-m-d 23:59:59');
  183. $list = Db::table('scydgy')
  184. ->alias('a')
  185. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  186. ->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, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  187. ->where([
  188. 'a.bwjg' => 1,
  189. 'a.iEndBz' => 0,
  190. 'a.iType' => 0,
  191. 'a.iStatus' => 10,
  192. ])
  193. ->where('a.dStamp', '>=', $startTime)
  194. ->where('a.dStamp', '<=', $endTime)
  195. ->order('a.dStamp', 'desc')
  196. ->select();
  197. if (!is_array($list)) {
  198. return [];
  199. }
  200. try {
  201. $redis = redis();
  202. $payload = [
  203. 'code' => 200,
  204. 'msg' => 'success',
  205. 'data' => $list,
  206. ];
  207. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  208. $this->procuremenRedisCache = $list;
  209. } catch (\Throwable $e) {
  210. }
  211. return $list;
  212. } catch (\Throwable $e) {
  213. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  214. return [];
  215. }
  216. }
  217. /**
  218. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  219. *
  220. * @return array<int, array<string, mixed>>
  221. */
  222. protected function procuremenEnsureRedisPool(): array
  223. {
  224. $pool = $this->ProcuremenRedis();
  225. if (is_array($pool) && $pool !== []) {
  226. return $pool;
  227. }
  228. static $warmed = false;
  229. if ($warmed) {
  230. return is_array($pool) ? $pool : [];
  231. }
  232. $warmed = true;
  233. return $this->procuremenFetchErpPoolFromDb();
  234. }
  235. /**
  236. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  237. *
  238. * @param array<string, mixed> $row
  239. */
  240. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  241. {
  242. $t = $this->procuremenRowListSortTime($row, $primary);
  243. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  244. return null;
  245. }
  246. $mo = (int)$m[2];
  247. if ($mo < 1 || $mo > 12) {
  248. return null;
  249. }
  250. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  251. }
  252. /**
  253. * @param array<int, array{year:string, months:array}> $sidebar
  254. * @return array<int, array{year:string, months:array}>
  255. */
  256. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  257. {
  258. $ym = trim($ym);
  259. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  260. return $sidebar;
  261. }
  262. foreach ($sidebar as $block) {
  263. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  264. continue;
  265. }
  266. foreach ($block['months'] as $item) {
  267. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  268. return $sidebar;
  269. }
  270. }
  271. }
  272. $y = substr($ym, 0, 4);
  273. $mo = (int)substr($ym, 5, 2);
  274. $sidebar[] = [
  275. 'year' => $y,
  276. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  277. ];
  278. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  279. }
  280. /**
  281. * @param array<int, array{year:string, months:array}> $sidebar
  282. * @return string[]
  283. */
  284. protected function flattenProcuremenSidebarYms(array $sidebar): array
  285. {
  286. $yms = [];
  287. foreach ($sidebar as $block) {
  288. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  289. continue;
  290. }
  291. foreach ($block['months'] as $item) {
  292. if (!is_array($item)) {
  293. continue;
  294. }
  295. $ym = trim((string)($item['ym'] ?? ''));
  296. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  297. $yms[$ym] = true;
  298. }
  299. }
  300. }
  301. return array_keys($yms);
  302. }
  303. /**
  304. * 左侧菜单(协助初选:Redis/ERP 工序按提交日期分组;与列表月份筛选字段一致)
  305. */
  306. protected function GetIndexYearMonths()
  307. {
  308. $ymSet = [];
  309. $pool = $this->procuremenEnsureRedisPool();
  310. foreach ($pool as $r) {
  311. if (!is_array($r)) {
  312. continue;
  313. }
  314. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  315. if ($ym !== null) {
  316. $ymSet[$ym] = true;
  317. }
  318. }
  319. foreach ($this->loadPickManualOrderRows() as $r) {
  320. if (!is_array($r)) {
  321. continue;
  322. }
  323. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  324. if ($ym !== null) {
  325. $ymSet[$ym] = true;
  326. }
  327. }
  328. $ymList = array_keys($ymSet);
  329. if ($ymList === []) {
  330. $ymList[] = $this->resolveProcuremenDefaultYm('pick');
  331. }
  332. return $this->buildYearMonthSidebar($ymList);
  333. }
  334. /**
  335. * @param string[] $ymList 形如 2026-06
  336. * @return array<int, array{year:string, months:array}>
  337. */
  338. protected function buildYearMonthSidebar(array $ymList): array
  339. {
  340. rsort($ymList, SORT_STRING);
  341. $byYear = [];
  342. foreach ($ymList as $ym) {
  343. $y = substr($ym, 0, 4);
  344. $mo = (int)substr($ym, 5, 2);
  345. if (!isset($byYear[$y])) {
  346. $byYear[$y] = [];
  347. }
  348. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  349. }
  350. krsort($byYear, SORT_NUMERIC);
  351. foreach ($byYear as $y => $items) {
  352. usort($byYear[$y], function ($a, $b) {
  353. return strcmp($b['ym'], $a['ym']);
  354. });
  355. }
  356. $sidebar = [];
  357. foreach ($byYear as $y => $months) {
  358. $sidebar[] = ['year' => $y, 'months' => $months];
  359. }
  360. return $sidebar;
  361. }
  362. /**
  363. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  364. */
  365. protected function GetIssuedOrderYearMonths(string $stage): array
  366. {
  367. $ymSet = [];
  368. try {
  369. $query = Db::table('purchase_order');
  370. $this->applyPurchaseOrderNotDeletedWhere($query);
  371. if ($stage === 'audit') {
  372. $query->whereIn('wflow_status', [1, '1']);
  373. } elseif ($stage === 'confirm') {
  374. $query->where('status', 0)->where(function ($q) {
  375. $q->where('wflow_status', 2)
  376. ->whereOr(function ($q2) {
  377. $q2->where('wflow_status', 0)->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
  378. });
  379. });
  380. } else {
  381. return $this->GetIndexYearMonths();
  382. }
  383. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  384. if (is_array($rows)) {
  385. foreach ($rows as $r) {
  386. if (!is_array($r)) {
  387. continue;
  388. }
  389. $ym = $this->procuremenRowYearMonth($r, 'pick_time');
  390. if ($ym !== null) {
  391. $ymSet[$ym] = true;
  392. }
  393. }
  394. }
  395. } catch (\Throwable $e) {
  396. $ymSet = [];
  397. }
  398. $ymList = array_keys($ymSet);
  399. if ($ymList === []) {
  400. $def = $this->resolveProcuremenDefaultYm($stage);
  401. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  402. }
  403. return $this->buildYearMonthSidebar($ymList);
  404. }
  405. /**
  406. * 列表默认月份:已下发类取最近有数据的月份,初选仍用当月
  407. */
  408. protected function resolveProcuremenDefaultYm(string $stage): string
  409. {
  410. if ($stage === 'pick') {
  411. return date('Y-m');
  412. }
  413. try {
  414. $query = Db::table('purchase_order');
  415. $this->applyPurchaseOrderNotDeletedWhere($query);
  416. if ($stage === 'audit') {
  417. $query->whereIn('wflow_status', [1, '1']);
  418. } elseif ($stage === 'confirm') {
  419. $query->where('status', 0)->where(function ($q) {
  420. $q->where('wflow_status', 2)
  421. ->whereOr(function ($q2) {
  422. $q2->where('wflow_status', 0)->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
  423. });
  424. });
  425. } else {
  426. return date('Y-m');
  427. }
  428. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  429. if ($latest === null || $latest === '') {
  430. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  431. }
  432. $t = $this->formatProcuremenDetailTime($latest);
  433. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  434. return $m[1] . '-' . $m[2];
  435. }
  436. } catch (\Throwable $e) {
  437. }
  438. return date('Y-m');
  439. }
  440. protected function applyPurchaseOrderNotDeletedWhere($query): void
  441. {
  442. $query->whereRaw(
  443. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  444. );
  445. }
  446. /** purchase_order_detail.status:2=废弃归档(保留留痕,不参与当前流程) */
  447. protected const PURCHASE_DETAIL_STATUS_VOID = 2;
  448. protected function isPurchaseOrderDetailVoid(array $row): bool
  449. {
  450. if ((int)($row['status'] ?? 0) === self::PURCHASE_DETAIL_STATUS_VOID) {
  451. return true;
  452. }
  453. return trim((string)($row['status_name'] ?? '')) === '已废弃';
  454. }
  455. /**
  456. * 仅当前有效下发明细(排除废弃归档)
  457. */
  458. protected function applyActivePurchaseOrderDetailWhere($query): void
  459. {
  460. $void = self::PURCHASE_DETAIL_STATUS_VOID;
  461. $query->whereRaw('(`status` IS NULL OR `status` <> ' . $void . ')')
  462. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'已废弃\')');
  463. }
  464. /**
  465. * 列表/流程判定:存在有效下发明细
  466. */
  467. protected function purchaseOrderDetailActiveExistsSql(string $detailAlias = 'd'): string
  468. {
  469. $void = self::PURCHASE_DETAIL_STATUS_VOID;
  470. return 'EXISTS (SELECT 1 FROM purchase_order_detail ' . $detailAlias
  471. . ' WHERE ' . $detailAlias . '.scydgy_id = purchase_order.scydgy_id'
  472. . ' AND (' . $detailAlias . '.`status` IS NULL OR ' . $detailAlias . '.`status` <> ' . $void . ')'
  473. . ' AND (' . $detailAlias . '.status_name IS NULL OR TRIM(' . $detailAlias . '.status_name) = \'\' OR ' . $detailAlias . '.status_name <> \'已废弃\')'
  474. . ' LIMIT 1)';
  475. }
  476. /**
  477. * 废弃退回初选:下发明细标记归档,不物理删除
  478. *
  479. * @param array<int, int|string> $scydgyIds
  480. */
  481. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  482. {
  483. $ids = [];
  484. foreach ($scydgyIds as $sid) {
  485. $n = (int)$sid;
  486. if ($this->isValidScydgyRowId($n) || $n < 0) {
  487. $ids[$n] = true;
  488. }
  489. }
  490. if ($ids === []) {
  491. return;
  492. }
  493. $void = self::PURCHASE_DETAIL_STATUS_VOID;
  494. Db::table('purchase_order_detail')
  495. ->where('scydgy_id', 'in', array_keys($ids))
  496. ->whereRaw('(`status` IS NULL OR `status` <> ' . $void . ')')
  497. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'已废弃\')')
  498. ->update([
  499. 'status' => $void,
  500. 'status_name' => '已废弃',
  501. ]);
  502. }
  503. /**
  504. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  505. */
  506. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  507. {
  508. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  509. $norm = function (string $col) use ($p): string {
  510. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  511. };
  512. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  513. $parts = [];
  514. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  515. if ($key === 'createtime') {
  516. $parts[] = $createtime;
  517. } else {
  518. $parts[] = $norm($key);
  519. }
  520. }
  521. return 'COALESCE(' . implode(', ', $parts) . ')';
  522. }
  523. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  524. {
  525. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  526. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  527. }
  528. /**
  529. * @return array<int, array<string, mixed>>
  530. */
  531. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  532. {
  533. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  534. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  535. try {
  536. $query = Db::table('purchase_order')->field($fields);
  537. $this->applyPurchaseOrderNotDeletedWhere($query);
  538. if ($stage === 'audit') {
  539. $query->whereIn('wflow_status', [1, '1'])->order('pick_time', 'desc')->order('id', 'desc');
  540. } elseif ($stage === 'confirm') {
  541. $query->where('status', 0)->where(function ($q) {
  542. $q->where('wflow_status', 2)
  543. ->whereOr(function ($q2) {
  544. $q2->where('wflow_status', 0)->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
  545. });
  546. })->order('pick_time', 'desc')->order('id', 'desc');
  547. } else {
  548. return [];
  549. }
  550. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  551. $monthStart = $ym . '-01 00:00:00';
  552. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  553. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  554. }
  555. $rows = $query->select();
  556. } catch (\Throwable $e) {
  557. $rows = [];
  558. }
  559. return is_array($rows) ? $rows : [];
  560. }
  561. /**
  562. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  563. */
  564. protected function resolveProcuremenListStage(): string
  565. {
  566. $action = strtolower((string)$this->request->action());
  567. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  568. return $action;
  569. }
  570. $tab = trim((string)$this->request->request('wff_tab', 'pick'));
  571. return in_array($tab, ['pick', 'audit', 'confirm'], true) ? $tab : 'pick';
  572. }
  573. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  574. {
  575. $rootTrue = rtrim((string)$this->request->root(true), '/');
  576. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  577. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  578. $indexPhpRoot = $rootTrue . '/index.php';
  579. }
  580. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  581. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  582. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  583. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  584. $this->view->assign('defaultYm', $defaultYm);
  585. $this->view->assign('sidebarYearMonths', $sidebar);
  586. $this->view->assign('procuremenStage', $stage);
  587. $this->view->assign('procuremenPageTitle', $pageTitle);
  588. }
  589. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  590. public function pick()
  591. {
  592. $this->request->filter(['strip_tags', 'trim']);
  593. if (!$this->request->isAjax()) {
  594. $this->assignProcuremenListPage('pick', '协助下发');
  595. return $this->view->fetch('procuremen/index');
  596. }
  597. return $this->index();
  598. }
  599. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  600. public function audit()
  601. {
  602. $this->request->filter(['strip_tags', 'trim']);
  603. if (!$this->request->isAjax()) {
  604. $this->assignProcuremenListPage('audit', '确认供应商');
  605. return $this->view->fetch('procuremen/index');
  606. }
  607. return $this->index();
  608. }
  609. /** 采购确认(定标) */
  610. public function confirm()
  611. {
  612. $this->request->filter(['strip_tags', 'trim']);
  613. if (!$this->request->isAjax()) {
  614. $this->assignProcuremenListPage('confirm', '采购确认');
  615. return $this->view->fetch('procuremen/index');
  616. }
  617. return $this->index();
  618. }
  619. /**
  620. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  621. */
  622. public function index()
  623. {
  624. $this->request->filter(['strip_tags', 'trim']);
  625. if (!$this->request->isAjax()) {
  626. $this->assignProcuremenListPage('pick', '协助下发');
  627. return $this->view->fetch('procuremen/index');
  628. }
  629. if ($this->request->request('keyField')) {
  630. return $this->selectpage();
  631. }
  632. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  633. $limit = max(10, min(500, (int)$limit));
  634. $ym = $this->request->request('ym', date('Y-m'));
  635. $ym = is_string($ym) ? trim($ym) : '';
  636. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  637. $ym = date('Y-m');
  638. }
  639. $monthStart = $ym . '-01 00:00:00';
  640. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  641. $search = trim((string)$this->request->get('search', ''));
  642. $hasActiveSearch = ($search !== '');
  643. if (!$hasActiveSearch) {
  644. $filterStr = $this->request->get('filter', '');
  645. if ($filterStr !== '' && $filterStr !== '[]' && $filterStr !== '{}') {
  646. $arr = json_decode($filterStr, true);
  647. if (is_array($arr) && count($arr) > 0) {
  648. foreach ($arr as $v) {
  649. if (is_array($v)) {
  650. if (array_filter($v, function ($x) {
  651. return $x !== '' && $x !== null;
  652. })) {
  653. $hasActiveSearch = true;
  654. break;
  655. }
  656. } elseif ($v !== '' && $v !== null) {
  657. $hasActiveSearch = true;
  658. break;
  659. }
  660. }
  661. }
  662. }
  663. }
  664. $applyMonthRange = !$hasActiveSearch;
  665. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  666. $opArr = (array)json_decode($this->request->get('op', ''), true);
  667. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  668. $wffTab = $this->resolveProcuremenListStage();
  669. try {
  670. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  671. if ($wffTab === 'audit') {
  672. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  673. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  674. );
  675. } elseif ($wffTab === 'confirm') {
  676. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  677. $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange)
  678. );
  679. } else {
  680. $pool = $this->procuremenEnsureRedisPool();
  681. if (!is_array($pool)) {
  682. $pool = [];
  683. }
  684. // 下发列表:已通知供应商(有明细)或已进入审核/确认/完结的工序不再显示
  685. $hideSet = $this->loadPickHiddenScydgySet();
  686. if ($pool !== [] && $hideSet !== []) {
  687. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  688. if (!is_array($r)) {
  689. return false;
  690. }
  691. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  692. return $id <= 0 || !isset($hideSet[$id]);
  693. }));
  694. }
  695. $manualPool = $this->loadPickManualOrderRows();
  696. if ($manualPool !== []) {
  697. $pool = array_merge($pool, $manualPool);
  698. }
  699. if ($pool === []) {
  700. return json([
  701. 'total' => 0,
  702. 'rows' => [],
  703. ]);
  704. }
  705. }
  706. $filtered = $this->filterProcuremenIndexPool(
  707. $pool,
  708. $monthStart,
  709. $monthEnd,
  710. $applyMonthRange,
  711. $search,
  712. $filterArr,
  713. $opArr,
  714. $listTimePrimary
  715. );
  716. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  717. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  718. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  719. }
  720. $sortField = 'ID';
  721. if (is_string($sort) && $sort !== '') {
  722. $parts = explode(',', $sort);
  723. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  724. if ($sortField === '') {
  725. $sortField = 'ID';
  726. }
  727. }
  728. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  729. $nFiltered = count($filtered);
  730. if ($nFiltered > 1) {
  731. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  732. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  733. $ta = $this->procuremenRowListSortTime($a, $sortField);
  734. $tb = $this->procuremenRowListSortTime($b, $sortField);
  735. if ($ta === $tb) {
  736. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  737. }
  738. if ($ta === '') {
  739. return 1;
  740. }
  741. if ($tb === '') {
  742. return -1;
  743. }
  744. return strcmp($ta, $tb) * $ord;
  745. });
  746. } elseif ($sortField === 'ID') {
  747. $sortKeys = [];
  748. foreach ($filtered as $i => $row) {
  749. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  750. }
  751. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  752. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  753. } elseif ($sortField === 'CCYDH') {
  754. usort($filtered, function ($a, $b) use ($ord) {
  755. $sa = trim((string)($a['CCYDH'] ?? ''));
  756. $sb = trim((string)($b['CCYDH'] ?? ''));
  757. if ($sa === $sb) {
  758. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  759. }
  760. if ($sa === '') {
  761. return 1;
  762. }
  763. if ($sb === '') {
  764. return -1;
  765. }
  766. return strcmp($sa, $sb) * $ord;
  767. });
  768. } else {
  769. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  770. $va = $a[$sortField] ?? null;
  771. $vb = $b[$sortField] ?? null;
  772. $sa = (string)$va;
  773. $sb = (string)$vb;
  774. if ($sa === $sb) {
  775. return 0;
  776. }
  777. return strcmp($sa, $sb) * $ord;
  778. });
  779. }
  780. }
  781. $offset = max(0, (int)$offset);
  782. $limit = max(1, (int)$limit);
  783. $rows = array_slice($filtered, $offset, $limit);
  784. foreach ($rows as &$rw) {
  785. if (!is_array($rw)) {
  786. continue;
  787. }
  788. $rid = (int)($rw['ID'] ?? 0);
  789. $rw['_iss_out'] = ($wffTab !== 'pick');
  790. }
  791. unset($rw);
  792. if ($wffTab === 'confirm' && count($rows) > 0) {
  793. $idList = [];
  794. foreach ($rows as $rw) {
  795. if (!is_array($rw)) {
  796. continue;
  797. }
  798. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  799. foreach ($rw['_order_merge_rows'] as $mr) {
  800. $mid = (int)($mr['ID'] ?? 0);
  801. if ($this->isValidScydgyRowId($mid)) {
  802. $idList[$mid] = true;
  803. }
  804. }
  805. }
  806. $id = (int)($rw['ID'] ?? 0);
  807. if ($this->isValidScydgyRowId($id)) {
  808. $idList[$id] = true;
  809. }
  810. }
  811. $sumMap = $this->OrderDetailSummary(array_keys($idList));
  812. foreach ($rows as &$rw) {
  813. if (!is_array($rw)) {
  814. continue;
  815. }
  816. $mergeIds = [];
  817. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  818. foreach ($rw['_order_merge_rows'] as $mr) {
  819. $mid = (int)($mr['ID'] ?? 0);
  820. if ($this->isValidScydgyRowId($mid)) {
  821. $mergeIds[$mid] = true;
  822. }
  823. }
  824. }
  825. $rid = (int)($rw['ID'] ?? 0);
  826. if ($this->isValidScydgyRowId($rid)) {
  827. $mergeIds[$rid] = true;
  828. }
  829. $cnt = 0;
  830. $amt = 0;
  831. $deliv = 0;
  832. foreach (array_keys($mergeIds) as $mid) {
  833. $s = isset($sumMap[$mid]) ? $sumMap[$mid] : ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  834. $cnt += (int)($s['cnt'] ?? 0);
  835. $amt += (int)($s['amt'] ?? 0);
  836. $deliv += (int)($s['deliv'] ?? 0);
  837. }
  838. $rw['po_detail_count'] = $cnt;
  839. $rw['po_amount_fill_cnt'] = $amt;
  840. $rw['po_delivery_fill_cnt'] = $deliv;
  841. }
  842. unset($rw);
  843. }
  844. if ($wffTab === 'confirm' && count($rows) > 0) {
  845. $idList = [];
  846. foreach ($rows as $rw) {
  847. if (!is_array($rw)) {
  848. continue;
  849. }
  850. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  851. foreach ($rw['_order_merge_rows'] as $mr) {
  852. $mid = (int)($mr['ID'] ?? 0);
  853. if ($this->isValidScydgyRowId($mid)) {
  854. $idList[$mid] = true;
  855. }
  856. }
  857. }
  858. $id = (int)($rw['ID'] ?? 0);
  859. if ($this->isValidScydgyRowId($id)) {
  860. $idList[$id] = true;
  861. }
  862. }
  863. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  864. foreach ($rows as &$rw) {
  865. if (!is_array($rw)) {
  866. continue;
  867. }
  868. $mergeIds = [];
  869. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  870. foreach ($rw['_order_merge_rows'] as $mr) {
  871. $mid = (int)($mr['ID'] ?? 0);
  872. if ($this->isValidScydgyRowId($mid)) {
  873. $mergeIds[$mid] = true;
  874. }
  875. }
  876. }
  877. $rid = (int)($rw['ID'] ?? 0);
  878. if ($this->isValidScydgyRowId($rid)) {
  879. $mergeIds[$rid] = true;
  880. }
  881. $buckets = [];
  882. foreach (array_keys($mergeIds) as $mid) {
  883. if (isset($quoteBucket[$mid])) {
  884. $buckets[] = $quoteBucket[$mid];
  885. }
  886. }
  887. $rw['picked_supplier_name'] = $buckets !== []
  888. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  889. : '';
  890. }
  891. unset($rw);
  892. }
  893. if ($wffTab === 'audit' && count($rows) > 0) {
  894. $idList = [];
  895. foreach ($rows as $rw) {
  896. if (!is_array($rw)) {
  897. continue;
  898. }
  899. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  900. foreach ($rw['_order_merge_rows'] as $mr) {
  901. $mid = (int)($mr['ID'] ?? 0);
  902. if ($this->isValidScydgyRowId($mid)) {
  903. $idList[$mid] = true;
  904. }
  905. }
  906. }
  907. $id = (int)($rw['ID'] ?? 0);
  908. if ($this->isValidScydgyRowId($id)) {
  909. $idList[$id] = true;
  910. }
  911. }
  912. $notifyMap = $this->loadNotifySupplierNamesByScydgyIds(array_keys($idList));
  913. foreach ($rows as &$rw) {
  914. if (!is_array($rw)) {
  915. continue;
  916. }
  917. $mergeIds = [];
  918. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  919. foreach ($rw['_order_merge_rows'] as $mr) {
  920. $mid = (int)($mr['ID'] ?? 0);
  921. if ($this->isValidScydgyRowId($mid)) {
  922. $mergeIds[$mid] = true;
  923. }
  924. }
  925. }
  926. $rid = (int)($rw['ID'] ?? 0);
  927. if ($this->isValidScydgyRowId($rid)) {
  928. $mergeIds[$rid] = true;
  929. }
  930. $names = [];
  931. foreach (array_keys($mergeIds) as $mid) {
  932. foreach ($notifyMap[$mid] ?? [] as $cn) {
  933. if ($cn !== '' && !in_array($cn, $names, true)) {
  934. $names[] = $cn;
  935. }
  936. }
  937. }
  938. sort($names, SORT_STRING);
  939. $rw['notify_supplier_text'] = $this->formatNotifySupplierDisplay($names);
  940. }
  941. unset($rw);
  942. }
  943. if ($wffTab === 'all' && count($rows) > 0) {
  944. $this->mergePurchaseOrder($rows);
  945. }
  946. if ($wffTab === 'pick' && count($rows) > 0) {
  947. $this->mergePurchaseOrder($rows);
  948. }
  949. foreach ($rows as &$rwClean) {
  950. if (is_array($rwClean)) {
  951. unset($rwClean['_order_merge_rows']);
  952. if (array_key_exists('NGZL', $rwClean)) {
  953. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  954. }
  955. }
  956. }
  957. unset($rwClean);
  958. return json([
  959. 'total' => count($filtered),
  960. 'rows' => $rows,
  961. ]);
  962. } catch (\Throwable $e) {
  963. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  964. return json([
  965. 'total' => 0,
  966. 'rows' => [],
  967. ]);
  968. }
  969. }
  970. /**
  971. * 已协助/不可再审核判定(与「未发」列表隐藏规则一致,避免仅保存数量却被当成已下发)
  972. * - purchase_order.status 为 0 或 1:已审核下发或已完结
  973. * - 或存在 purchase_order_detail:已向供应商下过明细
  974. * 仅写入 purchase_order 且 status 为空:视为未发(如只填本次数量、最高限价)
  975. *
  976. * @return array<int, true> scydgy_id => true
  977. */
  978. protected function loadIssuedScydgySet()
  979. {
  980. $issuedSet = [];
  981. try {
  982. $poList = Db::table('purchase_order')
  983. ->whereRaw('(`status` = 0 OR `status` = 1)')
  984. ->column('scydgy_id');
  985. if (is_array($poList)) {
  986. foreach ($poList as $ids) {
  987. $n = (int)$ids;
  988. if ($n > 0) {
  989. $issuedSet[$n] = true;
  990. }
  991. }
  992. }
  993. } catch (\Throwable $e) {
  994. }
  995. try {
  996. $detList = Db::table('purchase_order_detail');
  997. $this->applyActivePurchaseOrderDetailWhere($detList);
  998. $detList = $detList->group('scydgy_id')->column('scydgy_id');
  999. if (is_array($detList)) {
  1000. foreach ($detList as $ids) {
  1001. $n = (int)$ids;
  1002. if ($n > 0) {
  1003. $issuedSet[$n] = true;
  1004. }
  1005. }
  1006. }
  1007. } catch (\Throwable $e) {
  1008. }
  1009. return $issuedSet;
  1010. }
  1011. /**
  1012. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1013. *
  1014. * @return array<int, true>
  1015. */
  1016. protected function loadPickHiddenScydgySet(): array
  1017. {
  1018. if ($this->pickHiddenScydgySetCache !== null) {
  1019. return $this->pickHiddenScydgySetCache;
  1020. }
  1021. $hideSet = [];
  1022. try {
  1023. $poIds = Db::table('purchase_order')
  1024. ->where(function ($q) {
  1025. $q->where('wflow_status', '>=', 1)
  1026. ->whereOr('status', 1)
  1027. ->whereOr(function ($q2) {
  1028. $q2->whereNotNull('pick_time')
  1029. ->where('pick_time', '<>', '')
  1030. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1031. })
  1032. ->whereOr(function ($q3) {
  1033. $q3->whereNotNull('mod_rq')
  1034. ->where('mod_rq', '<>', '')
  1035. ->where('mod_rq', 'not like', '0000-00-00%');
  1036. });
  1037. })
  1038. ->column('scydgy_id');
  1039. if (is_array($poIds)) {
  1040. foreach ($poIds as $pid) {
  1041. $k = (int)$pid;
  1042. if ($k !== 0) {
  1043. $hideSet[$k] = true;
  1044. }
  1045. }
  1046. }
  1047. } catch (\Throwable $e) {
  1048. }
  1049. try {
  1050. $detIdsQuery = Db::table('purchase_order_detail');
  1051. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1052. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1053. if (is_array($detIds)) {
  1054. foreach ($detIds as $pid) {
  1055. $k = (int)$pid;
  1056. if ($this->isValidScydgyRowId($k)) {
  1057. $hideSet[$k] = true;
  1058. }
  1059. }
  1060. }
  1061. } catch (\Throwable $e) {
  1062. }
  1063. $this->pickHiddenScydgySetCache = $hideSet;
  1064. return $hideSet;
  1065. }
  1066. /**
  1067. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1068. *
  1069. * @return array<int, array<string, mixed>>
  1070. */
  1071. protected function loadPickManualOrderRows(): array
  1072. {
  1073. try {
  1074. $dbRows = Db::table('purchase_order')
  1075. ->where('scydgy_id', '<', 0)
  1076. ->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%\')')
  1077. ->order('scydgy_id', 'asc')
  1078. ->select();
  1079. } catch (\Throwable $e) {
  1080. try {
  1081. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1082. } catch (\Throwable $e2) {
  1083. return [];
  1084. }
  1085. }
  1086. if (!is_array($dbRows) || $dbRows === []) {
  1087. return [];
  1088. }
  1089. $detailSidSet = [];
  1090. try {
  1091. $negIds = [];
  1092. foreach ($dbRows as $dbRow) {
  1093. if (!is_array($dbRow)) {
  1094. continue;
  1095. }
  1096. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1097. if ($sid < 0) {
  1098. $negIds[$sid] = true;
  1099. }
  1100. }
  1101. if ($negIds !== []) {
  1102. $detQuery = Db::table('purchase_order_detail')
  1103. ->where('scydgy_id', 'in', array_keys($negIds));
  1104. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  1105. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  1106. if (is_array($detRows)) {
  1107. foreach ($detRows as $did) {
  1108. $detailSidSet[(int)$did] = true;
  1109. }
  1110. }
  1111. }
  1112. } catch (\Throwable $e) {
  1113. }
  1114. $pool = [];
  1115. foreach ($dbRows as $dbRow) {
  1116. if (!is_array($dbRow)) {
  1117. continue;
  1118. }
  1119. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1120. if ($sid >= 0) {
  1121. continue;
  1122. }
  1123. $wf = (int)($dbRow['wflow_status'] ?? 0);
  1124. if ($wf >= 1) {
  1125. continue;
  1126. }
  1127. $st = trim((string)($dbRow['status'] ?? ''));
  1128. if ($st === '1' || $st === '0') {
  1129. continue;
  1130. }
  1131. if (isset($detailSidSet[$sid])) {
  1132. continue;
  1133. }
  1134. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  1135. $r['_is_manual'] = 1;
  1136. $pool[] = $r;
  1137. }
  1138. return $pool;
  1139. }
  1140. /**
  1141. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  1142. */
  1143. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  1144. {
  1145. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  1146. foreach ($keys as $k) {
  1147. $t = trim((string)($row[$k] ?? ''));
  1148. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1149. return $t;
  1150. }
  1151. }
  1152. return '';
  1153. }
  1154. /**
  1155. * 分配手工新增工序行 ID(负数递减)
  1156. */
  1157. protected function allocateManualScydgyId(): int
  1158. {
  1159. try {
  1160. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  1161. $min = (int)$min;
  1162. return $min < 0 ? $min - 1 : -1;
  1163. } catch (\Throwable $e) {
  1164. return -1;
  1165. }
  1166. }
  1167. /**
  1168. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  1169. */
  1170. protected function allocateManualOrderCcydh(): string
  1171. {
  1172. $prefix = 'YW' . date('Ymd');
  1173. $maxSeq = 0;
  1174. try {
  1175. $rows = Db::table('purchase_order')
  1176. ->where('CCYDH', 'like', $prefix . '%')
  1177. ->column('CCYDH');
  1178. if (is_array($rows)) {
  1179. foreach ($rows as $ccydh) {
  1180. $ccydh = trim((string)$ccydh);
  1181. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  1182. $maxSeq = max($maxSeq, (int)$m[1]);
  1183. }
  1184. }
  1185. }
  1186. } catch (\Throwable $e) {
  1187. }
  1188. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  1189. }
  1190. /**
  1191. * purchase_order.mod_rq 是否有有效软删除时间
  1192. */
  1193. protected function isPurchaseOrderSoftDeleted($modRq): bool
  1194. {
  1195. $t = trim((string)$modRq);
  1196. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  1197. }
  1198. /**
  1199. * 列表行 → purchase_order 写入字段
  1200. *
  1201. * @return array<string, mixed>
  1202. */
  1203. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  1204. {
  1205. return [
  1206. 'scydgy_id' => $scydgyId,
  1207. 'CCYDH' => $row['CCYDH'] ?? null,
  1208. 'CYJMC' => $row['CYJMC'] ?? null,
  1209. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  1210. 'CDXMC' => $row['CDXMC'] ?? null,
  1211. 'CGYBH' => $row['CGYBH'] ?? null,
  1212. 'CGYMC' => $row['CGYMC'] ?? null,
  1213. 'CDW' => $row['CDW'] ?? null,
  1214. 'NGZL' => $row['NGZL'] ?? null,
  1215. 'CDF' => $row['CDF'] ?? null,
  1216. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  1217. 'MBZ' => $row['MBZ'] ?? null,
  1218. 'bwjg' => $row['bwjg'] ?? null,
  1219. 'iStatus' => $row['iStatus'] ?? null,
  1220. 'dStamp' => $row['dStamp'] ?? null,
  1221. 'dputrecord' => $row['dputrecord'] ?? null,
  1222. 'cywyxm' => $row['cywyxm'] ?? null,
  1223. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  1224. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  1225. ];
  1226. }
  1227. /**
  1228. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  1229. */
  1230. protected function softDeleteProcuremenPickRow(array $row): void
  1231. {
  1232. $sid = $this->extractScydgyRowId($row);
  1233. if (!$this->isValidScydgyRowId($sid)) {
  1234. throw new \InvalidArgumentException('无效的行主键');
  1235. }
  1236. $hideSet = $this->loadPickHiddenScydgySet();
  1237. if ($sid > 0 && isset($hideSet[$sid])) {
  1238. throw new \InvalidArgumentException('订单号「' . trim((string)($row['CCYDH'] ?? '')) . '」已下发或已进入后续流程,无法删除');
  1239. }
  1240. if ($sid < 0) {
  1241. try {
  1242. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1243. if (is_array($po)) {
  1244. if ((int)($po['wflow_status'] ?? 0) >= 1) {
  1245. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  1246. }
  1247. if ($this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1248. return;
  1249. }
  1250. }
  1251. } catch (\InvalidArgumentException $e) {
  1252. throw $e;
  1253. } catch (\Throwable $e) {
  1254. }
  1255. }
  1256. $now = date('Y-m-d H:i:s');
  1257. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1258. if (is_array($exists)) {
  1259. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  1260. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  1261. } else {
  1262. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  1263. $data['mod_rq'] = $now;
  1264. $data['createtime'] = $now;
  1265. Db::table('purchase_order')->insert($data);
  1266. $poIdLog = (int)Db::getLastInsID();
  1267. }
  1268. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  1269. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  1270. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  1271. if ($gymcLog !== '') {
  1272. $logTail .= ' / ' . $gymcLog;
  1273. }
  1274. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  1275. }
  1276. /**
  1277. * 手工新增协助工序(写入 purchase_order)
  1278. *
  1279. * @param array<string, mixed> $params
  1280. * @return int scydgy_id
  1281. */
  1282. protected function saveManualPickOrder(array $params): int
  1283. {
  1284. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  1285. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  1286. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  1287. if ($ccydh === '') {
  1288. $ccydh = $this->allocateManualOrderCcydh();
  1289. }
  1290. $now = date('Y-m-d H:i:s');
  1291. $sid = $this->allocateManualScydgyId();
  1292. $data = [
  1293. 'scydgy_id' => $sid,
  1294. 'CCYDH' => $ccydh,
  1295. 'CYJMC' => $cyjmc,
  1296. 'CGYMC' => $cgymc,
  1297. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  1298. 'CDW' => trim((string)($params['CDW'] ?? '')),
  1299. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  1300. 'CDF' => trim((string)($params['CDF'] ?? '')),
  1301. 'cGzzxMc' => trim((string)($params['cGzzxMc'] ?? '')),
  1302. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  1303. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  1304. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  1305. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  1306. 'wflow_status' => 0,
  1307. 'createtime' => $now,
  1308. 'dStamp' => $now,
  1309. 'dputrecord' => $now,
  1310. ];
  1311. Db::table('purchase_order')->insert($data);
  1312. $poId = (int)Db::getLastInsID();
  1313. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  1314. return $sid;
  1315. }
  1316. protected function formatProcuremenRowLabel(array $row): string
  1317. {
  1318. $dh = trim((string)($row['CCYDH'] ?? ''));
  1319. $gymc = trim((string)($row['CGYMC'] ?? ''));
  1320. if ($dh !== '' && $gymc !== '') {
  1321. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  1322. }
  1323. if ($dh !== '') {
  1324. return '订单「' . $dh . '」';
  1325. }
  1326. if ($gymc !== '') {
  1327. return '工序「' . $gymc . '」';
  1328. }
  1329. $id = $this->extractScydgyRowId($row);
  1330. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  1331. }
  1332. /**
  1333. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  1334. */
  1335. protected function extractScydgyRowId(array $row): int
  1336. {
  1337. return (int)($row['ID'] ?? $row['id'] ?? $row['scydgy_id'] ?? 0);
  1338. }
  1339. protected function isValidScydgyRowId(int $id): bool
  1340. {
  1341. return $id !== 0;
  1342. }
  1343. protected function isManualScydgyRowId(int $id): bool
  1344. {
  1345. return $id < 0;
  1346. }
  1347. /**
  1348. * 采购确认已选定供应商:明细 purchase_order_detail.status = 1 的工序行 scydgy_id 集合
  1349. *
  1350. * @return array<int, true>
  1351. */
  1352. protected function loadScydgyIdsWithPickedSupplierDetail(): array
  1353. {
  1354. $set = [];
  1355. try {
  1356. $rows = Db::table('purchase_order_detail')->where('status', 1)->field('scydgy_id')->select();
  1357. } catch (\Throwable $e) {
  1358. $rows = [];
  1359. }
  1360. if (!is_array($rows)) {
  1361. return $set;
  1362. }
  1363. foreach ($rows as $r) {
  1364. if (!is_array($r)) {
  1365. continue;
  1366. }
  1367. $sid = (int)($r['scydgy_id'] ?? $r['SCYDGY_ID'] ?? 0);
  1368. if ($sid > 0) {
  1369. $set[$sid] = true;
  1370. }
  1371. }
  1372. return $set;
  1373. }
  1374. /**
  1375. * 每个工序行对应已选中供应商名称(取 status=1 的首条明细 company_name)
  1376. *
  1377. * @param int[] $scydgyIds
  1378. * @return array<int, string> scydgy_id => company_name
  1379. */
  1380. protected function loadPickedSupplierCompanyByScydgyIds(array $scydgyIds): array
  1381. {
  1382. $out = [];
  1383. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1384. if ($scydgyIds === []) {
  1385. return $out;
  1386. }
  1387. try {
  1388. $rows = Db::table('purchase_order_detail')
  1389. ->where('scydgy_id', 'in', $scydgyIds)
  1390. ->where('status', 1)
  1391. ->field('scydgy_id,company_name')
  1392. ->order('id', 'asc')
  1393. ->select();
  1394. } catch (\Throwable $e) {
  1395. try {
  1396. $rows = Db::table('purchase_order_detail')
  1397. ->where('scydgy_id', 'in', $scydgyIds)
  1398. ->where('status', 1)
  1399. ->field('scydgy_id,company_name')
  1400. ->order('ID', 'asc')
  1401. ->select();
  1402. } catch (\Throwable $e2) {
  1403. $rows = [];
  1404. }
  1405. }
  1406. if (!is_array($rows)) {
  1407. return $out;
  1408. }
  1409. foreach ($rows as $r) {
  1410. if (!is_array($r)) {
  1411. continue;
  1412. }
  1413. $sid = (int)($r['scydgy_id'] ?? $r['SCYDGY_ID'] ?? 0);
  1414. if (!$this->isValidScydgyRowId($sid) || isset($out[$sid])) {
  1415. continue;
  1416. }
  1417. $name = trim((string)($r['company_name'] ?? ''));
  1418. $out[$sid] = $name;
  1419. }
  1420. return $out;
  1421. }
  1422. /**
  1423. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  1424. *
  1425. * @param int[] $scydgyIds
  1426. * @return array<int, string[]>
  1427. */
  1428. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  1429. {
  1430. $out = [];
  1431. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1432. if ($scydgyIds === []) {
  1433. return $out;
  1434. }
  1435. try {
  1436. $rows = Db::table('purchase_order_detail')
  1437. ->where('scydgy_id', 'in', $scydgyIds)
  1438. ->field('scydgy_id,company_name')
  1439. ->order('company_name', 'asc')
  1440. ->select();
  1441. } catch (\Throwable $e) {
  1442. $rows = [];
  1443. }
  1444. if (!is_array($rows)) {
  1445. return $out;
  1446. }
  1447. foreach ($rows as $r) {
  1448. if (!is_array($r)) {
  1449. continue;
  1450. }
  1451. $sid = (int)($r['scydgy_id'] ?? 0);
  1452. $cn = trim((string)($r['company_name'] ?? ''));
  1453. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1454. continue;
  1455. }
  1456. if (!isset($out[$sid])) {
  1457. $out[$sid] = [];
  1458. }
  1459. if (!in_array($cn, $out[$sid], true)) {
  1460. $out[$sid][] = $cn;
  1461. }
  1462. }
  1463. return $out;
  1464. }
  1465. /**
  1466. * 列表展示通知供应商(完整列表,前端单行省略展开)
  1467. *
  1468. * @param string[] $names
  1469. */
  1470. protected function formatNotifySupplierDisplay(array $names): string
  1471. {
  1472. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  1473. return trim((string)$n);
  1474. }, $names))));
  1475. if ($names === []) {
  1476. return '';
  1477. }
  1478. sort($names, SORT_STRING);
  1479. return implode('、', $names);
  1480. }
  1481. /**
  1482. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  1483. *
  1484. * @param int[] $scydgyIds
  1485. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  1486. */
  1487. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  1488. {
  1489. $out = [];
  1490. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1491. if ($scydgyIds === []) {
  1492. return $out;
  1493. }
  1494. try {
  1495. $rows = Db::table('purchase_order_detail')
  1496. ->where('scydgy_id', 'in', $scydgyIds)
  1497. ->field('scydgy_id,company_name,amount')
  1498. ->select();
  1499. } catch (\Throwable $e) {
  1500. $rows = [];
  1501. }
  1502. if (!is_array($rows)) {
  1503. return $out;
  1504. }
  1505. foreach ($rows as $r) {
  1506. if (!is_array($r)) {
  1507. continue;
  1508. }
  1509. $sid = (int)($r['scydgy_id'] ?? 0);
  1510. $cn = trim((string)($r['company_name'] ?? ''));
  1511. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1512. continue;
  1513. }
  1514. if (!isset($out[$sid])) {
  1515. $out[$sid] = ['all' => [], 'quoted' => []];
  1516. }
  1517. $out[$sid]['all'][$cn] = true;
  1518. $am = trim((string)($r['amount'] ?? ''));
  1519. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1520. $out[$sid]['quoted'][$cn] = true;
  1521. }
  1522. }
  1523. return $out;
  1524. }
  1525. /**
  1526. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  1527. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  1528. */
  1529. protected function mergeQuotedSupplierBuckets(array $buckets): array
  1530. {
  1531. $merged = ['all' => [], 'quoted' => []];
  1532. foreach ($buckets as $b) {
  1533. if (!is_array($b)) {
  1534. continue;
  1535. }
  1536. foreach ($b['all'] ?? [] as $cn => $_) {
  1537. $merged['all'][$cn] = true;
  1538. }
  1539. foreach ($b['quoted'] ?? [] as $cn => $_) {
  1540. $merged['quoted'][$cn] = true;
  1541. }
  1542. }
  1543. return $merged;
  1544. }
  1545. /**
  1546. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  1547. */
  1548. protected function formatQuotedSupplierLines(array $bucket): string
  1549. {
  1550. $all = array_keys($bucket['all'] ?? []);
  1551. if ($all === []) {
  1552. return '';
  1553. }
  1554. sort($all, SORT_STRING);
  1555. $lines = [];
  1556. foreach ($all as $cn) {
  1557. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  1558. $lines[] = $cn . '(' . $status . ')';
  1559. }
  1560. return implode("\n", $lines);
  1561. }
  1562. /**
  1563. * @param int[] $scydgyIds
  1564. * @return array<int, string>
  1565. */
  1566. protected function loadQuotedSupplierSummaryByScydgyIds(array $scydgyIds): array
  1567. {
  1568. $out = [];
  1569. foreach ($this->loadQuotedSupplierBucketByScydgyIds($scydgyIds) as $sid => $bucket) {
  1570. $text = $this->formatQuotedSupplierLines($bucket);
  1571. if ($text !== '') {
  1572. $out[$sid] = $text;
  1573. }
  1574. }
  1575. return $out;
  1576. }
  1577. /**
  1578. * 审核弹窗:按供应商汇总报价明细
  1579. *
  1580. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  1581. * @return array<int, array<string, mixed>>
  1582. */
  1583. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  1584. {
  1585. $sids = [];
  1586. foreach ($bundle['pos'] ?? [] as $po) {
  1587. if (!is_array($po)) {
  1588. continue;
  1589. }
  1590. $sid = (int)($po['scydgy_id'] ?? 0);
  1591. if ($this->isValidScydgyRowId($sid)) {
  1592. $sids[$sid] = true;
  1593. }
  1594. }
  1595. if ($sids === []) {
  1596. return [];
  1597. }
  1598. $gymcMap = [];
  1599. $qtyBySid = [];
  1600. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  1601. if (!is_array($mr)) {
  1602. continue;
  1603. }
  1604. $gid = $this->extractScydgyRowId($mr);
  1605. if ($this->isValidScydgyRowId($gid)) {
  1606. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  1607. $qty = trim((string)($mr['This_quantity'] ?? ''));
  1608. if ($qty === '') {
  1609. $qty = trim((string)($mr['NGZL'] ?? ''));
  1610. }
  1611. $qtyBySid[$gid] = $qty;
  1612. }
  1613. }
  1614. foreach ($bundle['pos'] ?? [] as $po) {
  1615. if (!is_array($po)) {
  1616. continue;
  1617. }
  1618. $gid = (int)($po['scydgy_id'] ?? 0);
  1619. if ($this->isValidScydgyRowId($gid)) {
  1620. $nm = trim((string)($po['CGYMC'] ?? ''));
  1621. if ($nm !== '') {
  1622. $gymcMap[$gid] = $nm;
  1623. }
  1624. }
  1625. }
  1626. try {
  1627. $detailsQuery = Db::table('purchase_order_detail')
  1628. ->where('scydgy_id', 'in', array_keys($sids));
  1629. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  1630. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  1631. } catch (\Throwable $e) {
  1632. try {
  1633. $detailsQuery = Db::table('purchase_order_detail')
  1634. ->where('scydgy_id', 'in', array_keys($sids));
  1635. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  1636. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  1637. } catch (\Throwable $e2) {
  1638. $details = [];
  1639. }
  1640. }
  1641. if (!is_array($details)) {
  1642. $details = [];
  1643. }
  1644. $byCompany = [];
  1645. foreach ($details as $d) {
  1646. if (!is_array($d)) {
  1647. continue;
  1648. }
  1649. $cn = trim((string)($d['company_name'] ?? ''));
  1650. if ($cn === '') {
  1651. continue;
  1652. }
  1653. if (!isset($byCompany[$cn])) {
  1654. $ph = trim((string)($d['phone'] ?? ''));
  1655. $username = trim((string)($d['username'] ?? ''));
  1656. if ($username === '') {
  1657. $username = $this->resolveCustomerContactName($ph, $cn);
  1658. }
  1659. $byCompany[$cn] = [
  1660. 'name' => $cn,
  1661. 'email' => trim((string)($d['email'] ?? '')),
  1662. 'phone' => $ph,
  1663. 'username' => $username,
  1664. 'has_quote' => false,
  1665. 'lines' => [],
  1666. ];
  1667. }
  1668. $sid = (int)($d['scydgy_id'] ?? 0);
  1669. $am = trim((string)($d['amount'] ?? ''));
  1670. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  1671. if ($gymc === '') {
  1672. $gymc = '工序';
  1673. }
  1674. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  1675. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  1676. if ($deliveryShow === '' && $deliveryRaw !== '') {
  1677. $deliveryShow = $deliveryRaw;
  1678. }
  1679. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  1680. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  1681. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  1682. $subtotal = null;
  1683. if ($amountNum !== null) {
  1684. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  1685. }
  1686. $unitPriceText = $amountFilled
  1687. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  1688. : '未填写';
  1689. $byCompany[$cn]['lines'][] = [
  1690. 'cgymc' => $gymc,
  1691. 'amount' => $am,
  1692. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  1693. 'amount_filled' => $amountFilled,
  1694. 'unit_price_text' => $unitPriceText,
  1695. 'delivery' => $deliveryRaw,
  1696. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  1697. 'delivery_filled' => $deliveryFilled,
  1698. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  1699. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  1700. 'subtotal_num' => $subtotal,
  1701. 'status_name' => trim((string)($d['status_name'] ?? '')),
  1702. 'is_quoted' => $amountFilled,
  1703. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  1704. ];
  1705. }
  1706. foreach ($byCompany as $cn => $g) {
  1707. $total = count($g['lines']);
  1708. $quoted = 0;
  1709. $groupTotal = 0.0;
  1710. $groupHasTotal = false;
  1711. foreach ($g['lines'] as $ln) {
  1712. $am = trim((string)($ln['amount'] ?? ''));
  1713. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1714. $quoted++;
  1715. }
  1716. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  1717. $groupTotal += (float)$ln['subtotal_num'];
  1718. $groupHasTotal = true;
  1719. }
  1720. }
  1721. $byCompany[$cn]['has_quote'] = $total > 0 && $quoted === $total;
  1722. $byCompany[$cn]['line_count'] = $total;
  1723. $byCompany[$cn]['has_total'] = $total > 0;
  1724. $byCompany[$cn]['total_text'] = $groupHasTotal ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  1725. $byCompany[$cn]['display_rowspan'] = $total + ($total > 0 ? 1 : 0);
  1726. }
  1727. return array_values($byCompany);
  1728. }
  1729. /**
  1730. * 确认供应商弹窗:通知对象(不含报价,仅工序与联系方式)
  1731. *
  1732. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  1733. * @return array<int, array<string, mixed>>
  1734. */
  1735. protected function loadAuditSupplierNotifyGroups(array $bundle): array
  1736. {
  1737. $groups = $this->loadAuditSupplierQuoteGroups($bundle);
  1738. $out = [];
  1739. foreach ($groups as $g) {
  1740. if (!is_array($g)) {
  1741. continue;
  1742. }
  1743. $processNames = [];
  1744. foreach ($g['lines'] ?? [] as $ln) {
  1745. if (!is_array($ln)) {
  1746. continue;
  1747. }
  1748. $n = trim((string)($ln['cgymc'] ?? ''));
  1749. if ($n !== '' && !in_array($n, $processNames, true)) {
  1750. $processNames[] = $n;
  1751. }
  1752. }
  1753. $out[] = [
  1754. 'name' => trim((string)($g['name'] ?? '')),
  1755. 'email' => trim((string)($g['email'] ?? '')),
  1756. 'phone' => trim((string)($g['phone'] ?? '')),
  1757. 'username' => trim((string)($g['username'] ?? '')),
  1758. 'process_names' => $processNames,
  1759. 'process_text' => implode('、', $processNames),
  1760. ];
  1761. }
  1762. return $out;
  1763. }
  1764. /**
  1765. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  1766. *
  1767. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  1768. * @return array<int, array<string, mixed>>
  1769. */
  1770. protected function loadConfirmSupplierPickGroups(array $bundle): array
  1771. {
  1772. $sids = [];
  1773. $poIdMap = [];
  1774. foreach ($bundle['pos'] ?? [] as $po) {
  1775. if (!is_array($po)) {
  1776. continue;
  1777. }
  1778. $sid = (int)($po['scydgy_id'] ?? 0);
  1779. if ($this->isValidScydgyRowId($sid)) {
  1780. $sids[$sid] = true;
  1781. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  1782. }
  1783. }
  1784. if ($sids === []) {
  1785. return [];
  1786. }
  1787. $gymcMap = [];
  1788. $qtyBySid = [];
  1789. $orderedSids = [];
  1790. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  1791. if (!is_array($mr)) {
  1792. continue;
  1793. }
  1794. $gid = $this->extractScydgyRowId($mr);
  1795. if ($this->isValidScydgyRowId($gid)) {
  1796. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  1797. $orderedSids[] = $gid;
  1798. $qty = trim((string)($mr['This_quantity'] ?? ''));
  1799. if ($qty === '') {
  1800. $qty = trim((string)($mr['NGZL'] ?? ''));
  1801. }
  1802. $qtyBySid[$gid] = $qty;
  1803. }
  1804. }
  1805. foreach ($bundle['pos'] ?? [] as $po) {
  1806. if (!is_array($po)) {
  1807. continue;
  1808. }
  1809. $gid = (int)($po['scydgy_id'] ?? 0);
  1810. if ($this->isValidScydgyRowId($gid)) {
  1811. $nm = trim((string)($po['CGYMC'] ?? ''));
  1812. if ($nm !== '') {
  1813. $gymcMap[$gid] = $nm;
  1814. }
  1815. }
  1816. }
  1817. try {
  1818. $details = Db::table('purchase_order_detail')
  1819. ->where('scydgy_id', 'in', array_keys($sids))
  1820. ->order('company_name', 'asc')
  1821. ->order('id', 'asc')
  1822. ->select();
  1823. } catch (\Throwable $e) {
  1824. try {
  1825. $details = Db::table('purchase_order_detail')
  1826. ->where('scydgy_id', 'in', array_keys($sids))
  1827. ->order('company_name', 'asc')
  1828. ->order('ID', 'asc')
  1829. ->select();
  1830. } catch (\Throwable $e2) {
  1831. $details = [];
  1832. }
  1833. }
  1834. if (!is_array($details)) {
  1835. $details = [];
  1836. }
  1837. $byCompany = [];
  1838. foreach ($details as $d) {
  1839. if (!is_array($d)) {
  1840. continue;
  1841. }
  1842. $cn = trim((string)($d['company_name'] ?? ''));
  1843. if ($cn === '') {
  1844. continue;
  1845. }
  1846. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  1847. $sid = (int)($d['scydgy_id'] ?? 0);
  1848. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  1849. continue;
  1850. }
  1851. if (!isset($byCompany[$cn])) {
  1852. $ph = trim((string)($d['phone'] ?? ''));
  1853. $username = trim((string)($d['username'] ?? ''));
  1854. if ($username === '') {
  1855. $username = $this->resolveCustomerContactName($ph, $cn);
  1856. }
  1857. $byCompany[$cn] = [
  1858. 'name' => $cn,
  1859. 'email' => trim((string)($d['email'] ?? '')),
  1860. 'phone' => $ph,
  1861. 'username' => $username,
  1862. 'pick_lines' => [],
  1863. 'detail_picks' => [],
  1864. ];
  1865. }
  1866. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  1867. if ($gymc === '') {
  1868. $gymc = '工序';
  1869. }
  1870. $am = trim((string)($d['amount'] ?? ''));
  1871. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  1872. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  1873. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  1874. if ($deliveryShow === '' && $deliveryRaw !== '') {
  1875. $deliveryShow = $deliveryRaw;
  1876. }
  1877. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  1878. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  1879. $subtotal = null;
  1880. if ($amountNum !== null) {
  1881. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  1882. }
  1883. $unitPriceText = $amountFilled
  1884. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  1885. : '未填写';
  1886. $byCompany[$cn]['pick_lines'][$sid] = [
  1887. 'cgymc' => $gymc,
  1888. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  1889. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  1890. 'amount_filled' => $amountFilled,
  1891. 'delivery_filled' => $deliveryFilled,
  1892. 'unit_price_text' => $unitPriceText,
  1893. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  1894. 'subtotal_num' => $subtotal,
  1895. 'is_quoted' => $amountFilled,
  1896. ];
  1897. $byCompany[$cn]['detail_picks'][$sid] = [
  1898. 'scydgy_id' => $sid,
  1899. 'detail_id' => $detailId,
  1900. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  1901. 'cgymc' => $gymc,
  1902. ];
  1903. }
  1904. $out = [];
  1905. foreach ($byCompany as $g) {
  1906. $pickLinesMap = $g['pick_lines'] ?? [];
  1907. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  1908. continue;
  1909. }
  1910. $pickLines = [];
  1911. $usedLineSids = [];
  1912. foreach ($orderedSids as $sid) {
  1913. if (!isset($pickLinesMap[$sid])) {
  1914. continue;
  1915. }
  1916. $pickLines[] = $pickLinesMap[$sid];
  1917. $usedLineSids[$sid] = true;
  1918. }
  1919. foreach ($pickLinesMap as $sid => $ln) {
  1920. if (isset($usedLineSids[$sid])) {
  1921. continue;
  1922. }
  1923. $pickLines[] = $ln;
  1924. }
  1925. $groupTotal = 0.0;
  1926. $groupHasTotal = false;
  1927. foreach ($pickLines as $ln) {
  1928. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  1929. $groupTotal += (float)$ln['subtotal_num'];
  1930. $groupHasTotal = true;
  1931. }
  1932. }
  1933. $lineCount = count($pickLines);
  1934. $g['pick_lines'] = $pickLines;
  1935. $g['line_count'] = $lineCount;
  1936. $g['has_total'] = $lineCount > 0;
  1937. $g['total_text'] = $groupHasTotal ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  1938. $g['display_rowspan'] = $lineCount + ($lineCount > 0 ? 1 : 0);
  1939. $detailPicks = $g['detail_picks'] ?? [];
  1940. $g['detail_picks'] = array_values(is_array($detailPicks) ? $detailPicks : []);
  1941. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  1942. unset($g['detail_picks']);
  1943. $out[] = $g;
  1944. }
  1945. return $out;
  1946. }
  1947. /**
  1948. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  1949. * @return array<int, int[]> scydgy_id => detail_id[]
  1950. */
  1951. protected function mapDetailIdsByScydgyId(array $details): array
  1952. {
  1953. $out = [];
  1954. foreach ($details as $d) {
  1955. if (!is_array($d)) {
  1956. continue;
  1957. }
  1958. $sid = (int)($d['scydgy_id'] ?? 0);
  1959. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  1960. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  1961. continue;
  1962. }
  1963. if (!isset($out[$sid])) {
  1964. $out[$sid] = [];
  1965. }
  1966. $out[$sid][] = $pk;
  1967. }
  1968. foreach ($out as $sid => $ids) {
  1969. $out[$sid] = array_values(array_unique($ids));
  1970. }
  1971. return $out;
  1972. }
  1973. /**
  1974. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  1975. *
  1976. * @param array<string, mixed> $dbRow
  1977. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  1978. */
  1979. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  1980. {
  1981. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1982. $r = [
  1983. 'ID' => $sid,
  1984. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  1985. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  1986. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  1987. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  1988. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  1989. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  1990. 'CDW' => $dbRow['CDW'] ?? '',
  1991. 'NGZL' => $dbRow['NGZL'] ?? '',
  1992. 'CDF' => $dbRow['CDF'] ?? '',
  1993. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  1994. 'MBZ' => $dbRow['MBZ'] ?? '',
  1995. 'bwjg' => $dbRow['bwjg'] ?? '',
  1996. 'iStatus' => $dbRow['iStatus'] ?? '',
  1997. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  1998. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  1999. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  2000. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  2001. 'dStamp' => $dbRow['dStamp'] ?? '',
  2002. 'pick_time' => $dbRow['pick_time'] ?? '',
  2003. ];
  2004. if ($sid > 0 && isset($dStampMap[$sid])) {
  2005. $t = trim((string)$dStampMap[$sid]);
  2006. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2007. $r['dStamp'] = $dStampMap[$sid];
  2008. }
  2009. }
  2010. $dsOut = trim((string)($r['dStamp'] ?? ''));
  2011. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  2012. $ct = $dbRow['createtime'];
  2013. if (is_numeric($ct) && (int)$ct > 946684800) {
  2014. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  2015. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  2016. $r['dStamp'] = trim($ct);
  2017. }
  2018. }
  2019. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  2020. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  2021. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  2022. $fallback = trim((string)($r['dStamp'] ?? ''));
  2023. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  2024. $r['dputrecord'] = $fallback;
  2025. }
  2026. }
  2027. if (array_key_exists('id', $dbRow)) {
  2028. $r['purchase_order_id'] = (int)$dbRow['id'];
  2029. }
  2030. if ($sid < 0) {
  2031. $r['_is_manual'] = 1;
  2032. }
  2033. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  2034. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  2035. if ($pickNm !== '') {
  2036. $r['pick_company_name'] = $pickNm;
  2037. $r['picked_supplier_name'] = $pickNm;
  2038. }
  2039. return $r;
  2040. }
  2041. /**
  2042. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  2043. *
  2044. * @return array<int, array<string, mixed>>
  2045. */
  2046. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  2047. {
  2048. $pool = [];
  2049. if (!is_array($dbRows) || $dbRows === []) {
  2050. return $pool;
  2051. }
  2052. $dStampMap = [];
  2053. $sidList = [];
  2054. foreach ($dbRows as $tmpRow) {
  2055. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  2056. $sid = (int)$tmpRow['scydgy_id'];
  2057. if ($sid > 0) {
  2058. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  2059. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2060. $sidList[$sid] = true;
  2061. }
  2062. }
  2063. }
  2064. }
  2065. if ($sidList !== []) {
  2066. try {
  2067. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  2068. } catch (\Throwable $e) {
  2069. $dStampMap = [];
  2070. }
  2071. }
  2072. foreach ($dbRows as $dbRow) {
  2073. if (!is_array($dbRow)) {
  2074. continue;
  2075. }
  2076. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  2077. }
  2078. return $pool;
  2079. }
  2080. /**
  2081. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  2082. *
  2083. * @param int[] $scydgyIds
  2084. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  2085. */
  2086. protected function OrderDetailSummary(array $scydgyIds)
  2087. {
  2088. $out = [];
  2089. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2090. if ($scydgyIds === []) {
  2091. return $out;
  2092. }
  2093. $list = [];
  2094. try {
  2095. $list = Db::table('purchase_order_detail')
  2096. ->where('scydgy_id', 'in', $scydgyIds)
  2097. ->field('id,scydgy_id,amount,delivery')
  2098. ->select();
  2099. } catch (\Throwable $e) {
  2100. $list = [];
  2101. }
  2102. if (!is_array($list)) {
  2103. return $out;
  2104. }
  2105. foreach ($list as $r) {
  2106. if (!is_array($r)) {
  2107. continue;
  2108. }
  2109. $ids = (int)($r['scydgy_id'] ?? 0);
  2110. if (!$this->isValidScydgyRowId($ids)) {
  2111. continue;
  2112. }
  2113. if (!isset($out[$ids])) {
  2114. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2115. }
  2116. $out[$ids]['cnt']++;
  2117. $am = $r['amount'] ?? null;
  2118. if ($am !== null && $am !== '') {
  2119. if (!(is_string($am) && trim($am) === '')) {
  2120. $out[$ids]['amt']++;
  2121. }
  2122. }
  2123. $dv = $r['delivery'] ?? null;
  2124. if ($dv !== null && trim((string)$dv) !== '') {
  2125. $out[$ids]['deliv']++;
  2126. }
  2127. }
  2128. return $out;
  2129. }
  2130. /**
  2131. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  2132. *
  2133. * @return array
  2134. */
  2135. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  2136. {
  2137. $strContains = function ($haystack, $needle) {
  2138. if ($needle === '') {
  2139. return false;
  2140. }
  2141. $haystack = (string)$haystack;
  2142. if (function_exists('mb_stripos')) {
  2143. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  2144. }
  2145. return stripos($haystack, $needle) !== false;
  2146. };
  2147. $stripAlias = function ($f) {
  2148. return preg_replace('/^[ab]\./i', '', (string)$f);
  2149. };
  2150. $searchColNames = [];
  2151. foreach (explode(',', $this->searchFields) as $colRaw) {
  2152. $c = $stripAlias(trim($colRaw));
  2153. if ($c !== '') {
  2154. $searchColNames[] = $c;
  2155. }
  2156. }
  2157. $filtered = [];
  2158. foreach ($pool as $r) {
  2159. if (!is_array($r)) {
  2160. continue;
  2161. }
  2162. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  2163. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  2164. if (!$isManual) {
  2165. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  2166. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  2167. continue;
  2168. }
  2169. if ($applyMonthRange) {
  2170. $mo = (int)$m[2];
  2171. if ($mo < 1 || $mo > 12) {
  2172. continue;
  2173. }
  2174. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2175. $rowMonthStart = $ymRow . '-01 00:00:00';
  2176. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2177. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2178. continue;
  2179. }
  2180. }
  2181. } elseif ($applyMonthRange) {
  2182. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  2183. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2184. $ds = $listTime;
  2185. }
  2186. if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  2187. continue;
  2188. }
  2189. $mo = (int)$m[2];
  2190. if ($mo < 1 || $mo > 12) {
  2191. continue;
  2192. }
  2193. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2194. $rowMonthStart = $ymRow . '-01 00:00:00';
  2195. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2196. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2197. continue;
  2198. }
  2199. }
  2200. if ($search !== '') {
  2201. $hitSearch = false;
  2202. foreach ($searchColNames as $c) {
  2203. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  2204. if ($cell !== '' && $strContains($cell, $search)) {
  2205. $hitSearch = true;
  2206. break;
  2207. }
  2208. }
  2209. if (!$hitSearch) {
  2210. continue;
  2211. }
  2212. }
  2213. foreach ($filterArr as $fk => $fv) {
  2214. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  2215. continue;
  2216. }
  2217. if (is_array($fv)) {
  2218. continue;
  2219. }
  2220. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  2221. continue;
  2222. }
  2223. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  2224. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  2225. $field = $stripAlias($fk);
  2226. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  2227. $cellStr = trim((string)$cell);
  2228. switch ($sym) {
  2229. case '=':
  2230. if ((string)$cell !== (string)$fv) {
  2231. continue 3;
  2232. }
  2233. break;
  2234. case '<>':
  2235. if ((string)$cell === (string)$fv) {
  2236. continue 3;
  2237. }
  2238. break;
  2239. case 'LIKE':
  2240. case 'NOT LIKE':
  2241. $needle = trim((string)$fv);
  2242. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  2243. if ($sym === 'LIKE' && !$hit) {
  2244. continue 3;
  2245. }
  2246. if ($sym === 'NOT LIKE' && $hit) {
  2247. continue 3;
  2248. }
  2249. break;
  2250. case '>':
  2251. case '>=':
  2252. case '<':
  2253. case '<=':
  2254. if (!is_numeric($cell) && $cellStr === '') {
  2255. continue 3;
  2256. }
  2257. $cv = is_numeric($cell) ? (float)$cell : (float)$cellStr;
  2258. $vv = (float)$fv;
  2259. if ($sym === '>' && !($cv > $vv)) {
  2260. continue 3;
  2261. }
  2262. if ($sym === '>=' && !($cv >= $vv)) {
  2263. continue 3;
  2264. }
  2265. if ($sym === '<' && !($cv < $vv)) {
  2266. continue 3;
  2267. }
  2268. if ($sym === '<=' && !($cv <= $vv)) {
  2269. continue 3;
  2270. }
  2271. break;
  2272. case 'RANGE':
  2273. case 'NOT RANGE':
  2274. case 'BETWEEN':
  2275. case 'NOT BETWEEN':
  2276. case 'BETWEEN TIME':
  2277. case 'NOT BETWEEN TIME':
  2278. $rawR = is_array($fv) ? implode(',', $fv) : (string)$fv;
  2279. $rawR = str_replace(' - ', ',', $rawR);
  2280. $arr = array_slice(array_map('trim', explode(',', $rawR)), 0, 2);
  2281. if (count($arr) < 2) {
  2282. break;
  2283. }
  2284. $lo = $arr[0];
  2285. $hi = $arr[1];
  2286. if ($lo === '' && $hi === '') {
  2287. break;
  2288. }
  2289. $isNot = (strpos($sym, 'NOT') !== false);
  2290. if ($lo === '') {
  2291. $in = ($cellStr !== '' && $cellStr <= $hi);
  2292. if ($isNot ? $in : !$in) {
  2293. continue 3;
  2294. }
  2295. break;
  2296. }
  2297. if ($hi === '') {
  2298. $in = ($cellStr !== '' && $cellStr >= $lo);
  2299. if ($isNot ? $in : !$in) {
  2300. continue 3;
  2301. }
  2302. break;
  2303. }
  2304. $in = ($cellStr >= $lo && $cellStr <= $hi);
  2305. if ($isNot ? $in : !$in) {
  2306. continue 3;
  2307. }
  2308. break;
  2309. case 'NULL':
  2310. case 'IS NULL':
  2311. if ($cell !== null && $cell !== '') {
  2312. continue 3;
  2313. }
  2314. break;
  2315. case 'NOT NULL':
  2316. case 'IS NOT NULL':
  2317. if ($cell === null || $cell === '') {
  2318. continue 3;
  2319. }
  2320. break;
  2321. default:
  2322. break;
  2323. }
  2324. }
  2325. $filtered[] = $r;
  2326. }
  2327. return $filtered;
  2328. }
  2329. /**
  2330. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  2331. */
  2332. public function snapshotToProcure()
  2333. {
  2334. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2335. $this->error(__('Invalid parameters'));
  2336. }
  2337. $row = json_decode($this->request->post('row_json', ''), true);
  2338. if (!is_array($row)) {
  2339. $this->error(__('Invalid parameters'));
  2340. }
  2341. try {
  2342. $ids = $this->extractScydgyRowId($row);
  2343. if (!$this->isValidScydgyRowId($ids)) {
  2344. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  2345. }
  2346. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2347. $data = [
  2348. 'scydgy_id' => $ids,
  2349. 'CCYDH' => $row['CCYDH'] ?? null,
  2350. 'CYJMC' => $row['CYJMC'] ?? null,
  2351. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2352. 'CDXMC' => $row['CDXMC'] ?? null,
  2353. 'CGYBH' => $row['CGYBH'] ?? null,
  2354. 'CGYMC' => $row['CGYMC'] ?? null,
  2355. 'CDW' => $row['CDW'] ?? null,
  2356. 'NGZL' => $row['NGZL'] ?? null,
  2357. 'CDF' => $row['CDF'] ?? null,
  2358. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2359. 'MBZ' => $row['MBZ'] ?? null,
  2360. 'bwjg' => $row['bwjg'] ?? null,
  2361. 'iStatus' => $row['iStatus'] ?? null,
  2362. 'dStamp' => $row['dStamp'] ?? null,
  2363. 'dputrecord' => $row['dputrecord'] ?? null,
  2364. 'cywyxm' => $row['cywyxm'] ?? null,
  2365. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2366. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2367. ];
  2368. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  2369. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  2370. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  2371. $this->success('操作成功');
  2372. return;
  2373. }
  2374. if ($exists) {
  2375. $upd = $data;
  2376. unset($upd['scydgy_id'], $upd['status']);
  2377. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  2378. } else {
  2379. // 新增:不写 status(空/走库默认);仅写创建时间
  2380. $data['createtime'] = date('Y-m-d H:i:s');
  2381. Db::table('purchase_order')->insert($data);
  2382. }
  2383. } catch (\Throwable $e) {
  2384. $this->error($e->getMessage());
  2385. }
  2386. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  2387. $this->success('操作成功');
  2388. }
  2389. /**
  2390. * 未发列表
  2391. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  2392. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  2393. */
  2394. public function completeDirectly()
  2395. {
  2396. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2397. $this->error(__('参数错误'));
  2398. }
  2399. $row = json_decode($this->request->post('row_json', ''), true);
  2400. if (!is_array($row)) {
  2401. $this->error(__('Invalid parameters'));
  2402. }
  2403. $finishRaw = $this->request->post('finish', '1');
  2404. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  2405. try {
  2406. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  2407. $ids = $this->extractScydgyRowId($row);
  2408. if (!$this->isValidScydgyRowId($ids)) {
  2409. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  2410. }
  2411. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2412. $data = [
  2413. 'scydgy_id' => $ids,
  2414. 'CCYDH' => $row['CCYDH'] ?? null,
  2415. 'CYJMC' => $row['CYJMC'] ?? null,
  2416. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2417. 'CDXMC' => $row['CDXMC'] ?? null,
  2418. 'CGYBH' => $row['CGYBH'] ?? null,
  2419. 'CGYMC' => $row['CGYMC'] ?? null,
  2420. 'CDW' => $row['CDW'] ?? null,
  2421. 'NGZL' => $row['NGZL'] ?? null,
  2422. 'CDF' => $row['CDF'] ?? null,
  2423. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2424. 'MBZ' => $row['MBZ'] ?? null,
  2425. 'bwjg' => $row['bwjg'] ?? null,
  2426. 'iStatus' => $row['iStatus'] ?? null,
  2427. 'dStamp' => $row['dStamp'] ?? null,
  2428. 'dputrecord' => $row['dputrecord'] ?? null,
  2429. 'cywyxm' => $row['cywyxm'] ?? null,
  2430. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2431. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2432. ];
  2433. if ($asComplete) {
  2434. // 主表 status 为 varchar 时统一写 '1',档案 procuremenarchive 按 status=1 查询
  2435. $data['status'] = '1';
  2436. }
  2437. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  2438. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  2439. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  2440. $this->success('操作成功');
  2441. return;
  2442. }
  2443. if ($exists) {
  2444. $upd = $data;
  2445. unset($upd['scydgy_id']);
  2446. if (!$asComplete) {
  2447. unset($upd['status']);
  2448. }
  2449. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  2450. } else {
  2451. // 新增:不写 status;完结时 $data 已含 status=1
  2452. $data['createtime'] = date('Y-m-d H:i:s');
  2453. Db::table('purchase_order')->insert($data);
  2454. }
  2455. } catch (\Throwable $e) {
  2456. $this->error($e->getMessage());
  2457. }
  2458. $poIdLog = null;
  2459. try {
  2460. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2461. if (is_array($rpo)) {
  2462. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  2463. $poIdLog = $tid > 0 ? $tid : null;
  2464. }
  2465. } catch (\Throwable $e) {
  2466. $poIdLog = null;
  2467. }
  2468. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  2469. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  2470. if ($asComplete) {
  2471. $this->addOrderLog(
  2472. $ids,
  2473. 'mark_complete',
  2474. '点击「完结」,已标记为已完结',
  2475. $poIdLog
  2476. );
  2477. try {
  2478. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  2479. if ($pdfPublicPath === '') {
  2480. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  2481. }
  2482. } catch (\Throwable $e) {
  2483. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  2484. }
  2485. } else {
  2486. $this->addOrderLog(
  2487. $ids,
  2488. 'save_qty_price',
  2489. '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  2490. $poIdLog
  2491. );
  2492. }
  2493. $this->success("操作成功");
  2494. }
  2495. /**
  2496. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  2497. *
  2498. * @param array<int, array> $rows 引用传递当前页行
  2499. */
  2500. protected function mergePurchaseOrder(array &$rows)
  2501. {
  2502. if ($rows === []) {
  2503. return;
  2504. }
  2505. $ids = [];
  2506. foreach ($rows as $rw) {
  2507. if (!is_array($rw)) {
  2508. continue;
  2509. }
  2510. $id = (int)($rw['ID'] ?? 0);
  2511. if ($id > 0) {
  2512. $ids[$id] = true;
  2513. }
  2514. }
  2515. $idList = array_keys($ids);
  2516. if ($idList === []) {
  2517. return;
  2518. }
  2519. try {
  2520. $list = Db::table('purchase_order')
  2521. ->where('scydgy_id', 'in', $idList)
  2522. ->field('scydgy_id,This_quantity,ceilingPrice')
  2523. ->select();
  2524. } catch (\Throwable $e) {
  2525. return;
  2526. }
  2527. if (!is_array($list)) {
  2528. return;
  2529. }
  2530. $byId = [];
  2531. foreach ($list as $dbRow) {
  2532. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  2533. continue;
  2534. }
  2535. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  2536. }
  2537. foreach ($rows as &$rw) {
  2538. if (!is_array($rw)) {
  2539. continue;
  2540. }
  2541. $sid = (int)($rw['ID'] ?? 0);
  2542. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  2543. continue;
  2544. }
  2545. $db = $byId[$sid];
  2546. if (array_key_exists('This_quantity', $db) && $db['This_quantity'] !== null && $db['This_quantity'] !== '') {
  2547. $rw['This_quantity'] = $db['This_quantity'];
  2548. }
  2549. if (array_key_exists('ceilingPrice', $db) && $db['ceilingPrice'] !== null && $db['ceilingPrice'] !== '') {
  2550. $rw['ceilingPrice'] = $db['ceilingPrice'];
  2551. } elseif (array_key_exists('ceiling_price', $db) && $db['ceiling_price'] !== null && $db['ceiling_price'] !== '') {
  2552. $rw['ceilingPrice'] = $db['ceiling_price'];
  2553. }
  2554. }
  2555. unset($rw);
  2556. }
  2557. /**
  2558. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  2559. */
  2560. public function purchaseConfirmPick()
  2561. {
  2562. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2563. $this->error(__('Invalid parameters'));
  2564. }
  2565. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  2566. if ($batchRaw !== '') {
  2567. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  2568. return;
  2569. }
  2570. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  2571. $sid = (int)$scydgyId;
  2572. if (!$this->isValidScydgyRowId($sid)) {
  2573. $this->error('参数无效');
  2574. }
  2575. $parseIdList = function ($raw) {
  2576. if (is_array($raw)) {
  2577. $arr = $raw;
  2578. } else {
  2579. $decoded = json_decode((string)$raw, true);
  2580. $arr = is_array($decoded) ? $decoded : [];
  2581. }
  2582. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  2583. };
  2584. $selectedRaw = $this->request->post('selected_ids', null);
  2585. if ($selectedRaw === null || $selectedRaw === '') {
  2586. $legacy = (int)$this->request->post('selected_id', 0);
  2587. $selectedIds = $legacy > 0 ? [$legacy] : [];
  2588. } else {
  2589. $selectedIds = $parseIdList($selectedRaw);
  2590. }
  2591. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  2592. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  2593. try {
  2594. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  2595. } catch (\InvalidArgumentException $e) {
  2596. $this->error($e->getMessage());
  2597. } catch (\Throwable $e) {
  2598. $this->error($e->getMessage());
  2599. }
  2600. $this->success('操作成功', '', $result);
  2601. }
  2602. /**
  2603. * 整单采购确认(多道工序一次提交)
  2604. */
  2605. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  2606. {
  2607. $decoded = json_decode($batchRaw, true);
  2608. if (!is_array($decoded) || $decoded === []) {
  2609. $this->error('提交数据无效');
  2610. }
  2611. $picks = [];
  2612. foreach ($decoded as $item) {
  2613. if (!is_array($item)) {
  2614. continue;
  2615. }
  2616. $sid = (int)($item['scydgy_id'] ?? 0);
  2617. if (!$this->isValidScydgyRowId($sid)) {
  2618. continue;
  2619. }
  2620. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  2621. if (!is_array($sel)) {
  2622. $sel = [(int)$sel];
  2623. }
  2624. $unsel = $item['unselected_ids'] ?? [];
  2625. if (!is_array($unsel)) {
  2626. $unsel = json_decode((string)$unsel, true);
  2627. $unsel = is_array($unsel) ? $unsel : [];
  2628. }
  2629. $picks[] = [
  2630. 'scydgy_id' => $sid,
  2631. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  2632. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  2633. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  2634. ];
  2635. }
  2636. if ($picks === []) {
  2637. $this->error('提交数据无效');
  2638. }
  2639. Db::startTrans();
  2640. $results = [];
  2641. try {
  2642. foreach ($picks as $pick) {
  2643. $results[] = $this->runPurchaseConfirmPick(
  2644. (int)$pick['scydgy_id'],
  2645. $pick['selected_ids'],
  2646. $pick['unselected_ids'],
  2647. (int)$pick['purchase_order_id'],
  2648. false
  2649. );
  2650. }
  2651. Db::commit();
  2652. } catch (\Throwable $e) {
  2653. Db::rollback();
  2654. $msg = $e->getMessage();
  2655. $this->error($msg !== '' ? $msg : '提交失败');
  2656. }
  2657. $this->success('操作成功', '', ['batch' => $results]);
  2658. }
  2659. /**
  2660. * @return array<string, mixed>
  2661. */
  2662. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true): array
  2663. {
  2664. $scydgyId = (string)$sid;
  2665. if ($selectedIds === []) {
  2666. throw new \InvalidArgumentException('请至少勾选一条明细');
  2667. }
  2668. $inter = array_intersect($selectedIds, $unselectedIds);
  2669. if ($inter !== []) {
  2670. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  2671. }
  2672. $allIds = $this->purchaseOrderDetail($sid);
  2673. if ($allIds === []) {
  2674. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  2675. }
  2676. foreach ($selectedIds as $id) {
  2677. if (!in_array($id, $allIds, true)) {
  2678. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  2679. }
  2680. }
  2681. foreach ($unselectedIds as $id) {
  2682. if (!in_array($id, $allIds, true)) {
  2683. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  2684. }
  2685. }
  2686. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  2687. sort($union, SORT_NUMERIC);
  2688. $expect = $allIds;
  2689. sort($expect, SORT_NUMERIC);
  2690. if ($union !== $expect) {
  2691. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  2692. }
  2693. if ($manageTransaction) {
  2694. Db::startTrans();
  2695. }
  2696. try {
  2697. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => 0]);
  2698. $aff = 0;
  2699. try {
  2700. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => 1]);
  2701. } catch (\Throwable $e) {
  2702. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => 1]);
  2703. }
  2704. if ($aff < 1) {
  2705. throw new \Exception('更新选中状态失败');
  2706. }
  2707. if ($purchaseOrderId > 0) {
  2708. $poAff = (int)Db::table('purchase_order')
  2709. ->where('id', $purchaseOrderId)
  2710. ->where('scydgy_id', $sid)
  2711. ->update(['status' => 1]);
  2712. if ($poAff < 1) {
  2713. throw new \Exception('主表订单不存在或与工序行不匹配');
  2714. }
  2715. } else {
  2716. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update(['status' => '1']);
  2717. if ($poAff < 1) {
  2718. throw new \Exception('未找到');
  2719. }
  2720. }
  2721. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  2722. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  2723. if ($manageTransaction) {
  2724. Db::commit();
  2725. }
  2726. } catch (\Throwable $e) {
  2727. if ($manageTransaction) {
  2728. Db::rollback();
  2729. }
  2730. throw $e;
  2731. }
  2732. $poIdFinal = $purchaseOrderId;
  2733. if ($poIdFinal <= 0) {
  2734. try {
  2735. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2736. if (is_array($rpo)) {
  2737. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  2738. }
  2739. } catch (\Throwable $e) {
  2740. $poIdFinal = 0;
  2741. }
  2742. }
  2743. $pickNames = [];
  2744. foreach ($selectedIds as $pid) {
  2745. $dr = $this->purchaseOrderDetai($sid, $pid);
  2746. $nm = trim((string)($dr['company_name'] ?? ''));
  2747. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  2748. }
  2749. $this->addOrderLog(
  2750. $sid,
  2751. 'purchase_confirm',
  2752. '采购确认:已选中供应商「' . implode('、', $pickNames) . '」;',
  2753. $poIdFinal > 0 ? $poIdFinal : null
  2754. );
  2755. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars($sid, $selectedIds[0] ?? 0);
  2756. $sendSmsSafe = function ($phone, $content) {
  2757. $phone = trim((string)$phone);
  2758. if ($phone === '') {
  2759. return;
  2760. }
  2761. try {
  2762. $this->smsbao($phone, $content);
  2763. } catch (\Throwable $e) {
  2764. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  2765. }
  2766. };
  2767. foreach ($selectedIds as $pid) {
  2768. $dr = $this->purchaseOrderDetai($sid, $pid);
  2769. if (!is_array($dr)) {
  2770. continue;
  2771. }
  2772. $cname = trim((string)($dr['company_name'] ?? ''));
  2773. $ph = trim((string)($dr['phone'] ?? ''));
  2774. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  2775. 'company_name' => $cname,
  2776. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  2777. 'phone' => $ph,
  2778. ]));
  2779. $sendSmsSafe((string)($dr['phone'] ?? ''), $sms);
  2780. }
  2781. foreach ($unselectedIds as $pid) {
  2782. $dr = $this->purchaseOrderDetai($sid, $pid);
  2783. if (!is_array($dr)) {
  2784. continue;
  2785. }
  2786. $cname = trim((string)($dr['company_name'] ?? ''));
  2787. $ph = trim((string)($dr['phone'] ?? ''));
  2788. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  2789. 'company_name' => $cname,
  2790. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  2791. 'phone' => $ph,
  2792. ]));
  2793. $sendSmsSafe((string)($dr['phone'] ?? ''), $sms);
  2794. }
  2795. Log::write(sprintf(
  2796. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  2797. $scydgyId,
  2798. $purchaseOrderId,
  2799. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  2800. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  2801. ), 'notice');
  2802. $pdfPublicPath = '';
  2803. try {
  2804. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  2805. } catch (\Throwable $e) {
  2806. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  2807. }
  2808. return [
  2809. 'scydgy_id' => $scydgyId,
  2810. 'purchase_order_id' => $purchaseOrderId,
  2811. 'selected_ids' => $selectedIds,
  2812. 'unselected_ids' => $unselectedIds,
  2813. 'purchase_confirm_pdf' => $pdfPublicPath,
  2814. ];
  2815. }
  2816. /**
  2817. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  2818. *
  2819. * @param int[] $detailIds
  2820. */
  2821. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  2822. {
  2823. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  2824. if ($detailIds === []) {
  2825. return;
  2826. }
  2827. $payload = ['status_name' => $statusName];
  2828. try {
  2829. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  2830. } catch (\Throwable $e) {
  2831. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  2832. }
  2833. }
  2834. /**
  2835. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  2836. */
  2837. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  2838. {
  2839. try {
  2840. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  2841. } catch (\Throwable $e) {
  2842. return;
  2843. }
  2844. if (!is_array($rows)) {
  2845. return;
  2846. }
  2847. foreach ($rows as $dr) {
  2848. if (!is_array($dr)) {
  2849. continue;
  2850. }
  2851. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  2852. if ($id <= 0) {
  2853. continue;
  2854. }
  2855. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  2856. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  2857. try {
  2858. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  2859. } catch (\Throwable $e) {
  2860. }
  2861. }
  2862. }
  2863. /**
  2864. * @param array<string, mixed> $detailRow
  2865. */
  2866. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  2867. {
  2868. $am = $detailRow['amount'] ?? null;
  2869. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  2870. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  2871. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  2872. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  2873. }
  2874. /**
  2875. * @return int[]
  2876. */
  2877. protected function purchaseOrderDetail(int $scydgyId): array
  2878. {
  2879. if (!$this->isValidScydgyRowId($scydgyId)) {
  2880. return [];
  2881. }
  2882. try {
  2883. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  2884. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  2885. $list = $listQuery->select();
  2886. } catch (\Throwable $e) {
  2887. return [];
  2888. }
  2889. if (!is_array($list)) {
  2890. return [];
  2891. }
  2892. $ids = [];
  2893. foreach ($list as $r) {
  2894. if (!is_array($r)) {
  2895. continue;
  2896. }
  2897. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  2898. if ($pk > 0) {
  2899. $ids[] = $pk;
  2900. }
  2901. }
  2902. return array_values(array_unique($ids));
  2903. }
  2904. /**
  2905. * 获取当前登录用户信息 [id, 展示名]
  2906. */
  2907. protected function GetUseName(): array
  2908. {
  2909. $id = 0;
  2910. $name = '';
  2911. try {
  2912. if ($this->auth && $this->auth->isLogin()) {
  2913. $u = $this->auth->getUserInfo();
  2914. if (is_array($u)) {
  2915. $id = (int)($u['id'] ?? 0);
  2916. $name = trim((string)($u['nickname'] ?? ''));
  2917. if ($name === '') {
  2918. $name = trim((string)($u['username'] ?? ''));
  2919. }
  2920. }
  2921. }
  2922. } catch (\Throwable $e) {
  2923. }
  2924. if ($name === '') {
  2925. $name = '未知用户';
  2926. }
  2927. return [$id, $name];
  2928. }
  2929. /**
  2930. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  2931. */
  2932. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  2933. {
  2934. if (!$this->isValidScydgyRowId($scydgyId) || $content === '') {
  2935. return;
  2936. }
  2937. list($adminId, $adminName) = $this->GetUseName();
  2938. $cut = function ($s, $max) {
  2939. if (function_exists('mb_substr')) {
  2940. return mb_substr($s, 0, $max, 'UTF-8');
  2941. }
  2942. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  2943. };
  2944. try {
  2945. Db::table('purchase_order_oper_log')->insert([
  2946. 'scydgy_id' => $scydgyId,
  2947. 'purchase_order_id' => $purchaseOrderId,
  2948. 'admin_id' => $adminId,
  2949. 'admin_name' => $cut($adminName, 64),
  2950. 'action' => $cut((string)$action, 64),
  2951. 'content' => $cut($content, 1000),
  2952. // 表结构 createtime 为 int Unix 时间戳;日期字符串会导致插入失败或时间为 0,详情「操作记录」为空
  2953. 'createtime' => time(),
  2954. ]);
  2955. } catch (\Throwable $e) {
  2956. Log::write('procuremen addOrderLog: ' . $e->getMessage(), 'error');
  2957. }
  2958. }
  2959. /**
  2960. * 按主键取一条
  2961. */
  2962. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  2963. {
  2964. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  2965. return [];
  2966. }
  2967. try {
  2968. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  2969. if (is_array($one)) {
  2970. return $one;
  2971. }
  2972. } catch (\Throwable $e) {
  2973. }
  2974. try {
  2975. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  2976. if (is_array($one)) {
  2977. return $one;
  2978. }
  2979. } catch (\Throwable $e) {
  2980. }
  2981. return [];
  2982. }
  2983. /**
  2984. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  2985. */
  2986. protected function formatProcuremenDetailTime($v): string
  2987. {
  2988. if ($v === null || $v === '') {
  2989. return '';
  2990. }
  2991. if (is_numeric($v) && (int)$v > 946684800) {
  2992. return date('Y-m-d H:i:s', (int)$v);
  2993. }
  2994. $s = trim((string)$v);
  2995. if ($s !== '' && stripos($s, '0000-00-00') !== 0) {
  2996. return $s;
  2997. }
  2998. return '';
  2999. }
  3000. /**
  3001. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  3002. */
  3003. protected function formatDeliveryYmd($v): string
  3004. {
  3005. if ($v === null || $v === '') {
  3006. return '';
  3007. }
  3008. $s = trim((string)$v);
  3009. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  3010. return '';
  3011. }
  3012. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  3013. return $m[1];
  3014. }
  3015. $ts = strtotime($s);
  3016. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  3017. }
  3018. /**
  3019. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  3020. */
  3021. protected function detailRowSupplierOperated(array $r): bool
  3022. {
  3023. $am = $r['amount'] ?? null;
  3024. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3025. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3026. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3027. return $okAmt || $okDel;
  3028. }
  3029. /**
  3030. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  3031. */
  3032. protected function resolveDetailSupplierOperTime(array $r): string
  3033. {
  3034. if (!$this->detailRowSupplierOperated($r)) {
  3035. return '';
  3036. }
  3037. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  3038. if ($t !== '') {
  3039. return $t;
  3040. }
  3041. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  3042. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  3043. continue;
  3044. }
  3045. $t = $this->formatProcuremenDetailTime($r[$col]);
  3046. if ($t !== '') {
  3047. return $t;
  3048. }
  3049. }
  3050. return '';
  3051. }
  3052. /**
  3053. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  3054. */
  3055. protected function detailRowSupplierAccepted(array $r): bool
  3056. {
  3057. $am = $r['amount'] ?? null;
  3058. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3059. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3060. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3061. return $okAmt && $okDel;
  3062. }
  3063. /**
  3064. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  3065. */
  3066. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  3067. {
  3068. if ($detailCount > 0) {
  3069. return true;
  3070. }
  3071. $wf = (int)($main['wflow_status'] ?? 0);
  3072. if ($wf >= 1) {
  3073. return true;
  3074. }
  3075. $pickTime = trim((string)($main['pick_time'] ?? ''));
  3076. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  3077. return true;
  3078. }
  3079. return false;
  3080. }
  3081. /**
  3082. * 下发时间:优先 pick_time,其次首条下发明细时间
  3083. */
  3084. protected function resolveProcuremenIssueTime(array $main, array $details): string
  3085. {
  3086. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  3087. if ($issueTime !== '') {
  3088. return $issueTime;
  3089. }
  3090. foreach ($details as $dr) {
  3091. if (!is_array($dr)) {
  3092. continue;
  3093. }
  3094. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3095. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  3096. $issueTime = $t;
  3097. }
  3098. }
  3099. if ($issueTime !== '') {
  3100. return $issueTime;
  3101. }
  3102. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  3103. }
  3104. /**
  3105. * 直接点「完结」时间:优先操作记录 mark_complete
  3106. */
  3107. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  3108. {
  3109. if (!$this->isValidScydgyRowId($scydgyId)) {
  3110. return '';
  3111. }
  3112. try {
  3113. $log = Db::table('purchase_order_oper_log')
  3114. ->where('scydgy_id', $scydgyId)
  3115. ->where('action', 'mark_complete')
  3116. ->order('id', 'desc')
  3117. ->find();
  3118. if (is_array($log)) {
  3119. $ct = (int)($log['createtime'] ?? 0);
  3120. if ($ct > 946684800) {
  3121. return date('Y-m-d H:i:s', $ct);
  3122. }
  3123. }
  3124. } catch (\Throwable $e) {
  3125. }
  3126. return '';
  3127. }
  3128. /**
  3129. * 操作记录时间(取指定 action 最近一条)
  3130. *
  3131. * @param string|array<int, string> $actions
  3132. */
  3133. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  3134. {
  3135. if (!$this->isValidScydgyRowId($scydgyId)) {
  3136. return '';
  3137. }
  3138. $acts = is_array($actions) ? $actions : [$actions];
  3139. $acts = array_values(array_filter(array_map('strval', $acts)));
  3140. if ($acts === []) {
  3141. return '';
  3142. }
  3143. try {
  3144. $log = Db::table('purchase_order_oper_log')
  3145. ->where('scydgy_id', $scydgyId)
  3146. ->where('action', 'in', $acts)
  3147. ->order('id', 'desc')
  3148. ->find();
  3149. if (is_array($log)) {
  3150. $ct = (int)($log['createtime'] ?? 0);
  3151. if ($ct > 946684800) {
  3152. return date('Y-m-d H:i:s', $ct);
  3153. }
  3154. }
  3155. } catch (\Throwable $e) {
  3156. }
  3157. return '';
  3158. }
  3159. /**
  3160. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  3161. *
  3162. * @param array $main purchase_order 一行
  3163. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  3164. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  3165. */
  3166. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  3167. {
  3168. $issueCnt = count($details);
  3169. $acceptCnt = 0;
  3170. $pickedName = '';
  3171. $pickedTime = '';
  3172. foreach ($details as $dr) {
  3173. if (!is_array($dr)) {
  3174. continue;
  3175. }
  3176. if ($this->detailRowSupplierAccepted($dr)) {
  3177. $acceptCnt++;
  3178. }
  3179. if ((int)($dr['status'] ?? 0) === 1) {
  3180. if ($pickedName === '') {
  3181. $pickedName = trim((string)($dr['company_name'] ?? ''));
  3182. }
  3183. if ($pickedTime === '') {
  3184. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  3185. if ($pickedTime === '') {
  3186. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3187. }
  3188. }
  3189. }
  3190. }
  3191. $hasMain = $main !== [];
  3192. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  3193. if ($poTime === '') {
  3194. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  3195. }
  3196. $mainStatus = isset($main['status']) ? (int)$main['status'] : 0;
  3197. $wflowStatus = (int)($main['wflow_status'] ?? 0);
  3198. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  3199. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  3200. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  3201. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  3202. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  3203. $supplierTime = '';
  3204. if ($acceptCnt > 0) {
  3205. foreach ($details as $dr) {
  3206. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  3207. continue;
  3208. }
  3209. $t = $this->resolveDetailSupplierOperTime($dr);
  3210. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  3211. $supplierTime = $t;
  3212. }
  3213. }
  3214. }
  3215. $directComplete = ($mainStatus === 1 && !$issued);
  3216. $doneTime = '';
  3217. if ($mainStatus === 1) {
  3218. if ($directComplete) {
  3219. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  3220. }
  3221. if ($doneTime === '') {
  3222. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  3223. }
  3224. if ($doneTime === '') {
  3225. foreach ($details as $dr) {
  3226. if (!is_array($dr)) {
  3227. continue;
  3228. }
  3229. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  3230. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  3231. $doneTime = $t;
  3232. }
  3233. }
  3234. }
  3235. if ($doneTime === '') {
  3236. $doneTime = $poTime;
  3237. }
  3238. }
  3239. if ($directComplete) {
  3240. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  3241. $step1Done = $hasMain;
  3242. $step2Done = false;
  3243. $step3Done = false;
  3244. $step4Done = false;
  3245. $step5Done = false;
  3246. $step6Done = true;
  3247. } else {
  3248. $step1Done = $issued;
  3249. $step2Done = $issued;
  3250. $step3Done = $acceptCnt > 0;
  3251. $step4Done = $wflowStatus >= 2;
  3252. if (!$step4Done) {
  3253. foreach ($details as $dr) {
  3254. if (is_array($dr) && (int)($dr['status'] ?? 0) === 1) {
  3255. $step4Done = true;
  3256. break;
  3257. }
  3258. }
  3259. }
  3260. $step5Done = $confirmApproveTime !== '' || $mainStatus === 1;
  3261. $step6Done = $mainStatus === 1;
  3262. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  3263. if ($mainStatus === 1 && $issued) {
  3264. $step3Done = true;
  3265. $step4Done = true;
  3266. $step5Done = true;
  3267. if ($supplierTime === '') {
  3268. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3269. if ($fillT !== '') {
  3270. $supplierTime = $fillT;
  3271. }
  3272. }
  3273. if ($pickedTime === '') {
  3274. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3275. if ($fillT !== '') {
  3276. $pickedTime = $fillT;
  3277. }
  3278. }
  3279. if ($auditSelectTime === '') {
  3280. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3281. if ($fillT !== '') {
  3282. $auditSelectTime = $fillT;
  3283. }
  3284. }
  3285. if ($confirmApproveTime === '') {
  3286. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3287. if ($fillT !== '') {
  3288. $confirmApproveTime = $fillT;
  3289. }
  3290. }
  3291. }
  3292. }
  3293. $steps = [
  3294. [
  3295. 'title' => '未发',
  3296. 'subtitle' => '',
  3297. 'time' => $issued ? '—' : ($hasMain ? $poTime : ''),
  3298. 'done' => $step1Done,
  3299. ],
  3300. [
  3301. 'title' => '下发',
  3302. 'subtitle' => '',
  3303. 'time' => $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '',
  3304. 'done' => $step2Done,
  3305. ],
  3306. [
  3307. 'title' => '供应商接单',
  3308. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  3309. 'time' => $step3Done ? $supplierTime : '',
  3310. 'done' => $step3Done,
  3311. ],
  3312. [
  3313. 'title' => '待确认',
  3314. 'subtitle' => $step4Done
  3315. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  3316. : ($issued ? '待选供应商' : ''),
  3317. 'time' => $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '',
  3318. 'done' => $step4Done,
  3319. ],
  3320. [
  3321. 'title' => '待审批',
  3322. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  3323. 'time' => $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : $doneTime) : '',
  3324. 'done' => $step5Done,
  3325. ],
  3326. [
  3327. 'title' => '已完结',
  3328. 'subtitle' => '',
  3329. 'time' => $step6Done ? $doneTime : '',
  3330. 'done' => $step6Done,
  3331. ],
  3332. ];
  3333. $currentIdx = count($steps) - 1;
  3334. if (!$directComplete) {
  3335. foreach ($steps as $i => $s) {
  3336. if (!$s['done']) {
  3337. $currentIdx = $i;
  3338. break;
  3339. }
  3340. }
  3341. }
  3342. $nSteps = count($steps);
  3343. foreach ($steps as $idx => &$s) {
  3344. $s['current'] = ($idx === $currentIdx);
  3345. if ($idx === 0) {
  3346. $s['pdf_left_bg'] = '';
  3347. } else {
  3348. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  3349. }
  3350. if ($idx >= $nSteps - 1) {
  3351. $s['pdf_right_bg'] = '';
  3352. } else {
  3353. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  3354. }
  3355. }
  3356. unset($s);
  3357. $labelMap = [
  3358. 'CCYDH' => '订单号',
  3359. 'CYJMC' => '印件名称',
  3360. 'CCLBMMC' => '承揽部门',
  3361. 'CGYMC' => '工序名称',
  3362. 'CDW' => '单位',
  3363. 'NGZL' => '工作量',
  3364. 'CDF' => '单价',
  3365. 'cGzzxMc' => '工作中心',
  3366. 'MBZ' => '备注',
  3367. 'This_quantity' => '本次数量',
  3368. 'ceilingPrice' => '最高限价',
  3369. ];
  3370. $orderSummary = [];
  3371. foreach ($labelMap as $key => $lab) {
  3372. if (!array_key_exists($key, $main)) {
  3373. continue;
  3374. }
  3375. $val = $main[$key];
  3376. if ($val === null) {
  3377. $val = '';
  3378. } elseif (!is_scalar($val)) {
  3379. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  3380. } else {
  3381. $val = (string)$val;
  3382. }
  3383. $orderSummary[] = ['label' => $lab, 'value' => $val];
  3384. }
  3385. $orderSummaryGrid = [];
  3386. $n = count($orderSummary);
  3387. for ($i = 0; $i < $n; $i += 2) {
  3388. $left = $orderSummary[$i];
  3389. $hasRight = ($i + 1) < $n;
  3390. $orderSummaryGrid[] = [
  3391. 'l1' => $left['label'],
  3392. 'v1' => $left['value'],
  3393. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  3394. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  3395. ];
  3396. }
  3397. return [
  3398. 'steps' => $steps,
  3399. 'orderSummary' => $orderSummary,
  3400. 'orderSummaryGrid' => $orderSummaryGrid,
  3401. 'detailRows' => $details,
  3402. ];
  3403. }
  3404. /**
  3405. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  3406. *
  3407. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  3408. */
  3409. protected function prepareProcuremenDetailsView(string $ids): array
  3410. {
  3411. $main = [];
  3412. try {
  3413. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3414. $main = is_array($one) ? $one : [];
  3415. } catch (\Throwable $e) {
  3416. $main = [];
  3417. }
  3418. $details = [];
  3419. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  3420. if ($mergeRows === []) {
  3421. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  3422. if ($mergeRows === [] && $main !== []) {
  3423. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  3424. }
  3425. }
  3426. $detailSidList = [];
  3427. $anchorSid = (int)$ids;
  3428. if ($anchorSid !== 0) {
  3429. $detailSidList[$anchorSid] = true;
  3430. }
  3431. foreach ($mergeRows as $mr) {
  3432. if (!is_array($mr)) {
  3433. continue;
  3434. }
  3435. $sid = $this->extractScydgyRowId($mr);
  3436. if ($sid !== 0) {
  3437. $detailSidList[$sid] = true;
  3438. }
  3439. }
  3440. try {
  3441. if ($detailSidList !== []) {
  3442. $details = Db::table('purchase_order_detail')
  3443. ->where('scydgy_id', 'in', array_keys($detailSidList))
  3444. ->order('id', 'asc')
  3445. ->select();
  3446. }
  3447. } catch (\Throwable $e) {
  3448. $details = [];
  3449. }
  3450. if (!is_array($details)) {
  3451. $details = [];
  3452. }
  3453. foreach ($details as &$r) {
  3454. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  3455. $r['id'] = $r['ID'];
  3456. }
  3457. if (isset($r['createtime'])) {
  3458. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  3459. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  3460. } else {
  3461. $r['createtime_text'] = (string)$r['createtime'];
  3462. }
  3463. } else {
  3464. $r['createtime_text'] = '';
  3465. }
  3466. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  3467. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  3468. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  3469. }
  3470. unset($r);
  3471. $activeDetails = [];
  3472. foreach ($details as $r) {
  3473. if (is_array($r) && empty($r['is_void'])) {
  3474. $activeDetails[] = $r;
  3475. }
  3476. }
  3477. $operLogs = [];
  3478. try {
  3479. $operLogs = Db::table('purchase_order_oper_log')->where('scydgy_id', $ids)->order('id', 'asc')->select();
  3480. } catch (\Throwable $e) {
  3481. $operLogs = [];
  3482. }
  3483. if (!is_array($operLogs)) {
  3484. $operLogs = [];
  3485. }
  3486. foreach ($operLogs as &$lg) {
  3487. if (!is_array($lg)) {
  3488. continue;
  3489. }
  3490. $ct = isset($lg['createtime']) ? (int)$lg['createtime'] : 0;
  3491. $lg['createtime_text'] = $ct > 946684800 ? date('Y-m-d H:i:s', $ct) : '';
  3492. }
  3493. unset($lg);
  3494. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  3495. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  3496. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  3497. if ($ccydh === '') {
  3498. foreach ($details as $r) {
  3499. if (!is_array($r)) {
  3500. continue;
  3501. }
  3502. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  3503. if ($ccydh !== '') {
  3504. break;
  3505. }
  3506. }
  3507. }
  3508. $this->view->assign('ccydh', $ccydh);
  3509. $this->view->assign('steps', $bundle['steps']);
  3510. $this->view->assign('orderSummary', $bundle['orderSummary']);
  3511. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  3512. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  3513. $this->view->assign('processCount', count($mergeRows));
  3514. $this->view->assign('detailRows', $details);
  3515. $this->view->assign('supplierQuoteGroups', $quoteView['supplier_groups']);
  3516. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  3517. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  3518. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  3519. $this->view->assign('operLogs', $operLogs);
  3520. return [
  3521. 'ok' => $main !== [] || $details !== [],
  3522. 'ccydh' => $ccydh,
  3523. ];
  3524. }
  3525. /**
  3526. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  3527. */
  3528. public function details()
  3529. {
  3530. $ids = $this->request->param('ids', $this->request->param('id', ''));
  3531. if (is_array($ids)) {
  3532. $ids = isset($ids[0]) ? $ids[0] : '';
  3533. }
  3534. $ids = trim((string)$ids);
  3535. if ($ids === '') {
  3536. $this->error(__('Invalid parameters'));
  3537. }
  3538. $this->assertManualOrderDetailsViewable((int)$ids);
  3539. $this->prepareProcuremenDetailsView($ids);
  3540. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  3541. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  3542. $this->view->engine->layout(false);
  3543. try {
  3544. return $this->view->fetch('procuremen/details_dialog_shell');
  3545. } finally {
  3546. if ($restoreLayout) {
  3547. $this->view->engine->layout($restoreLayout);
  3548. }
  3549. }
  3550. }
  3551. /**
  3552. * 解析合并审核工序行(订单号须一致,且均未协助)
  3553. *
  3554. * @return array<int, array<string, mixed>>
  3555. */
  3556. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  3557. {
  3558. $primary = json_decode($rowJson, true);
  3559. if (!is_array($primary)) {
  3560. $this->error(__('Invalid parameters'));
  3561. }
  3562. $merge = json_decode($mergeRowsJson, true);
  3563. if (!is_array($merge) || $merge === []) {
  3564. $merge = [$primary];
  3565. }
  3566. $seen = [];
  3567. $out = [];
  3568. foreach ($merge as $r) {
  3569. if (!is_array($r)) {
  3570. continue;
  3571. }
  3572. $id = $this->extractScydgyRowId($r);
  3573. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  3574. continue;
  3575. }
  3576. $seen[$id] = true;
  3577. $out[] = $r;
  3578. }
  3579. if ($out === []) {
  3580. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  3581. }
  3582. $ccydh = null;
  3583. foreach ($out as $r) {
  3584. $dh = trim((string)($r['CCYDH'] ?? ''));
  3585. if ($ccydh === null) {
  3586. $ccydh = $dh;
  3587. } elseif ($dh !== $ccydh) {
  3588. $this->error('合并审核要求所选行的订单号一致');
  3589. }
  3590. }
  3591. $ids = [];
  3592. foreach ($out as $r) {
  3593. $id = $this->extractScydgyRowId($r);
  3594. if ($this->isValidScydgyRowId($id)) {
  3595. $ids[$id] = true;
  3596. }
  3597. }
  3598. $poBySid = [];
  3599. $detCntBySid = [];
  3600. if ($ids !== []) {
  3601. $idList = array_keys($ids);
  3602. try {
  3603. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  3604. if (is_array($poList)) {
  3605. foreach ($poList as $po) {
  3606. if (!is_array($po)) {
  3607. continue;
  3608. }
  3609. $sid = (int)($po['scydgy_id'] ?? 0);
  3610. if ($this->isValidScydgyRowId($sid)) {
  3611. $poBySid[$sid] = $po;
  3612. }
  3613. }
  3614. }
  3615. } catch (\Throwable $e) {
  3616. }
  3617. try {
  3618. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  3619. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  3620. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  3621. if (is_array($detRows)) {
  3622. foreach ($detRows as $dr) {
  3623. if (!is_array($dr)) {
  3624. continue;
  3625. }
  3626. $sid = (int)($dr['scydgy_id'] ?? 0);
  3627. if ($this->isValidScydgyRowId($sid)) {
  3628. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  3629. }
  3630. }
  3631. }
  3632. } catch (\Throwable $e) {
  3633. }
  3634. }
  3635. foreach ($out as $r) {
  3636. $id = $this->extractScydgyRowId($r);
  3637. if (!$this->isValidScydgyRowId($id)) {
  3638. continue;
  3639. }
  3640. $po = $poBySid[$id] ?? null;
  3641. if (!is_array($po)) {
  3642. continue;
  3643. }
  3644. $wf = (int)($po['wflow_status'] ?? 0);
  3645. $st = $po['status'] ?? null;
  3646. if ($wf >= 1 || $st === 1 || $st === '1') {
  3647. $gymc = trim((string)($r['CGYMC'] ?? ''));
  3648. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  3649. }
  3650. $detCnt = (int)($detCntBySid[$id] ?? 0);
  3651. if ($detCnt > 0 && $wf < 1) {
  3652. $gymc = trim((string)($r['CGYMC'] ?? ''));
  3653. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  3654. }
  3655. }
  3656. return $out;
  3657. }
  3658. /**
  3659. * 规范化下发/确认时勾选的供应商
  3660. *
  3661. * @param array<int, mixed> $companies
  3662. * @return array<int, array<string, string>>
  3663. */
  3664. protected function normalizePickCompanies(array $companies): array
  3665. {
  3666. $out = [];
  3667. foreach ($companies as $c) {
  3668. if (!is_array($c)) {
  3669. continue;
  3670. }
  3671. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  3672. if ($name === '') {
  3673. continue;
  3674. }
  3675. $out[] = [
  3676. 'name' => $name,
  3677. 'company_name' => $name,
  3678. 'username' => trim((string)($c['username'] ?? '')),
  3679. 'email' => trim((string)($c['email'] ?? '')),
  3680. 'phone' => trim((string)($c['phone'] ?? '')),
  3681. 'company_type' => trim((string)($c['company_type'] ?? $c['category'] ?? '')),
  3682. ];
  3683. }
  3684. return $out;
  3685. }
  3686. /**
  3687. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  3688. *
  3689. * @param array<int, array<string, mixed>> $pool
  3690. * @return array<int, array<string, mixed>>
  3691. */
  3692. protected function collapseProcuremenPoolByOrder(array $pool): array
  3693. {
  3694. if ($pool === []) {
  3695. return [];
  3696. }
  3697. $groups = [];
  3698. foreach ($pool as $row) {
  3699. if (!is_array($row)) {
  3700. continue;
  3701. }
  3702. $dh = trim((string)($row['CCYDH'] ?? ''));
  3703. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  3704. if (!isset($groups[$key])) {
  3705. $groups[$key] = [];
  3706. }
  3707. $groups[$key][] = $row;
  3708. }
  3709. $out = [];
  3710. foreach ($groups as $ccydh => $rows) {
  3711. if ($rows === []) {
  3712. continue;
  3713. }
  3714. usort($rows, function ($a, $b) {
  3715. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  3716. });
  3717. $head = $rows[0];
  3718. $gymcList = [];
  3719. foreach ($rows as $r) {
  3720. $g = trim((string)($r['CGYMC'] ?? ''));
  3721. if ($g !== '' && !in_array($g, $gymcList, true)) {
  3722. $gymcList[] = $g;
  3723. }
  3724. }
  3725. $merged = $head;
  3726. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  3727. $merged['process_count'] = count($rows);
  3728. $merged['_order_merge_rows'] = $rows;
  3729. if (count($rows) > 1) {
  3730. $merged['CGYMC'] = implode('、', $gymcList);
  3731. }
  3732. $mergedPickTime = '';
  3733. foreach ($rows as $r) {
  3734. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  3735. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  3736. $mergedPickTime = $t;
  3737. }
  3738. }
  3739. if ($mergedPickTime !== '') {
  3740. $merged['pick_time'] = $mergedPickTime;
  3741. }
  3742. $out[] = $merged;
  3743. }
  3744. usort($out, function ($a, $b) {
  3745. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  3746. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  3747. if ($ta === $tb) {
  3748. $ida = (int)($a['purchase_order_id'] ?? 0);
  3749. $idb = (int)($b['purchase_order_id'] ?? 0);
  3750. if ($ida !== $idb) {
  3751. return $idb <=> $ida;
  3752. }
  3753. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  3754. }
  3755. if ($ta === '') {
  3756. return 1;
  3757. }
  3758. if ($tb === '') {
  3759. return -1;
  3760. }
  3761. return strcmp($tb, $ta);
  3762. });
  3763. return $out;
  3764. }
  3765. /**
  3766. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  3767. *
  3768. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3769. */
  3770. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  3771. {
  3772. $scydgyId = trim($scydgyId);
  3773. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3774. if ($scydgyId === '') {
  3775. return $empty;
  3776. }
  3777. try {
  3778. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  3779. } catch (\Throwable $e) {
  3780. $anchor = null;
  3781. }
  3782. if (!is_array($anchor) || (int)($anchor['wflow_status'] ?? 0) !== 1) {
  3783. return $empty;
  3784. }
  3785. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  3786. if ($ccydh === '') {
  3787. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  3788. }
  3789. try {
  3790. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->where('wflow_status', 1)->order('scydgy_id', 'asc')->select();
  3791. } catch (\Throwable $e) {
  3792. $pos = [$anchor];
  3793. }
  3794. if (!is_array($pos) || $pos === []) {
  3795. $pos = [$anchor];
  3796. }
  3797. return [
  3798. 'ccydh' => $ccydh,
  3799. 'pos' => $pos,
  3800. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3801. ];
  3802. }
  3803. /**
  3804. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  3805. */
  3806. protected function purchaseOrderRowInConfirmStage(array $po): bool
  3807. {
  3808. $st = $po['status'] ?? null;
  3809. if ($st === 1 || $st === '1') {
  3810. return false;
  3811. }
  3812. $wf = (int)($po['wflow_status'] ?? 0);
  3813. if ($wf === 2) {
  3814. return true;
  3815. }
  3816. if ($wf === 0) {
  3817. $sid = (int)($po['scydgy_id'] ?? 0);
  3818. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  3819. }
  3820. return false;
  3821. }
  3822. /**
  3823. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  3824. *
  3825. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3826. */
  3827. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  3828. {
  3829. $scydgyId = trim($scydgyId);
  3830. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3831. if ($scydgyId === '') {
  3832. return $empty;
  3833. }
  3834. try {
  3835. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  3836. } catch (\Throwable $e) {
  3837. $anchor = null;
  3838. }
  3839. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  3840. return $empty;
  3841. }
  3842. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  3843. if ($ccydh === '') {
  3844. return [
  3845. 'ccydh' => '',
  3846. 'pos' => [$anchor],
  3847. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  3848. ];
  3849. }
  3850. try {
  3851. $pos = Db::table('purchase_order')
  3852. ->where('CCYDH', $ccydh)
  3853. ->where('status', 0)
  3854. ->where(function ($q) {
  3855. $q->where('wflow_status', 2)
  3856. ->whereOr(function ($q2) {
  3857. $q2->where('wflow_status', 0)->whereRaw($this->purchaseOrderDetailActiveExistsSql('d'));
  3858. });
  3859. })
  3860. ->order('scydgy_id', 'asc')
  3861. ->select();
  3862. } catch (\Throwable $e) {
  3863. $pos = [$anchor];
  3864. }
  3865. if (!is_array($pos) || $pos === []) {
  3866. $pos = [$anchor];
  3867. }
  3868. $pos = array_values(array_filter($pos, function ($po) {
  3869. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  3870. }));
  3871. if ($pos === []) {
  3872. $pos = [$anchor];
  3873. }
  3874. return [
  3875. 'ccydh' => $ccydh,
  3876. 'pos' => $pos,
  3877. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3878. ];
  3879. }
  3880. /**
  3881. * @param array<int, array<string, mixed>> $purchaseOrders
  3882. * @return array<int, array<string, mixed>>
  3883. */
  3884. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  3885. {
  3886. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  3887. $byId = [];
  3888. foreach ($pool as $r) {
  3889. if (!is_array($r)) {
  3890. continue;
  3891. }
  3892. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  3893. if ($this->isValidScydgyRowId($sid)) {
  3894. $byId[$sid] = $r;
  3895. }
  3896. }
  3897. $out = [];
  3898. foreach ($purchaseOrders as $po) {
  3899. if (!is_array($po)) {
  3900. continue;
  3901. }
  3902. $sid = (int)($po['scydgy_id'] ?? 0);
  3903. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  3904. $out[] = $byId[$sid];
  3905. }
  3906. }
  3907. return $out;
  3908. }
  3909. /**
  3910. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  3911. *
  3912. * @return array<int, array<string, mixed>>
  3913. */
  3914. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  3915. {
  3916. $scydgyId = trim($scydgyId);
  3917. if ($scydgyId === '') {
  3918. return [];
  3919. }
  3920. try {
  3921. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  3922. } catch (\Throwable $e) {
  3923. $anchor = null;
  3924. }
  3925. if (!is_array($anchor)) {
  3926. return [];
  3927. }
  3928. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  3929. return [];
  3930. }
  3931. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  3932. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  3933. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  3934. try {
  3935. $q = Db::table('purchase_order');
  3936. if ($ccydh !== '') {
  3937. $q->where('CCYDH', $ccydh);
  3938. } else {
  3939. $q->where('scydgy_id', $scydgyId);
  3940. }
  3941. if ($isValidPick) {
  3942. $q->where('pick_time', $pickTime);
  3943. }
  3944. $pos = $q->order('scydgy_id', 'asc')->select();
  3945. } catch (\Throwable $e) {
  3946. $pos = [$anchor];
  3947. }
  3948. if (!is_array($pos) || $pos === []) {
  3949. $pos = [$anchor];
  3950. }
  3951. $pos = array_values(array_filter($pos, function ($po) {
  3952. if (!is_array($po)) {
  3953. return false;
  3954. }
  3955. $mr = $po['mod_rq'] ?? null;
  3956. if ($mr === null || $mr === '') {
  3957. return true;
  3958. }
  3959. $mrs = trim((string)$mr);
  3960. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  3961. }));
  3962. if ($pos === []) {
  3963. $pos = [$anchor];
  3964. }
  3965. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  3966. if ($rows === []) {
  3967. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  3968. }
  3969. return $rows;
  3970. }
  3971. /**
  3972. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  3973. *
  3974. * @param array<int, array<string, mixed>> $mergeRows
  3975. * @return array<int, array<string, mixed>>
  3976. */
  3977. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  3978. {
  3979. $list = array_values($mergeRows);
  3980. $n = count($list);
  3981. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  3982. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  3983. $mergeSame = $n > 1 && $orderKey0 !== '';
  3984. if ($mergeSame) {
  3985. foreach ($list as $rr) {
  3986. if (!is_array($rr)) {
  3987. $mergeSame = false;
  3988. break;
  3989. }
  3990. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  3991. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  3992. $mergeSame = false;
  3993. break;
  3994. }
  3995. }
  3996. }
  3997. $out = [];
  3998. foreach ($list as $idx => $r) {
  3999. if (!is_array($r)) {
  4000. continue;
  4001. }
  4002. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  4003. if (is_scalar($qty)) {
  4004. $qty = trim((string)$qty);
  4005. } else {
  4006. $qty = '';
  4007. }
  4008. if ($qty === '') {
  4009. $gzl = $r['NGZL'] ?? '';
  4010. if (is_scalar($gzl)) {
  4011. $qty = trim((string)$gzl);
  4012. }
  4013. }
  4014. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  4015. $sid = $this->extractScydgyRowId($r);
  4016. $out[] = [
  4017. 'seq' => $idx + 1,
  4018. 'scydgy_id' => $sid,
  4019. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  4020. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  4021. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  4022. 'CDW' => trim((string)($r['CDW'] ?? '')),
  4023. 'NGZL' => $r['NGZL'] ?? '',
  4024. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  4025. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  4026. 'CDF' => trim((string)($r['CDF'] ?? '')),
  4027. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  4028. 'show_order_cells' => !$mergeSame || $idx === 0,
  4029. 'order_rowspan' => $mergeSame ? $n : 1,
  4030. ];
  4031. }
  4032. return $out;
  4033. }
  4034. /**
  4035. * 解析金额/数量(去千分位等非数字字符)
  4036. */
  4037. protected function parseProcuremenMoneyNumber($value): ?float
  4038. {
  4039. if ($value === null || $value === '') {
  4040. return null;
  4041. }
  4042. if (is_numeric($value)) {
  4043. return (float)$value;
  4044. }
  4045. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  4046. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  4047. }
  4048. protected function formatProcuremenMoneyDisplay(?float $amount): string
  4049. {
  4050. if ($amount === null) {
  4051. return '';
  4052. }
  4053. return (string)(int)round($amount);
  4054. }
  4055. /**
  4056. * 列表/详情展示:工作量为 0 时显示空
  4057. */
  4058. protected function formatProcuremenWorkloadDisplay($value): string
  4059. {
  4060. if ($value === null || $value === '') {
  4061. return '';
  4062. }
  4063. $s = trim((string)$value);
  4064. if ($s === '') {
  4065. return '';
  4066. }
  4067. if (is_numeric($s) && (float)$s == 0) {
  4068. return '';
  4069. }
  4070. return $s;
  4071. }
  4072. /**
  4073. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  4074. */
  4075. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  4076. {
  4077. foreach ($details as $d) {
  4078. if (!is_array($d)) {
  4079. continue;
  4080. }
  4081. if (!$this->isPurchaseOrderDetailVoid($d) && (int)($d['status'] ?? 0) === 1) {
  4082. $cn = trim((string)($d['company_name'] ?? ''));
  4083. if ($cn !== '') {
  4084. return $cn;
  4085. }
  4086. }
  4087. }
  4088. return trim((string)($main['pick_company_name'] ?? ''));
  4089. }
  4090. /**
  4091. * 详情报价小计:单价 × 本工序本次数量
  4092. */
  4093. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  4094. {
  4095. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  4096. if ($unit === null) {
  4097. return null;
  4098. }
  4099. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  4100. if ($qty === null || $qty <= 0) {
  4101. return null;
  4102. }
  4103. return $unit * $qty;
  4104. }
  4105. /**
  4106. * 详情页:工序小计 + 供应商分组报价与总计
  4107. *
  4108. * @param array<int, array<string, mixed>> $mergeRows
  4109. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  4110. * @return array{
  4111. * process_rows: array,
  4112. * supplier_groups: array,
  4113. * order_total_text: string,
  4114. * order_total_has: bool,
  4115. * selected_company: string
  4116. * }
  4117. */
  4118. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  4119. {
  4120. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  4121. $qtyBySid = [];
  4122. $gymcBySid = [];
  4123. $orderedSids = [];
  4124. foreach ($mergeRows as $mr) {
  4125. if (!is_array($mr)) {
  4126. continue;
  4127. }
  4128. $sid = $this->extractScydgyRowId($mr);
  4129. if ($sid > 0) {
  4130. $orderedSids[] = $sid;
  4131. }
  4132. $qty = trim((string)($mr['This_quantity'] ?? ''));
  4133. if ($qty === '') {
  4134. $qty = trim((string)($mr['NGZL'] ?? ''));
  4135. }
  4136. $qtyBySid[$sid] = $qty;
  4137. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  4138. }
  4139. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  4140. $detailByCompanySid = [];
  4141. foreach ($details as $d) {
  4142. if (!is_array($d)) {
  4143. continue;
  4144. }
  4145. $cn = trim((string)($d['company_name'] ?? ''));
  4146. $sid = (int)($d['scydgy_id'] ?? 0);
  4147. if ($cn === '' || $sid === 0) {
  4148. continue;
  4149. }
  4150. if (!isset($detailByCompanySid[$cn])) {
  4151. $detailByCompanySid[$cn] = [];
  4152. }
  4153. $detailByCompanySid[$cn][$sid] = $d;
  4154. }
  4155. $supplierGroups = [];
  4156. foreach ($detailByCompanySid as $cn => $bySid) {
  4157. $lines = [];
  4158. $groupTotal = 0.0;
  4159. $groupHas = false;
  4160. $groupVoid = true;
  4161. $usedSids = [];
  4162. $appendLine = function (int $sid, array $d) use (
  4163. &$lines,
  4164. &$groupTotal,
  4165. &$groupHas,
  4166. &$groupVoid,
  4167. $qtyBySid,
  4168. $gymcBySid
  4169. ) {
  4170. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  4171. if (!$isVoid) {
  4172. $groupVoid = false;
  4173. }
  4174. $qtyStr = $qtyBySid[$sid] ?? '';
  4175. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  4176. $sub = null;
  4177. if (!$isVoid && $amountNum !== null) {
  4178. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  4179. if ($sub !== null) {
  4180. $groupTotal += $sub;
  4181. $groupHas = true;
  4182. }
  4183. }
  4184. $ct = $this->resolveDetailSupplierOperTime($d);
  4185. $lines[] = [
  4186. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  4187. 'unit_price_text' => $amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : trim((string)($d['amount'] ?? '')),
  4188. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  4189. 'delivery_ymd' => $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null),
  4190. 'status' => (int)($d['status'] ?? 0),
  4191. 'is_void' => $isVoid,
  4192. 'oper_time_text' => $ct,
  4193. ];
  4194. };
  4195. foreach ($orderedSids as $sid) {
  4196. if (!isset($bySid[$sid])) {
  4197. continue;
  4198. }
  4199. $usedSids[$sid] = true;
  4200. $appendLine($sid, $bySid[$sid]);
  4201. }
  4202. foreach ($bySid as $sid => $d) {
  4203. if (isset($usedSids[$sid])) {
  4204. continue;
  4205. }
  4206. $appendLine((int)$sid, $d);
  4207. }
  4208. $firstDetail = null;
  4209. foreach ($bySid as $d) {
  4210. if (is_array($d)) {
  4211. $firstDetail = $d;
  4212. break;
  4213. }
  4214. }
  4215. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  4216. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  4217. if ($username === '' && $ph !== '') {
  4218. $username = $this->resolveCustomerContactName($ph, $cn);
  4219. }
  4220. $lineCount = count($lines);
  4221. $supplierGroups[] = [
  4222. 'company_name' => $cn,
  4223. 'username' => $username,
  4224. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  4225. 'phone' => $ph,
  4226. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  4227. 'is_void' => $groupVoid,
  4228. 'lines' => $lines,
  4229. 'line_count' => $lineCount,
  4230. 'display_rowspan'=> $lineCount + ($lineCount > 0 ? 1 : 0),
  4231. 'total_text' => $groupHas ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  4232. 'has_total' => $lineCount > 0,
  4233. ];
  4234. }
  4235. usort($supplierGroups, function ($a, $b) {
  4236. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  4237. return ($a['is_void'] ?? false) ? 1 : -1;
  4238. }
  4239. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  4240. return ($a['is_selected'] ?? false) ? -1 : 1;
  4241. }
  4242. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  4243. });
  4244. return [
  4245. 'process_rows' => $processRows,
  4246. 'supplier_groups' => $supplierGroups,
  4247. 'order_total_text' => '',
  4248. 'order_total_has' => false,
  4249. 'selected_company' => $selectedCompany,
  4250. ];
  4251. }
  4252. /**
  4253. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  4254. */
  4255. protected function buildProcessLinesPlain(array $mergeRows): string
  4256. {
  4257. $lines = [];
  4258. $i = 1;
  4259. foreach ($mergeRows as $r) {
  4260. if (!is_array($r)) {
  4261. continue;
  4262. }
  4263. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4264. $dw = trim((string)($r['CDW'] ?? ''));
  4265. $gzl = trim((string)($r['NGZL'] ?? ''));
  4266. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  4267. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  4268. if ($dw !== '') {
  4269. $parts[] = '单位:' . $dw;
  4270. }
  4271. if ($gzl !== '') {
  4272. $parts[] = '工作量:' . $gzl;
  4273. }
  4274. if ($qty !== '') {
  4275. $parts[] = '本次数量:' . $qty;
  4276. }
  4277. $lines[] = implode(' ', $parts);
  4278. $i++;
  4279. }
  4280. return implode("\n", $lines);
  4281. }
  4282. /**
  4283. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  4284. *
  4285. * @return array<string, string>
  4286. */
  4287. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0): array
  4288. {
  4289. $po = null;
  4290. try {
  4291. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4292. } catch (\Throwable $e) {
  4293. $po = null;
  4294. }
  4295. $ccydh = is_array($po) ? trim((string)($po['CCYDH'] ?? '')) : '';
  4296. $cyjmc = is_array($po) ? trim((string)($po['CYJMC'] ?? '')) : '';
  4297. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0) {
  4298. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  4299. if (is_array($any)) {
  4300. if ($ccydh === '') {
  4301. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  4302. }
  4303. if ($cyjmc === '') {
  4304. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  4305. }
  4306. }
  4307. }
  4308. $mergeRows = is_array($po) && $po !== [] ? [$po] : [];
  4309. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  4310. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  4311. return [
  4312. 'ccydh' => $ccydh,
  4313. 'cyjmc' => $cyjmc,
  4314. 'cgymc' => is_array($po) ? trim((string)($po['CGYMC'] ?? '')) : '',
  4315. 'process_lines' => $processLines,
  4316. 'process_lines_html' => '',
  4317. ];
  4318. }
  4319. /**
  4320. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  4321. */
  4322. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  4323. {
  4324. $lines = [];
  4325. if ($ccydh !== '') {
  4326. $lines[] = '订单号:' . $ccydh;
  4327. }
  4328. if ($cyjmc !== '') {
  4329. $lines[] = '印件名称:' . $cyjmc;
  4330. }
  4331. if ($processPlain !== '') {
  4332. $lines[] = $processPlain;
  4333. }
  4334. return implode("\n", $lines);
  4335. }
  4336. /**
  4337. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  4338. *
  4339. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  4340. */
  4341. protected function buildPlatformLinksPlain(array $detailLinks): string
  4342. {
  4343. $lines = [];
  4344. $i = 1;
  4345. foreach ($detailLinks as $lk) {
  4346. if (!is_array($lk)) {
  4347. continue;
  4348. }
  4349. $url = trim((string)($lk['url'] ?? ''));
  4350. if ($url === '') {
  4351. continue;
  4352. }
  4353. $label = trim((string)($lk['cgymc'] ?? ''));
  4354. if ($label === '') {
  4355. $label = '工序' . $i;
  4356. }
  4357. $lines[] = $label . ':' . $url;
  4358. $i++;
  4359. }
  4360. return implode("\n", $lines);
  4361. }
  4362. /**
  4363. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  4364. *
  4365. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  4366. */
  4367. protected function buildPlatformLinksHtml(array $detailLinks): string
  4368. {
  4369. $parts = [];
  4370. $i = 1;
  4371. foreach ($detailLinks as $lk) {
  4372. if (!is_array($lk)) {
  4373. continue;
  4374. }
  4375. $url = trim((string)($lk['url'] ?? ''));
  4376. if ($url === '') {
  4377. continue;
  4378. }
  4379. $label = trim((string)($lk['cgymc'] ?? ''));
  4380. if ($label === '') {
  4381. $label = '工序' . $i;
  4382. }
  4383. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  4384. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  4385. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  4386. $i++;
  4387. }
  4388. return implode("<br>\n", $parts);
  4389. }
  4390. /**
  4391. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  4392. *
  4393. * @return array<string, mixed>
  4394. */
  4395. protected function loadMailerConfig(): array
  4396. {
  4397. try {
  4398. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  4399. } catch (\Throwable $e) {
  4400. $cfg = [];
  4401. }
  4402. return is_array($cfg) ? $cfg : [];
  4403. }
  4404. protected function loadNotifyTemplateRow(string $scene): ?array
  4405. {
  4406. try {
  4407. $row = Db::table('purchase_sms_template')
  4408. ->where('scene', $scene)
  4409. ->where(function ($q) {
  4410. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  4411. })
  4412. ->order('id', 'asc')
  4413. ->find();
  4414. } catch (\Throwable $e) {
  4415. return null;
  4416. }
  4417. if (!is_array($row) || $row === []) {
  4418. return null;
  4419. }
  4420. return [
  4421. 'title' => trim((string)($row['title'] ?? '')),
  4422. 'content' => trim((string)($row['content'] ?? '')),
  4423. ];
  4424. }
  4425. /**
  4426. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  4427. */
  4428. protected function buildProcessLinesHtml(array $mergeRows): string
  4429. {
  4430. if (count($mergeRows) <= 1) {
  4431. $r = $mergeRows[0] ?? [];
  4432. if (!is_array($r)) {
  4433. return '';
  4434. }
  4435. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4436. $dw = trim((string)($r['CDW'] ?? ''));
  4437. $gzl = trim((string)($r['NGZL'] ?? ''));
  4438. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  4439. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  4440. if ($dw !== '') {
  4441. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  4442. }
  4443. if ($gzl !== '') {
  4444. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  4445. }
  4446. if ($qty !== '') {
  4447. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  4448. }
  4449. return $html;
  4450. }
  4451. $rows = '';
  4452. $i = 1;
  4453. foreach ($mergeRows as $r) {
  4454. if (!is_array($r)) {
  4455. continue;
  4456. }
  4457. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  4458. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  4459. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  4460. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  4461. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  4462. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  4463. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  4464. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  4465. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  4466. $i++;
  4467. }
  4468. if ($rows === '') {
  4469. return '';
  4470. }
  4471. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  4472. . '<thead><tr style="background:#f5f5f5;">'
  4473. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  4474. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  4475. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  4476. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  4477. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  4478. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  4479. }
  4480. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true): string
  4481. {
  4482. $sysRq = trim($sysRq);
  4483. if ($sysRq === '') {
  4484. if ($required) {
  4485. $this->error('请选择截止时间');
  4486. }
  4487. return '';
  4488. }
  4489. $ts = strtotime($sysRq);
  4490. if ($ts === false || $ts <= 0) {
  4491. $this->error('截止时间格式无效');
  4492. }
  4493. return date('Y-m-d H:i:s', $ts);
  4494. }
  4495. protected function formatProcuremenSysRqForInput($sysRq): string
  4496. {
  4497. $sr = trim((string)$sysRq);
  4498. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  4499. return '';
  4500. }
  4501. $ts = strtotime($sr);
  4502. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  4503. }
  4504. /**
  4505. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  4506. * @return array{ccydh?:string,pos:array,merge_rows:array}
  4507. */
  4508. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  4509. {
  4510. $sysRqPost = trim($sysRqPost);
  4511. if ($sysRqPost === '') {
  4512. return $bundle;
  4513. }
  4514. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqPost, true);
  4515. $pos = $bundle['pos'] ?? [];
  4516. foreach ($pos as $poRow) {
  4517. if (!is_array($poRow)) {
  4518. continue;
  4519. }
  4520. $sid = (int)($poRow['scydgy_id'] ?? 0);
  4521. if (!$this->isValidScydgyRowId($sid)) {
  4522. continue;
  4523. }
  4524. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['sys_rq' => $sysRqDb]);
  4525. }
  4526. foreach ($pos as $i => $poRow) {
  4527. if (is_array($pos[$i])) {
  4528. $pos[$i]['sys_rq'] = $sysRqDb;
  4529. }
  4530. }
  4531. $bundle['pos'] = $pos;
  4532. return $bundle;
  4533. }
  4534. /**
  4535. * 写入/更新 purchase_order(单道工序行)
  4536. */
  4537. protected function upsertPurchaseOrderFromRow(
  4538. array $row,
  4539. string $sysRqDb,
  4540. ?int $wflowStatus = null,
  4541. ?string $pickTime = null,
  4542. ?array $exists = null
  4543. ): void {
  4544. $ids = $this->extractScydgyRowId($row);
  4545. if (!$this->isValidScydgyRowId($ids)) {
  4546. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  4547. }
  4548. if ($exists === null) {
  4549. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4550. }
  4551. $data = [
  4552. 'scydgy_id' => $ids,
  4553. 'CCYDH' => $row['CCYDH'] ?? null,
  4554. 'CYJMC' => $row['CYJMC'] ?? null,
  4555. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4556. 'CDXMC' => $row['CDXMC'] ?? null,
  4557. 'CGYBH' => $row['CGYBH'] ?? null,
  4558. 'CGYMC' => $row['CGYMC'] ?? null,
  4559. 'CDW' => $row['CDW'] ?? null,
  4560. 'NGZL' => $row['NGZL'] ?? null,
  4561. 'CDF' => $row['CDF'] ?? null,
  4562. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4563. 'MBZ' => $row['MBZ'] ?? null,
  4564. 'bwjg' => $row['bwjg'] ?? null,
  4565. 'iStatus' => $row['iStatus'] ?? null,
  4566. 'dStamp' => $row['dStamp'] ?? null,
  4567. 'dputrecord' => $row['dputrecord'] ?? null,
  4568. 'cywyxm' => $row['cywyxm'] ?? null,
  4569. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4570. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4571. 'status' => 0,
  4572. 'sys_rq' => $sysRqDb,
  4573. ];
  4574. if ($wflowStatus !== null) {
  4575. $data['wflow_status'] = $wflowStatus;
  4576. }
  4577. if ($pickTime !== null && $pickTime !== '') {
  4578. $data['pick_time'] = $pickTime;
  4579. $data['pick_company_name'] = '';
  4580. }
  4581. if ($exists) {
  4582. $upd = $data;
  4583. unset($upd['scydgy_id']);
  4584. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4585. } else {
  4586. $data['createtime'] = date('Y-m-d H:i:s');
  4587. Db::table('purchase_order')->insert($data);
  4588. }
  4589. }
  4590. /**
  4591. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  4592. *
  4593. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  4594. */
  4595. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  4596. {
  4597. $toDb = function ($value) {
  4598. if ($value === null) {
  4599. return null;
  4600. }
  4601. if (is_scalar($value)) {
  4602. return $value;
  4603. }
  4604. return json_encode($value, JSON_UNESCAPED_UNICODE);
  4605. };
  4606. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  4607. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  4608. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  4609. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  4610. if ($username === '') {
  4611. $username = $this->resolveCustomerContactName($phone, $companyName);
  4612. }
  4613. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  4614. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  4615. }
  4616. if ($phone === '') {
  4617. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  4618. }
  4619. $detailLinks = [];
  4620. foreach ($mergeRows as $row) {
  4621. if (!is_array($row)) {
  4622. continue;
  4623. }
  4624. $sid = $this->extractScydgyRowId($row);
  4625. $detailId = 0;
  4626. if ($skipExisting) {
  4627. try {
  4628. $existsQuery = Db::table('purchase_order_detail')
  4629. ->where('scydgy_id', $sid)
  4630. ->where('company_name', $companyName);
  4631. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  4632. $exists = $existsQuery->find();
  4633. } catch (\Throwable $e) {
  4634. $exists = null;
  4635. }
  4636. if (is_array($exists)) {
  4637. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  4638. }
  4639. }
  4640. if ($detailId <= 0) {
  4641. $one = [
  4642. 'scydgy_id' => $toDb($sid),
  4643. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  4644. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  4645. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  4646. 'username' => $username !== '' ? $username : null,
  4647. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  4648. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  4649. 'createtime' => date('Y-m-d H:i:s'),
  4650. 'status' => 0,
  4651. 'status_name' => '未提交',
  4652. ];
  4653. Db::table('purchase_order_detail')->insert($one);
  4654. $detailId = (int)Db::getLastInsID();
  4655. }
  4656. $mprocUrl = '';
  4657. if ($buildMobileLinks && $detailId > 0) {
  4658. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  4659. }
  4660. $detailLinks[] = [
  4661. 'detail_id' => $detailId,
  4662. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  4663. 'url' => $mprocUrl,
  4664. ];
  4665. }
  4666. return $detailLinks;
  4667. }
  4668. /**
  4669. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  4670. * @return array<string, mixed>
  4671. */
  4672. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  4673. {
  4674. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  4675. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  4676. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  4677. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  4678. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  4679. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  4680. $isMerge = !empty($ctx['is_merge']);
  4681. $contactName = trim((string)($c['username'] ?? ''));
  4682. if ($contactName === '') {
  4683. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  4684. }
  4685. $notifyVars = [
  4686. 'company_name' => $companyName,
  4687. 'contact_name' => $contactName,
  4688. 'phone' => $phone,
  4689. 'email' => $toEmail,
  4690. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  4691. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  4692. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  4693. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  4694. 'deadline' => (string)($ctx['deadline'] ?? ''),
  4695. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  4696. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  4697. 'platform_url' => $platformUrl,
  4698. 'platform_links' => $platformLinksPlain,
  4699. 'platform_links_html' => $platformLinksHtml,
  4700. ];
  4701. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  4702. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  4703. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  4704. return [
  4705. 'company_name' => $companyName,
  4706. 'phone' => $phone,
  4707. 'email' => $toEmail,
  4708. 'sms_content' => $smsContent,
  4709. 'mail_plain' => $mailPlain,
  4710. 'mail_body' => $mailBody,
  4711. 'notify_vars' => $notifyVars,
  4712. 'detail_links' => $detailLinks,
  4713. ];
  4714. }
  4715. /**
  4716. * 确认供应商 — 向选定一家发送短信/邮件(第二步)
  4717. *
  4718. * @param array<string, mixed> $chosen
  4719. * @param array<int, array<string, mixed>> $mergeRows
  4720. * @param array{ccydh:string, pos:array} $bundle
  4721. */
  4722. protected function sendAuditSupplierConfirmNotify(array $chosen, array $mergeRows, array $bundle): void
  4723. {
  4724. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, true, true);
  4725. }
  4726. /**
  4727. * @param array<string, mixed> $chosen
  4728. * @param array<int, array<string, mixed>> $mergeRows
  4729. * @param array{ccydh:string, pos:array} $bundle
  4730. */
  4731. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail): void
  4732. {
  4733. if (!$sendSms && !$sendEmail) {
  4734. return;
  4735. }
  4736. $companyName = trim((string)($chosen['name'] ?? ''));
  4737. $phone = trim((string)($chosen['phone'] ?? ''));
  4738. $toEmail = trim((string)($chosen['email'] ?? ''));
  4739. if ($companyName === '') {
  4740. throw new \Exception('供应商名称无效');
  4741. }
  4742. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  4743. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  4744. }
  4745. if ($sendSms && $phone === '') {
  4746. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  4747. }
  4748. $sids = [];
  4749. foreach ($mergeRows as $mr) {
  4750. if (!is_array($mr)) {
  4751. continue;
  4752. }
  4753. $sid = $this->extractScydgyRowId($mr);
  4754. if ($this->isValidScydgyRowId($sid)) {
  4755. $sids[$sid] = true;
  4756. }
  4757. }
  4758. if ($sids === []) {
  4759. throw new \Exception('未找到工序行,无法发送通知');
  4760. }
  4761. $sysRqNotify = '';
  4762. $pos = $bundle['pos'] ?? [];
  4763. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  4764. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  4765. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  4766. $ts = strtotime($sr);
  4767. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  4768. }
  4769. }
  4770. try {
  4771. $detailsQuery = Db::table('purchase_order_detail')
  4772. ->where('scydgy_id', 'in', array_keys($sids))
  4773. ->where('company_name', $companyName);
  4774. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  4775. $details = $detailsQuery->order('id', 'asc')->select();
  4776. } catch (\Throwable $e) {
  4777. $details = [];
  4778. }
  4779. if (!is_array($details) || $details === []) {
  4780. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  4781. try {
  4782. $detailsQuery = Db::table('purchase_order_detail')
  4783. ->where('scydgy_id', 'in', array_keys($sids))
  4784. ->where('company_name', $companyName);
  4785. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  4786. $details = $detailsQuery->order('id', 'asc')->select();
  4787. } catch (\Throwable $e) {
  4788. $details = [];
  4789. }
  4790. }
  4791. if (!is_array($details) || $details === []) {
  4792. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  4793. }
  4794. $detailLinks = [];
  4795. foreach ($details as $d) {
  4796. if (!is_array($d)) {
  4797. continue;
  4798. }
  4799. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  4800. if ($detailId <= 0) {
  4801. continue;
  4802. }
  4803. $sid = (int)($d['scydgy_id'] ?? 0);
  4804. $gymc = '';
  4805. foreach ($mergeRows as $mr) {
  4806. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  4807. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  4808. break;
  4809. }
  4810. }
  4811. $detailLinks[] = [
  4812. 'detail_id' => $detailId,
  4813. 'cgymc' => $gymc,
  4814. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  4815. ];
  4816. }
  4817. if ($detailLinks === []) {
  4818. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  4819. }
  4820. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  4821. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  4822. if ($sendEmail) {
  4823. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  4824. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  4825. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  4826. }
  4827. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  4828. $mailConfig = $this->loadMailerConfig();
  4829. if (!$this->isProcuremenNotifyDryRun()) {
  4830. if (empty($mailConfig['host'])) {
  4831. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  4832. }
  4833. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  4834. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  4835. }
  4836. }
  4837. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  4838. }
  4839. if ($sendSms) {
  4840. $this->issueSendSupplierSms($notifyBundle);
  4841. }
  4842. }
  4843. /**
  4844. * @param array<int, array<string, mixed>> $quoteGroups
  4845. * @return array<int, array<string, mixed>>
  4846. */
  4847. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  4848. {
  4849. $names = [];
  4850. if (is_string($companiesJson) && $companiesJson !== '') {
  4851. $decoded = json_decode($companiesJson, true);
  4852. if (is_array($decoded)) {
  4853. foreach ($decoded as $nm) {
  4854. $nm = trim((string)$nm);
  4855. if ($nm !== '') {
  4856. $names[] = $nm;
  4857. }
  4858. }
  4859. }
  4860. }
  4861. $names = array_values(array_unique($names));
  4862. if ($names === [] && $selectedCompany !== '') {
  4863. $names = [$selectedCompany];
  4864. }
  4865. if ($names === []) {
  4866. return $quoteGroups;
  4867. }
  4868. $targets = [];
  4869. foreach ($quoteGroups as $g) {
  4870. if (!is_array($g)) {
  4871. continue;
  4872. }
  4873. $cn = trim((string)($g['name'] ?? ''));
  4874. if ($cn !== '' && in_array($cn, $names, true)) {
  4875. $targets[] = $g;
  4876. }
  4877. }
  4878. return $targets;
  4879. }
  4880. /**
  4881. * @return array{pos:array, merge_rows:array, bundle:array}
  4882. */
  4883. protected function loadAuditResendBundle(string $scydgyId): array
  4884. {
  4885. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  4886. $pos = $bundle['pos'];
  4887. $mergeRows = $bundle['merge_rows'];
  4888. if ($pos === [] || $mergeRows === []) {
  4889. $this->error('该订单不在待确认供应商状态');
  4890. }
  4891. $sysRqDb = '';
  4892. if (isset($pos[0]) && is_array($pos[0])) {
  4893. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  4894. }
  4895. foreach ($pos as $i => $poRow) {
  4896. if (is_array($pos[$i]) && $sysRqDb !== '') {
  4897. $pos[$i]['sys_rq'] = $sysRqDb;
  4898. }
  4899. }
  4900. $bundle['pos'] = $pos;
  4901. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  4902. }
  4903. /**
  4904. * @param array<int, array<string, mixed>> $targets
  4905. */
  4906. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  4907. {
  4908. if ($targets === []) {
  4909. $this->error('未找到可通知的供应商');
  4910. }
  4911. $notifyErrors = [];
  4912. try {
  4913. $this->notifyDryRunPreview = [];
  4914. foreach ($targets as $g) {
  4915. if (!is_array($g)) {
  4916. continue;
  4917. }
  4918. $cname = trim((string)($g['name'] ?? ''));
  4919. if ($cname === '') {
  4920. continue;
  4921. }
  4922. $chosen = [
  4923. 'name' => $cname,
  4924. 'company_name' => $cname,
  4925. 'email' => trim((string)($g['email'] ?? '')),
  4926. 'phone' => trim((string)($g['phone'] ?? '')),
  4927. 'username' => trim((string)($g['username'] ?? '')),
  4928. ];
  4929. try {
  4930. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail);
  4931. } catch (\Throwable $e) {
  4932. $notifyErrors[] = $cname . ':' . $e->getMessage();
  4933. }
  4934. }
  4935. } catch (\Throwable $e) {
  4936. $this->error('通知发送失败:' . $e->getMessage());
  4937. }
  4938. if ($notifyErrors !== []) {
  4939. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  4940. }
  4941. if ($this->isProcuremenNotifyDryRun()) {
  4942. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  4943. 'notify_dry_run' => true,
  4944. 'notify_preview' => $this->notifyDryRunPreview,
  4945. ]);
  4946. }
  4947. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  4948. }
  4949. /**
  4950. * 协助下发 — 写入下发明细并拼好短信/邮件内容(供第二步发送)
  4951. *
  4952. * @return array<string, mixed>
  4953. */
  4954. protected function issueBuildSupplierNotifyBundle(array $c, array $mergeRows, array $ctx): array
  4955. {
  4956. $detailLinks = $this->issuePersistSupplierDetails($c, $mergeRows);
  4957. return $this->composeSupplierNotifyBundle($c, $ctx, $detailLinks);
  4958. }
  4959. /**
  4960. * 协助下发 — 发送短信(一家供应商)
  4961. *
  4962. * @param array<string, mixed> $bundle issueBuildSupplierNotifyBundle 返回值
  4963. */
  4964. protected function issueSendSupplierSms(array $bundle): void
  4965. {
  4966. $companyName = (string)($bundle['company_name'] ?? '');
  4967. $phone = (string)($bundle['phone'] ?? '');
  4968. $smsContent = (string)($bundle['sms_content'] ?? '');
  4969. $this->logIssueNotifyDebug('短信', [
  4970. 'company' => $companyName,
  4971. 'phone' => $phone,
  4972. 'sms_content' => $smsContent,
  4973. ]);
  4974. if ($this->isProcuremenNotifyDryRun()) {
  4975. $this->recordNotifyDryRunPreview([
  4976. 'scene' => 'issue_sms',
  4977. 'company_name' => $companyName,
  4978. 'phone' => $phone,
  4979. 'sms_content' => $smsContent,
  4980. ]);
  4981. return;
  4982. }
  4983. $this->smsbao($phone, $smsContent);
  4984. }
  4985. /**
  4986. * 协助下发 — 发送邮件(一家供应商)
  4987. *
  4988. * @param array<string, mixed> $bundle
  4989. * @param array<string, mixed> $mailConfig
  4990. */
  4991. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  4992. {
  4993. $companyName = (string)($bundle['company_name'] ?? '');
  4994. $toEmail = (string)($bundle['email'] ?? '');
  4995. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  4996. $mailBody = (string)($bundle['mail_body'] ?? '');
  4997. $this->logIssueNotifyDebug('邮件', [
  4998. 'company' => $companyName,
  4999. 'email' => $toEmail,
  5000. 'mail_subject' => $mailSubject,
  5001. 'mail_body' => $mailPlain,
  5002. ]);
  5003. if ($this->isProcuremenNotifyDryRun()) {
  5004. $this->recordNotifyDryRunPreview([
  5005. 'scene' => 'issue_email',
  5006. 'company_name' => $companyName,
  5007. 'email' => $toEmail,
  5008. 'mail_subject' => $mailSubject,
  5009. 'mail_body' => $mailPlain,
  5010. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  5011. 'notify_vars' => $bundle['notify_vars'] ?? [],
  5012. 'detail_links' => $bundle['detail_links'] ?? [],
  5013. ]);
  5014. return;
  5015. }
  5016. $mail = new PHPMailer(true);
  5017. $mail->isSMTP();
  5018. $mail->Host = $mailConfig['host'];
  5019. $mail->SMTPAuth = true;
  5020. $mail->Username = $mailConfig['addr'];
  5021. $mail->Password = $mailConfig['pass'];
  5022. $mail->SMTPSecure = $mailConfig['security'];
  5023. $mail->Port = $mailConfig['port'];
  5024. $mail->CharSet = $mailConfig['charset'];
  5025. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  5026. $mail->addAddress($toEmail, $companyName);
  5027. $mail->isHTML(true);
  5028. $mail->Subject = $mailSubject;
  5029. $mail->Body = $mailBody;
  5030. $mail->send();
  5031. }
  5032. /**
  5033. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  5034. *
  5035. * @param array<int, array<string, mixed>> $mergeRows
  5036. * @return array<string, mixed>
  5037. */
  5038. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  5039. {
  5040. $head = $mergeRows[0] ?? [];
  5041. $isMerge = count($mergeRows) > 1;
  5042. return [
  5043. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  5044. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  5045. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  5046. 'is_merge' => $isMerge,
  5047. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  5048. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  5049. 'deadline' => $sysRqNotify,
  5050. ];
  5051. }
  5052. /**
  5053. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  5054. *
  5055. * @param array<string, mixed> $data
  5056. */
  5057. protected function logIssueNotifyDebug(string $type, array $data): void
  5058. {
  5059. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  5060. return;
  5061. }
  5062. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  5063. }
  5064. /**
  5065. * 协助下发弹窗(选多家供应商并通知)
  5066. */
  5067. public function pickReview()
  5068. {
  5069. if ($this->request->isPost()) {
  5070. $this->error('请使用弹窗内「确认下发」提交');
  5071. }
  5072. $this->view->assign('pickMode', 1);
  5073. return $this->view->fetch('procuremen/review');
  5074. }
  5075. /**
  5076. * 协助新增(独立页面)
  5077. */
  5078. public function add()
  5079. {
  5080. if ($this->request->isPost()) {
  5081. $params = $this->request->post('row/a');
  5082. if (!is_array($params)) {
  5083. $this->error(__('Parameter %s can not be empty', ''));
  5084. }
  5085. [, $adminName] = $this->GetUseName();
  5086. $params['cywyxm'] = $adminName;
  5087. try {
  5088. $sid = $this->saveManualPickOrder($params);
  5089. } catch (\InvalidArgumentException $e) {
  5090. $this->error($e->getMessage());
  5091. } catch (\Throwable $e) {
  5092. $this->error($e->getMessage());
  5093. }
  5094. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  5095. }
  5096. [, $adminName] = $this->GetUseName();
  5097. $this->view->assign('adminNickname', $adminName);
  5098. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  5099. return $this->view->fetch();
  5100. }
  5101. /**
  5102. * 业务员新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  5103. */
  5104. public function rfqlist()
  5105. {
  5106. $this->relationSearch = false;
  5107. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  5108. $this->request->filter(['strip_tags', 'trim']);
  5109. if ($this->request->isAjax()) {
  5110. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  5111. $limit = max(10, min(500, (int)$limit));
  5112. $applyFilters = function ($query) use ($where) {
  5113. $query->where('scydgy_id', '<', 0);
  5114. $query->whereRaw(
  5115. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  5116. );
  5117. if (!$this->auth->isSuperAdmin()) {
  5118. [, $adminName] = $this->GetUseName();
  5119. $query->where('cywyxm', $adminName);
  5120. }
  5121. if (!empty($where)) {
  5122. $query->where($where);
  5123. }
  5124. };
  5125. $countQuery = Db::table('purchase_order');
  5126. $applyFilters($countQuery);
  5127. $total = (int)$countQuery->count();
  5128. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  5129. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  5130. $listQuery = Db::table('purchase_order');
  5131. $applyFilters($listQuery);
  5132. $rows = $listQuery
  5133. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  5134. ->order($sortField, $orderDir)
  5135. ->limit($offset, $limit)
  5136. ->select();
  5137. if (!is_array($rows)) {
  5138. $rows = [];
  5139. }
  5140. $out = [];
  5141. foreach ($rows as $r) {
  5142. if (!is_array($r)) {
  5143. continue;
  5144. }
  5145. $sid = (int)($r['scydgy_id'] ?? 0);
  5146. if ($sid >= 0) {
  5147. continue;
  5148. }
  5149. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  5150. if ($createdText === '') {
  5151. $createdText = trim((string)($r['dStamp'] ?? ''));
  5152. }
  5153. $out[] = [
  5154. 'id' => (int)($r['id'] ?? 0),
  5155. 'scydgy_id' => $sid,
  5156. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  5157. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  5158. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  5159. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  5160. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  5161. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  5162. 'createtime' => $r['createtime'] ?? null,
  5163. 'createtime_text' => $createdText,
  5164. ];
  5165. }
  5166. return json(['total' => $total, 'rows' => $out]);
  5167. }
  5168. [, $adminName] = $this->GetUseName();
  5169. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  5170. $this->view->assign('adminNickname', $adminName);
  5171. return $this->view->fetch('procuremen/rfqlist');
  5172. }
  5173. /**
  5174. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  5175. */
  5176. public function rfqlistDetails()
  5177. {
  5178. return $this->details();
  5179. }
  5180. /**
  5181. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  5182. */
  5183. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  5184. {
  5185. if ($scydgyId >= 0) {
  5186. return;
  5187. }
  5188. try {
  5189. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5190. } catch (\Throwable $e) {
  5191. $po = null;
  5192. }
  5193. if (!is_array($po)) {
  5194. $this->error('订单不存在');
  5195. }
  5196. $modRq = trim((string)($po['mod_rq'] ?? ''));
  5197. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  5198. $this->error('订单不存在');
  5199. }
  5200. if ($this->auth->isSuperAdmin()) {
  5201. return;
  5202. }
  5203. [, $adminName] = $this->GetUseName();
  5204. $cywy = trim((string)($po['cywyxm'] ?? ''));
  5205. if ($cywy !== '' && $cywy === $adminName) {
  5206. return;
  5207. }
  5208. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  5209. try {
  5210. if ($this->auth->check($rule)) {
  5211. return;
  5212. }
  5213. } catch (\Throwable $e) {
  5214. }
  5215. }
  5216. $this->error('无权查看该订单');
  5217. }
  5218. /**
  5219. * @deprecated 使用 {@see assertManualOrderDetailsViewable}
  5220. */
  5221. protected function assertRfqRowViewable(int $scydgyId): void
  5222. {
  5223. $this->assertManualOrderDetailsViewable($scydgyId);
  5224. }
  5225. /**
  5226. * 手工新增协助工序进度文案
  5227. */
  5228. protected function formatProcuremenRfqProgressText(array $row): string
  5229. {
  5230. $st = trim((string)($row['status'] ?? ''));
  5231. // status=1 才表示主单已完结;status=0 为流程进行中(与详情 buildProcuremenDetailsViewData 一致)
  5232. if ($st === '1') {
  5233. return '已完结';
  5234. }
  5235. $wf = (int)($row['wflow_status'] ?? 0);
  5236. if ($wf === 2) {
  5237. return '待采购确认';
  5238. }
  5239. if ($wf === 1) {
  5240. return '待确认供应商';
  5241. }
  5242. $sid = (int)($row['scydgy_id'] ?? 0);
  5243. if ($sid < 0) {
  5244. try {
  5245. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  5246. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  5247. $detCnt = (int)$detCntQuery->count();
  5248. if ($detCnt > 0) {
  5249. return '已下发待确认';
  5250. }
  5251. } catch (\Throwable $e) {
  5252. }
  5253. }
  5254. return '待协助下发';
  5255. }
  5256. /**
  5257. * 协助初选列表 — 批量软删除
  5258. */
  5259. public function pickDelete()
  5260. {
  5261. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5262. $this->error(__('Invalid parameters'));
  5263. }
  5264. $rowsRaw = $this->request->post('rows_json', '[]');
  5265. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  5266. if (!is_array($rows) || $rows === []) {
  5267. $this->error('请至少勾选一条工序');
  5268. }
  5269. $done = 0;
  5270. Db::startTrans();
  5271. try {
  5272. foreach ($rows as $row) {
  5273. if (!is_array($row)) {
  5274. continue;
  5275. }
  5276. $this->softDeleteProcuremenPickRow($row);
  5277. $done++;
  5278. }
  5279. if ($done < 1) {
  5280. throw new \Exception('没有可删除的工序');
  5281. }
  5282. Db::commit();
  5283. } catch (\InvalidArgumentException $e) {
  5284. Db::rollback();
  5285. $this->error($e->getMessage());
  5286. } catch (\Throwable $e) {
  5287. Db::rollback();
  5288. $this->error($e->getMessage());
  5289. }
  5290. $this->success('已删除 ' . $done . ' 条工序');
  5291. }
  5292. /**
  5293. * 协助下发 — 手工新增工序(弹窗)
  5294. */
  5295. public function pickAdd()
  5296. {
  5297. if ($this->request->isPost()) {
  5298. $params = $this->request->post('row/a');
  5299. if (!is_array($params)) {
  5300. $this->error(__('Parameter %s can not be empty', ''));
  5301. }
  5302. try {
  5303. $sid = $this->saveManualPickOrder($params);
  5304. } catch (\InvalidArgumentException $e) {
  5305. $this->error($e->getMessage());
  5306. } catch (\Throwable $e) {
  5307. $this->error($e->getMessage());
  5308. }
  5309. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  5310. }
  5311. return $this->view->fetch('procuremen/pick_add');
  5312. }
  5313. /**
  5314. * 协助下发提交 — 弹窗「确认下发」→ POST procuremen/picksubmit
  5315. */
  5316. public function pickSubmit()
  5317. {
  5318. if (!$this->request->isPost()) {
  5319. $this->error(__('Invalid parameters'));
  5320. }
  5321. // ---------- 接口订单数据 ----------
  5322. $rowJson = $this->request->post('row_json', '');
  5323. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  5324. $companiesJson = $this->request->post('companies_json', '[]');
  5325. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  5326. $companies = json_decode($companiesJson, true);
  5327. if (!is_array($companies)) {
  5328. $this->error('供应商数据无效');
  5329. }
  5330. $issueCompanies = $this->normalizePickCompanies($companies);
  5331. if ($issueCompanies === []) {
  5332. $this->error('请至少选择一家合作供应商');
  5333. }
  5334. $issueNameLabels = [];
  5335. foreach ($issueCompanies as $pc) {
  5336. $issueNameLabels[] = $pc['name'];
  5337. }
  5338. $issueNamesSummary = implode('、', $issueNameLabels);
  5339. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  5340. if ($sysRq === '') {
  5341. $this->error('请选择截止时间');
  5342. }
  5343. $sysRqTs = strtotime($sysRq);
  5344. if ($sysRqTs === false || $sysRqTs <= 0) {
  5345. $this->error('截止时间格式无效');
  5346. }
  5347. $sysRqDb = date('Y-m-d H:i:s', $sysRqTs);
  5348. $isMerge = count($mergeRows) > 1;
  5349. $logMsg = ($isMerge ? '合并协助初选(' . count($mergeRows) . ' 道工序)' : '协助初选')
  5350. . ',通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  5351. $issueTime = date('Y-m-d H:i:s');
  5352. $logSidList = [];
  5353. foreach ($mergeRows as $row) {
  5354. if (!is_array($row)) {
  5355. continue;
  5356. }
  5357. $sid = $this->extractScydgyRowId($row);
  5358. if ($this->isValidScydgyRowId($sid)) {
  5359. $logSidList[$sid] = true;
  5360. }
  5361. }
  5362. $existingBySid = [];
  5363. if ($logSidList !== []) {
  5364. try {
  5365. $existingRows = Db::table('purchase_order')
  5366. ->where('scydgy_id', 'in', array_keys($logSidList))
  5367. ->select();
  5368. if (is_array($existingRows)) {
  5369. foreach ($existingRows as $poRow) {
  5370. if (!is_array($poRow)) {
  5371. continue;
  5372. }
  5373. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5374. if ($this->isValidScydgyRowId($sid)) {
  5375. $existingBySid[$sid] = $poRow;
  5376. }
  5377. }
  5378. }
  5379. } catch (\Throwable $e) {
  5380. $existingBySid = [];
  5381. }
  5382. }
  5383. Db::startTrans();
  5384. try {
  5385. // ---------- 主表 wflow_status=1;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  5386. foreach ($mergeRows as $row) {
  5387. if (!is_array($row)) {
  5388. continue;
  5389. }
  5390. $sid = $this->extractScydgyRowId($row);
  5391. $this->upsertPurchaseOrderFromRow(
  5392. $row,
  5393. $sysRqDb,
  5394. 1,
  5395. $issueTime,
  5396. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null
  5397. );
  5398. }
  5399. foreach ($issueCompanies as $c) {
  5400. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  5401. }
  5402. Db::commit();
  5403. } catch (\Throwable $e) {
  5404. Db::rollback();
  5405. $this->error($e->getMessage());
  5406. }
  5407. $poIdBySid = [];
  5408. if ($logSidList !== []) {
  5409. try {
  5410. $poIdBySid = Db::table('purchase_order')
  5411. ->where('scydgy_id', 'in', array_keys($logSidList))
  5412. ->column('id', 'scydgy_id');
  5413. } catch (\Throwable $e) {
  5414. $poIdBySid = [];
  5415. }
  5416. }
  5417. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  5418. if ($logSidList !== []) {
  5419. list($adminId, $adminName) = $this->GetUseName();
  5420. $cut = function ($s, $max) {
  5421. if (function_exists('mb_substr')) {
  5422. return mb_substr($s, 0, $max, 'UTF-8');
  5423. }
  5424. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  5425. };
  5426. $logRows = [];
  5427. $seenLogSid = [];
  5428. foreach ($mergeRows as $row) {
  5429. if (!is_array($row)) {
  5430. continue;
  5431. }
  5432. $ids = $this->extractScydgyRowId($row);
  5433. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  5434. continue;
  5435. }
  5436. $seenLogSid[$ids] = true;
  5437. $poIdLog = null;
  5438. if (isset($poIdBySid[$ids])) {
  5439. $tid = (int)$poIdBySid[$ids];
  5440. $poIdLog = $tid > 0 ? $tid : null;
  5441. }
  5442. $logRows[] = [
  5443. 'scydgy_id' => $ids,
  5444. 'purchase_order_id' => $poIdLog,
  5445. 'admin_id' => $adminId,
  5446. 'admin_name' => $cut($adminName, 64),
  5447. 'action' => $cut('issue_submit', 64),
  5448. 'content' => $cut($logMsg, 1000),
  5449. 'createtime' => time(),
  5450. ];
  5451. }
  5452. if ($logRows !== []) {
  5453. try {
  5454. Db::table('purchase_order_oper_log')->insertAll($logRows);
  5455. } catch (\Throwable $e) {
  5456. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  5457. }
  5458. }
  5459. }
  5460. $notifyErrors = [];
  5461. $posNotify = [];
  5462. if ($logSidList !== []) {
  5463. try {
  5464. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  5465. } catch (\Throwable $e) {
  5466. $posNotify = [];
  5467. }
  5468. }
  5469. if (!is_array($posNotify)) {
  5470. $posNotify = [];
  5471. }
  5472. foreach ($posNotify as $i => $prow) {
  5473. if (is_array($posNotify[$i])) {
  5474. $posNotify[$i]['sys_rq'] = $sysRqDb;
  5475. }
  5476. }
  5477. $ccydhPick = '';
  5478. foreach ($mergeRows as $row) {
  5479. if (!is_array($row)) {
  5480. continue;
  5481. }
  5482. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  5483. if ($ccydhPick !== '') {
  5484. break;
  5485. }
  5486. }
  5487. $notifyBundleBase = [
  5488. 'ccydh' => $ccydhPick,
  5489. 'pos' => $posNotify,
  5490. 'merge_rows' => $mergeRows,
  5491. ];
  5492. try {
  5493. $this->notifyDryRunPreview = [];
  5494. foreach ($issueCompanies as $c) {
  5495. if (!is_array($c)) {
  5496. continue;
  5497. }
  5498. $cname = trim((string)($c['name'] ?? ''));
  5499. if ($cname === '') {
  5500. continue;
  5501. }
  5502. try {
  5503. $this->sendAuditSupplierConfirmNotify($c, $mergeRows, $notifyBundleBase);
  5504. } catch (\Throwable $e) {
  5505. $notifyErrors[] = $cname . ':' . $e->getMessage();
  5506. }
  5507. }
  5508. } catch (\Throwable $e) {
  5509. $this->error('通知发送失败:' . $e->getMessage());
  5510. }
  5511. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  5512. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  5513. }
  5514. if ($this->isProcuremenNotifyDryRun()) {
  5515. $this->success('【演练模式】已保存并生成通知预览', '', [
  5516. 'notify_dry_run' => true,
  5517. 'notify_preview' => $this->notifyDryRunPreview,
  5518. ]);
  5519. }
  5520. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  5521. }
  5522. /**
  5523. * 确认供应商弹窗
  5524. */
  5525. public function auditIssue()
  5526. {
  5527. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5528. if (is_array($ids)) {
  5529. $ids = isset($ids[0]) ? $ids[0] : '';
  5530. }
  5531. $ids = trim((string)$ids);
  5532. if ($ids === '') {
  5533. $this->error(__('Invalid parameters'));
  5534. }
  5535. if ($this->request->isPost()) {
  5536. $this->error('请使用弹窗内「确认」提交');
  5537. }
  5538. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  5539. $pos = $bundle['pos'];
  5540. if ($pos === []) {
  5541. $this->error('该订单不在待确认供应商状态');
  5542. }
  5543. $po = $pos[0];
  5544. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5545. if ($quoteGroups === []) {
  5546. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  5547. }
  5548. $pickedName = '';
  5549. foreach ($pos as $poRow) {
  5550. if (!is_array($poRow)) {
  5551. continue;
  5552. }
  5553. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  5554. if ($pn !== '') {
  5555. $pickedName = $pn;
  5556. break;
  5557. }
  5558. }
  5559. $this->view->assign('po', $po);
  5560. $this->view->assign('scydgyId', $ids);
  5561. $this->view->assign('orderCcydh', $bundle['ccydh']);
  5562. $mergeRows = $bundle['merge_rows'];
  5563. $this->view->assign('processRows', $mergeRows);
  5564. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  5565. $this->view->assign('processCount', count($mergeRows));
  5566. $this->view->assign('quoteGroups', $quoteGroups);
  5567. $this->view->assign('quoteGroupsJson', json_encode($quoteGroups, JSON_UNESCAPED_UNICODE));
  5568. $this->view->assign('pickedCompanyName', $pickedName);
  5569. $this->view->assign('sysRq', $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null));
  5570. return $this->view->fetch('procuremen/audit_issue');
  5571. }
  5572. /**
  5573. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  5574. */
  5575. public function auditSubmit()
  5576. {
  5577. if (!$this->request->isPost()) {
  5578. $this->error(__('Invalid parameters'));
  5579. }
  5580. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5581. if ($scydgyId === '') {
  5582. $this->error('参数无效');
  5583. }
  5584. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  5585. $pos = $bundle['pos'];
  5586. $mergeRows = $bundle['merge_rows'];
  5587. if ($pos === [] || $mergeRows === []) {
  5588. $this->error('该订单不在待确认供应商状态');
  5589. }
  5590. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5591. if ($quoteGroups === []) {
  5592. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  5593. }
  5594. $companyName = trim((string)$this->request->post('selected_company', ''));
  5595. if ($companyName === '') {
  5596. $this->error('请选择一家供应商');
  5597. }
  5598. $matched = null;
  5599. foreach ($quoteGroups as $g) {
  5600. if (!is_array($g)) {
  5601. continue;
  5602. }
  5603. if (trim((string)($g['name'] ?? '')) === $companyName) {
  5604. $matched = $g;
  5605. break;
  5606. }
  5607. }
  5608. if ($matched === null) {
  5609. $this->error('所选供应商不在本单报价列表中');
  5610. }
  5611. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true);
  5612. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  5613. $procCnt = count($mergeRows);
  5614. $logMsg = '确认供应商(订单' . ($ccydhLog !== '' ? $ccydhLog : '')
  5615. . ($procCnt > 1 ? ',' . $procCnt . ' 道工序' : '')
  5616. . '),选定:' . $companyName;
  5617. Db::startTrans();
  5618. try {
  5619. foreach ($pos as $poRow) {
  5620. if (!is_array($poRow)) {
  5621. continue;
  5622. }
  5623. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5624. if (!$this->isValidScydgyRowId($sid)) {
  5625. continue;
  5626. }
  5627. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  5628. 'wflow_status' => 2,
  5629. 'status' => 0,
  5630. 'pick_company_name' => $companyName,
  5631. 'sys_rq' => $sysRqDb,
  5632. ]);
  5633. }
  5634. Db::commit();
  5635. } catch (\Throwable $e) {
  5636. Db::rollback();
  5637. $this->error($e->getMessage());
  5638. }
  5639. foreach ($pos as $poRow) {
  5640. if (!is_array($poRow)) {
  5641. continue;
  5642. }
  5643. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5644. if (!$this->isValidScydgyRowId($sid)) {
  5645. continue;
  5646. }
  5647. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  5648. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  5649. }
  5650. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  5651. }
  5652. /**
  5653. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  5654. */
  5655. public function auditResendSms()
  5656. {
  5657. if (!$this->request->isPost()) {
  5658. $this->error(__('Invalid parameters'));
  5659. }
  5660. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5661. if ($scydgyId === '') {
  5662. $this->error('参数无效');
  5663. }
  5664. $loaded = $this->loadAuditResendBundle($scydgyId);
  5665. $mergeRows = $loaded['merge_rows'];
  5666. $bundle = $loaded['bundle'];
  5667. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  5668. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5669. if ($quoteGroups === []) {
  5670. $this->error('暂无可通知的供应商');
  5671. }
  5672. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  5673. $companiesJson = (string)$this->request->post('companies_json', '');
  5674. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  5675. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  5676. }
  5677. /**
  5678. * 确认供应商 — 二次发送邮件(可选单家/批量)
  5679. */
  5680. public function auditResendEmail()
  5681. {
  5682. if (!$this->request->isPost()) {
  5683. $this->error(__('Invalid parameters'));
  5684. }
  5685. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5686. if ($scydgyId === '') {
  5687. $this->error('参数无效');
  5688. }
  5689. $loaded = $this->loadAuditResendBundle($scydgyId);
  5690. $mergeRows = $loaded['merge_rows'];
  5691. $bundle = $loaded['bundle'];
  5692. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  5693. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5694. if ($quoteGroups === []) {
  5695. $this->error('暂无可通知的供应商');
  5696. }
  5697. $companiesJson = (string)$this->request->post('companies_json', '');
  5698. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  5699. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  5700. if ($companiesJson === '' && $selectedCompany === '') {
  5701. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  5702. }
  5703. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  5704. }
  5705. /**
  5706. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  5707. *
  5708. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  5709. * @return array<int, true> 已处理的 scydgy_id 集合
  5710. */
  5711. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  5712. {
  5713. $pos = $bundle['pos'] ?? [];
  5714. if (!is_array($pos) || $pos === []) {
  5715. return [];
  5716. }
  5717. $sids = [];
  5718. foreach ($pos as $poRow) {
  5719. if (!is_array($poRow)) {
  5720. continue;
  5721. }
  5722. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5723. if ($this->isValidScydgyRowId($sid)) {
  5724. $sids[$sid] = true;
  5725. }
  5726. }
  5727. if ($sids === []) {
  5728. return [];
  5729. }
  5730. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  5731. $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '') . $logSuffix;
  5732. Db::table('purchase_order')
  5733. ->where('scydgy_id', 'in', array_keys($sids))
  5734. ->update([
  5735. 'wflow_status' => 0,
  5736. 'status' => 0,
  5737. 'pick_company_name' => '',
  5738. 'pick_time' => null,
  5739. 'sys_rq' => null,
  5740. 'mod_rq' => null,
  5741. ]);
  5742. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  5743. foreach (array_keys($sids) as $sid) {
  5744. $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
  5745. }
  5746. return $sids;
  5747. }
  5748. /**
  5749. * 废弃单个审批订单 bundle(退回协助初选,明细归档留痕)
  5750. *
  5751. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  5752. * @return array<int, true> 已处理的 scydgy_id 集合
  5753. */
  5754. protected function abandonAuditOrderBundle(array $bundle): array
  5755. {
  5756. return $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  5757. }
  5758. /**
  5759. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  5760. *
  5761. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  5762. */
  5763. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  5764. {
  5765. $scydgyId = trim($scydgyId);
  5766. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  5767. if ($scydgyId === '') {
  5768. return $empty;
  5769. }
  5770. try {
  5771. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5772. } catch (\Throwable $e) {
  5773. $anchor = null;
  5774. }
  5775. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  5776. return $empty;
  5777. }
  5778. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5779. if ($ccydh === '') {
  5780. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  5781. }
  5782. try {
  5783. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  5784. $query->whereRaw("(TRIM(CAST(`status` AS CHAR)) = '1' OR CAST(`status` AS UNSIGNED) = 1)");
  5785. $pos = $query->order('scydgy_id', 'asc')->select();
  5786. } catch (\Throwable $e) {
  5787. $pos = [$anchor];
  5788. }
  5789. if (!is_array($pos) || $pos === []) {
  5790. $pos = [$anchor];
  5791. }
  5792. return [
  5793. 'ccydh' => $ccydh,
  5794. 'pos' => $pos,
  5795. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  5796. ];
  5797. }
  5798. protected function purchaseOrderRowIsCompleted(array $po): bool
  5799. {
  5800. $st = $po['status'] ?? null;
  5801. if ($st === 1 || $st === '1') {
  5802. return true;
  5803. }
  5804. if (is_string($st) && trim($st) === '1') {
  5805. return true;
  5806. }
  5807. return is_numeric($st) && (int)$st === 1;
  5808. }
  5809. /**
  5810. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  5811. */
  5812. public function auditAbandon()
  5813. {
  5814. if (!$this->request->isPost()) {
  5815. $this->error(__('Invalid parameters'));
  5816. }
  5817. $anchorIds = [];
  5818. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  5819. if ($batchRaw !== '') {
  5820. $decoded = json_decode($batchRaw, true);
  5821. if (is_array($decoded)) {
  5822. foreach ($decoded as $id) {
  5823. $s = trim((string)$id);
  5824. if ($s !== '') {
  5825. $anchorIds[] = $s;
  5826. }
  5827. }
  5828. }
  5829. }
  5830. if ($anchorIds === []) {
  5831. $single = trim((string)$this->request->post('scydgy_id', ''));
  5832. if ($single !== '') {
  5833. $anchorIds[] = $single;
  5834. }
  5835. }
  5836. if ($anchorIds === []) {
  5837. $this->error('请至少选择一条订单');
  5838. }
  5839. $processedCcydh = [];
  5840. $doneOrders = 0;
  5841. $allSids = [];
  5842. Db::startTrans();
  5843. try {
  5844. foreach ($anchorIds as $anchorId) {
  5845. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  5846. if (($bundle['pos'] ?? []) === []) {
  5847. continue;
  5848. }
  5849. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5850. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  5851. if (isset($processedCcydh[$dedupeKey])) {
  5852. continue;
  5853. }
  5854. $processedCcydh[$dedupeKey] = true;
  5855. $sids = $this->abandonAuditOrderBundle($bundle);
  5856. if ($sids === []) {
  5857. continue;
  5858. }
  5859. $doneOrders++;
  5860. foreach (array_keys($sids) as $sid) {
  5861. $allSids[(int)$sid] = true;
  5862. }
  5863. }
  5864. if ($doneOrders < 1) {
  5865. throw new \Exception('所选订单均不在待确认供应商状态');
  5866. }
  5867. Db::commit();
  5868. } catch (\Throwable $e) {
  5869. Db::rollback();
  5870. $this->error($e->getMessage());
  5871. }
  5872. $this->pickHiddenScydgySetCache = null;
  5873. $msg = $doneOrders > 1
  5874. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  5875. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  5876. $this->success($msg);
  5877. }
  5878. /**
  5879. * 历史存证 — 已完结订单重新下发,退回协助初选(支持单条或批量)
  5880. */
  5881. public function archiveAbandon()
  5882. {
  5883. if (!$this->request->isPost()) {
  5884. $this->error(__('Invalid parameters'));
  5885. }
  5886. $anchorIds = [];
  5887. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  5888. if ($batchRaw !== '') {
  5889. $decoded = json_decode($batchRaw, true);
  5890. if (is_array($decoded)) {
  5891. foreach ($decoded as $id) {
  5892. $s = trim((string)$id);
  5893. if ($s !== '') {
  5894. $anchorIds[] = $s;
  5895. }
  5896. }
  5897. }
  5898. }
  5899. if ($anchorIds === []) {
  5900. $single = trim((string)$this->request->post('scydgy_id', ''));
  5901. if ($single !== '') {
  5902. $anchorIds[] = $single;
  5903. }
  5904. }
  5905. if ($anchorIds === []) {
  5906. $this->error('请至少选择一条订单');
  5907. }
  5908. $processedCcydh = [];
  5909. $doneOrders = 0;
  5910. Db::startTrans();
  5911. try {
  5912. foreach ($anchorIds as $anchorId) {
  5913. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  5914. if (($bundle['pos'] ?? []) === []) {
  5915. continue;
  5916. }
  5917. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5918. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  5919. if (isset($processedCcydh[$dedupeKey])) {
  5920. continue;
  5921. }
  5922. $processedCcydh[$dedupeKey] = true;
  5923. $sids = $this->abandonOrderBundleToPick(
  5924. $bundle,
  5925. 'archive_abandon',
  5926. ',从历史存证退回协助初选'
  5927. );
  5928. if ($sids === []) {
  5929. continue;
  5930. }
  5931. $doneOrders++;
  5932. }
  5933. if ($doneOrders < 1) {
  5934. throw new \Exception('所选订单均不是已完结状态');
  5935. }
  5936. Db::commit();
  5937. } catch (\Throwable $e) {
  5938. Db::rollback();
  5939. $this->error($e->getMessage());
  5940. }
  5941. $this->pickHiddenScydgySetCache = null;
  5942. $msg = $doneOrders > 1
  5943. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史记录已保留')
  5944. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  5945. $this->success($msg);
  5946. }
  5947. /**
  5948. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  5949. */
  5950. public function purchaseApprovalReject()
  5951. {
  5952. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5953. $this->error(__('Invalid parameters'));
  5954. }
  5955. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  5956. $decoded = json_decode($batchRaw, true);
  5957. if (!is_array($decoded) || $decoded === []) {
  5958. $this->error('提交数据无效');
  5959. }
  5960. Db::startTrans();
  5961. try {
  5962. foreach ($decoded as $item) {
  5963. if (!is_array($item)) {
  5964. continue;
  5965. }
  5966. $sid = (int)($item['scydgy_id'] ?? 0);
  5967. if (!$this->isValidScydgyRowId($sid)) {
  5968. continue;
  5969. }
  5970. $this->runPurchaseApprovalRejectForSid($sid);
  5971. }
  5972. Db::commit();
  5973. } catch (\Throwable $e) {
  5974. Db::rollback();
  5975. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  5976. }
  5977. $this->success('已驳回并退回「协助审批下发」');
  5978. }
  5979. /**
  5980. * @throws \Exception
  5981. */
  5982. protected function runPurchaseApprovalRejectForSid(int $sid): void
  5983. {
  5984. $allIds = $this->purchaseOrderDetail($sid);
  5985. if ($allIds === []) {
  5986. throw new \Exception('未找到下发明细');
  5987. }
  5988. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  5989. 'wflow_status' => 1,
  5990. 'status' => 0,
  5991. 'pick_company_name' => '',
  5992. ]);
  5993. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => 0]);
  5994. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  5995. $poId = 0;
  5996. try {
  5997. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  5998. if (is_array($po)) {
  5999. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  6000. }
  6001. } catch (\Throwable $e) {
  6002. }
  6003. $this->addOrderLog($sid, 'purchase_reject', '采购终审驳回,退回协助审批下发', $poId > 0 ? $poId : null);
  6004. }
  6005. /**
  6006. * 审核弹窗(旧入口,POST 已关闭)
  6007. */
  6008. public function review()
  6009. {
  6010. if ($this->request->isPost()) {
  6011. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  6012. }
  6013. $this->view->assign('pickMode', 0);
  6014. return $this->view->fetch('procuremen/review');
  6015. }
  6016. /**
  6017. * 审核弹窗获取公司列表
  6018. */
  6019. public function reviewCompanies()
  6020. {
  6021. if (!$this->request->isAjax()) {
  6022. $this->error(__('Invalid parameters'));
  6023. }
  6024. $list = [];
  6025. try {
  6026. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  6027. $rows = Db::table('customer')
  6028. ->where(function ($q) {
  6029. $q->where('status', 1)
  6030. ->whereOr('status', '1')
  6031. ->whereOr('status', '')
  6032. ->whereNull('status');
  6033. })
  6034. ->order('id', 'desc')
  6035. ->select();
  6036. } catch (\Throwable $e) {
  6037. $this->success('', '', []);
  6038. return;
  6039. }
  6040. if (!is_array($rows)) {
  6041. $this->success('', '', []);
  6042. return;
  6043. }
  6044. $detailColCandidates = [
  6045. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  6046. 'company_detail', 'company_desc', 'address',
  6047. ];
  6048. foreach ($rows as $row) {
  6049. if (!is_array($row)) {
  6050. continue;
  6051. }
  6052. $norm = [];
  6053. foreach ($row as $k => $v) {
  6054. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  6055. }
  6056. $row = $norm;
  6057. $st = $row['status'] ?? '';
  6058. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  6059. continue;
  6060. }
  6061. $id = isset($row['id']) ? (string)$row['id'] : '';
  6062. $companyName = '';
  6063. foreach (['company_name', 'name'] as $nk) {
  6064. if (!empty($row[$nk])) {
  6065. $companyName = trim((string)$row[$nk]);
  6066. break;
  6067. }
  6068. }
  6069. $username = '';
  6070. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  6071. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  6072. $username = trim((string)$row[$uk]);
  6073. break;
  6074. }
  6075. }
  6076. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  6077. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  6078. if ($phone === '' && isset($row['account'])) {
  6079. $phone = trim((string)$row['account']);
  6080. }
  6081. if ($phone === '' && isset($row['mobile'])) {
  6082. $phone = trim((string)$row['mobile']);
  6083. }
  6084. /* 邮箱、手机号均为空则无法发短信/邮件,不在下发弹窗展示 */
  6085. if ($email === '' && $phone === '') {
  6086. continue;
  6087. }
  6088. $category = '';
  6089. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6090. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6091. $category = trim((string)$row[$ck]);
  6092. break;
  6093. }
  6094. }
  6095. $detail = '';
  6096. foreach ($detailColCandidates as $dk) {
  6097. if (!isset($row[$dk])) {
  6098. continue;
  6099. }
  6100. $dv = trim((string)$row[$dk]);
  6101. if ($dv !== '') {
  6102. $detail = $dv;
  6103. break;
  6104. }
  6105. }
  6106. $list[] = [
  6107. 'id' => $id,
  6108. 'name' => $companyName,
  6109. 'company_name' => $companyName,
  6110. 'username' => $username,
  6111. 'email' => $email,
  6112. 'phone' => $phone,
  6113. 'category' => $category,
  6114. 'company_type' => $category,
  6115. 'detail' => $detail,
  6116. ];
  6117. }
  6118. $this->success('', '', $list);
  6119. }
  6120. /**
  6121. * 采购确认-下发明细弹窗:
  6122. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  6123. */
  6124. public function outward_detail()
  6125. {
  6126. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6127. if (is_array($ids)) {
  6128. $ids = isset($ids[0]) ? $ids[0] : '';
  6129. }
  6130. $ids = trim((string)$ids);
  6131. if ($ids === '') {
  6132. $this->error(__('Invalid parameters'));
  6133. }
  6134. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  6135. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  6136. $wffTab = 'all';
  6137. }
  6138. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  6139. $purchaseOrderId = 0;
  6140. $po = null;
  6141. try {
  6142. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  6143. if (is_array($po)) {
  6144. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  6145. }
  6146. } catch (\Throwable $e) {
  6147. $purchaseOrderId = 0;
  6148. $po = null;
  6149. }
  6150. if (!$isPurchaseConfirm && is_array($po)) {
  6151. $wf = (int)($po['wflow_status'] ?? 0);
  6152. $st = trim((string)($po['status'] ?? ''));
  6153. $isDone = ($st === '1' || $st === 1);
  6154. if ($wf === 2 && !$isDone) {
  6155. $isPurchaseConfirm = true;
  6156. }
  6157. }
  6158. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  6159. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6160. $confirmProcessCount = 1;
  6161. $confirmPickGroups = [];
  6162. $processDisplayRows = [];
  6163. $allDetailsBySid = [];
  6164. $requiredSidList = [];
  6165. $sidList = [$ids];
  6166. if ($isPurchaseConfirm) {
  6167. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  6168. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  6169. if ($mergeRows !== []) {
  6170. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  6171. }
  6172. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  6173. if ($confirmBundle['pos'] !== []) {
  6174. $sidList = [];
  6175. foreach ($confirmBundle['pos'] as $poRow) {
  6176. if (!is_array($poRow)) {
  6177. continue;
  6178. }
  6179. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6180. if (!$this->isValidScydgyRowId($sid)) {
  6181. continue;
  6182. }
  6183. $sidList[] = (string)$sid;
  6184. $requiredSidList[] = $sid;
  6185. }
  6186. }
  6187. if ($sidList === []) {
  6188. $sidList = [$ids];
  6189. $requiredSidList = [(int)$ids];
  6190. }
  6191. $confirmProcessCount = max(1, count($requiredSidList));
  6192. if (is_array($po) && $purchaseOrderId <= 0) {
  6193. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  6194. }
  6195. }
  6196. $rows = [];
  6197. try {
  6198. if (count($sidList) === 1) {
  6199. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  6200. } else {
  6201. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  6202. }
  6203. } catch (\Throwable $e) {
  6204. $rows = [];
  6205. }
  6206. if ($isPurchaseConfirm) {
  6207. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  6208. }
  6209. foreach ($rows as &$r) {
  6210. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  6211. $r['id'] = $r['ID'];
  6212. }
  6213. if (isset($r['createtime'])) {
  6214. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  6215. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  6216. } else {
  6217. $r['createtime_text'] = (string)$r['createtime'];
  6218. }
  6219. } else {
  6220. $r['createtime_text'] = '';
  6221. }
  6222. }
  6223. unset($r);
  6224. $pickedCompanyName = '';
  6225. if ($isPurchaseConfirm) {
  6226. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  6227. if (!is_array($poRow)) {
  6228. continue;
  6229. }
  6230. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  6231. if ($pn !== '') {
  6232. $pickedCompanyName = $pn;
  6233. break;
  6234. }
  6235. }
  6236. }
  6237. $this->view->assign('rows', $rows ?: []);
  6238. $this->view->assign('rowCount', count($rows ?: []));
  6239. $this->view->assign('scydgyId', $ids);
  6240. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  6241. $this->view->assign('headTitle', $headTitle);
  6242. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  6243. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  6244. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  6245. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  6246. $this->view->assign('processDisplayRows', $processDisplayRows);
  6247. $this->view->assign('confirmPickGroups', $confirmPickGroups);
  6248. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  6249. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  6250. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  6251. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  6252. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  6253. if ($isPurchaseConfirm) {
  6254. return $this->view->fetch();
  6255. }
  6256. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  6257. $this->view->engine->layout(false);
  6258. try {
  6259. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  6260. $this->view->assign('dialogBody', $bodyHtml);
  6261. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  6262. } finally {
  6263. if ($restoreLayout) {
  6264. $this->view->engine->layout($restoreLayout);
  6265. }
  6266. }
  6267. }
  6268. /**
  6269. * 月度导出记录表(不存在时自动创建)
  6270. */
  6271. protected function ensurePurchaseMonthExportLogTable(): void
  6272. {
  6273. try {
  6274. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  6275. } catch (\Throwable $e) {
  6276. Db::execute(
  6277. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  6278. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  6279. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  6280. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  6281. `admin_name` varchar(64) NOT NULL DEFAULT '',
  6282. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  6283. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  6284. `createtime` int(10) unsigned DEFAULT NULL,
  6285. PRIMARY KEY (`id`),
  6286. KEY `idx_ym` (`ym`),
  6287. KEY `idx_ct` (`createtime`)
  6288. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  6289. );
  6290. }
  6291. }
  6292. /**
  6293. * 已完结订单归属月份(与历史存证、月度列表一致)
  6294. *
  6295. * @param array<string, mixed> $row purchase_order 行
  6296. */
  6297. protected function resolveCompletedPurchaseOrderYm(array $row): string
  6298. {
  6299. foreach (['createtime', 'dStamp', 'updatetime'] as $key) {
  6300. $raw = $row[$key] ?? null;
  6301. if ($raw === null || $raw === '') {
  6302. continue;
  6303. }
  6304. if (is_numeric($raw) && (int)$raw > 946684800) {
  6305. return date('Y-m', (int)$raw);
  6306. }
  6307. $t = trim((string)$raw);
  6308. if ($t !== '' && preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  6309. return $m[1];
  6310. }
  6311. }
  6312. return '';
  6313. }
  6314. /**
  6315. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  6316. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  6317. */
  6318. public function export_month_outward()
  6319. {
  6320. $this->request->filter(['strip_tags', 'trim']);
  6321. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  6322. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  6323. $ym = date('Y-m');
  6324. }
  6325. $dbRows = [];
  6326. try {
  6327. $query = Db::table('purchase_order');
  6328. $query->whereRaw("(TRIM(CAST(`status` AS CHAR)) = '1' OR CAST(`status` AS UNSIGNED) = 1)");
  6329. $dbRows = $query->select();
  6330. } catch (\Throwable $e) {
  6331. $dbRows = [];
  6332. }
  6333. if (!is_array($dbRows)) {
  6334. $dbRows = [];
  6335. }
  6336. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym) {
  6337. if (!is_array($dbRow)) {
  6338. return false;
  6339. }
  6340. return $this->resolveCompletedPurchaseOrderYm($dbRow) === $ym;
  6341. }));
  6342. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  6343. $filtered = $pool;
  6344. $mainBySid = [];
  6345. foreach ($filtered as $rw) {
  6346. if (!is_array($rw)) {
  6347. continue;
  6348. }
  6349. $rid = (int)($rw['ID'] ?? 0);
  6350. if ($rid > 0) {
  6351. $mainBySid[$rid] = $rw;
  6352. }
  6353. }
  6354. if ($mainBySid === []) {
  6355. $detailRows = [];
  6356. } else {
  6357. try {
  6358. $detailRows = Db::table('purchase_order_detail')
  6359. ->where('scydgy_id', 'in', array_keys($mainBySid))
  6360. ->where('status', '<>', self::PURCHASE_DETAIL_STATUS_VOID)
  6361. ->order('status', 'desc')
  6362. ->order('CCYDH', 'asc')
  6363. ->order('company_name', 'asc')
  6364. ->order('id', 'asc')
  6365. ->select();
  6366. } catch (\Throwable $e) {
  6367. try {
  6368. $detailRows = Db::table('purchase_order_detail')
  6369. ->where('scydgy_id', 'in', array_keys($mainBySid))
  6370. ->where('status', '<>', self::PURCHASE_DETAIL_STATUS_VOID)
  6371. ->order('status', 'desc')
  6372. ->order('CCYDH', 'asc')
  6373. ->order('company_name', 'asc')
  6374. ->order('ID', 'asc')
  6375. ->select();
  6376. } catch (\Throwable $e2) {
  6377. $detailRows = [];
  6378. }
  6379. }
  6380. }
  6381. if (!is_array($detailRows)) {
  6382. $detailRows = [];
  6383. }
  6384. $exportLines = [];
  6385. $detailSidSeen = [];
  6386. foreach ($detailRows as $dr) {
  6387. if (!is_array($dr)) {
  6388. continue;
  6389. }
  6390. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  6391. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  6392. continue;
  6393. }
  6394. if (isset($detailSidSeen[$sid])) {
  6395. continue;
  6396. }
  6397. if ((int)($dr['status'] ?? 0) !== 1) {
  6398. continue;
  6399. }
  6400. $detailSidSeen[$sid] = true;
  6401. $m = $mainBySid[$sid];
  6402. $exportLines[] = [
  6403. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  6404. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  6405. 'company_name' => (string)($dr['company_name'] ?? ''),
  6406. 'CDF' => (string)($m['CDF'] ?? ''),
  6407. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  6408. 'gx' => $this->procuremenExportGxText($m),
  6409. 'detail' => $dr,
  6410. ];
  6411. }
  6412. foreach ($detailRows as $dr) {
  6413. if (!is_array($dr)) {
  6414. continue;
  6415. }
  6416. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  6417. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  6418. continue;
  6419. }
  6420. $detailSidSeen[$sid] = true;
  6421. $m = $mainBySid[$sid];
  6422. $exportLines[] = [
  6423. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  6424. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  6425. 'company_name' => (string)($dr['company_name'] ?? ''),
  6426. 'CDF' => (string)($m['CDF'] ?? ''),
  6427. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  6428. 'gx' => $this->procuremenExportGxText($m),
  6429. 'detail' => $dr,
  6430. ];
  6431. }
  6432. foreach ($mainBySid as $sid => $m) {
  6433. if (isset($detailSidSeen[$sid])) {
  6434. continue;
  6435. }
  6436. $company = trim((string)($m['pick_company_name'] ?? ''));
  6437. $exportLines[] = [
  6438. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  6439. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  6440. 'company_name' => $company,
  6441. 'CDF' => (string)($m['CDF'] ?? ''),
  6442. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  6443. 'gx' => $this->procuremenExportGxText($m),
  6444. 'detail' => [],
  6445. ];
  6446. }
  6447. $groups = [];
  6448. foreach ($exportLines as $line) {
  6449. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  6450. if (!isset($groups[$k])) {
  6451. $groups[$k] = [];
  6452. }
  6453. $groups[$k][] = $line;
  6454. }
  6455. ksort($groups, SORT_STRING);
  6456. $spreadsheet = new Spreadsheet();
  6457. $sheet = $spreadsheet->getActiveSheet();
  6458. $sheet->setTitle('协助明细');
  6459. $mon = (int)substr($ym, 5, 2);
  6460. $sheet->mergeCells('A1:H1');
  6461. $sheet->setCellValue('A1', $mon . '月协助明细');
  6462. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  6463. $sheet->getStyle('A1')->getAlignment()
  6464. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  6465. ->setVertical(Alignment::VERTICAL_CENTER);
  6466. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  6467. $col = 'A';
  6468. foreach ($headers as $h) {
  6469. $sheet->setCellValue($col . '2', $h);
  6470. $col++;
  6471. }
  6472. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  6473. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  6474. $rowNum = 3;
  6475. $sumSubtotalCounts = 0;
  6476. $grandAmount = 0.0;
  6477. if ($groups === []) {
  6478. $sheet->mergeCells('A3:H3');
  6479. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  6480. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  6481. $rowNum = 4;
  6482. } else {
  6483. foreach ($groups as $items) {
  6484. if ($items === []) {
  6485. continue;
  6486. }
  6487. $groupLineCount = count($items);
  6488. $subAmount = 0.0;
  6489. $i = 0;
  6490. foreach ($items as $line) {
  6491. $i++;
  6492. $dr = $line['detail'];
  6493. $amt = $this->procuremenExportAmount($dr);
  6494. $subAmount += $amt;
  6495. $sheet->setCellValue('A' . $rowNum, $i);
  6496. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  6497. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  6498. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  6499. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  6500. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  6501. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  6502. $sheet->setCellValue('H' . $rowNum, $amt);
  6503. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  6504. $rowNum++;
  6505. }
  6506. $sumSubtotalCounts += $groupLineCount;
  6507. $grandAmount += $subAmount;
  6508. $sheet->setCellValue('A' . $rowNum, $groupLineCount);
  6509. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  6510. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  6511. $sheet->getStyle('G' . $rowNum)->getAlignment()
  6512. ->setHorizontal(Alignment::HORIZONTAL_RIGHT)
  6513. ->setVertical(Alignment::VERTICAL_CENTER);
  6514. $rowNum++;
  6515. }
  6516. }
  6517. $sheet->setCellValue('A' . $rowNum, '总计');
  6518. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  6519. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  6520. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  6521. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  6522. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
  6523. $lastRow = $rowNum;
  6524. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  6525. 'borders' => [
  6526. 'allBorders' => [
  6527. 'borderStyle' => Border::BORDER_THIN,
  6528. 'color' => ['rgb' => '000000'],
  6529. ],
  6530. ],
  6531. ]);
  6532. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  6533. if ($lastRow >= 3) {
  6534. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6535. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6536. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6537. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6538. }
  6539. $sheet->getColumnDimension('A')->setWidth(7);
  6540. $sheet->getColumnDimension('B')->setWidth(16);
  6541. $sheet->getColumnDimension('C')->setWidth(52);
  6542. $sheet->getColumnDimension('D')->setWidth(32);
  6543. $sheet->getColumnDimension('E')->setWidth(12);
  6544. $sheet->getColumnDimension('F')->setWidth(44);
  6545. $sheet->getColumnDimension('G')->setWidth(26);
  6546. $sheet->getColumnDimension('H')->setWidth(13);
  6547. $sheet->getRowDimension(1)->setRowHeight(28);
  6548. $fileBase = '协助明细_' . str_replace('-', '', $ym);
  6549. $filename = $fileBase . '.xlsx';
  6550. try {
  6551. $this->ensurePurchaseMonthExportLogTable();
  6552. list($adminId, $adminName) = $this->GetUseName();
  6553. Db::table('purchase_month_export_log')->insert([
  6554. 'ym' => $ym,
  6555. 'admin_id' => (int)$adminId,
  6556. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  6557. 'row_count' => count($exportLines),
  6558. 'total_amount' => round($grandAmount, 2),
  6559. 'createtime' => time(),
  6560. ]);
  6561. } catch (\Throwable $e) {
  6562. Log::write('month export log: ' . $e->getMessage(), 'error');
  6563. }
  6564. if (ob_get_length()) {
  6565. ob_end_clean();
  6566. }
  6567. $asciiName = 'outward_' . str_replace('-', '', $ym) . '.xlsx';
  6568. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  6569. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  6570. header('Cache-Control: max-age=0');
  6571. $writer = new Xlsx($spreadsheet);
  6572. $writer->save('php://output');
  6573. $spreadsheet->disconnectWorksheets();
  6574. unset($spreadsheet);
  6575. exit;
  6576. }
  6577. /**
  6578. * 导出用:工序列文案
  6579. */
  6580. protected function procuremenExportGxText(array $r)
  6581. {
  6582. $a = trim((string)($r['CDXMC'] ?? ''));
  6583. $b = trim((string)($r['CGYMC'] ?? ''));
  6584. if ($a !== '' && $b !== '') {
  6585. return $a . ':' . $b;
  6586. }
  6587. return $a !== '' ? $a : $b;
  6588. }
  6589. /**
  6590. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  6591. */
  6592. protected function procuremenExportAmount(array $r)
  6593. {
  6594. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  6595. if (!array_key_exists($k, $r)) {
  6596. continue;
  6597. }
  6598. $v = $r[$k];
  6599. if ($v === null || $v === '') {
  6600. continue;
  6601. }
  6602. if (is_numeric($v)) {
  6603. return (float)$v;
  6604. }
  6605. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  6606. if ($v !== '' && is_numeric($v)) {
  6607. return (float)$v;
  6608. }
  6609. }
  6610. return 0.0;
  6611. }
  6612. /**
  6613. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  6614. */
  6615. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  6616. {
  6617. $s = trim($ccydh);
  6618. if ($s === '') {
  6619. return 'ORDER';
  6620. }
  6621. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  6622. $s = trim($s, '._-');
  6623. if ($s === '') {
  6624. return 'ORDER';
  6625. }
  6626. if (function_exists('mb_substr')) {
  6627. return mb_substr($s, 0, 80, 'UTF-8');
  6628. }
  6629. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  6630. }
  6631. /**
  6632. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  6633. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  6634. *
  6635. * @return array{objectKey: string, webPath: string}
  6636. */
  6637. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  6638. {
  6639. $sid = (int)$scydgyId;
  6640. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  6641. $y = date('Y');
  6642. $m = date('m');
  6643. $d = date('d');
  6644. $basename = $safeOrder . '_' . $sid . '.pdf';
  6645. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  6646. return [
  6647. 'objectKey' => $objectKey,
  6648. 'webPath' => '/' . $objectKey,
  6649. ];
  6650. }
  6651. /**
  6652. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  6653. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  6654. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  6655. *
  6656. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  6657. */
  6658. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  6659. {
  6660. if (!$this->isValidScydgyRowId($scydgyId)) {
  6661. return '';
  6662. }
  6663. $ids = trim((string)$scydgyId);
  6664. $prep = $this->prepareProcuremenDetailsView($ids);
  6665. if (!$prep['ok']) {
  6666. return '';
  6667. }
  6668. $ccydh = $prep['ccydh'];
  6669. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  6670. $objectKey = $paths['objectKey'];
  6671. $webPath = $paths['webPath'];
  6672. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  6673. $this->view->assign([
  6674. 'pdf_export' => 1,
  6675. 'pdfMetaLine' => $meta,
  6676. ]);
  6677. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  6678. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  6679. $this->view->engine->layout(false);
  6680. try {
  6681. $html = $this->view->fetch('procuremen/details_pdf_shell');
  6682. } catch (\Throwable $e) {
  6683. if ($restoreLayout) {
  6684. $this->view->engine->layout($restoreLayout);
  6685. }
  6686. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  6687. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  6688. return '';
  6689. }
  6690. if ($restoreLayout) {
  6691. $this->view->engine->layout($restoreLayout);
  6692. }
  6693. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  6694. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  6695. if (!is_dir($tempDir)) {
  6696. @mkdir($tempDir, 0755, true);
  6697. }
  6698. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  6699. try {
  6700. $mpdf = new \Mpdf\Mpdf([
  6701. 'mode' => 'utf-8',
  6702. 'format' => 'A4',
  6703. 'margin_left' => 12,
  6704. 'margin_right' => 12,
  6705. 'margin_top' => 14,
  6706. 'margin_bottom' => 14,
  6707. 'tempDir' => $tempDir,
  6708. 'autoScriptToLang' => true,
  6709. 'autoLangToFont' => true,
  6710. ]);
  6711. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  6712. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  6713. $mpdf->SetBasePath('http://127.0.0.1/');
  6714. $mpdf->WriteHTML($html);
  6715. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  6716. } catch (\Throwable $e) {
  6717. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  6718. if (is_file($tempPdf)) {
  6719. @unlink($tempPdf);
  6720. }
  6721. return '';
  6722. }
  6723. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  6724. if ($ossUrl !== '') {
  6725. @unlink($tempPdf);
  6726. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  6727. return $ossUrl;
  6728. }
  6729. $pi = pathinfo($objectKey);
  6730. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  6731. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  6732. if ($baseFile === '') {
  6733. @unlink($tempPdf);
  6734. return '';
  6735. }
  6736. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  6737. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  6738. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  6739. @unlink($tempPdf);
  6740. return '';
  6741. }
  6742. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  6743. if (!@copy($tempPdf, $fullPath)) {
  6744. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  6745. @unlink($tempPdf);
  6746. return '';
  6747. }
  6748. @unlink($tempPdf);
  6749. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  6750. return $webPath;
  6751. }
  6752. /**
  6753. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  6754. */
  6755. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  6756. {
  6757. if ($scydgyId <= 0 || $webPath === '') {
  6758. return;
  6759. }
  6760. try {
  6761. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  6762. } catch (\Throwable $e) {
  6763. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  6764. }
  6765. }
  6766. /**
  6767. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  6768. *
  6769. * @param array<string, string> $vars
  6770. * @return array<string, string>
  6771. */
  6772. protected function normalizeSmsTemplateVars(array $vars): array
  6773. {
  6774. $out = [];
  6775. foreach ($vars as $k => $v) {
  6776. $out[(string)$k] = trim((string)$v);
  6777. }
  6778. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  6779. $out['contact_name'] = $out['company_name'];
  6780. }
  6781. return $out;
  6782. }
  6783. /**
  6784. * 按手机号或公司名称查 customer 表联系人姓名
  6785. */
  6786. protected function resolveCustomerContactName(string $phone, string $companyName): string
  6787. {
  6788. $phone = trim($phone);
  6789. $companyName = trim($companyName);
  6790. try {
  6791. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  6792. $row = Db::table('customer')
  6793. ->where(function ($q) use ($phone) {
  6794. $q->where('phone', $phone)->whereOr('account', $phone);
  6795. })
  6796. ->order('id', 'asc')
  6797. ->find();
  6798. if (is_array($row)) {
  6799. $nm = trim((string)($row['username'] ?? ''));
  6800. if ($nm !== '') {
  6801. return $nm;
  6802. }
  6803. }
  6804. }
  6805. if ($companyName !== '') {
  6806. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  6807. if (is_array($row)) {
  6808. return trim((string)($row['username'] ?? ''));
  6809. }
  6810. }
  6811. } catch (\Throwable $e) {
  6812. }
  6813. return '';
  6814. }
  6815. /**
  6816. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  6817. */
  6818. protected function plainTextToHtmlEmailBody(string $text): string
  6819. {
  6820. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  6821. $parts = explode("\n", $text);
  6822. $out = [];
  6823. foreach ($parts as $line) {
  6824. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  6825. $out[] = $line;
  6826. } else {
  6827. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  6828. }
  6829. }
  6830. return implode("<br>\n", $out);
  6831. }
  6832. /**
  6833. * 短信场景:去掉链接类变量,避免误填 URL
  6834. *
  6835. * @param array<string, string> $vars
  6836. * @return array<string, string>
  6837. */
  6838. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  6839. {
  6840. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  6841. return $vars;
  6842. }
  6843. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  6844. $vars[$k] = '';
  6845. }
  6846. return $vars;
  6847. }
  6848. /**
  6849. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  6850. *
  6851. * @param array<string, string> $vars
  6852. */
  6853. protected function renderNotifyTemplate(string $scene, array $vars): string
  6854. {
  6855. $vars = $this->normalizeSmsTemplateVars($vars);
  6856. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  6857. $row = $this->loadNotifyTemplateRow($scene);
  6858. if ($row === null) {
  6859. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  6860. }
  6861. $tpl = trim((string)($row['content'] ?? ''));
  6862. if ($tpl === '') {
  6863. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  6864. }
  6865. foreach ($vars as $k => $v) {
  6866. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  6867. }
  6868. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  6869. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  6870. return $tpl;
  6871. }
  6872. protected function resolveProcuremenEmailSubject(string $scene): string
  6873. {
  6874. $map = [
  6875. 'review_email' => '您有新的协助加工订单',
  6876. ];
  6877. $subject = trim((string)($map[$scene] ?? ''));
  6878. if ($subject === '') {
  6879. $this->error('未配置邮件主题:' . $scene);
  6880. }
  6881. return $subject;
  6882. }
  6883. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  6884. {
  6885. $map = [
  6886. 'review_email' => '协助下发-邮箱',
  6887. 'review_sms' => '协助下发-短信',
  6888. 'confirm_ok' => '采购确认-通过',
  6889. 'confirm_fail' => '采购确认-未通过',
  6890. ];
  6891. $label = $map[$scene] ?? $scene;
  6892. if ($titleRequired) {
  6893. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  6894. }
  6895. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  6896. }
  6897. /** @deprecated 使用 renderNotifyTemplate */
  6898. protected function renderSmsTemplate(string $scene, array $vars): string
  6899. {
  6900. return $this->renderNotifyTemplate($scene, $vars);
  6901. }
  6902. /**
  6903. * 是否开启协助通知演练(不发真实短信/邮件)
  6904. */
  6905. protected function isProcuremenNotifyDryRun(): bool
  6906. {
  6907. return (bool)Config::get('procuremen_notify_dry_run');
  6908. }
  6909. /**
  6910. * @param array<string, mixed> $payload
  6911. */
  6912. protected function recordNotifyDryRunPreview(array $payload): void
  6913. {
  6914. $this->notifyDryRunPreview[] = $payload;
  6915. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  6916. }
  6917. /**
  6918. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  6919. * @throws \Exception
  6920. */
  6921. protected function smsbao($phone, $content)
  6922. {
  6923. if ($this->isProcuremenNotifyDryRun()) {
  6924. $this->recordNotifyDryRunPreview([
  6925. 'scene' => 'sms_only',
  6926. 'phone' => $phone,
  6927. 'sms_content' => $content,
  6928. ]);
  6929. return;
  6930. }
  6931. $statusStr = [
  6932. '0' => '短信发送成功',
  6933. '-1' => '参数不全',
  6934. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  6935. '30' => '密码错误',
  6936. '40' => '账号不存在',
  6937. '41' => '余额不足',
  6938. '42' => '帐户已过期',
  6939. '43' => 'IP地址限制',
  6940. '50' => '内容含有敏感词',
  6941. ];
  6942. $smsapi = 'http://api.smsbao.com/';
  6943. $user = 'zhuwei123';
  6944. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  6945. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  6946. $result = @file_get_contents($sendurl);
  6947. if ($result === false) {
  6948. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  6949. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  6950. }
  6951. $result = trim((string)$result);
  6952. if ($result !== '0') {
  6953. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  6954. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  6955. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  6956. }
  6957. }
  6958. }