Procuremen.php 293 KB

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