Procuremen.php 294 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868
  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. $amountFilled = !empty($line['amount_filled']);
  1754. $deliveryFilled = !empty($line['delivery_filled']);
  1755. $line['unit_price_text'] = $amountFilled ? '未到截止时间' : '未填写';
  1756. $line['amount_show'] = '';
  1757. if (array_key_exists('amount_text', $line)) {
  1758. $line['amount_text'] = $line['unit_price_text'];
  1759. }
  1760. $deliveryText = $deliveryFilled ? '未到截止时间' : '未填写';
  1761. $line['delivery_show'] = $deliveryText;
  1762. if (array_key_exists('delivery_text', $line)) {
  1763. $line['delivery_text'] = $deliveryText;
  1764. }
  1765. $line['delivery_ymd'] = '';
  1766. $line['subtotal_text'] = $amountFilled ? '未到截止时间' : '';
  1767. $line['subtotal_num'] = null;
  1768. $line['amount_quote_pending'] = $amountFilled;
  1769. $line['delivery_quote_pending'] = $deliveryFilled;
  1770. $line['quote_before_deadline'] = $amountFilled || $deliveryFilled;
  1771. $line['amount_filled'] = false;
  1772. $line['delivery_filled'] = false;
  1773. $line['is_quoted'] = false;
  1774. if (array_key_exists('quote_label', $line)) {
  1775. $line['quote_label'] = ($amountFilled || $deliveryFilled) ? '未到截止时间' : '未报价';
  1776. }
  1777. }
  1778. /**
  1779. * 审核弹窗:按供应商汇总报价明细
  1780. *
  1781. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  1782. * @return array<int, array<string, mixed>>
  1783. */
  1784. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  1785. {
  1786. $sids = [];
  1787. foreach ($bundle['pos'] ?? [] as $po) {
  1788. if (!is_array($po)) {
  1789. continue;
  1790. }
  1791. $sid = (int)($po['scydgy_id'] ?? 0);
  1792. if ($this->isValidScydgyRowId($sid)) {
  1793. $sids[$sid] = true;
  1794. }
  1795. }
  1796. if ($sids === []) {
  1797. return [];
  1798. }
  1799. $deadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle));
  1800. $gymcMap = [];
  1801. $qtyBySid = [];
  1802. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  1803. if (!is_array($mr)) {
  1804. continue;
  1805. }
  1806. $gid = $this->extractScydgyRowId($mr);
  1807. if ($this->isValidScydgyRowId($gid)) {
  1808. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  1809. $qty = trim((string)($mr['This_quantity'] ?? ''));
  1810. if ($qty === '') {
  1811. $qty = trim((string)($mr['NGZL'] ?? ''));
  1812. }
  1813. $qtyBySid[$gid] = $qty;
  1814. }
  1815. }
  1816. foreach ($bundle['pos'] ?? [] as $po) {
  1817. if (!is_array($po)) {
  1818. continue;
  1819. }
  1820. $gid = (int)($po['scydgy_id'] ?? 0);
  1821. if ($this->isValidScydgyRowId($gid)) {
  1822. $nm = trim((string)($po['CGYMC'] ?? ''));
  1823. if ($nm !== '') {
  1824. $gymcMap[$gid] = $nm;
  1825. }
  1826. }
  1827. }
  1828. try {
  1829. $detailsQuery = Db::table('purchase_order_detail')
  1830. ->where('scydgy_id', 'in', array_keys($sids));
  1831. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  1832. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  1833. } catch (\Throwable $e) {
  1834. try {
  1835. $detailsQuery = Db::table('purchase_order_detail')
  1836. ->where('scydgy_id', 'in', array_keys($sids));
  1837. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  1838. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  1839. } catch (\Throwable $e2) {
  1840. $details = [];
  1841. }
  1842. }
  1843. if (!is_array($details)) {
  1844. $details = [];
  1845. }
  1846. $byCompany = [];
  1847. foreach ($details as $d) {
  1848. if (!is_array($d)) {
  1849. continue;
  1850. }
  1851. $cn = trim((string)($d['company_name'] ?? ''));
  1852. if ($cn === '') {
  1853. continue;
  1854. }
  1855. if (!isset($byCompany[$cn])) {
  1856. $ph = trim((string)($d['phone'] ?? ''));
  1857. $username = trim((string)($d['username'] ?? ''));
  1858. if ($username === '') {
  1859. $username = $this->resolveCustomerContactName($ph, $cn);
  1860. }
  1861. $byCompany[$cn] = [
  1862. 'name' => $cn,
  1863. 'email' => trim((string)($d['email'] ?? '')),
  1864. 'phone' => $ph,
  1865. 'username' => $username,
  1866. 'has_quote' => false,
  1867. 'lines' => [],
  1868. ];
  1869. }
  1870. $sid = (int)($d['scydgy_id'] ?? 0);
  1871. $am = trim((string)($d['amount'] ?? ''));
  1872. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  1873. if ($gymc === '') {
  1874. $gymc = '工序';
  1875. }
  1876. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  1877. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  1878. if ($deliveryShow === '' && $deliveryRaw !== '') {
  1879. $deliveryShow = $deliveryRaw;
  1880. }
  1881. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  1882. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  1883. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  1884. $subtotal = null;
  1885. if ($amountNum !== null) {
  1886. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  1887. }
  1888. $unitPriceText = $amountFilled
  1889. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  1890. : '未填写';
  1891. $lineRow = [
  1892. 'cgymc' => $gymc,
  1893. 'amount' => $am,
  1894. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  1895. 'amount_filled' => $amountFilled,
  1896. 'unit_price_text' => $unitPriceText,
  1897. 'delivery' => $deliveryRaw,
  1898. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  1899. 'delivery_filled' => $deliveryFilled,
  1900. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  1901. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  1902. 'subtotal_num' => $subtotal,
  1903. 'status_name' => trim((string)($d['status_name'] ?? '')),
  1904. 'is_quoted' => $amountFilled,
  1905. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  1906. ];
  1907. if (!$deadlineReached) {
  1908. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  1909. }
  1910. $byCompany[$cn]['lines'][] = $lineRow;
  1911. }
  1912. foreach ($byCompany as $cn => $g) {
  1913. $total = count($g['lines']);
  1914. $quoted = 0;
  1915. $groupTotal = 0.0;
  1916. $groupHasTotal = false;
  1917. if ($deadlineReached) {
  1918. foreach ($g['lines'] as $ln) {
  1919. $am = trim((string)($ln['amount'] ?? ''));
  1920. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1921. $quoted++;
  1922. }
  1923. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  1924. $groupTotal += (float)$ln['subtotal_num'];
  1925. $groupHasTotal = true;
  1926. }
  1927. }
  1928. }
  1929. $byCompany[$cn]['has_quote'] = $deadlineReached && $total > 0 && $quoted === $total;
  1930. $byCompany[$cn]['line_count'] = $total;
  1931. $byCompany[$cn]['has_total'] = $total > 0;
  1932. $byCompany[$cn]['total_text'] = ($deadlineReached && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  1933. $byCompany[$cn]['display_rowspan'] = $total + ($total > 0 ? 1 : 0);
  1934. }
  1935. return array_values($byCompany);
  1936. }
  1937. /**
  1938. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  1939. *
  1940. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  1941. * @return array<int, array<string, mixed>>
  1942. */
  1943. protected function loadConfirmSupplierPickGroups(array $bundle): array
  1944. {
  1945. $sids = [];
  1946. $poIdMap = [];
  1947. foreach ($bundle['pos'] ?? [] as $po) {
  1948. if (!is_array($po)) {
  1949. continue;
  1950. }
  1951. $sid = (int)($po['scydgy_id'] ?? 0);
  1952. if ($this->isValidScydgyRowId($sid)) {
  1953. $sids[$sid] = true;
  1954. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  1955. }
  1956. }
  1957. if ($sids === []) {
  1958. return [];
  1959. }
  1960. $deadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle));
  1961. $gymcMap = [];
  1962. $qtyBySid = [];
  1963. $orderedSids = [];
  1964. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  1965. if (!is_array($mr)) {
  1966. continue;
  1967. }
  1968. $gid = $this->extractScydgyRowId($mr);
  1969. if ($this->isValidScydgyRowId($gid)) {
  1970. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  1971. $orderedSids[] = $gid;
  1972. $qty = trim((string)($mr['This_quantity'] ?? ''));
  1973. if ($qty === '') {
  1974. $qty = trim((string)($mr['NGZL'] ?? ''));
  1975. }
  1976. $qtyBySid[$gid] = $qty;
  1977. }
  1978. }
  1979. foreach ($bundle['pos'] ?? [] as $po) {
  1980. if (!is_array($po)) {
  1981. continue;
  1982. }
  1983. $gid = (int)($po['scydgy_id'] ?? 0);
  1984. if ($this->isValidScydgyRowId($gid)) {
  1985. $nm = trim((string)($po['CGYMC'] ?? ''));
  1986. if ($nm !== '') {
  1987. $gymcMap[$gid] = $nm;
  1988. }
  1989. }
  1990. }
  1991. try {
  1992. $details = Db::table('purchase_order_detail')
  1993. ->where('scydgy_id', 'in', array_keys($sids))
  1994. ->order('company_name', 'asc')
  1995. ->order('id', 'asc')
  1996. ->select();
  1997. } catch (\Throwable $e) {
  1998. try {
  1999. $details = Db::table('purchase_order_detail')
  2000. ->where('scydgy_id', 'in', array_keys($sids))
  2001. ->order('company_name', 'asc')
  2002. ->order('ID', 'asc')
  2003. ->select();
  2004. } catch (\Throwable $e2) {
  2005. $details = [];
  2006. }
  2007. }
  2008. if (!is_array($details)) {
  2009. $details = [];
  2010. }
  2011. $byCompany = [];
  2012. foreach ($details as $d) {
  2013. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2014. continue;
  2015. }
  2016. $cn = trim((string)($d['company_name'] ?? ''));
  2017. if ($cn === '') {
  2018. continue;
  2019. }
  2020. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  2021. $sid = (int)($d['scydgy_id'] ?? 0);
  2022. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  2023. continue;
  2024. }
  2025. if (!isset($byCompany[$cn])) {
  2026. $ph = trim((string)($d['phone'] ?? ''));
  2027. $username = trim((string)($d['username'] ?? ''));
  2028. if ($username === '') {
  2029. $username = $this->resolveCustomerContactName($ph, $cn);
  2030. }
  2031. $byCompany[$cn] = [
  2032. 'name' => $cn,
  2033. 'email' => trim((string)($d['email'] ?? '')),
  2034. 'phone' => $ph,
  2035. 'username' => $username,
  2036. 'pick_lines' => [],
  2037. 'detail_picks' => [],
  2038. ];
  2039. }
  2040. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2041. if ($gymc === '') {
  2042. $gymc = '工序';
  2043. }
  2044. $am = trim((string)($d['amount'] ?? ''));
  2045. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2046. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2047. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2048. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2049. $deliveryShow = $deliveryRaw;
  2050. }
  2051. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2052. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2053. $subtotal = null;
  2054. if ($amountNum !== null) {
  2055. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2056. }
  2057. $unitPriceText = $amountFilled
  2058. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2059. : '未填写';
  2060. $pickLine = [
  2061. 'cgymc' => $gymc,
  2062. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  2063. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  2064. 'amount_filled' => $amountFilled,
  2065. 'delivery_filled' => $deliveryFilled,
  2066. 'unit_price_text' => $unitPriceText,
  2067. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2068. 'subtotal_num' => $subtotal,
  2069. 'is_quoted' => $amountFilled,
  2070. ];
  2071. if (!$deadlineReached) {
  2072. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  2073. }
  2074. $byCompany[$cn]['pick_lines'][$sid] = $pickLine;
  2075. $byCompany[$cn]['detail_picks'][$sid] = [
  2076. 'scydgy_id' => $sid,
  2077. 'detail_id' => $detailId,
  2078. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  2079. 'cgymc' => $gymc,
  2080. ];
  2081. }
  2082. $out = [];
  2083. foreach ($byCompany as $g) {
  2084. $pickLinesMap = $g['pick_lines'] ?? [];
  2085. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  2086. continue;
  2087. }
  2088. $pickLines = [];
  2089. $usedLineSids = [];
  2090. foreach ($orderedSids as $sid) {
  2091. if (!isset($pickLinesMap[$sid])) {
  2092. continue;
  2093. }
  2094. $pickLines[] = $pickLinesMap[$sid];
  2095. $usedLineSids[$sid] = true;
  2096. }
  2097. foreach ($pickLinesMap as $sid => $ln) {
  2098. if (isset($usedLineSids[$sid])) {
  2099. continue;
  2100. }
  2101. $pickLines[] = $ln;
  2102. }
  2103. $groupTotal = 0.0;
  2104. $groupHasTotal = false;
  2105. if ($deadlineReached) {
  2106. foreach ($pickLines as $ln) {
  2107. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2108. $groupTotal += (float)$ln['subtotal_num'];
  2109. $groupHasTotal = true;
  2110. }
  2111. }
  2112. }
  2113. $lineCount = count($pickLines);
  2114. $g['pick_lines'] = $pickLines;
  2115. $g['line_count'] = $lineCount;
  2116. $g['has_total'] = $lineCount > 0;
  2117. $g['total_text'] = ($deadlineReached && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2118. $g['display_rowspan'] = $lineCount + ($lineCount > 0 ? 1 : 0);
  2119. $detailPicks = $g['detail_picks'] ?? [];
  2120. $g['detail_picks'] = array_values(is_array($detailPicks) ? $detailPicks : []);
  2121. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  2122. unset($g['detail_picks']);
  2123. $out[] = $g;
  2124. }
  2125. return $out;
  2126. }
  2127. /**
  2128. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  2129. * @return array<int, int[]> scydgy_id => detail_id[]
  2130. */
  2131. protected function mapDetailIdsByScydgyId(array $details): array
  2132. {
  2133. $out = [];
  2134. foreach ($details as $d) {
  2135. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2136. continue;
  2137. }
  2138. $sid = (int)($d['scydgy_id'] ?? 0);
  2139. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  2140. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  2141. continue;
  2142. }
  2143. if (!isset($out[$sid])) {
  2144. $out[$sid] = [];
  2145. }
  2146. $out[$sid][] = $pk;
  2147. }
  2148. foreach ($out as $sid => $ids) {
  2149. $out[$sid] = array_values(array_unique($ids));
  2150. }
  2151. return $out;
  2152. }
  2153. /**
  2154. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  2155. *
  2156. * @param array<string, mixed> $dbRow
  2157. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  2158. */
  2159. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  2160. {
  2161. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2162. $r = [
  2163. 'ID' => $sid,
  2164. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  2165. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  2166. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  2167. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  2168. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  2169. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  2170. 'CDW' => $dbRow['CDW'] ?? '',
  2171. 'NGZL' => $dbRow['NGZL'] ?? '',
  2172. 'CDF' => $dbRow['CDF'] ?? '',
  2173. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  2174. 'MBZ' => $dbRow['MBZ'] ?? '',
  2175. 'bwjg' => $dbRow['bwjg'] ?? '',
  2176. 'iStatus' => $dbRow['iStatus'] ?? '',
  2177. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  2178. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  2179. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  2180. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  2181. 'dStamp' => $dbRow['dStamp'] ?? '',
  2182. 'pick_time' => $dbRow['pick_time'] ?? '',
  2183. ];
  2184. if ($sid > 0 && isset($dStampMap[$sid])) {
  2185. $t = trim((string)$dStampMap[$sid]);
  2186. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2187. $r['dStamp'] = $dStampMap[$sid];
  2188. }
  2189. }
  2190. $dsOut = trim((string)($r['dStamp'] ?? ''));
  2191. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  2192. $ct = $dbRow['createtime'];
  2193. if (is_numeric($ct) && (int)$ct > 946684800) {
  2194. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  2195. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  2196. $r['dStamp'] = trim($ct);
  2197. }
  2198. }
  2199. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  2200. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  2201. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  2202. $fallback = trim((string)($r['dStamp'] ?? ''));
  2203. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  2204. $r['dputrecord'] = $fallback;
  2205. }
  2206. }
  2207. if (array_key_exists('id', $dbRow)) {
  2208. $r['purchase_order_id'] = (int)$dbRow['id'];
  2209. }
  2210. if ($sid < 0) {
  2211. $r['_is_manual'] = 1;
  2212. }
  2213. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  2214. $pickOut = trim((string)($r['pick_time'] ?? ''));
  2215. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  2216. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  2217. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  2218. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  2219. $r['pick_time'] = $pickFallback;
  2220. break;
  2221. }
  2222. }
  2223. }
  2224. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  2225. if ($pickNm !== '') {
  2226. $r['pick_company_name'] = $pickNm;
  2227. $r['picked_supplier_name'] = $pickNm;
  2228. }
  2229. return $r;
  2230. }
  2231. /**
  2232. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  2233. *
  2234. * @return array<int, array<string, mixed>>
  2235. */
  2236. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  2237. {
  2238. $pool = [];
  2239. if (!is_array($dbRows) || $dbRows === []) {
  2240. return $pool;
  2241. }
  2242. $dStampMap = [];
  2243. $sidList = [];
  2244. foreach ($dbRows as $tmpRow) {
  2245. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  2246. $sid = (int)$tmpRow['scydgy_id'];
  2247. if ($sid > 0) {
  2248. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  2249. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2250. $sidList[$sid] = true;
  2251. }
  2252. }
  2253. }
  2254. }
  2255. if ($sidList !== []) {
  2256. try {
  2257. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  2258. } catch (\Throwable $e) {
  2259. $dStampMap = [];
  2260. }
  2261. }
  2262. foreach ($dbRows as $dbRow) {
  2263. if (!is_array($dbRow)) {
  2264. continue;
  2265. }
  2266. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  2267. }
  2268. return $pool;
  2269. }
  2270. /**
  2271. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  2272. *
  2273. * @param int[] $scydgyIds
  2274. * @return array<int, array<string, mixed>>
  2275. */
  2276. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  2277. {
  2278. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2279. if ($scydgyIds === []) {
  2280. return [];
  2281. }
  2282. try {
  2283. $list = Db::table('purchase_order_detail')
  2284. ->where('scydgy_id', 'in', $scydgyIds)
  2285. ->field('scydgy_id,company_name,amount,delivery')
  2286. ->select();
  2287. } catch (\Throwable $e) {
  2288. $list = [];
  2289. }
  2290. return is_array($list) ? $list : [];
  2291. }
  2292. /**
  2293. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  2294. *
  2295. * @param int[] $scydgyIds
  2296. * @param array<int, array<string, mixed>> $allRows
  2297. * @return array{cnt:int, amt:int, deliv:int}
  2298. */
  2299. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  2300. {
  2301. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2302. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2303. if ($scydgyIds === [] || $allRows === []) {
  2304. return $out;
  2305. }
  2306. $idSet = array_flip($scydgyIds);
  2307. $all = [];
  2308. $withAmt = [];
  2309. $withDeliv = [];
  2310. foreach ($allRows as $r) {
  2311. if (!is_array($r)) {
  2312. continue;
  2313. }
  2314. $sid = (int)($r['scydgy_id'] ?? 0);
  2315. if (!isset($idSet[$sid])) {
  2316. continue;
  2317. }
  2318. $cn = trim((string)($r['company_name'] ?? ''));
  2319. if ($cn === '') {
  2320. continue;
  2321. }
  2322. $all[$cn] = true;
  2323. $am = $r['amount'] ?? null;
  2324. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  2325. $withAmt[$cn] = true;
  2326. }
  2327. $dv = $r['delivery'] ?? null;
  2328. if ($dv !== null && trim((string)$dv) !== '') {
  2329. $withDeliv[$cn] = true;
  2330. }
  2331. }
  2332. return [
  2333. 'cnt' => count($all),
  2334. 'amt' => count($withAmt),
  2335. 'deliv' => count($withDeliv),
  2336. ];
  2337. }
  2338. /**
  2339. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  2340. *
  2341. * @param int[] $scydgyIds
  2342. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  2343. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  2344. */
  2345. protected function OrderDetailSummary(array $scydgyIds)
  2346. {
  2347. $out = [];
  2348. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2349. if ($scydgyIds === []) {
  2350. return $out;
  2351. }
  2352. $list = [];
  2353. try {
  2354. $list = Db::table('purchase_order_detail')
  2355. ->where('scydgy_id', 'in', $scydgyIds)
  2356. ->field('id,scydgy_id,amount,delivery')
  2357. ->select();
  2358. } catch (\Throwable $e) {
  2359. $list = [];
  2360. }
  2361. if (!is_array($list)) {
  2362. return $out;
  2363. }
  2364. foreach ($list as $r) {
  2365. if (!is_array($r)) {
  2366. continue;
  2367. }
  2368. $ids = (int)($r['scydgy_id'] ?? 0);
  2369. if (!$this->isValidScydgyRowId($ids)) {
  2370. continue;
  2371. }
  2372. if (!isset($out[$ids])) {
  2373. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2374. }
  2375. $out[$ids]['cnt']++;
  2376. $am = $r['amount'] ?? null;
  2377. if ($am !== null && $am !== '') {
  2378. if (!(is_string($am) && trim($am) === '')) {
  2379. $out[$ids]['amt']++;
  2380. }
  2381. }
  2382. $dv = $r['delivery'] ?? null;
  2383. if ($dv !== null && trim((string)$dv) !== '') {
  2384. $out[$ids]['deliv']++;
  2385. }
  2386. }
  2387. return $out;
  2388. }
  2389. /**
  2390. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  2391. *
  2392. * @return array
  2393. */
  2394. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  2395. {
  2396. $strContains = function ($haystack, $needle) {
  2397. if ($needle === '') {
  2398. return false;
  2399. }
  2400. $haystack = (string)$haystack;
  2401. if (function_exists('mb_stripos')) {
  2402. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  2403. }
  2404. return stripos($haystack, $needle) !== false;
  2405. };
  2406. $stripAlias = function ($f) {
  2407. return preg_replace('/^[ab]\./i', '', (string)$f);
  2408. };
  2409. $searchColNames = [];
  2410. foreach (explode(',', $this->searchFields) as $colRaw) {
  2411. $c = $stripAlias(trim($colRaw));
  2412. if ($c !== '') {
  2413. $searchColNames[] = $c;
  2414. }
  2415. }
  2416. $filtered = [];
  2417. foreach ($pool as $r) {
  2418. if (!is_array($r)) {
  2419. continue;
  2420. }
  2421. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  2422. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  2423. if (!$isManual) {
  2424. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  2425. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  2426. continue;
  2427. }
  2428. if ($applyMonthRange) {
  2429. $mo = (int)$m[2];
  2430. if ($mo < 1 || $mo > 12) {
  2431. continue;
  2432. }
  2433. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2434. $rowMonthStart = $ymRow . '-01 00:00:00';
  2435. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2436. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2437. continue;
  2438. }
  2439. }
  2440. } elseif ($applyMonthRange) {
  2441. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  2442. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2443. $ds = $listTime;
  2444. }
  2445. if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  2446. continue;
  2447. }
  2448. $mo = (int)$m[2];
  2449. if ($mo < 1 || $mo > 12) {
  2450. continue;
  2451. }
  2452. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2453. $rowMonthStart = $ymRow . '-01 00:00:00';
  2454. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2455. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2456. continue;
  2457. }
  2458. }
  2459. if ($search !== '') {
  2460. $hitSearch = false;
  2461. foreach ($searchColNames as $c) {
  2462. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  2463. if ($cell !== '' && $strContains($cell, $search)) {
  2464. $hitSearch = true;
  2465. break;
  2466. }
  2467. }
  2468. if (!$hitSearch) {
  2469. continue;
  2470. }
  2471. }
  2472. foreach ($filterArr as $fk => $fv) {
  2473. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  2474. continue;
  2475. }
  2476. if (is_array($fv)) {
  2477. continue;
  2478. }
  2479. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  2480. continue;
  2481. }
  2482. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  2483. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  2484. $field = $stripAlias($fk);
  2485. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  2486. $cellStr = trim((string)$cell);
  2487. switch ($sym) {
  2488. case '=':
  2489. if ((string)$cell !== (string)$fv) {
  2490. continue 3;
  2491. }
  2492. break;
  2493. case '<>':
  2494. if ((string)$cell === (string)$fv) {
  2495. continue 3;
  2496. }
  2497. break;
  2498. case 'LIKE':
  2499. case 'NOT LIKE':
  2500. $needle = trim((string)$fv);
  2501. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  2502. if ($sym === 'LIKE' && !$hit) {
  2503. continue 3;
  2504. }
  2505. if ($sym === 'NOT LIKE' && $hit) {
  2506. continue 3;
  2507. }
  2508. break;
  2509. case '>':
  2510. case '>=':
  2511. case '<':
  2512. case '<=':
  2513. if (!is_numeric($cell) && $cellStr === '') {
  2514. continue 3;
  2515. }
  2516. $cv = is_numeric($cell) ? (float)$cell : (float)$cellStr;
  2517. $vv = (float)$fv;
  2518. if ($sym === '>' && !($cv > $vv)) {
  2519. continue 3;
  2520. }
  2521. if ($sym === '>=' && !($cv >= $vv)) {
  2522. continue 3;
  2523. }
  2524. if ($sym === '<' && !($cv < $vv)) {
  2525. continue 3;
  2526. }
  2527. if ($sym === '<=' && !($cv <= $vv)) {
  2528. continue 3;
  2529. }
  2530. break;
  2531. case 'RANGE':
  2532. case 'NOT RANGE':
  2533. case 'BETWEEN':
  2534. case 'NOT BETWEEN':
  2535. case 'BETWEEN TIME':
  2536. case 'NOT BETWEEN TIME':
  2537. $rawR = is_array($fv) ? implode(',', $fv) : (string)$fv;
  2538. $rawR = str_replace(' - ', ',', $rawR);
  2539. $arr = array_slice(array_map('trim', explode(',', $rawR)), 0, 2);
  2540. if (count($arr) < 2) {
  2541. break;
  2542. }
  2543. $lo = $arr[0];
  2544. $hi = $arr[1];
  2545. if ($lo === '' && $hi === '') {
  2546. break;
  2547. }
  2548. $isNot = (strpos($sym, 'NOT') !== false);
  2549. if ($lo === '') {
  2550. $in = ($cellStr !== '' && $cellStr <= $hi);
  2551. if ($isNot ? $in : !$in) {
  2552. continue 3;
  2553. }
  2554. break;
  2555. }
  2556. if ($hi === '') {
  2557. $in = ($cellStr !== '' && $cellStr >= $lo);
  2558. if ($isNot ? $in : !$in) {
  2559. continue 3;
  2560. }
  2561. break;
  2562. }
  2563. $in = ($cellStr >= $lo && $cellStr <= $hi);
  2564. if ($isNot ? $in : !$in) {
  2565. continue 3;
  2566. }
  2567. break;
  2568. case 'NULL':
  2569. case 'IS NULL':
  2570. if ($cell !== null && $cell !== '') {
  2571. continue 3;
  2572. }
  2573. break;
  2574. case 'NOT NULL':
  2575. case 'IS NOT NULL':
  2576. if ($cell === null || $cell === '') {
  2577. continue 3;
  2578. }
  2579. break;
  2580. default:
  2581. break;
  2582. }
  2583. }
  2584. $filtered[] = $r;
  2585. }
  2586. return $filtered;
  2587. }
  2588. /**
  2589. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  2590. */
  2591. public function snapshotToProcure()
  2592. {
  2593. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2594. $this->error(__('Invalid parameters'));
  2595. }
  2596. $row = json_decode($this->request->post('row_json', ''), true);
  2597. if (!is_array($row)) {
  2598. $this->error(__('Invalid parameters'));
  2599. }
  2600. try {
  2601. $ids = $this->extractScydgyRowId($row);
  2602. if (!$this->isValidScydgyRowId($ids)) {
  2603. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  2604. }
  2605. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2606. $data = [
  2607. 'scydgy_id' => $ids,
  2608. 'CCYDH' => $row['CCYDH'] ?? null,
  2609. 'CYJMC' => $row['CYJMC'] ?? null,
  2610. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2611. 'CDXMC' => $row['CDXMC'] ?? null,
  2612. 'CGYBH' => $row['CGYBH'] ?? null,
  2613. 'CGYMC' => $row['CGYMC'] ?? null,
  2614. 'CDW' => $row['CDW'] ?? null,
  2615. 'NGZL' => $row['NGZL'] ?? null,
  2616. 'CDF' => $row['CDF'] ?? null,
  2617. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2618. 'MBZ' => $row['MBZ'] ?? null,
  2619. 'bwjg' => $row['bwjg'] ?? null,
  2620. 'iStatus' => $row['iStatus'] ?? null,
  2621. 'dStamp' => $row['dStamp'] ?? null,
  2622. 'dputrecord' => $row['dputrecord'] ?? null,
  2623. 'cywyxm' => $row['cywyxm'] ?? null,
  2624. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2625. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2626. ];
  2627. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  2628. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  2629. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  2630. $this->success('操作成功');
  2631. return;
  2632. }
  2633. if ($exists) {
  2634. $upd = $data;
  2635. unset($upd['scydgy_id'], $upd['status']);
  2636. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  2637. } else {
  2638. // 新增:不写 status(空/走库默认);仅写创建时间
  2639. $data['createtime'] = date('Y-m-d H:i:s');
  2640. Db::table('purchase_order')->insert($data);
  2641. }
  2642. } catch (\Throwable $e) {
  2643. $this->error($e->getMessage());
  2644. }
  2645. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  2646. $this->success('操作成功');
  2647. }
  2648. /**
  2649. * 未发列表
  2650. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  2651. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  2652. */
  2653. public function completeDirectly()
  2654. {
  2655. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2656. $this->error(__('参数错误'));
  2657. }
  2658. if (!$this->procuremenCanComplete()) {
  2659. $this->error(__('You have no permission'));
  2660. }
  2661. $row = json_decode($this->request->post('row_json', ''), true);
  2662. if (!is_array($row)) {
  2663. $this->error(__('Invalid parameters'));
  2664. }
  2665. $finishRaw = $this->request->post('finish', '1');
  2666. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  2667. $poIdLog = null;
  2668. try {
  2669. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  2670. $ids = $this->extractScydgyRowId($row);
  2671. if (!$this->isValidScydgyRowId($ids)) {
  2672. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  2673. }
  2674. if ($asComplete) {
  2675. $this->assertPickRowCanComplete($ids, $row);
  2676. }
  2677. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2678. $data = [
  2679. 'scydgy_id' => $ids,
  2680. 'CCYDH' => $row['CCYDH'] ?? null,
  2681. 'CYJMC' => $row['CYJMC'] ?? null,
  2682. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2683. 'CDXMC' => $row['CDXMC'] ?? null,
  2684. 'CGYBH' => $row['CGYBH'] ?? null,
  2685. 'CGYMC' => $row['CGYMC'] ?? null,
  2686. 'CDW' => $row['CDW'] ?? null,
  2687. 'NGZL' => $row['NGZL'] ?? null,
  2688. 'CDF' => $row['CDF'] ?? null,
  2689. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2690. 'MBZ' => $row['MBZ'] ?? null,
  2691. 'bwjg' => $row['bwjg'] ?? null,
  2692. 'iStatus' => $row['iStatus'] ?? null,
  2693. 'dStamp' => $row['dStamp'] ?? null,
  2694. 'dputrecord' => $row['dputrecord'] ?? null,
  2695. 'cywyxm' => $row['cywyxm'] ?? null,
  2696. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2697. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2698. ];
  2699. if ($asComplete) {
  2700. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  2701. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  2702. }
  2703. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  2704. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  2705. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  2706. $this->success('操作成功');
  2707. return;
  2708. }
  2709. if ($exists) {
  2710. $upd = $data;
  2711. unset($upd['scydgy_id']);
  2712. if (!$asComplete) {
  2713. unset($upd['status']);
  2714. }
  2715. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  2716. } else {
  2717. // 新增:不写 status;完结时 $data 已含 status=1
  2718. $data['createtime'] = date('Y-m-d H:i:s');
  2719. Db::table('purchase_order')->insert($data);
  2720. }
  2721. } catch (\Throwable $e) {
  2722. $this->error($e->getMessage());
  2723. }
  2724. try {
  2725. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  2726. if (is_array($rpo)) {
  2727. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  2728. $poIdLog = $tid > 0 ? $tid : null;
  2729. }
  2730. } catch (\Throwable $e) {
  2731. $poIdLog = null;
  2732. }
  2733. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  2734. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  2735. if ($asComplete) {
  2736. $this->addOrderLog(
  2737. $ids,
  2738. 'mark_complete',
  2739. '点击「完结」,已标记为已完结',
  2740. $poIdLog
  2741. );
  2742. try {
  2743. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  2744. if ($pdfPublicPath === '') {
  2745. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  2746. }
  2747. } catch (\Throwable $e) {
  2748. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  2749. }
  2750. } else {
  2751. $this->addOrderLog(
  2752. $ids,
  2753. 'save_qty_price',
  2754. '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  2755. $poIdLog
  2756. );
  2757. }
  2758. $this->pickHiddenScydgySetCache = null;
  2759. $this->success("操作成功");
  2760. }
  2761. /**
  2762. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  2763. *
  2764. * @param array<int, array> $rows 引用传递当前页行
  2765. */
  2766. protected function mergePurchaseOrder(array &$rows)
  2767. {
  2768. if ($rows === []) {
  2769. return;
  2770. }
  2771. $ids = [];
  2772. foreach ($rows as $rw) {
  2773. if (!is_array($rw)) {
  2774. continue;
  2775. }
  2776. $id = (int)($rw['ID'] ?? 0);
  2777. if ($id > 0) {
  2778. $ids[$id] = true;
  2779. }
  2780. }
  2781. $idList = array_keys($ids);
  2782. if ($idList === []) {
  2783. return;
  2784. }
  2785. try {
  2786. $list = Db::table('purchase_order')
  2787. ->where('scydgy_id', 'in', $idList)
  2788. ->field('scydgy_id,This_quantity,ceilingPrice')
  2789. ->select();
  2790. } catch (\Throwable $e) {
  2791. return;
  2792. }
  2793. if (!is_array($list)) {
  2794. return;
  2795. }
  2796. $byId = [];
  2797. foreach ($list as $dbRow) {
  2798. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  2799. continue;
  2800. }
  2801. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  2802. }
  2803. foreach ($rows as &$rw) {
  2804. if (!is_array($rw)) {
  2805. continue;
  2806. }
  2807. $sid = (int)($rw['ID'] ?? 0);
  2808. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  2809. continue;
  2810. }
  2811. $db = $byId[$sid];
  2812. if (array_key_exists('This_quantity', $db) && $db['This_quantity'] !== null && $db['This_quantity'] !== '') {
  2813. $rw['This_quantity'] = $db['This_quantity'];
  2814. }
  2815. if (array_key_exists('ceilingPrice', $db) && $db['ceilingPrice'] !== null && $db['ceilingPrice'] !== '') {
  2816. $rw['ceilingPrice'] = $db['ceilingPrice'];
  2817. } elseif (array_key_exists('ceiling_price', $db) && $db['ceiling_price'] !== null && $db['ceiling_price'] !== '') {
  2818. $rw['ceilingPrice'] = $db['ceiling_price'];
  2819. }
  2820. }
  2821. unset($rw);
  2822. }
  2823. /**
  2824. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  2825. */
  2826. public function purchaseConfirmPick()
  2827. {
  2828. if (!$this->request->isPost() || !$this->request->isAjax()) {
  2829. $this->error(__('Invalid parameters'));
  2830. }
  2831. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  2832. $this->error(__('You have no permission'));
  2833. }
  2834. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  2835. if ($batchRaw !== '') {
  2836. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  2837. return;
  2838. }
  2839. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  2840. $sid = (int)$scydgyId;
  2841. if (!$this->isValidScydgyRowId($sid)) {
  2842. $this->error('参数无效');
  2843. }
  2844. $parseIdList = function ($raw) {
  2845. if (is_array($raw)) {
  2846. $arr = $raw;
  2847. } else {
  2848. $decoded = json_decode((string)$raw, true);
  2849. $arr = is_array($decoded) ? $decoded : [];
  2850. }
  2851. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  2852. };
  2853. $selectedRaw = $this->request->post('selected_ids', null);
  2854. if ($selectedRaw === null || $selectedRaw === '') {
  2855. $legacy = (int)$this->request->post('selected_id', 0);
  2856. $selectedIds = $legacy > 0 ? [$legacy] : [];
  2857. } else {
  2858. $selectedIds = $parseIdList($selectedRaw);
  2859. }
  2860. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  2861. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  2862. try {
  2863. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  2864. } catch (\InvalidArgumentException $e) {
  2865. $this->error($e->getMessage());
  2866. } catch (\Throwable $e) {
  2867. $this->error($e->getMessage());
  2868. }
  2869. $this->pickHiddenScydgySetCache = null;
  2870. $this->success('操作成功', '', $result);
  2871. }
  2872. /**
  2873. * 整单采购确认(多道工序一次提交)
  2874. */
  2875. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  2876. {
  2877. $decoded = json_decode($batchRaw, true);
  2878. if (!is_array($decoded) || $decoded === []) {
  2879. $this->error('提交数据无效');
  2880. }
  2881. $picks = [];
  2882. foreach ($decoded as $item) {
  2883. if (!is_array($item)) {
  2884. continue;
  2885. }
  2886. $sid = (int)($item['scydgy_id'] ?? 0);
  2887. if (!$this->isValidScydgyRowId($sid)) {
  2888. continue;
  2889. }
  2890. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  2891. if (!is_array($sel)) {
  2892. $sel = [(int)$sel];
  2893. }
  2894. $unsel = $item['unselected_ids'] ?? [];
  2895. if (!is_array($unsel)) {
  2896. $unsel = json_decode((string)$unsel, true);
  2897. $unsel = is_array($unsel) ? $unsel : [];
  2898. }
  2899. $picks[] = [
  2900. 'scydgy_id' => $sid,
  2901. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  2902. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  2903. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  2904. ];
  2905. }
  2906. if ($picks === []) {
  2907. $this->error('提交数据无效');
  2908. }
  2909. Db::startTrans();
  2910. $results = [];
  2911. try {
  2912. foreach ($picks as $pick) {
  2913. $results[] = $this->runPurchaseConfirmPick(
  2914. (int)$pick['scydgy_id'],
  2915. $pick['selected_ids'],
  2916. $pick['unselected_ids'],
  2917. (int)$pick['purchase_order_id'],
  2918. false
  2919. );
  2920. }
  2921. Db::commit();
  2922. } catch (\Throwable $e) {
  2923. Db::rollback();
  2924. $msg = $e->getMessage();
  2925. $this->error($msg !== '' ? $msg : '提交失败');
  2926. }
  2927. $this->pickHiddenScydgySetCache = null;
  2928. $this->success('操作成功', '', ['batch' => $results]);
  2929. }
  2930. /**
  2931. * @return array<string, mixed>
  2932. */
  2933. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true): array
  2934. {
  2935. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  2936. ProcuremenGuard::assertWflowPendingApproval($poRow);
  2937. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  2938. $scydgyId = (string)$sid;
  2939. if ($selectedIds === []) {
  2940. throw new \InvalidArgumentException('请至少勾选一条明细');
  2941. }
  2942. $inter = array_intersect($selectedIds, $unselectedIds);
  2943. if ($inter !== []) {
  2944. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  2945. }
  2946. $allIds = $this->purchaseOrderDetail($sid);
  2947. if ($allIds === []) {
  2948. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  2949. }
  2950. foreach ($selectedIds as $id) {
  2951. if (!in_array($id, $allIds, true)) {
  2952. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  2953. }
  2954. }
  2955. foreach ($unselectedIds as $id) {
  2956. if (!in_array($id, $allIds, true)) {
  2957. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  2958. }
  2959. }
  2960. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  2961. sort($union, SORT_NUMERIC);
  2962. $expect = $allIds;
  2963. sort($expect, SORT_NUMERIC);
  2964. if ($union !== $expect) {
  2965. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  2966. }
  2967. if ($manageTransaction) {
  2968. Db::startTrans();
  2969. }
  2970. try {
  2971. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  2972. $aff = 0;
  2973. try {
  2974. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  2975. } catch (\Throwable $e) {
  2976. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  2977. }
  2978. if ($aff < 1) {
  2979. throw new \Exception('更新选中状态失败');
  2980. }
  2981. $poPayload = [
  2982. 'status' => ProcuremenStatus::PO_COMPLETED,
  2983. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  2984. ];
  2985. if ($purchaseOrderId > 0) {
  2986. $poAff = (int)Db::table('purchase_order')
  2987. ->where('id', $purchaseOrderId)
  2988. ->where('scydgy_id', $sid)
  2989. ->update($poPayload);
  2990. if ($poAff < 1) {
  2991. throw new \Exception('主表订单不存在或与工序行不匹配');
  2992. }
  2993. } else {
  2994. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  2995. if ($poAff < 1) {
  2996. throw new \Exception('未找到');
  2997. }
  2998. }
  2999. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  3000. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  3001. if ($manageTransaction) {
  3002. Db::commit();
  3003. }
  3004. } catch (\Throwable $e) {
  3005. if ($manageTransaction) {
  3006. Db::rollback();
  3007. }
  3008. throw $e;
  3009. }
  3010. $poIdFinal = $purchaseOrderId;
  3011. if ($poIdFinal <= 0) {
  3012. try {
  3013. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3014. if (is_array($rpo)) {
  3015. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3016. }
  3017. } catch (\Throwable $e) {
  3018. $poIdFinal = 0;
  3019. }
  3020. }
  3021. $pickNames = [];
  3022. foreach ($selectedIds as $pid) {
  3023. $dr = $this->purchaseOrderDetai($sid, $pid);
  3024. $nm = trim((string)($dr['company_name'] ?? ''));
  3025. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  3026. }
  3027. $this->addOrderLog(
  3028. $sid,
  3029. 'purchase_confirm',
  3030. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  3031. $poIdFinal > 0 ? $poIdFinal : null
  3032. );
  3033. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars($sid, $selectedIds[0] ?? 0);
  3034. $sendSmsSafe = function ($phone, $content) {
  3035. $phone = trim((string)$phone);
  3036. if ($phone === '') {
  3037. return;
  3038. }
  3039. try {
  3040. $this->smsbao($phone, $content);
  3041. } catch (\Throwable $e) {
  3042. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  3043. }
  3044. };
  3045. foreach ($selectedIds as $pid) {
  3046. $dr = $this->purchaseOrderDetai($sid, $pid);
  3047. if (!is_array($dr)) {
  3048. continue;
  3049. }
  3050. $cname = trim((string)($dr['company_name'] ?? ''));
  3051. $ph = trim((string)($dr['phone'] ?? ''));
  3052. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  3053. 'company_name' => $cname,
  3054. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3055. 'phone' => $ph,
  3056. ]));
  3057. $sendSmsSafe((string)($dr['phone'] ?? ''), $sms);
  3058. }
  3059. foreach ($unselectedIds as $pid) {
  3060. $dr = $this->purchaseOrderDetai($sid, $pid);
  3061. if (!is_array($dr)) {
  3062. continue;
  3063. }
  3064. $cname = trim((string)($dr['company_name'] ?? ''));
  3065. $ph = trim((string)($dr['phone'] ?? ''));
  3066. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  3067. 'company_name' => $cname,
  3068. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3069. 'phone' => $ph,
  3070. ]));
  3071. $sendSmsSafe((string)($dr['phone'] ?? ''), $sms);
  3072. }
  3073. Log::write(sprintf(
  3074. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  3075. $scydgyId,
  3076. $purchaseOrderId,
  3077. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  3078. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  3079. ), 'notice');
  3080. $pdfPublicPath = '';
  3081. try {
  3082. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  3083. } catch (\Throwable $e) {
  3084. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  3085. }
  3086. return [
  3087. 'scydgy_id' => $scydgyId,
  3088. 'purchase_order_id' => $purchaseOrderId,
  3089. 'selected_ids' => $selectedIds,
  3090. 'unselected_ids' => $unselectedIds,
  3091. 'purchase_confirm_pdf' => $pdfPublicPath,
  3092. ];
  3093. }
  3094. /**
  3095. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  3096. *
  3097. * @param int[] $detailIds
  3098. */
  3099. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  3100. {
  3101. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  3102. if ($detailIds === []) {
  3103. return;
  3104. }
  3105. $payload = ['status_name' => $statusName];
  3106. try {
  3107. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  3108. } catch (\Throwable $e) {
  3109. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  3110. }
  3111. }
  3112. /**
  3113. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  3114. */
  3115. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  3116. {
  3117. try {
  3118. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  3119. } catch (\Throwable $e) {
  3120. return;
  3121. }
  3122. if (!is_array($rows)) {
  3123. return;
  3124. }
  3125. foreach ($rows as $dr) {
  3126. if (!is_array($dr)) {
  3127. continue;
  3128. }
  3129. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  3130. if ($id <= 0) {
  3131. continue;
  3132. }
  3133. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  3134. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  3135. try {
  3136. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  3137. } catch (\Throwable $e) {
  3138. }
  3139. }
  3140. }
  3141. /**
  3142. * @param array<string, mixed> $detailRow
  3143. */
  3144. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  3145. {
  3146. $am = $detailRow['amount'] ?? null;
  3147. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  3148. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  3149. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  3150. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  3151. }
  3152. /**
  3153. * @return int[]
  3154. */
  3155. protected function purchaseOrderDetail(int $scydgyId): array
  3156. {
  3157. if (!$this->isValidScydgyRowId($scydgyId)) {
  3158. return [];
  3159. }
  3160. try {
  3161. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  3162. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  3163. $list = $listQuery->select();
  3164. } catch (\Throwable $e) {
  3165. return [];
  3166. }
  3167. if (!is_array($list)) {
  3168. return [];
  3169. }
  3170. $ids = [];
  3171. foreach ($list as $r) {
  3172. if (!is_array($r)) {
  3173. continue;
  3174. }
  3175. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  3176. if ($pk > 0) {
  3177. $ids[] = $pk;
  3178. }
  3179. }
  3180. return array_values(array_unique($ids));
  3181. }
  3182. /**
  3183. * 获取当前登录用户信息 [id, 展示名]
  3184. */
  3185. protected function GetUseName(): array
  3186. {
  3187. $id = 0;
  3188. $name = '';
  3189. try {
  3190. if ($this->auth && $this->auth->isLogin()) {
  3191. $u = $this->auth->getUserInfo();
  3192. if (is_array($u)) {
  3193. $id = (int)($u['id'] ?? 0);
  3194. $name = trim((string)($u['nickname'] ?? ''));
  3195. if ($name === '') {
  3196. $name = trim((string)($u['username'] ?? ''));
  3197. }
  3198. }
  3199. }
  3200. } catch (\Throwable $e) {
  3201. }
  3202. if ($name === '') {
  3203. $name = '未知用户';
  3204. }
  3205. return [$id, $name];
  3206. }
  3207. /**
  3208. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  3209. */
  3210. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  3211. {
  3212. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  3213. }
  3214. /**
  3215. * 按主键取一条
  3216. */
  3217. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  3218. {
  3219. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  3220. return [];
  3221. }
  3222. try {
  3223. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  3224. if (is_array($one)) {
  3225. return $one;
  3226. }
  3227. } catch (\Throwable $e) {
  3228. }
  3229. try {
  3230. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  3231. if (is_array($one)) {
  3232. return $one;
  3233. }
  3234. } catch (\Throwable $e) {
  3235. }
  3236. return [];
  3237. }
  3238. /**
  3239. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  3240. */
  3241. protected function formatProcuremenDetailTime($v): string
  3242. {
  3243. if ($v === null || $v === '') {
  3244. return '';
  3245. }
  3246. if (is_numeric($v) && (int)$v > 946684800) {
  3247. return date('Y-m-d H:i:s', (int)$v);
  3248. }
  3249. return ProcuremenTime::formatDisplayDateTime($v);
  3250. }
  3251. /**
  3252. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  3253. */
  3254. protected function formatDeliveryYmd($v): string
  3255. {
  3256. if ($v === null || $v === '') {
  3257. return '';
  3258. }
  3259. $s = trim((string)$v);
  3260. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  3261. return '';
  3262. }
  3263. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  3264. return $m[1];
  3265. }
  3266. $ts = strtotime($s);
  3267. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  3268. }
  3269. /**
  3270. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  3271. */
  3272. protected function detailRowSupplierOperated(array $r): bool
  3273. {
  3274. $am = $r['amount'] ?? null;
  3275. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3276. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3277. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3278. return $okAmt || $okDel;
  3279. }
  3280. /**
  3281. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  3282. */
  3283. protected function resolveDetailSupplierOperTime(array $r): string
  3284. {
  3285. if (!$this->detailRowSupplierOperated($r)) {
  3286. return '';
  3287. }
  3288. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  3289. if ($t !== '') {
  3290. return $t;
  3291. }
  3292. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  3293. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  3294. continue;
  3295. }
  3296. $t = $this->formatProcuremenDetailTime($r[$col]);
  3297. if ($t !== '') {
  3298. return $t;
  3299. }
  3300. }
  3301. return '';
  3302. }
  3303. /**
  3304. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  3305. */
  3306. protected function detailRowSupplierAccepted(array $r): bool
  3307. {
  3308. $am = $r['amount'] ?? null;
  3309. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3310. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3311. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3312. return $okAmt && $okDel;
  3313. }
  3314. /**
  3315. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  3316. */
  3317. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  3318. {
  3319. if ($detailCount > 0) {
  3320. return true;
  3321. }
  3322. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  3323. return true;
  3324. }
  3325. $pickTime = trim((string)($main['pick_time'] ?? ''));
  3326. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  3327. return true;
  3328. }
  3329. return false;
  3330. }
  3331. /**
  3332. * 下发时间:优先 pick_time,其次首条下发明细时间
  3333. */
  3334. protected function resolveProcuremenIssueTime(array $main, array $details): string
  3335. {
  3336. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  3337. if ($issueTime !== '') {
  3338. return $issueTime;
  3339. }
  3340. foreach ($details as $dr) {
  3341. if (!is_array($dr)) {
  3342. continue;
  3343. }
  3344. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3345. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  3346. $issueTime = $t;
  3347. }
  3348. }
  3349. if ($issueTime !== '') {
  3350. return $issueTime;
  3351. }
  3352. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  3353. }
  3354. /**
  3355. * 直接点「完结」时间:优先操作记录 mark_complete
  3356. */
  3357. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  3358. {
  3359. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  3360. }
  3361. /**
  3362. * 操作记录时间(取指定 action 最近一条)
  3363. *
  3364. * @param string|array<int, string> $actions
  3365. */
  3366. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  3367. {
  3368. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  3369. }
  3370. /**
  3371. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  3372. *
  3373. * @param array $main purchase_order 一行
  3374. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  3375. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  3376. */
  3377. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  3378. {
  3379. $issueCnt = count($details);
  3380. $acceptCnt = 0;
  3381. $pickedName = '';
  3382. $pickedTime = '';
  3383. foreach ($details as $dr) {
  3384. if (!is_array($dr)) {
  3385. continue;
  3386. }
  3387. if ($this->detailRowSupplierAccepted($dr)) {
  3388. $acceptCnt++;
  3389. }
  3390. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  3391. if ($pickedName === '') {
  3392. $pickedName = trim((string)($dr['company_name'] ?? ''));
  3393. }
  3394. if ($pickedTime === '') {
  3395. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  3396. if ($pickedTime === '') {
  3397. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3398. }
  3399. }
  3400. }
  3401. }
  3402. $hasMain = $main !== [];
  3403. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  3404. if ($poTime === '') {
  3405. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  3406. }
  3407. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  3408. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  3409. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  3410. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  3411. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  3412. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  3413. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  3414. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  3415. $supplierTime = '';
  3416. if ($acceptCnt > 0) {
  3417. foreach ($details as $dr) {
  3418. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  3419. continue;
  3420. }
  3421. $t = $this->resolveDetailSupplierOperTime($dr);
  3422. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  3423. $supplierTime = $t;
  3424. }
  3425. }
  3426. }
  3427. $directComplete = ($mainCompleted && !$issued);
  3428. $doneTime = '';
  3429. if ($mainCompleted) {
  3430. if ($directComplete) {
  3431. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  3432. }
  3433. if ($doneTime === '') {
  3434. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  3435. }
  3436. if ($doneTime === '') {
  3437. foreach ($details as $dr) {
  3438. if (!is_array($dr)) {
  3439. continue;
  3440. }
  3441. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  3442. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  3443. $doneTime = $t;
  3444. }
  3445. }
  3446. }
  3447. if ($doneTime === '') {
  3448. $doneTime = $poTime;
  3449. }
  3450. if ($confirmApproveTime !== '') {
  3451. $doneTime = $confirmApproveTime;
  3452. }
  3453. }
  3454. if ($directComplete) {
  3455. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  3456. $step1Done = $hasMain;
  3457. $step2Done = false;
  3458. $step3Done = false;
  3459. $step4Done = false;
  3460. $step5Done = false;
  3461. $step6Done = true;
  3462. } else {
  3463. $step1Done = $issued;
  3464. $step2Done = $issued;
  3465. $step3Done = $acceptCnt > 0;
  3466. $step4Done = $wflowPendingApproval;
  3467. if (!$step4Done) {
  3468. foreach ($details as $dr) {
  3469. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  3470. $step4Done = true;
  3471. break;
  3472. }
  3473. }
  3474. }
  3475. $step5Done = $confirmApproveTime !== '' || $mainCompleted;
  3476. $step6Done = $mainCompleted;
  3477. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  3478. if ($mainCompleted && $issued) {
  3479. $step3Done = true;
  3480. $step4Done = true;
  3481. $step5Done = true;
  3482. if ($supplierTime === '') {
  3483. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3484. if ($fillT !== '') {
  3485. $supplierTime = $fillT;
  3486. }
  3487. }
  3488. if ($pickedTime === '') {
  3489. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3490. if ($fillT !== '') {
  3491. $pickedTime = $fillT;
  3492. }
  3493. }
  3494. if ($auditSelectTime === '') {
  3495. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3496. if ($fillT !== '') {
  3497. $auditSelectTime = $fillT;
  3498. }
  3499. }
  3500. if ($confirmApproveTime === '') {
  3501. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  3502. if ($fillT !== '') {
  3503. $confirmApproveTime = $fillT;
  3504. }
  3505. }
  3506. }
  3507. }
  3508. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  3509. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  3510. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  3511. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  3512. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  3513. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  3514. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  3515. $steps = [
  3516. [
  3517. 'title' => '未发',
  3518. 'subtitle' => '',
  3519. 'time' => $issued ? '—' : ($hasMain ? $poTime : ''),
  3520. 'done' => $step1Done,
  3521. ],
  3522. [
  3523. 'title' => '下发',
  3524. 'subtitle' => '',
  3525. 'time' => $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '',
  3526. 'done' => $step2Done,
  3527. ],
  3528. [
  3529. 'title' => '供应商接单',
  3530. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  3531. 'time' => '',
  3532. 'done' => $step3Done,
  3533. ],
  3534. [
  3535. 'title' => '待确认',
  3536. 'subtitle' => $step4Done
  3537. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  3538. : ($issued ? '待选供应商' : ''),
  3539. 'time' => $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '',
  3540. 'done' => $step4Done,
  3541. ],
  3542. [
  3543. 'title' => '待审批',
  3544. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  3545. 'time' => $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : $doneTime) : '',
  3546. 'done' => $step5Done,
  3547. ],
  3548. [
  3549. 'title' => '已完结',
  3550. 'subtitle' => '',
  3551. 'time' => $step6Done ? $doneTime : '',
  3552. 'done' => $step6Done,
  3553. ],
  3554. ];
  3555. $currentIdx = count($steps) - 1;
  3556. if (!$directComplete) {
  3557. foreach ($steps as $i => $s) {
  3558. if (!$s['done']) {
  3559. $currentIdx = $i;
  3560. break;
  3561. }
  3562. }
  3563. }
  3564. $nSteps = count($steps);
  3565. foreach ($steps as $idx => &$s) {
  3566. $s['current'] = ($idx === $currentIdx);
  3567. if ($idx === 0) {
  3568. $s['pdf_left_bg'] = '';
  3569. } else {
  3570. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  3571. }
  3572. if ($idx >= $nSteps - 1) {
  3573. $s['pdf_right_bg'] = '';
  3574. } else {
  3575. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  3576. }
  3577. }
  3578. unset($s);
  3579. $labelMap = [
  3580. 'CCYDH' => '订单号',
  3581. 'CYJMC' => '印件名称',
  3582. 'CCLBMMC' => '承揽部门',
  3583. 'CGYMC' => '工序名称',
  3584. 'CDW' => '单位',
  3585. 'NGZL' => '工作量',
  3586. 'CDF' => '单价',
  3587. 'cGzzxMc' => '工作中心',
  3588. 'MBZ' => '备注',
  3589. 'This_quantity' => '本次数量',
  3590. 'ceilingPrice' => '最高限价',
  3591. ];
  3592. $orderSummary = [];
  3593. foreach ($labelMap as $key => $lab) {
  3594. if (!array_key_exists($key, $main)) {
  3595. continue;
  3596. }
  3597. $val = $main[$key];
  3598. if ($val === null) {
  3599. $val = '';
  3600. } elseif (!is_scalar($val)) {
  3601. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  3602. } else {
  3603. $val = (string)$val;
  3604. }
  3605. $orderSummary[] = ['label' => $lab, 'value' => $val];
  3606. }
  3607. $orderSummaryGrid = [];
  3608. $n = count($orderSummary);
  3609. for ($i = 0; $i < $n; $i += 2) {
  3610. $left = $orderSummary[$i];
  3611. $hasRight = ($i + 1) < $n;
  3612. $orderSummaryGrid[] = [
  3613. 'l1' => $left['label'],
  3614. 'v1' => $left['value'],
  3615. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  3616. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  3617. ];
  3618. }
  3619. return [
  3620. 'steps' => $steps,
  3621. 'orderSummary' => $orderSummary,
  3622. 'orderSummaryGrid' => $orderSummaryGrid,
  3623. 'detailRows' => $details,
  3624. ];
  3625. }
  3626. /**
  3627. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  3628. *
  3629. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  3630. */
  3631. protected function prepareProcuremenDetailsView(string $ids): array
  3632. {
  3633. $main = [];
  3634. try {
  3635. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3636. $main = is_array($one) ? $one : [];
  3637. } catch (\Throwable $e) {
  3638. $main = [];
  3639. }
  3640. $details = [];
  3641. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  3642. if ($mergeRows === []) {
  3643. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  3644. if ($mergeRows === [] && $main !== []) {
  3645. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  3646. }
  3647. }
  3648. $detailSidList = [];
  3649. $anchorSid = (int)$ids;
  3650. if ($anchorSid !== 0) {
  3651. $detailSidList[$anchorSid] = true;
  3652. }
  3653. foreach ($mergeRows as $mr) {
  3654. if (!is_array($mr)) {
  3655. continue;
  3656. }
  3657. $sid = $this->extractScydgyRowId($mr);
  3658. if ($sid !== 0) {
  3659. $detailSidList[$sid] = true;
  3660. }
  3661. }
  3662. try {
  3663. if ($detailSidList !== []) {
  3664. $details = Db::table('purchase_order_detail')
  3665. ->where('scydgy_id', 'in', array_keys($detailSidList))
  3666. ->order('id', 'asc')
  3667. ->select();
  3668. }
  3669. } catch (\Throwable $e) {
  3670. $details = [];
  3671. }
  3672. if (!is_array($details)) {
  3673. $details = [];
  3674. }
  3675. foreach ($details as &$r) {
  3676. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  3677. $r['id'] = $r['ID'];
  3678. }
  3679. if (isset($r['createtime'])) {
  3680. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  3681. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  3682. } else {
  3683. $r['createtime_text'] = (string)$r['createtime'];
  3684. }
  3685. } else {
  3686. $r['createtime_text'] = '';
  3687. }
  3688. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  3689. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  3690. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  3691. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  3692. }
  3693. unset($r);
  3694. $activeDetails = [];
  3695. foreach ($details as $r) {
  3696. if (is_array($r) && empty($r['is_void'])) {
  3697. $activeDetails[] = $r;
  3698. }
  3699. }
  3700. $operLogs = [];
  3701. try {
  3702. $operLogs = Db::table('purchase_order_oper_log')->where('scydgy_id', $ids)->order('id', 'asc')->select();
  3703. } catch (\Throwable $e) {
  3704. $operLogs = [];
  3705. }
  3706. if (!is_array($operLogs)) {
  3707. $operLogs = [];
  3708. }
  3709. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs);
  3710. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  3711. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  3712. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  3713. if ($ccydh === '') {
  3714. foreach ($details as $r) {
  3715. if (!is_array($r)) {
  3716. continue;
  3717. }
  3718. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  3719. if ($ccydh !== '') {
  3720. break;
  3721. }
  3722. }
  3723. }
  3724. $this->view->assign('ccydh', $ccydh);
  3725. $this->view->assign('steps', $bundle['steps']);
  3726. $this->view->assign('orderSummary', $bundle['orderSummary']);
  3727. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  3728. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  3729. $this->view->assign('processCount', count($mergeRows));
  3730. $this->view->assign('detailRows', $details);
  3731. $this->view->assign('supplierQuoteGroups', $quoteView['supplier_groups']);
  3732. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  3733. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  3734. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  3735. $this->view->assign('operLogs', $operLogs);
  3736. return [
  3737. 'ok' => $main !== [] || $details !== [],
  3738. 'ccydh' => $ccydh,
  3739. ];
  3740. }
  3741. /**
  3742. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  3743. */
  3744. public function details()
  3745. {
  3746. $ids = $this->request->param('ids', $this->request->param('id', ''));
  3747. if (is_array($ids)) {
  3748. $ids = isset($ids[0]) ? $ids[0] : '';
  3749. }
  3750. $ids = trim((string)$ids);
  3751. if ($ids === '') {
  3752. $this->error(__('Invalid parameters'));
  3753. }
  3754. $this->assertManualOrderDetailsViewable((int)$ids);
  3755. $this->prepareProcuremenDetailsView($ids);
  3756. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  3757. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  3758. $this->view->engine->layout(false);
  3759. try {
  3760. return $this->view->fetch('procuremen/details_dialog_shell');
  3761. } finally {
  3762. if ($restoreLayout) {
  3763. $this->view->engine->layout($restoreLayout);
  3764. }
  3765. }
  3766. }
  3767. /**
  3768. * 解析合并审核工序行(订单号须一致,且均未协助)
  3769. *
  3770. * @return array<int, array<string, mixed>>
  3771. */
  3772. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  3773. {
  3774. $primary = json_decode($rowJson, true);
  3775. if (!is_array($primary)) {
  3776. $this->error(__('Invalid parameters'));
  3777. }
  3778. $merge = json_decode($mergeRowsJson, true);
  3779. if (!is_array($merge) || $merge === []) {
  3780. $merge = [$primary];
  3781. }
  3782. $seen = [];
  3783. $out = [];
  3784. foreach ($merge as $r) {
  3785. if (!is_array($r)) {
  3786. continue;
  3787. }
  3788. $id = $this->extractScydgyRowId($r);
  3789. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  3790. continue;
  3791. }
  3792. $seen[$id] = true;
  3793. $out[] = $r;
  3794. }
  3795. if ($out === []) {
  3796. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  3797. }
  3798. $ccydh = null;
  3799. foreach ($out as $r) {
  3800. $dh = trim((string)($r['CCYDH'] ?? ''));
  3801. if ($ccydh === null) {
  3802. $ccydh = $dh;
  3803. } elseif ($dh !== $ccydh) {
  3804. $this->error('合并审核要求所选行的订单号一致');
  3805. }
  3806. }
  3807. $ids = [];
  3808. foreach ($out as $r) {
  3809. $id = $this->extractScydgyRowId($r);
  3810. if ($this->isValidScydgyRowId($id)) {
  3811. $ids[$id] = true;
  3812. }
  3813. }
  3814. $poBySid = [];
  3815. $detCntBySid = [];
  3816. if ($ids !== []) {
  3817. $idList = array_keys($ids);
  3818. try {
  3819. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  3820. if (is_array($poList)) {
  3821. foreach ($poList as $po) {
  3822. if (!is_array($po)) {
  3823. continue;
  3824. }
  3825. $sid = (int)($po['scydgy_id'] ?? 0);
  3826. if ($this->isValidScydgyRowId($sid)) {
  3827. $poBySid[$sid] = $po;
  3828. }
  3829. }
  3830. }
  3831. } catch (\Throwable $e) {
  3832. }
  3833. try {
  3834. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  3835. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  3836. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  3837. if (is_array($detRows)) {
  3838. foreach ($detRows as $dr) {
  3839. if (!is_array($dr)) {
  3840. continue;
  3841. }
  3842. $sid = (int)($dr['scydgy_id'] ?? 0);
  3843. if ($this->isValidScydgyRowId($sid)) {
  3844. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  3845. }
  3846. }
  3847. }
  3848. } catch (\Throwable $e) {
  3849. }
  3850. }
  3851. foreach ($out as $r) {
  3852. $id = $this->extractScydgyRowId($r);
  3853. if (!$this->isValidScydgyRowId($id)) {
  3854. continue;
  3855. }
  3856. $po = $poBySid[$id] ?? null;
  3857. if (!is_array($po)) {
  3858. continue;
  3859. }
  3860. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  3861. $gymc = trim((string)($r['CGYMC'] ?? ''));
  3862. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  3863. }
  3864. $detCnt = (int)($detCntBySid[$id] ?? 0);
  3865. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  3866. $gymc = trim((string)($r['CGYMC'] ?? ''));
  3867. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  3868. }
  3869. }
  3870. return $out;
  3871. }
  3872. /**
  3873. * 规范化下发/确认时勾选的供应商
  3874. *
  3875. * @param array<int, mixed> $companies
  3876. * @return array<int, array<string, string>>
  3877. */
  3878. protected function normalizePickCompanies(array $companies): array
  3879. {
  3880. $out = [];
  3881. foreach ($companies as $c) {
  3882. if (!is_array($c)) {
  3883. continue;
  3884. }
  3885. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  3886. if ($name === '') {
  3887. continue;
  3888. }
  3889. $out[] = [
  3890. 'name' => $name,
  3891. 'company_name' => $name,
  3892. 'username' => trim((string)($c['username'] ?? '')),
  3893. 'email' => trim((string)($c['email'] ?? '')),
  3894. 'phone' => trim((string)($c['phone'] ?? '')),
  3895. 'company_type' => trim((string)($c['company_type'] ?? $c['category'] ?? '')),
  3896. ];
  3897. }
  3898. return $out;
  3899. }
  3900. /**
  3901. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  3902. *
  3903. * @param array<int, array<string, mixed>> $pool
  3904. * @return array<int, array<string, mixed>>
  3905. */
  3906. protected function collapseProcuremenPoolByOrder(array $pool): array
  3907. {
  3908. if ($pool === []) {
  3909. return [];
  3910. }
  3911. $groups = [];
  3912. foreach ($pool as $row) {
  3913. if (!is_array($row)) {
  3914. continue;
  3915. }
  3916. $dh = trim((string)($row['CCYDH'] ?? ''));
  3917. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  3918. if (!isset($groups[$key])) {
  3919. $groups[$key] = [];
  3920. }
  3921. $groups[$key][] = $row;
  3922. }
  3923. $out = [];
  3924. foreach ($groups as $ccydh => $rows) {
  3925. if ($rows === []) {
  3926. continue;
  3927. }
  3928. usort($rows, function ($a, $b) {
  3929. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  3930. });
  3931. $head = $rows[0];
  3932. $gymcList = [];
  3933. foreach ($rows as $r) {
  3934. $g = trim((string)($r['CGYMC'] ?? ''));
  3935. if ($g !== '' && !in_array($g, $gymcList, true)) {
  3936. $gymcList[] = $g;
  3937. }
  3938. }
  3939. $merged = $head;
  3940. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  3941. $merged['process_count'] = count($rows);
  3942. $merged['_order_merge_rows'] = $rows;
  3943. if (count($rows) > 1) {
  3944. $merged['CGYMC'] = implode('、', $gymcList);
  3945. }
  3946. $mergedPickTime = '';
  3947. foreach ($rows as $r) {
  3948. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  3949. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  3950. $mergedPickTime = $t;
  3951. }
  3952. }
  3953. if ($mergedPickTime !== '') {
  3954. $merged['pick_time'] = $mergedPickTime;
  3955. }
  3956. $out[] = $merged;
  3957. }
  3958. usort($out, function ($a, $b) {
  3959. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  3960. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  3961. if ($ta === $tb) {
  3962. $ida = (int)($a['purchase_order_id'] ?? 0);
  3963. $idb = (int)($b['purchase_order_id'] ?? 0);
  3964. if ($ida !== $idb) {
  3965. return $idb <=> $ida;
  3966. }
  3967. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  3968. }
  3969. if ($ta === '') {
  3970. return 1;
  3971. }
  3972. if ($tb === '') {
  3973. return -1;
  3974. }
  3975. return strcmp($tb, $ta);
  3976. });
  3977. return $out;
  3978. }
  3979. /**
  3980. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  3981. *
  3982. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3983. */
  3984. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  3985. {
  3986. $scydgyId = trim($scydgyId);
  3987. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3988. if ($scydgyId === '') {
  3989. return $empty;
  3990. }
  3991. try {
  3992. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  3993. } catch (\Throwable $e) {
  3994. $anchor = null;
  3995. }
  3996. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  3997. return $empty;
  3998. }
  3999. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4000. if ($ccydh === '') {
  4001. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  4002. }
  4003. try {
  4004. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  4005. } catch (\Throwable $e) {
  4006. $pos = [$anchor];
  4007. }
  4008. if (!is_array($pos) || $pos === []) {
  4009. $pos = [$anchor];
  4010. }
  4011. return [
  4012. 'ccydh' => $ccydh,
  4013. 'pos' => $pos,
  4014. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4015. ];
  4016. }
  4017. /**
  4018. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  4019. */
  4020. protected function purchaseOrderRowInConfirmStage(array $po): bool
  4021. {
  4022. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4023. return false;
  4024. }
  4025. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  4026. return false;
  4027. }
  4028. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  4029. return true;
  4030. }
  4031. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  4032. $sid = (int)($po['scydgy_id'] ?? 0);
  4033. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  4034. }
  4035. return false;
  4036. }
  4037. /**
  4038. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  4039. *
  4040. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4041. */
  4042. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  4043. {
  4044. $scydgyId = trim($scydgyId);
  4045. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4046. if ($scydgyId === '') {
  4047. return $empty;
  4048. }
  4049. try {
  4050. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4051. } catch (\Throwable $e) {
  4052. $anchor = null;
  4053. }
  4054. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  4055. return $empty;
  4056. }
  4057. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4058. if ($ccydh === '') {
  4059. return [
  4060. 'ccydh' => '',
  4061. 'pos' => [$anchor],
  4062. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  4063. ];
  4064. }
  4065. try {
  4066. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  4067. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  4068. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  4069. } catch (\Throwable $e) {
  4070. $pos = [$anchor];
  4071. }
  4072. if (!is_array($pos) || $pos === []) {
  4073. $pos = [$anchor];
  4074. }
  4075. $pos = array_values(array_filter($pos, function ($po) {
  4076. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  4077. }));
  4078. if ($pos === []) {
  4079. $pos = [$anchor];
  4080. }
  4081. return [
  4082. 'ccydh' => $ccydh,
  4083. 'pos' => $pos,
  4084. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4085. ];
  4086. }
  4087. /**
  4088. * @param array<int, array<string, mixed>> $purchaseOrders
  4089. * @return array<int, array<string, mixed>>
  4090. */
  4091. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  4092. {
  4093. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  4094. $byId = [];
  4095. foreach ($pool as $r) {
  4096. if (!is_array($r)) {
  4097. continue;
  4098. }
  4099. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  4100. if ($this->isValidScydgyRowId($sid)) {
  4101. $byId[$sid] = $r;
  4102. }
  4103. }
  4104. $out = [];
  4105. foreach ($purchaseOrders as $po) {
  4106. if (!is_array($po)) {
  4107. continue;
  4108. }
  4109. $sid = (int)($po['scydgy_id'] ?? 0);
  4110. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  4111. $out[] = $byId[$sid];
  4112. }
  4113. }
  4114. return $out;
  4115. }
  4116. /**
  4117. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  4118. *
  4119. * @return array<int, array<string, mixed>>
  4120. */
  4121. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  4122. {
  4123. $scydgyId = trim($scydgyId);
  4124. if ($scydgyId === '') {
  4125. return [];
  4126. }
  4127. try {
  4128. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4129. } catch (\Throwable $e) {
  4130. $anchor = null;
  4131. }
  4132. if (!is_array($anchor)) {
  4133. return [];
  4134. }
  4135. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  4136. return [];
  4137. }
  4138. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4139. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  4140. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  4141. try {
  4142. $q = Db::table('purchase_order');
  4143. if ($ccydh !== '') {
  4144. $q->where('CCYDH', $ccydh);
  4145. } else {
  4146. $q->where('scydgy_id', $scydgyId);
  4147. }
  4148. if ($isValidPick) {
  4149. $q->where('pick_time', $pickTime);
  4150. }
  4151. $pos = $q->order('scydgy_id', 'asc')->select();
  4152. } catch (\Throwable $e) {
  4153. $pos = [$anchor];
  4154. }
  4155. if (!is_array($pos) || $pos === []) {
  4156. $pos = [$anchor];
  4157. }
  4158. $pos = array_values(array_filter($pos, function ($po) {
  4159. if (!is_array($po)) {
  4160. return false;
  4161. }
  4162. $mr = $po['mod_rq'] ?? null;
  4163. if ($mr === null || $mr === '') {
  4164. return true;
  4165. }
  4166. $mrs = trim((string)$mr);
  4167. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  4168. }));
  4169. if ($pos === []) {
  4170. $pos = [$anchor];
  4171. }
  4172. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  4173. if ($rows === []) {
  4174. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  4175. }
  4176. return $rows;
  4177. }
  4178. /**
  4179. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  4180. *
  4181. * @param array<int, array<string, mixed>> $mergeRows
  4182. * @return array<int, array<string, mixed>>
  4183. */
  4184. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  4185. {
  4186. $list = array_values($mergeRows);
  4187. $n = count($list);
  4188. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  4189. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  4190. $mergeSame = $n > 1 && $orderKey0 !== '';
  4191. if ($mergeSame) {
  4192. foreach ($list as $rr) {
  4193. if (!is_array($rr)) {
  4194. $mergeSame = false;
  4195. break;
  4196. }
  4197. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  4198. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  4199. $mergeSame = false;
  4200. break;
  4201. }
  4202. }
  4203. }
  4204. $out = [];
  4205. foreach ($list as $idx => $r) {
  4206. if (!is_array($r)) {
  4207. continue;
  4208. }
  4209. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  4210. if (is_scalar($qty)) {
  4211. $qty = trim((string)$qty);
  4212. } else {
  4213. $qty = '';
  4214. }
  4215. if ($qty === '') {
  4216. $gzl = $r['NGZL'] ?? '';
  4217. if (is_scalar($gzl)) {
  4218. $qty = trim((string)$gzl);
  4219. }
  4220. }
  4221. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  4222. $sid = $this->extractScydgyRowId($r);
  4223. $out[] = [
  4224. 'seq' => $idx + 1,
  4225. 'scydgy_id' => $sid,
  4226. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  4227. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  4228. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  4229. 'CDW' => trim((string)($r['CDW'] ?? '')),
  4230. 'NGZL' => $r['NGZL'] ?? '',
  4231. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  4232. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  4233. 'CDF' => trim((string)($r['CDF'] ?? '')),
  4234. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  4235. 'show_order_cells' => !$mergeSame || $idx === 0,
  4236. 'order_rowspan' => $mergeSame ? $n : 1,
  4237. ];
  4238. }
  4239. return $out;
  4240. }
  4241. /**
  4242. * 解析金额/数量(去千分位等非数字字符)
  4243. */
  4244. protected function parseProcuremenMoneyNumber($value): ?float
  4245. {
  4246. if ($value === null || $value === '') {
  4247. return null;
  4248. }
  4249. if (is_numeric($value)) {
  4250. return (float)$value;
  4251. }
  4252. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  4253. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  4254. }
  4255. protected function formatProcuremenMoneyDisplay(?float $amount): string
  4256. {
  4257. if ($amount === null) {
  4258. return '';
  4259. }
  4260. return (string)(int)round($amount);
  4261. }
  4262. /**
  4263. * 列表/详情展示:工作量为 0 时显示空
  4264. */
  4265. protected function formatProcuremenWorkloadDisplay($value): string
  4266. {
  4267. if ($value === null || $value === '') {
  4268. return '';
  4269. }
  4270. $s = trim((string)$value);
  4271. if ($s === '') {
  4272. return '';
  4273. }
  4274. if (is_numeric($s) && (float)$s == 0) {
  4275. return '';
  4276. }
  4277. return $s;
  4278. }
  4279. /**
  4280. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  4281. */
  4282. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  4283. {
  4284. foreach ($details as $d) {
  4285. if (!is_array($d)) {
  4286. continue;
  4287. }
  4288. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  4289. $cn = trim((string)($d['company_name'] ?? ''));
  4290. if ($cn !== '') {
  4291. return $cn;
  4292. }
  4293. }
  4294. }
  4295. return trim((string)($main['pick_company_name'] ?? ''));
  4296. }
  4297. /**
  4298. * 详情报价小计:单价 × 本工序本次数量
  4299. */
  4300. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  4301. {
  4302. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  4303. if ($unit === null) {
  4304. return null;
  4305. }
  4306. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  4307. if ($qty === null || $qty <= 0) {
  4308. return null;
  4309. }
  4310. return $unit * $qty;
  4311. }
  4312. /**
  4313. * 详情页:工序小计 + 供应商分组报价与总计
  4314. *
  4315. * @param array<int, array<string, mixed>> $mergeRows
  4316. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  4317. * @return array{
  4318. * process_rows: array,
  4319. * supplier_groups: array,
  4320. * order_total_text: string,
  4321. * order_total_has: bool,
  4322. * selected_company: string
  4323. * }
  4324. */
  4325. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  4326. {
  4327. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  4328. $deadlineReached = $this->isProcuremenQuoteDeadlineReached($main['sys_rq'] ?? '');
  4329. $qtyBySid = [];
  4330. $gymcBySid = [];
  4331. $orderedSids = [];
  4332. foreach ($mergeRows as $mr) {
  4333. if (!is_array($mr)) {
  4334. continue;
  4335. }
  4336. $sid = $this->extractScydgyRowId($mr);
  4337. if ($sid > 0) {
  4338. $orderedSids[] = $sid;
  4339. }
  4340. $qty = trim((string)($mr['This_quantity'] ?? ''));
  4341. if ($qty === '') {
  4342. $qty = trim((string)($mr['NGZL'] ?? ''));
  4343. }
  4344. $qtyBySid[$sid] = $qty;
  4345. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  4346. }
  4347. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  4348. $detailByCompanySid = [];
  4349. foreach ($details as $d) {
  4350. if (!is_array($d)) {
  4351. continue;
  4352. }
  4353. $cn = trim((string)($d['company_name'] ?? ''));
  4354. $sid = (int)($d['scydgy_id'] ?? 0);
  4355. if ($cn === '' || $sid === 0) {
  4356. continue;
  4357. }
  4358. if (!isset($detailByCompanySid[$cn])) {
  4359. $detailByCompanySid[$cn] = [];
  4360. }
  4361. $detailByCompanySid[$cn][$sid] = $d;
  4362. }
  4363. $supplierGroups = [];
  4364. foreach ($detailByCompanySid as $cn => $bySid) {
  4365. $lines = [];
  4366. $groupTotal = 0.0;
  4367. $groupHas = false;
  4368. $groupVoid = true;
  4369. $usedSids = [];
  4370. $appendLine = function (int $sid, array $d) use (
  4371. &$lines,
  4372. &$groupTotal,
  4373. &$groupHas,
  4374. &$groupVoid,
  4375. $qtyBySid,
  4376. $gymcBySid,
  4377. $deadlineReached
  4378. ) {
  4379. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  4380. if (!$isVoid) {
  4381. $groupVoid = false;
  4382. }
  4383. $qtyStr = $qtyBySid[$sid] ?? '';
  4384. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  4385. $am = trim((string)($d['amount'] ?? ''));
  4386. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  4387. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  4388. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  4389. $sub = null;
  4390. if (!$isVoid && $amountNum !== null) {
  4391. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  4392. }
  4393. $ct = $this->resolveDetailSupplierOperTime($d);
  4394. $line = [
  4395. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  4396. 'unit_price_text' => $amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am,
  4397. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  4398. 'delivery_ymd' => $deliveryYmd,
  4399. 'amount_filled' => $amountFilled,
  4400. 'delivery_filled' => $deliveryFilled,
  4401. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  4402. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  4403. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  4404. 'is_void' => $isVoid,
  4405. 'oper_time_text' => $ct,
  4406. ];
  4407. if (!$deadlineReached && !$isVoid) {
  4408. $this->maskSupplierQuoteLineBeforeDeadline($line);
  4409. } elseif ($sub !== null) {
  4410. $groupTotal += $sub;
  4411. $groupHas = true;
  4412. }
  4413. $lines[] = $line;
  4414. };
  4415. foreach ($orderedSids as $sid) {
  4416. if (!isset($bySid[$sid])) {
  4417. continue;
  4418. }
  4419. $usedSids[$sid] = true;
  4420. $appendLine($sid, $bySid[$sid]);
  4421. }
  4422. foreach ($bySid as $sid => $d) {
  4423. if (isset($usedSids[$sid])) {
  4424. continue;
  4425. }
  4426. $appendLine((int)$sid, $d);
  4427. }
  4428. $firstDetail = null;
  4429. foreach ($bySid as $d) {
  4430. if (is_array($d)) {
  4431. $firstDetail = $d;
  4432. break;
  4433. }
  4434. }
  4435. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  4436. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  4437. if ($username === '' && $ph !== '') {
  4438. $username = $this->resolveCustomerContactName($ph, $cn);
  4439. }
  4440. $lineCount = count($lines);
  4441. $supplierGroups[] = [
  4442. 'company_name' => $cn,
  4443. 'username' => $username,
  4444. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  4445. 'phone' => $ph,
  4446. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  4447. 'is_void' => $groupVoid,
  4448. 'lines' => $lines,
  4449. 'line_count' => $lineCount,
  4450. 'display_rowspan'=> $lineCount + ($lineCount > 0 ? 1 : 0),
  4451. 'total_text' => ($deadlineReached && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  4452. 'has_total' => $lineCount > 0,
  4453. ];
  4454. }
  4455. usort($supplierGroups, function ($a, $b) {
  4456. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  4457. return ($a['is_void'] ?? false) ? 1 : -1;
  4458. }
  4459. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  4460. return ($a['is_selected'] ?? false) ? -1 : 1;
  4461. }
  4462. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  4463. });
  4464. return [
  4465. 'process_rows' => $processRows,
  4466. 'supplier_groups' => $supplierGroups,
  4467. 'order_total_text' => '',
  4468. 'order_total_has' => false,
  4469. 'selected_company' => $selectedCompany,
  4470. ];
  4471. }
  4472. /**
  4473. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  4474. */
  4475. protected function buildProcessLinesPlain(array $mergeRows): string
  4476. {
  4477. $lines = [];
  4478. $i = 1;
  4479. foreach ($mergeRows as $r) {
  4480. if (!is_array($r)) {
  4481. continue;
  4482. }
  4483. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4484. $dw = trim((string)($r['CDW'] ?? ''));
  4485. $gzl = trim((string)($r['NGZL'] ?? ''));
  4486. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  4487. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  4488. if ($dw !== '') {
  4489. $parts[] = '单位:' . $dw;
  4490. }
  4491. if ($gzl !== '') {
  4492. $parts[] = '工作量:' . $gzl;
  4493. }
  4494. if ($qty !== '') {
  4495. $parts[] = '本次数量:' . $qty;
  4496. }
  4497. $lines[] = implode(' ', $parts);
  4498. $i++;
  4499. }
  4500. return implode("\n", $lines);
  4501. }
  4502. /**
  4503. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  4504. *
  4505. * @return array<string, string>
  4506. */
  4507. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0): array
  4508. {
  4509. $po = null;
  4510. try {
  4511. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4512. } catch (\Throwable $e) {
  4513. $po = null;
  4514. }
  4515. $ccydh = is_array($po) ? trim((string)($po['CCYDH'] ?? '')) : '';
  4516. $cyjmc = is_array($po) ? trim((string)($po['CYJMC'] ?? '')) : '';
  4517. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0) {
  4518. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  4519. if (is_array($any)) {
  4520. if ($ccydh === '') {
  4521. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  4522. }
  4523. if ($cyjmc === '') {
  4524. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  4525. }
  4526. }
  4527. }
  4528. $mergeRows = is_array($po) && $po !== [] ? [$po] : [];
  4529. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  4530. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  4531. return [
  4532. 'ccydh' => $ccydh,
  4533. 'cyjmc' => $cyjmc,
  4534. 'cgymc' => is_array($po) ? trim((string)($po['CGYMC'] ?? '')) : '',
  4535. 'process_lines' => $processLines,
  4536. 'process_lines_html' => '',
  4537. ];
  4538. }
  4539. /**
  4540. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  4541. */
  4542. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  4543. {
  4544. $lines = [];
  4545. if ($ccydh !== '') {
  4546. $lines[] = '订单号:' . $ccydh;
  4547. }
  4548. if ($cyjmc !== '') {
  4549. $lines[] = '印件名称:' . $cyjmc;
  4550. }
  4551. if ($processPlain !== '') {
  4552. $lines[] = $processPlain;
  4553. }
  4554. return implode("\n", $lines);
  4555. }
  4556. /**
  4557. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  4558. *
  4559. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  4560. */
  4561. protected function buildPlatformLinksPlain(array $detailLinks): string
  4562. {
  4563. $lines = [];
  4564. $i = 1;
  4565. foreach ($detailLinks as $lk) {
  4566. if (!is_array($lk)) {
  4567. continue;
  4568. }
  4569. $url = trim((string)($lk['url'] ?? ''));
  4570. if ($url === '') {
  4571. continue;
  4572. }
  4573. $label = trim((string)($lk['cgymc'] ?? ''));
  4574. if ($label === '') {
  4575. $label = '工序' . $i;
  4576. }
  4577. $lines[] = $label . ':' . $url;
  4578. $i++;
  4579. }
  4580. return implode("\n", $lines);
  4581. }
  4582. /**
  4583. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  4584. *
  4585. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  4586. */
  4587. protected function buildPlatformLinksHtml(array $detailLinks): string
  4588. {
  4589. $parts = [];
  4590. $i = 1;
  4591. foreach ($detailLinks as $lk) {
  4592. if (!is_array($lk)) {
  4593. continue;
  4594. }
  4595. $url = trim((string)($lk['url'] ?? ''));
  4596. if ($url === '') {
  4597. continue;
  4598. }
  4599. $label = trim((string)($lk['cgymc'] ?? ''));
  4600. if ($label === '') {
  4601. $label = '工序' . $i;
  4602. }
  4603. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  4604. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  4605. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  4606. $i++;
  4607. }
  4608. return implode("<br>\n", $parts);
  4609. }
  4610. /**
  4611. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  4612. *
  4613. * @return array<string, mixed>
  4614. */
  4615. protected function loadMailerConfig(): array
  4616. {
  4617. try {
  4618. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  4619. } catch (\Throwable $e) {
  4620. $cfg = [];
  4621. }
  4622. return is_array($cfg) ? $cfg : [];
  4623. }
  4624. protected function loadNotifyTemplateRow(string $scene): ?array
  4625. {
  4626. try {
  4627. $row = Db::table('purchase_sms_template')
  4628. ->where('scene', $scene)
  4629. ->where(function ($q) {
  4630. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  4631. })
  4632. ->order('id', 'asc')
  4633. ->find();
  4634. } catch (\Throwable $e) {
  4635. return null;
  4636. }
  4637. if (!is_array($row) || $row === []) {
  4638. return null;
  4639. }
  4640. return [
  4641. 'title' => trim((string)($row['title'] ?? '')),
  4642. 'content' => trim((string)($row['content'] ?? '')),
  4643. ];
  4644. }
  4645. /**
  4646. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  4647. */
  4648. protected function buildProcessLinesHtml(array $mergeRows): string
  4649. {
  4650. if (count($mergeRows) <= 1) {
  4651. $r = $mergeRows[0] ?? [];
  4652. if (!is_array($r)) {
  4653. return '';
  4654. }
  4655. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4656. $dw = trim((string)($r['CDW'] ?? ''));
  4657. $gzl = trim((string)($r['NGZL'] ?? ''));
  4658. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  4659. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  4660. if ($dw !== '') {
  4661. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  4662. }
  4663. if ($gzl !== '') {
  4664. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  4665. }
  4666. if ($qty !== '') {
  4667. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  4668. }
  4669. return $html;
  4670. }
  4671. $rows = '';
  4672. $i = 1;
  4673. foreach ($mergeRows as $r) {
  4674. if (!is_array($r)) {
  4675. continue;
  4676. }
  4677. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  4678. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  4679. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  4680. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  4681. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  4682. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  4683. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  4684. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  4685. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  4686. $i++;
  4687. }
  4688. if ($rows === '') {
  4689. return '';
  4690. }
  4691. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  4692. . '<thead><tr style="background:#f5f5f5;">'
  4693. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  4694. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  4695. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  4696. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  4697. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  4698. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  4699. }
  4700. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true): string
  4701. {
  4702. $sysRq = trim($sysRq);
  4703. if ($sysRq === '') {
  4704. if ($required) {
  4705. $this->error('请选择截止时间');
  4706. }
  4707. return '';
  4708. }
  4709. $ts = strtotime($sysRq);
  4710. if ($ts === false || $ts <= 0) {
  4711. $this->error('截止时间格式无效');
  4712. }
  4713. return date('Y-m-d H:i:s', $ts);
  4714. }
  4715. protected function formatProcuremenSysRqForInput($sysRq): string
  4716. {
  4717. $sr = trim((string)$sysRq);
  4718. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  4719. return '';
  4720. }
  4721. $ts = strtotime($sr);
  4722. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  4723. }
  4724. /**
  4725. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  4726. * @return array{ccydh?:string,pos:array,merge_rows:array}
  4727. */
  4728. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  4729. {
  4730. $sysRqPost = trim($sysRqPost);
  4731. if ($sysRqPost === '') {
  4732. return $bundle;
  4733. }
  4734. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqPost, true);
  4735. $pos = $bundle['pos'] ?? [];
  4736. foreach ($pos as $poRow) {
  4737. if (!is_array($poRow)) {
  4738. continue;
  4739. }
  4740. $sid = (int)($poRow['scydgy_id'] ?? 0);
  4741. if (!$this->isValidScydgyRowId($sid)) {
  4742. continue;
  4743. }
  4744. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['sys_rq' => $sysRqDb]);
  4745. }
  4746. foreach ($pos as $i => $poRow) {
  4747. if (is_array($pos[$i])) {
  4748. $pos[$i]['sys_rq'] = $sysRqDb;
  4749. }
  4750. }
  4751. $bundle['pos'] = $pos;
  4752. return $bundle;
  4753. }
  4754. /**
  4755. * 写入/更新 purchase_order(单道工序行)
  4756. */
  4757. protected function upsertPurchaseOrderFromRow(
  4758. array $row,
  4759. string $sysRqDb,
  4760. $wflowStatus = null,
  4761. ?string $pickTime = null,
  4762. ?array $exists = null
  4763. ): void {
  4764. $ids = $this->extractScydgyRowId($row);
  4765. if (!$this->isValidScydgyRowId($ids)) {
  4766. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  4767. }
  4768. if ($exists === null) {
  4769. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4770. }
  4771. $data = [
  4772. 'scydgy_id' => $ids,
  4773. 'CCYDH' => $row['CCYDH'] ?? null,
  4774. 'CYJMC' => $row['CYJMC'] ?? null,
  4775. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4776. 'CDXMC' => $row['CDXMC'] ?? null,
  4777. 'CGYBH' => $row['CGYBH'] ?? null,
  4778. 'CGYMC' => $row['CGYMC'] ?? null,
  4779. 'CDW' => $row['CDW'] ?? null,
  4780. 'NGZL' => $row['NGZL'] ?? null,
  4781. 'CDF' => $row['CDF'] ?? null,
  4782. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4783. 'MBZ' => $row['MBZ'] ?? null,
  4784. 'bwjg' => $row['bwjg'] ?? null,
  4785. 'iStatus' => $row['iStatus'] ?? null,
  4786. 'dStamp' => $row['dStamp'] ?? null,
  4787. 'dputrecord' => $row['dputrecord'] ?? null,
  4788. 'cywyxm' => $row['cywyxm'] ?? null,
  4789. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4790. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4791. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  4792. 'sys_rq' => $sysRqDb,
  4793. ];
  4794. if ($wflowStatus !== null && $wflowStatus !== '') {
  4795. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  4796. }
  4797. if ($pickTime !== null && $pickTime !== '') {
  4798. $data['pick_time'] = $pickTime;
  4799. $data['pick_company_name'] = '';
  4800. }
  4801. if ($exists) {
  4802. $upd = $data;
  4803. unset($upd['scydgy_id']);
  4804. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4805. } else {
  4806. $data['createtime'] = date('Y-m-d H:i:s');
  4807. Db::table('purchase_order')->insert($data);
  4808. }
  4809. }
  4810. /**
  4811. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  4812. *
  4813. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  4814. */
  4815. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  4816. {
  4817. $toDb = function ($value) {
  4818. if ($value === null) {
  4819. return null;
  4820. }
  4821. if (is_scalar($value)) {
  4822. return $value;
  4823. }
  4824. return json_encode($value, JSON_UNESCAPED_UNICODE);
  4825. };
  4826. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  4827. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  4828. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  4829. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  4830. if ($username === '') {
  4831. $username = $this->resolveCustomerContactName($phone, $companyName);
  4832. }
  4833. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  4834. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  4835. }
  4836. if ($phone === '') {
  4837. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  4838. }
  4839. $detailLinks = [];
  4840. foreach ($mergeRows as $row) {
  4841. if (!is_array($row)) {
  4842. continue;
  4843. }
  4844. $sid = $this->extractScydgyRowId($row);
  4845. $detailId = 0;
  4846. if ($skipExisting) {
  4847. try {
  4848. $existsQuery = Db::table('purchase_order_detail')
  4849. ->where('scydgy_id', $sid)
  4850. ->where('company_name', $companyName);
  4851. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  4852. $exists = $existsQuery->find();
  4853. } catch (\Throwable $e) {
  4854. $exists = null;
  4855. }
  4856. if (is_array($exists)) {
  4857. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  4858. }
  4859. }
  4860. if ($detailId <= 0) {
  4861. $one = [
  4862. 'scydgy_id' => $toDb($sid),
  4863. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  4864. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  4865. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  4866. 'username' => $username !== '' ? $username : null,
  4867. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  4868. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  4869. 'createtime' => date('Y-m-d H:i:s'),
  4870. 'status' => ProcuremenStatus::POD_UNPICKED,
  4871. 'status_name' => '未提交',
  4872. ];
  4873. Db::table('purchase_order_detail')->insert($one);
  4874. $detailId = (int)Db::getLastInsID();
  4875. }
  4876. $mprocUrl = '';
  4877. if ($buildMobileLinks && $detailId > 0) {
  4878. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  4879. }
  4880. $detailLinks[] = [
  4881. 'detail_id' => $detailId,
  4882. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  4883. 'url' => $mprocUrl,
  4884. ];
  4885. }
  4886. return $detailLinks;
  4887. }
  4888. /**
  4889. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  4890. * @return array<string, mixed>
  4891. */
  4892. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  4893. {
  4894. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  4895. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  4896. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  4897. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  4898. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  4899. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  4900. $isMerge = !empty($ctx['is_merge']);
  4901. $contactName = trim((string)($c['username'] ?? ''));
  4902. if ($contactName === '') {
  4903. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  4904. }
  4905. $notifyVars = [
  4906. 'company_name' => $companyName,
  4907. 'contact_name' => $contactName,
  4908. 'phone' => $phone,
  4909. 'email' => $toEmail,
  4910. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  4911. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  4912. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  4913. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  4914. 'deadline' => (string)($ctx['deadline'] ?? ''),
  4915. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  4916. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  4917. 'platform_url' => $platformUrl,
  4918. 'platform_links' => $platformLinksPlain,
  4919. 'platform_links_html' => $platformLinksHtml,
  4920. ];
  4921. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  4922. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  4923. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  4924. return [
  4925. 'company_name' => $companyName,
  4926. 'phone' => $phone,
  4927. 'email' => $toEmail,
  4928. 'sms_content' => $smsContent,
  4929. 'mail_plain' => $mailPlain,
  4930. 'mail_body' => $mailBody,
  4931. 'notify_vars' => $notifyVars,
  4932. 'detail_links' => $detailLinks,
  4933. ];
  4934. }
  4935. /**
  4936. * @param array<string, mixed> $chosen
  4937. * @param array<int, array<string, mixed>> $mergeRows
  4938. * @param array{ccydh:string, pos:array} $bundle
  4939. */
  4940. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail): void
  4941. {
  4942. if (!$sendSms && !$sendEmail) {
  4943. return;
  4944. }
  4945. $companyName = trim((string)($chosen['name'] ?? ''));
  4946. $phone = trim((string)($chosen['phone'] ?? ''));
  4947. $toEmail = trim((string)($chosen['email'] ?? ''));
  4948. if ($companyName === '') {
  4949. throw new \Exception('供应商名称无效');
  4950. }
  4951. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  4952. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  4953. }
  4954. if ($sendSms && $phone === '') {
  4955. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  4956. }
  4957. $sids = [];
  4958. foreach ($mergeRows as $mr) {
  4959. if (!is_array($mr)) {
  4960. continue;
  4961. }
  4962. $sid = $this->extractScydgyRowId($mr);
  4963. if ($this->isValidScydgyRowId($sid)) {
  4964. $sids[$sid] = true;
  4965. }
  4966. }
  4967. if ($sids === []) {
  4968. throw new \Exception('未找到工序行,无法发送通知');
  4969. }
  4970. $sysRqNotify = '';
  4971. $pos = $bundle['pos'] ?? [];
  4972. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  4973. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  4974. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  4975. $ts = strtotime($sr);
  4976. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  4977. }
  4978. }
  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. if (!is_array($details) || $details === []) {
  4989. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  4990. try {
  4991. $detailsQuery = Db::table('purchase_order_detail')
  4992. ->where('scydgy_id', 'in', array_keys($sids))
  4993. ->where('company_name', $companyName);
  4994. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  4995. $details = $detailsQuery->order('id', 'asc')->select();
  4996. } catch (\Throwable $e) {
  4997. $details = [];
  4998. }
  4999. }
  5000. if (!is_array($details) || $details === []) {
  5001. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  5002. }
  5003. $detailLinks = [];
  5004. foreach ($details as $d) {
  5005. if (!is_array($d)) {
  5006. continue;
  5007. }
  5008. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  5009. if ($detailId <= 0) {
  5010. continue;
  5011. }
  5012. $sid = (int)($d['scydgy_id'] ?? 0);
  5013. $gymc = '';
  5014. foreach ($mergeRows as $mr) {
  5015. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  5016. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5017. break;
  5018. }
  5019. }
  5020. $detailLinks[] = [
  5021. 'detail_id' => $detailId,
  5022. 'cgymc' => $gymc,
  5023. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  5024. ];
  5025. }
  5026. if ($detailLinks === []) {
  5027. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  5028. }
  5029. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  5030. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  5031. if ($sendEmail) {
  5032. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  5033. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  5034. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  5035. }
  5036. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  5037. $mailConfig = $this->loadMailerConfig();
  5038. if (!$this->isProcuremenNotifyDryRun()) {
  5039. if (empty($mailConfig['host'])) {
  5040. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  5041. }
  5042. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  5043. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  5044. }
  5045. }
  5046. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  5047. }
  5048. if ($sendSms) {
  5049. $this->issueSendSupplierSms($notifyBundle);
  5050. }
  5051. }
  5052. /**
  5053. * @param array<int, array<string, mixed>> $quoteGroups
  5054. * @return array<int, array<string, mixed>>
  5055. */
  5056. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  5057. {
  5058. $names = [];
  5059. if (is_string($companiesJson) && $companiesJson !== '') {
  5060. $decoded = json_decode($companiesJson, true);
  5061. if (is_array($decoded)) {
  5062. foreach ($decoded as $nm) {
  5063. $nm = trim((string)$nm);
  5064. if ($nm !== '') {
  5065. $names[] = $nm;
  5066. }
  5067. }
  5068. }
  5069. }
  5070. $names = array_values(array_unique($names));
  5071. if ($names === [] && $selectedCompany !== '') {
  5072. $names = [$selectedCompany];
  5073. }
  5074. if ($names === []) {
  5075. return $quoteGroups;
  5076. }
  5077. $targets = [];
  5078. foreach ($quoteGroups as $g) {
  5079. if (!is_array($g)) {
  5080. continue;
  5081. }
  5082. $cn = trim((string)($g['name'] ?? ''));
  5083. if ($cn !== '' && in_array($cn, $names, true)) {
  5084. $targets[] = $g;
  5085. }
  5086. }
  5087. return $targets;
  5088. }
  5089. /**
  5090. * @return array{pos:array, merge_rows:array, bundle:array}
  5091. */
  5092. protected function loadAuditResendBundle(string $scydgyId): array
  5093. {
  5094. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  5095. $pos = $bundle['pos'];
  5096. $mergeRows = $bundle['merge_rows'];
  5097. if ($pos === [] || $mergeRows === []) {
  5098. $this->error('该订单不在待确认供应商状态');
  5099. }
  5100. $sysRqDb = '';
  5101. if (isset($pos[0]) && is_array($pos[0])) {
  5102. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  5103. }
  5104. foreach ($pos as $i => $poRow) {
  5105. if (is_array($pos[$i]) && $sysRqDb !== '') {
  5106. $pos[$i]['sys_rq'] = $sysRqDb;
  5107. }
  5108. }
  5109. $bundle['pos'] = $pos;
  5110. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  5111. }
  5112. /**
  5113. * @param array<int, array<string, mixed>> $targets
  5114. */
  5115. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  5116. {
  5117. if ($targets === []) {
  5118. $this->error('未找到可通知的供应商');
  5119. }
  5120. $notifyErrors = [];
  5121. try {
  5122. $this->notifyDryRunPreview = [];
  5123. foreach ($targets as $g) {
  5124. if (!is_array($g)) {
  5125. continue;
  5126. }
  5127. $cname = trim((string)($g['name'] ?? ''));
  5128. if ($cname === '') {
  5129. continue;
  5130. }
  5131. $chosen = [
  5132. 'name' => $cname,
  5133. 'company_name' => $cname,
  5134. 'email' => trim((string)($g['email'] ?? '')),
  5135. 'phone' => trim((string)($g['phone'] ?? '')),
  5136. 'username' => trim((string)($g['username'] ?? '')),
  5137. ];
  5138. try {
  5139. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail);
  5140. } catch (\Throwable $e) {
  5141. $notifyErrors[] = $cname . ':' . $e->getMessage();
  5142. }
  5143. }
  5144. } catch (\Throwable $e) {
  5145. $this->error('通知发送失败:' . $e->getMessage());
  5146. }
  5147. if ($notifyErrors !== []) {
  5148. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  5149. }
  5150. if ($this->isProcuremenNotifyDryRun()) {
  5151. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  5152. 'notify_dry_run' => true,
  5153. 'notify_preview' => $this->notifyDryRunPreview,
  5154. ]);
  5155. }
  5156. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  5157. }
  5158. /**
  5159. * 协助下发 — 发送短信(一家供应商)
  5160. *
  5161. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  5162. */
  5163. protected function issueSendSupplierSms(array $bundle): void
  5164. {
  5165. $companyName = (string)($bundle['company_name'] ?? '');
  5166. $phone = (string)($bundle['phone'] ?? '');
  5167. $smsContent = (string)($bundle['sms_content'] ?? '');
  5168. $this->logIssueNotifyDebug('短信', [
  5169. 'company' => $companyName,
  5170. 'phone' => $phone,
  5171. 'sms_content' => $smsContent,
  5172. ]);
  5173. if ($this->isProcuremenNotifyDryRun()) {
  5174. $this->recordNotifyDryRunPreview([
  5175. 'scene' => 'issue_sms',
  5176. 'company_name' => $companyName,
  5177. 'phone' => $phone,
  5178. 'sms_content' => $smsContent,
  5179. ]);
  5180. return;
  5181. }
  5182. $this->smsbao($phone, $smsContent);
  5183. }
  5184. /**
  5185. * 协助下发 — 发送邮件(一家供应商)
  5186. *
  5187. * @param array<string, mixed> $bundle
  5188. * @param array<string, mixed> $mailConfig
  5189. */
  5190. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  5191. {
  5192. $companyName = (string)($bundle['company_name'] ?? '');
  5193. $toEmail = (string)($bundle['email'] ?? '');
  5194. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  5195. $mailBody = (string)($bundle['mail_body'] ?? '');
  5196. $this->logIssueNotifyDebug('邮件', [
  5197. 'company' => $companyName,
  5198. 'email' => $toEmail,
  5199. 'mail_subject' => $mailSubject,
  5200. 'mail_body' => $mailPlain,
  5201. ]);
  5202. if ($this->isProcuremenNotifyDryRun()) {
  5203. $this->recordNotifyDryRunPreview([
  5204. 'scene' => 'issue_email',
  5205. 'company_name' => $companyName,
  5206. 'email' => $toEmail,
  5207. 'mail_subject' => $mailSubject,
  5208. 'mail_body' => $mailPlain,
  5209. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  5210. 'notify_vars' => $bundle['notify_vars'] ?? [],
  5211. 'detail_links' => $bundle['detail_links'] ?? [],
  5212. ]);
  5213. return;
  5214. }
  5215. $mail = new PHPMailer(true);
  5216. $mail->isSMTP();
  5217. $mail->Host = $mailConfig['host'];
  5218. $mail->SMTPAuth = true;
  5219. $mail->Username = $mailConfig['addr'];
  5220. $mail->Password = $mailConfig['pass'];
  5221. $mail->SMTPSecure = $mailConfig['security'];
  5222. $mail->Port = $mailConfig['port'];
  5223. $mail->CharSet = $mailConfig['charset'];
  5224. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  5225. $mail->addAddress($toEmail, $companyName);
  5226. $mail->isHTML(true);
  5227. $mail->Subject = $mailSubject;
  5228. $mail->Body = $mailBody;
  5229. $mail->send();
  5230. }
  5231. /**
  5232. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  5233. *
  5234. * @param array<int, array<string, mixed>> $mergeRows
  5235. * @return array<string, mixed>
  5236. */
  5237. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  5238. {
  5239. $head = $mergeRows[0] ?? [];
  5240. $isMerge = count($mergeRows) > 1;
  5241. return [
  5242. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  5243. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  5244. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  5245. 'is_merge' => $isMerge,
  5246. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  5247. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  5248. 'deadline' => $sysRqNotify,
  5249. ];
  5250. }
  5251. /**
  5252. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  5253. *
  5254. * @param array<string, mixed> $data
  5255. */
  5256. protected function logIssueNotifyDebug(string $type, array $data): void
  5257. {
  5258. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  5259. return;
  5260. }
  5261. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  5262. }
  5263. /**
  5264. * 协助下发弹窗(选多家供应商并通知)
  5265. */
  5266. public function pickReview()
  5267. {
  5268. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  5269. $this->error(__('You have no permission'));
  5270. }
  5271. if ($this->request->isPost()) {
  5272. $this->error('请使用弹窗内「确认下发」提交');
  5273. }
  5274. $this->view->assign('pickMode', 1);
  5275. return $this->view->fetch('procuremen/review');
  5276. }
  5277. /**
  5278. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  5279. */
  5280. public function add()
  5281. {
  5282. if ($this->request->isPost()) {
  5283. $params = $this->request->post('row/a');
  5284. if (!is_array($params)) {
  5285. $this->error(__('Parameter %s can not be empty', ''));
  5286. }
  5287. [, $adminName] = $this->GetUseName();
  5288. $params['cywyxm'] = $adminName;
  5289. try {
  5290. $sid = $this->saveManualPickOrder($params);
  5291. } catch (\InvalidArgumentException $e) {
  5292. $this->error($e->getMessage());
  5293. } catch (\Throwable $e) {
  5294. $this->error($e->getMessage());
  5295. }
  5296. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  5297. }
  5298. [, $adminName] = $this->GetUseName();
  5299. $this->view->assign('adminNickname', $adminName);
  5300. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  5301. return $this->view->fetch();
  5302. }
  5303. /**
  5304. * 业务员新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  5305. */
  5306. public function rfqlist()
  5307. {
  5308. $this->relationSearch = false;
  5309. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  5310. $this->request->filter(['strip_tags', 'trim']);
  5311. if ($this->request->isAjax()) {
  5312. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  5313. $limit = max(10, min(500, (int)$limit));
  5314. $applyFilters = function ($query) use ($where) {
  5315. $query->where('scydgy_id', '<', 0);
  5316. $query->whereRaw(
  5317. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  5318. );
  5319. if (!$this->auth->isSuperAdmin()) {
  5320. [, $adminName] = $this->GetUseName();
  5321. $query->where('cywyxm', $adminName);
  5322. }
  5323. if (!empty($where)) {
  5324. $query->where($where);
  5325. }
  5326. };
  5327. $countQuery = Db::table('purchase_order');
  5328. $applyFilters($countQuery);
  5329. $total = (int)$countQuery->count();
  5330. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  5331. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  5332. $listQuery = Db::table('purchase_order');
  5333. $applyFilters($listQuery);
  5334. $rows = $listQuery
  5335. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  5336. ->order($sortField, $orderDir)
  5337. ->limit($offset, $limit)
  5338. ->select();
  5339. if (!is_array($rows)) {
  5340. $rows = [];
  5341. }
  5342. $out = [];
  5343. foreach ($rows as $r) {
  5344. if (!is_array($r)) {
  5345. continue;
  5346. }
  5347. $sid = (int)($r['scydgy_id'] ?? 0);
  5348. if ($sid >= 0) {
  5349. continue;
  5350. }
  5351. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  5352. if ($createdText === '') {
  5353. $createdText = trim((string)($r['dStamp'] ?? ''));
  5354. }
  5355. $out[] = [
  5356. 'id' => (int)($r['id'] ?? 0),
  5357. 'scydgy_id' => $sid,
  5358. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  5359. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  5360. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  5361. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  5362. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  5363. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  5364. 'createtime' => $r['createtime'] ?? null,
  5365. 'createtime_text' => $createdText,
  5366. ];
  5367. }
  5368. return json(['total' => $total, 'rows' => $out]);
  5369. }
  5370. [, $adminName] = $this->GetUseName();
  5371. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  5372. $this->view->assign('adminNickname', $adminName);
  5373. return $this->view->fetch('procuremen/rfqlist');
  5374. }
  5375. /**
  5376. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  5377. */
  5378. public function rfqlistDetails()
  5379. {
  5380. return $this->details();
  5381. }
  5382. /**
  5383. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  5384. */
  5385. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  5386. {
  5387. if ($scydgyId >= 0) {
  5388. return;
  5389. }
  5390. try {
  5391. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5392. } catch (\Throwable $e) {
  5393. $po = null;
  5394. }
  5395. if (!is_array($po)) {
  5396. $this->error('订单不存在');
  5397. }
  5398. $modRq = trim((string)($po['mod_rq'] ?? ''));
  5399. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  5400. $this->error('订单不存在');
  5401. }
  5402. if ($this->auth->isSuperAdmin()) {
  5403. return;
  5404. }
  5405. [, $adminName] = $this->GetUseName();
  5406. $cywy = trim((string)($po['cywyxm'] ?? ''));
  5407. if ($cywy !== '' && $cywy === $adminName) {
  5408. return;
  5409. }
  5410. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  5411. try {
  5412. if ($this->auth->check($rule)) {
  5413. return;
  5414. }
  5415. } catch (\Throwable $e) {
  5416. }
  5417. }
  5418. $this->error('无权查看该订单');
  5419. }
  5420. /**
  5421. * 手工新增协助工序进度文案
  5422. */
  5423. protected function formatProcuremenRfqProgressText(array $row): string
  5424. {
  5425. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  5426. return ProcuremenStatus::PO_COMPLETED;
  5427. }
  5428. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  5429. return '待采购确认';
  5430. }
  5431. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  5432. return '待确认供应商';
  5433. }
  5434. $sid = (int)($row['scydgy_id'] ?? 0);
  5435. if ($sid < 0) {
  5436. try {
  5437. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  5438. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  5439. $detCnt = (int)$detCntQuery->count();
  5440. if ($detCnt > 0) {
  5441. return '已下发待确认';
  5442. }
  5443. } catch (\Throwable $e) {
  5444. }
  5445. }
  5446. return '待协助下发';
  5447. }
  5448. /**
  5449. * 协助初选列表 — 批量软删除
  5450. */
  5451. public function pickDelete()
  5452. {
  5453. if (!$this->request->isPost() || !$this->request->isAjax()) {
  5454. $this->error(__('Invalid parameters'));
  5455. }
  5456. if (!$this->procuremenCanPickDelete()) {
  5457. $this->error(__('You have no permission'));
  5458. }
  5459. $rowsRaw = $this->request->post('rows_json', '[]');
  5460. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  5461. if (!is_array($rows) || $rows === []) {
  5462. $this->error('请至少勾选一条工序');
  5463. }
  5464. $done = 0;
  5465. Db::startTrans();
  5466. try {
  5467. foreach ($rows as $row) {
  5468. if (!is_array($row)) {
  5469. continue;
  5470. }
  5471. $this->softDeleteProcuremenPickRow($row);
  5472. $done++;
  5473. }
  5474. if ($done < 1) {
  5475. throw new \Exception('没有可删除的工序');
  5476. }
  5477. Db::commit();
  5478. } catch (\InvalidArgumentException $e) {
  5479. Db::rollback();
  5480. $this->error($e->getMessage());
  5481. } catch (\Throwable $e) {
  5482. Db::rollback();
  5483. $this->error($e->getMessage());
  5484. }
  5485. $this->pickHiddenScydgySetCache = null;
  5486. $this->success('已删除 ' . $done . ' 条工序');
  5487. }
  5488. /**
  5489. * 下发 — 手工新增工序(弹窗)
  5490. */
  5491. public function pickAdd()
  5492. {
  5493. if ($this->request->isPost()) {
  5494. $params = $this->request->post('row/a');
  5495. if (!is_array($params)) {
  5496. $this->error(__('Parameter %s can not be empty', ''));
  5497. }
  5498. try {
  5499. $sid = $this->saveManualPickOrder($params);
  5500. } catch (\InvalidArgumentException $e) {
  5501. $this->error($e->getMessage());
  5502. } catch (\Throwable $e) {
  5503. $this->error($e->getMessage());
  5504. }
  5505. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  5506. }
  5507. return $this->view->fetch('procuremen/pick_add');
  5508. }
  5509. /**
  5510. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  5511. */
  5512. public function pickSubmit()
  5513. {
  5514. if (!$this->request->isPost()) {
  5515. $this->error(__('Invalid parameters'));
  5516. }
  5517. // ---------- 接口订单数据 ----------
  5518. $rowJson = $this->request->post('row_json', '');
  5519. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  5520. $companiesJson = $this->request->post('companies_json', '[]');
  5521. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  5522. $companies = json_decode($companiesJson, true);
  5523. if (!is_array($companies)) {
  5524. $this->error('供应商数据无效');
  5525. }
  5526. $issueCompanies = $this->normalizePickCompanies($companies);
  5527. if ($issueCompanies === []) {
  5528. $this->error('请至少选择一家合作供应商');
  5529. }
  5530. $issueNameLabels = [];
  5531. foreach ($issueCompanies as $pc) {
  5532. $issueNameLabels[] = $pc['name'];
  5533. }
  5534. $issueNamesSummary = implode('、', $issueNameLabels);
  5535. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  5536. if ($sysRq === '') {
  5537. $this->error('请选择截止时间');
  5538. }
  5539. $sysRqTs = strtotime($sysRq);
  5540. if ($sysRqTs === false || $sysRqTs <= 0) {
  5541. $this->error('截止时间格式无效');
  5542. }
  5543. $sysRqDb = date('Y-m-d H:i:s', $sysRqTs);
  5544. $isMerge = count($mergeRows) > 1;
  5545. $ccydhLog = '';
  5546. foreach ($mergeRows as $row) {
  5547. if (!is_array($row)) {
  5548. continue;
  5549. }
  5550. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  5551. if ($ccydhLog !== '') {
  5552. break;
  5553. }
  5554. }
  5555. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  5556. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  5557. $logMsg = '下发' . $orderPart . $procPart
  5558. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  5559. $issueTime = date('Y-m-d H:i:s');
  5560. $logSidList = [];
  5561. foreach ($mergeRows as $row) {
  5562. if (!is_array($row)) {
  5563. continue;
  5564. }
  5565. $sid = $this->extractScydgyRowId($row);
  5566. if ($this->isValidScydgyRowId($sid)) {
  5567. $logSidList[$sid] = true;
  5568. }
  5569. }
  5570. $existingBySid = [];
  5571. if ($logSidList !== []) {
  5572. try {
  5573. $existingRows = Db::table('purchase_order')
  5574. ->where('scydgy_id', 'in', array_keys($logSidList))
  5575. ->select();
  5576. if (is_array($existingRows)) {
  5577. foreach ($existingRows as $poRow) {
  5578. if (!is_array($poRow)) {
  5579. continue;
  5580. }
  5581. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5582. if ($this->isValidScydgyRowId($sid)) {
  5583. $existingBySid[$sid] = $poRow;
  5584. }
  5585. }
  5586. }
  5587. } catch (\Throwable $e) {
  5588. $existingBySid = [];
  5589. }
  5590. }
  5591. Db::startTrans();
  5592. try {
  5593. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  5594. foreach ($mergeRows as $row) {
  5595. if (!is_array($row)) {
  5596. continue;
  5597. }
  5598. $sid = $this->extractScydgyRowId($row);
  5599. $this->upsertPurchaseOrderFromRow(
  5600. $row,
  5601. $sysRqDb,
  5602. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  5603. $issueTime,
  5604. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null
  5605. );
  5606. }
  5607. foreach ($issueCompanies as $c) {
  5608. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  5609. }
  5610. Db::commit();
  5611. } catch (\Throwable $e) {
  5612. Db::rollback();
  5613. $this->error($e->getMessage());
  5614. }
  5615. $poIdBySid = [];
  5616. if ($logSidList !== []) {
  5617. try {
  5618. $poIdBySid = Db::table('purchase_order')
  5619. ->where('scydgy_id', 'in', array_keys($logSidList))
  5620. ->column('id', 'scydgy_id');
  5621. } catch (\Throwable $e) {
  5622. $poIdBySid = [];
  5623. }
  5624. }
  5625. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  5626. if ($logSidList !== []) {
  5627. list($adminId, $adminName) = $this->GetUseName();
  5628. $cut = function ($s, $max) {
  5629. if (function_exists('mb_substr')) {
  5630. return mb_substr($s, 0, $max, 'UTF-8');
  5631. }
  5632. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  5633. };
  5634. $logRows = [];
  5635. $seenLogSid = [];
  5636. foreach ($mergeRows as $row) {
  5637. if (!is_array($row)) {
  5638. continue;
  5639. }
  5640. $ids = $this->extractScydgyRowId($row);
  5641. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  5642. continue;
  5643. }
  5644. $seenLogSid[$ids] = true;
  5645. $poIdLog = null;
  5646. if (isset($poIdBySid[$ids])) {
  5647. $tid = (int)$poIdBySid[$ids];
  5648. $poIdLog = $tid > 0 ? $tid : null;
  5649. }
  5650. $logRows[] = [
  5651. 'scydgy_id' => $ids,
  5652. 'purchase_order_id' => $poIdLog,
  5653. 'admin_id' => $adminId,
  5654. 'admin_name' => $cut($adminName, 64),
  5655. 'action' => $cut('issue_submit', 64),
  5656. 'content' => $cut($logMsg, 1000),
  5657. 'createtime' => ProcuremenTime::nowDateTime(),
  5658. ];
  5659. }
  5660. if ($logRows !== []) {
  5661. try {
  5662. Db::table('purchase_order_oper_log')->insertAll($logRows);
  5663. } catch (\Throwable $e) {
  5664. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  5665. }
  5666. }
  5667. }
  5668. $notifyErrors = [];
  5669. $posNotify = [];
  5670. if ($logSidList !== []) {
  5671. try {
  5672. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  5673. } catch (\Throwable $e) {
  5674. $posNotify = [];
  5675. }
  5676. }
  5677. if (!is_array($posNotify)) {
  5678. $posNotify = [];
  5679. }
  5680. foreach ($posNotify as $i => $prow) {
  5681. if (is_array($posNotify[$i])) {
  5682. $posNotify[$i]['sys_rq'] = $sysRqDb;
  5683. }
  5684. }
  5685. $ccydhPick = '';
  5686. foreach ($mergeRows as $row) {
  5687. if (!is_array($row)) {
  5688. continue;
  5689. }
  5690. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  5691. if ($ccydhPick !== '') {
  5692. break;
  5693. }
  5694. }
  5695. $notifyBundleBase = [
  5696. 'ccydh' => $ccydhPick,
  5697. 'pos' => $posNotify,
  5698. 'merge_rows' => $mergeRows,
  5699. ];
  5700. try {
  5701. $this->notifyDryRunPreview = [];
  5702. foreach ($issueCompanies as $c) {
  5703. if (!is_array($c)) {
  5704. continue;
  5705. }
  5706. $cname = trim((string)($c['name'] ?? ''));
  5707. if ($cname === '') {
  5708. continue;
  5709. }
  5710. try {
  5711. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  5712. } catch (\Throwable $e) {
  5713. $notifyErrors[] = $cname . ':' . $e->getMessage();
  5714. }
  5715. }
  5716. } catch (\Throwable $e) {
  5717. $this->error('通知发送失败:' . $e->getMessage());
  5718. }
  5719. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  5720. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  5721. }
  5722. if ($this->isProcuremenNotifyDryRun()) {
  5723. $this->success('【演练模式】已保存并生成通知预览', '', [
  5724. 'notify_dry_run' => true,
  5725. 'notify_preview' => $this->notifyDryRunPreview,
  5726. ]);
  5727. }
  5728. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  5729. }
  5730. /**
  5731. * 确认供应商弹窗
  5732. */
  5733. public function auditIssue()
  5734. {
  5735. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5736. if (is_array($ids)) {
  5737. $ids = isset($ids[0]) ? $ids[0] : '';
  5738. }
  5739. $ids = trim((string)$ids);
  5740. if ($ids === '') {
  5741. $this->error(__('Invalid parameters'));
  5742. }
  5743. if ($this->request->isPost()) {
  5744. $this->error('请使用弹窗内「确认」提交');
  5745. }
  5746. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  5747. $pos = $bundle['pos'];
  5748. if ($pos === []) {
  5749. $this->error('该订单不在待确认供应商状态');
  5750. }
  5751. $po = $pos[0];
  5752. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5753. if ($quoteGroups === []) {
  5754. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  5755. }
  5756. $pickedName = '';
  5757. foreach ($pos as $poRow) {
  5758. if (!is_array($poRow)) {
  5759. continue;
  5760. }
  5761. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  5762. if ($pn !== '') {
  5763. $pickedName = $pn;
  5764. break;
  5765. }
  5766. }
  5767. $this->view->assign('po', $po);
  5768. $this->view->assign('scydgyId', $ids);
  5769. $this->view->assign('orderCcydh', $bundle['ccydh']);
  5770. $mergeRows = $bundle['merge_rows'];
  5771. $this->view->assign('processRows', $mergeRows);
  5772. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  5773. $this->view->assign('processCount', count($mergeRows));
  5774. $this->view->assign('quoteGroups', $quoteGroups);
  5775. $this->view->assign('quoteGroupsJson', json_encode($quoteGroups, JSON_UNESCAPED_UNICODE));
  5776. $this->view->assign('pickedCompanyName', $pickedName);
  5777. $this->view->assign('sysRq', $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null));
  5778. $this->view->assign('quoteDeadlineReached', $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0);
  5779. return $this->view->fetch('procuremen/audit_issue');
  5780. }
  5781. /**
  5782. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  5783. */
  5784. public function auditSubmit()
  5785. {
  5786. if (!$this->request->isPost()) {
  5787. $this->error(__('Invalid parameters'));
  5788. }
  5789. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5790. if ($scydgyId === '') {
  5791. $this->error('参数无效');
  5792. }
  5793. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  5794. $pos = $bundle['pos'];
  5795. $mergeRows = $bundle['merge_rows'];
  5796. if ($pos === [] || $mergeRows === []) {
  5797. $this->error('该订单不在待确认供应商状态');
  5798. }
  5799. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5800. if ($quoteGroups === []) {
  5801. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  5802. }
  5803. $companyName = trim((string)$this->request->post('selected_company', ''));
  5804. if ($companyName === '') {
  5805. $this->error('请选择一家供应商');
  5806. }
  5807. $matched = null;
  5808. foreach ($quoteGroups as $g) {
  5809. if (!is_array($g)) {
  5810. continue;
  5811. }
  5812. if (trim((string)($g['name'] ?? '')) === $companyName) {
  5813. $matched = $g;
  5814. break;
  5815. }
  5816. }
  5817. if ($matched === null) {
  5818. $this->error('所选供应商不在本单报价列表中');
  5819. }
  5820. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true);
  5821. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  5822. $this->error('报价截止时间未到,暂不能确认供应商');
  5823. }
  5824. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  5825. $procCnt = count($mergeRows);
  5826. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  5827. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  5828. $logMsg = '确认供应商' . $orderPart . $procPart . ':已选定「' . $companyName . '」';
  5829. Db::startTrans();
  5830. try {
  5831. foreach ($pos as $poRow) {
  5832. if (!is_array($poRow)) {
  5833. continue;
  5834. }
  5835. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5836. if (!$this->isValidScydgyRowId($sid)) {
  5837. continue;
  5838. }
  5839. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  5840. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  5841. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5842. 'pick_company_name' => $companyName,
  5843. 'sys_rq' => $sysRqDb,
  5844. ]);
  5845. }
  5846. Db::commit();
  5847. } catch (\Throwable $e) {
  5848. Db::rollback();
  5849. $this->error($e->getMessage());
  5850. }
  5851. foreach ($pos as $poRow) {
  5852. if (!is_array($poRow)) {
  5853. continue;
  5854. }
  5855. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5856. if (!$this->isValidScydgyRowId($sid)) {
  5857. continue;
  5858. }
  5859. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  5860. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  5861. }
  5862. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  5863. }
  5864. /**
  5865. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  5866. */
  5867. public function auditResendSms()
  5868. {
  5869. if (!$this->request->isPost()) {
  5870. $this->error(__('Invalid parameters'));
  5871. }
  5872. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5873. if ($scydgyId === '') {
  5874. $this->error('参数无效');
  5875. }
  5876. $loaded = $this->loadAuditResendBundle($scydgyId);
  5877. $mergeRows = $loaded['merge_rows'];
  5878. $bundle = $loaded['bundle'];
  5879. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  5880. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5881. if ($quoteGroups === []) {
  5882. $this->error('暂无可通知的供应商');
  5883. }
  5884. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  5885. $companiesJson = (string)$this->request->post('companies_json', '');
  5886. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  5887. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  5888. }
  5889. /**
  5890. * 确认供应商 — 二次发送邮件(可选单家/批量)
  5891. */
  5892. public function auditResendEmail()
  5893. {
  5894. if (!$this->request->isPost()) {
  5895. $this->error(__('Invalid parameters'));
  5896. }
  5897. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  5898. if ($scydgyId === '') {
  5899. $this->error('参数无效');
  5900. }
  5901. $loaded = $this->loadAuditResendBundle($scydgyId);
  5902. $mergeRows = $loaded['merge_rows'];
  5903. $bundle = $loaded['bundle'];
  5904. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  5905. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  5906. if ($quoteGroups === []) {
  5907. $this->error('暂无可通知的供应商');
  5908. }
  5909. $companiesJson = (string)$this->request->post('companies_json', '');
  5910. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  5911. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  5912. if ($companiesJson === '' && $selectedCompany === '') {
  5913. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  5914. }
  5915. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  5916. }
  5917. /**
  5918. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  5919. *
  5920. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  5921. * @return array<int, true> 已处理的 scydgy_id 集合
  5922. */
  5923. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  5924. {
  5925. $pos = $bundle['pos'] ?? [];
  5926. if (!is_array($pos) || $pos === []) {
  5927. return [];
  5928. }
  5929. $sids = [];
  5930. foreach ($pos as $poRow) {
  5931. if (!is_array($poRow)) {
  5932. continue;
  5933. }
  5934. $sid = (int)($poRow['scydgy_id'] ?? 0);
  5935. if ($this->isValidScydgyRowId($sid)) {
  5936. $sids[$sid] = true;
  5937. }
  5938. }
  5939. if ($sids === []) {
  5940. return [];
  5941. }
  5942. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  5943. $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '');
  5944. $suffix = trim((string)$logSuffix, ',, ');
  5945. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  5946. $logMsg .= ':从历史存证退回协助初选';
  5947. } else {
  5948. $logMsg .= ':退回协助初选';
  5949. }
  5950. Db::table('purchase_order')
  5951. ->where('scydgy_id', 'in', array_keys($sids))
  5952. ->update([
  5953. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  5954. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5955. 'pick_company_name' => '',
  5956. 'pick_time' => null,
  5957. 'sys_rq' => null,
  5958. 'mod_rq' => null,
  5959. ]);
  5960. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  5961. foreach (array_keys($sids) as $sid) {
  5962. $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
  5963. }
  5964. return $sids;
  5965. }
  5966. /**
  5967. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  5968. *
  5969. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  5970. */
  5971. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  5972. {
  5973. $scydgyId = trim($scydgyId);
  5974. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  5975. if ($scydgyId === '') {
  5976. return $empty;
  5977. }
  5978. try {
  5979. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  5980. } catch (\Throwable $e) {
  5981. $anchor = null;
  5982. }
  5983. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  5984. return $empty;
  5985. }
  5986. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  5987. if ($ccydh === '') {
  5988. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  5989. }
  5990. try {
  5991. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  5992. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  5993. $pos = $query->order('scydgy_id', 'asc')->select();
  5994. } catch (\Throwable $e) {
  5995. $pos = [$anchor];
  5996. }
  5997. if (!is_array($pos) || $pos === []) {
  5998. $pos = [$anchor];
  5999. }
  6000. return [
  6001. 'ccydh' => $ccydh,
  6002. 'pos' => $pos,
  6003. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6004. ];
  6005. }
  6006. protected function purchaseOrderRowIsCompleted(array $po): bool
  6007. {
  6008. $st = $po['status'] ?? null;
  6009. if ($st === 1 || $st === '1') {
  6010. return true;
  6011. }
  6012. if (is_string($st) && trim($st) === '1') {
  6013. return true;
  6014. }
  6015. return is_numeric($st) && (int)$st === 1;
  6016. }
  6017. /**
  6018. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  6019. */
  6020. public function auditAbandon()
  6021. {
  6022. if (!$this->request->isPost()) {
  6023. $this->error(__('Invalid parameters'));
  6024. }
  6025. $anchorIds = [];
  6026. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  6027. if ($batchRaw !== '') {
  6028. $decoded = json_decode($batchRaw, true);
  6029. if (is_array($decoded)) {
  6030. foreach ($decoded as $id) {
  6031. $s = trim((string)$id);
  6032. if ($s !== '') {
  6033. $anchorIds[] = $s;
  6034. }
  6035. }
  6036. }
  6037. }
  6038. if ($anchorIds === []) {
  6039. $single = trim((string)$this->request->post('scydgy_id', ''));
  6040. if ($single !== '') {
  6041. $anchorIds[] = $single;
  6042. }
  6043. }
  6044. if ($anchorIds === []) {
  6045. $this->error('请至少选择一条订单');
  6046. }
  6047. $processedCcydh = [];
  6048. $doneOrders = 0;
  6049. $allSids = [];
  6050. Db::startTrans();
  6051. try {
  6052. foreach ($anchorIds as $anchorId) {
  6053. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  6054. if (($bundle['pos'] ?? []) === []) {
  6055. continue;
  6056. }
  6057. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6058. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  6059. if (isset($processedCcydh[$dedupeKey])) {
  6060. continue;
  6061. }
  6062. $processedCcydh[$dedupeKey] = true;
  6063. $sids = $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  6064. if ($sids === []) {
  6065. continue;
  6066. }
  6067. $doneOrders++;
  6068. foreach (array_keys($sids) as $sid) {
  6069. $allSids[(int)$sid] = true;
  6070. }
  6071. }
  6072. if ($doneOrders < 1) {
  6073. throw new \Exception('所选订单均不在待确认供应商状态');
  6074. }
  6075. Db::commit();
  6076. } catch (\Throwable $e) {
  6077. Db::rollback();
  6078. $this->error($e->getMessage());
  6079. }
  6080. $this->pickHiddenScydgySetCache = null;
  6081. $msg = $doneOrders > 1
  6082. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  6083. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  6084. $this->success($msg);
  6085. }
  6086. /**
  6087. * 历史存证 — 已完结订单重新下发,退回协助初选(支持单条或批量)
  6088. */
  6089. public function archiveAbandon()
  6090. {
  6091. if (!$this->request->isPost()) {
  6092. $this->error(__('Invalid parameters'));
  6093. }
  6094. $anchorIds = [];
  6095. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  6096. if ($batchRaw !== '') {
  6097. $decoded = json_decode($batchRaw, true);
  6098. if (is_array($decoded)) {
  6099. foreach ($decoded as $id) {
  6100. $s = trim((string)$id);
  6101. if ($s !== '') {
  6102. $anchorIds[] = $s;
  6103. }
  6104. }
  6105. }
  6106. }
  6107. if ($anchorIds === []) {
  6108. $single = trim((string)$this->request->post('scydgy_id', ''));
  6109. if ($single !== '') {
  6110. $anchorIds[] = $single;
  6111. }
  6112. }
  6113. if ($anchorIds === []) {
  6114. $this->error('请至少选择一条订单');
  6115. }
  6116. $processedCcydh = [];
  6117. $doneOrders = 0;
  6118. Db::startTrans();
  6119. try {
  6120. foreach ($anchorIds as $anchorId) {
  6121. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  6122. if (($bundle['pos'] ?? []) === []) {
  6123. continue;
  6124. }
  6125. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6126. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  6127. if (isset($processedCcydh[$dedupeKey])) {
  6128. continue;
  6129. }
  6130. $processedCcydh[$dedupeKey] = true;
  6131. $sids = $this->abandonOrderBundleToPick(
  6132. $bundle,
  6133. 'archive_abandon',
  6134. ',从历史存证退回协助初选'
  6135. );
  6136. if ($sids === []) {
  6137. continue;
  6138. }
  6139. $doneOrders++;
  6140. }
  6141. if ($doneOrders < 1) {
  6142. throw new \Exception('所选订单均不是已完结状态');
  6143. }
  6144. Db::commit();
  6145. } catch (\Throwable $e) {
  6146. Db::rollback();
  6147. $this->error($e->getMessage());
  6148. }
  6149. $this->pickHiddenScydgySetCache = null;
  6150. $msg = $doneOrders > 1
  6151. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史记录已保留')
  6152. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  6153. $this->success($msg);
  6154. }
  6155. /**
  6156. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  6157. */
  6158. public function purchaseApprovalReject()
  6159. {
  6160. if (!$this->request->isPost() || !$this->request->isAjax()) {
  6161. $this->error(__('Invalid parameters'));
  6162. }
  6163. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  6164. $this->error(__('You have no permission'));
  6165. }
  6166. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  6167. $decoded = json_decode($batchRaw, true);
  6168. if (!is_array($decoded) || $decoded === []) {
  6169. $this->error('提交数据无效');
  6170. }
  6171. $done = 0;
  6172. Db::startTrans();
  6173. try {
  6174. foreach ($decoded as $item) {
  6175. if (!is_array($item)) {
  6176. continue;
  6177. }
  6178. $sid = (int)($item['scydgy_id'] ?? 0);
  6179. if (!$this->isValidScydgyRowId($sid)) {
  6180. continue;
  6181. }
  6182. $this->runPurchaseApprovalRejectForSid($sid);
  6183. $done++;
  6184. }
  6185. if ($done < 1) {
  6186. throw new \Exception('所选订单均不在待审批状态');
  6187. }
  6188. Db::commit();
  6189. } catch (\Throwable $e) {
  6190. Db::rollback();
  6191. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  6192. }
  6193. $this->pickHiddenScydgySetCache = null;
  6194. $this->success('已驳回并退回「协助审批下发」');
  6195. }
  6196. /**
  6197. * @throws \Exception
  6198. */
  6199. protected function runPurchaseApprovalRejectForSid(int $sid): void
  6200. {
  6201. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  6202. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  6203. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  6204. $allIds = $this->purchaseOrderDetail($sid);
  6205. if ($allIds === []) {
  6206. throw new \Exception('未找到下发明细');
  6207. }
  6208. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  6209. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  6210. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6211. 'pick_company_name' => '',
  6212. ]);
  6213. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  6214. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  6215. $poId = 0;
  6216. try {
  6217. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  6218. if (is_array($po)) {
  6219. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  6220. }
  6221. } catch (\Throwable $e) {
  6222. }
  6223. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  6224. }
  6225. /**
  6226. * 审核弹窗(旧入口,POST 已关闭)
  6227. */
  6228. public function review()
  6229. {
  6230. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  6231. $this->error(__('You have no permission'));
  6232. }
  6233. if ($this->request->isPost()) {
  6234. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  6235. }
  6236. $this->view->assign('pickMode', 0);
  6237. return $this->view->fetch('procuremen/review');
  6238. }
  6239. /**
  6240. * 审核弹窗获取公司列表
  6241. */
  6242. public function reviewCompanies()
  6243. {
  6244. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review'])) {
  6245. $this->error(__('You have no permission'));
  6246. }
  6247. if (!$this->request->isAjax()) {
  6248. $this->error(__('Invalid parameters'));
  6249. }
  6250. $list = [];
  6251. try {
  6252. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  6253. $rows = Db::table('customer')
  6254. ->where(function ($q) {
  6255. $q->where('status', 1)
  6256. ->whereOr('status', '1')
  6257. ->whereOr('status', '')
  6258. ->whereNull('status');
  6259. })
  6260. ->order('id', 'desc')
  6261. ->select();
  6262. } catch (\Throwable $e) {
  6263. $this->success('', '', []);
  6264. return;
  6265. }
  6266. if (!is_array($rows)) {
  6267. $this->success('', '', []);
  6268. return;
  6269. }
  6270. $detailColCandidates = [
  6271. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  6272. 'company_detail', 'company_desc', 'address',
  6273. ];
  6274. foreach ($rows as $row) {
  6275. if (!is_array($row)) {
  6276. continue;
  6277. }
  6278. $norm = [];
  6279. foreach ($row as $k => $v) {
  6280. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  6281. }
  6282. $row = $norm;
  6283. $st = $row['status'] ?? '';
  6284. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  6285. continue;
  6286. }
  6287. $id = isset($row['id']) ? (string)$row['id'] : '';
  6288. $companyName = '';
  6289. foreach (['company_name', 'name'] as $nk) {
  6290. if (!empty($row[$nk])) {
  6291. $companyName = trim((string)$row[$nk]);
  6292. break;
  6293. }
  6294. }
  6295. $username = '';
  6296. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  6297. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  6298. $username = trim((string)$row[$uk]);
  6299. break;
  6300. }
  6301. }
  6302. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  6303. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  6304. if ($phone === '' && isset($row['account'])) {
  6305. $phone = trim((string)$row['account']);
  6306. }
  6307. if ($phone === '' && isset($row['mobile'])) {
  6308. $phone = trim((string)$row['mobile']);
  6309. }
  6310. /* 邮箱、手机号均为空则无法发短信/邮件,不在下发弹窗展示 */
  6311. if ($email === '' && $phone === '') {
  6312. continue;
  6313. }
  6314. $category = '';
  6315. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6316. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6317. $category = trim((string)$row[$ck]);
  6318. break;
  6319. }
  6320. }
  6321. $detail = '';
  6322. foreach ($detailColCandidates as $dk) {
  6323. if (!isset($row[$dk])) {
  6324. continue;
  6325. }
  6326. $dv = trim((string)$row[$dk]);
  6327. if ($dv !== '') {
  6328. $detail = $dv;
  6329. break;
  6330. }
  6331. }
  6332. $list[] = [
  6333. 'id' => $id,
  6334. 'name' => $companyName,
  6335. 'company_name' => $companyName,
  6336. 'username' => $username,
  6337. 'email' => $email,
  6338. 'phone' => $phone,
  6339. 'category' => $category,
  6340. 'company_type' => $category,
  6341. 'detail' => $detail,
  6342. ];
  6343. }
  6344. $this->success('', '', $list);
  6345. }
  6346. /**
  6347. * 采购确认-下发明细弹窗:
  6348. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  6349. */
  6350. public function outward_detail()
  6351. {
  6352. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6353. if (is_array($ids)) {
  6354. $ids = isset($ids[0]) ? $ids[0] : '';
  6355. }
  6356. $ids = trim((string)$ids);
  6357. if ($ids === '') {
  6358. $this->error(__('Invalid parameters'));
  6359. }
  6360. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  6361. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  6362. $wffTab = 'all';
  6363. }
  6364. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  6365. $purchaseOrderId = 0;
  6366. $po = null;
  6367. try {
  6368. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  6369. if (is_array($po)) {
  6370. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  6371. }
  6372. } catch (\Throwable $e) {
  6373. $purchaseOrderId = 0;
  6374. $po = null;
  6375. }
  6376. if (!$isPurchaseConfirm && is_array($po)) {
  6377. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  6378. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  6379. $isPurchaseConfirm = true;
  6380. }
  6381. }
  6382. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  6383. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6384. $confirmProcessCount = 1;
  6385. $confirmPickGroups = [];
  6386. $processDisplayRows = [];
  6387. $allDetailsBySid = [];
  6388. $requiredSidList = [];
  6389. $sidList = [$ids];
  6390. if ($isPurchaseConfirm) {
  6391. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  6392. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  6393. if ($mergeRows !== []) {
  6394. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  6395. }
  6396. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  6397. if ($confirmBundle['pos'] !== []) {
  6398. $sidList = [];
  6399. foreach ($confirmBundle['pos'] as $poRow) {
  6400. if (!is_array($poRow)) {
  6401. continue;
  6402. }
  6403. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6404. if (!$this->isValidScydgyRowId($sid)) {
  6405. continue;
  6406. }
  6407. $sidList[] = (string)$sid;
  6408. $requiredSidList[] = $sid;
  6409. }
  6410. }
  6411. if ($sidList === []) {
  6412. $sidList = [$ids];
  6413. $requiredSidList = [(int)$ids];
  6414. }
  6415. $confirmProcessCount = max(1, count($requiredSidList));
  6416. if (is_array($po) && $purchaseOrderId <= 0) {
  6417. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  6418. }
  6419. }
  6420. $rows = [];
  6421. try {
  6422. if (count($sidList) === 1) {
  6423. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  6424. } else {
  6425. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  6426. }
  6427. } catch (\Throwable $e) {
  6428. $rows = [];
  6429. }
  6430. if ($isPurchaseConfirm) {
  6431. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  6432. }
  6433. foreach ($rows as &$r) {
  6434. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  6435. $r['id'] = $r['ID'];
  6436. }
  6437. if (isset($r['createtime'])) {
  6438. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  6439. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  6440. } else {
  6441. $r['createtime_text'] = (string)$r['createtime'];
  6442. }
  6443. } else {
  6444. $r['createtime_text'] = '';
  6445. }
  6446. }
  6447. unset($r);
  6448. $pickedCompanyName = '';
  6449. if ($isPurchaseConfirm) {
  6450. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  6451. if (!is_array($poRow)) {
  6452. continue;
  6453. }
  6454. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  6455. if ($pn !== '') {
  6456. $pickedCompanyName = $pn;
  6457. break;
  6458. }
  6459. }
  6460. }
  6461. $this->view->assign('rows', $rows ?: []);
  6462. $this->view->assign('rowCount', count($rows ?: []));
  6463. $this->view->assign('scydgyId', $ids);
  6464. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  6465. $this->view->assign('headTitle', $headTitle);
  6466. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  6467. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  6468. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  6469. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  6470. $this->view->assign('processDisplayRows', $processDisplayRows);
  6471. $this->view->assign('confirmPickGroups', $confirmPickGroups);
  6472. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  6473. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  6474. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  6475. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  6476. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  6477. if ($isPurchaseConfirm) {
  6478. return $this->view->fetch();
  6479. }
  6480. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  6481. $this->view->engine->layout(false);
  6482. try {
  6483. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  6484. $this->view->assign('dialogBody', $bodyHtml);
  6485. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  6486. } finally {
  6487. if ($restoreLayout) {
  6488. $this->view->engine->layout($restoreLayout);
  6489. }
  6490. }
  6491. }
  6492. /**
  6493. * 月度导出记录表(不存在时自动创建)
  6494. */
  6495. protected function ensurePurchaseMonthExportLogTable(): void
  6496. {
  6497. try {
  6498. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  6499. } catch (\Throwable $e) {
  6500. Db::execute(
  6501. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  6502. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  6503. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  6504. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  6505. `admin_name` varchar(64) NOT NULL DEFAULT '',
  6506. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  6507. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  6508. `createtime` int(10) unsigned DEFAULT NULL,
  6509. PRIMARY KEY (`id`),
  6510. KEY `idx_ym` (`ym`),
  6511. KEY `idx_ct` (`createtime`)
  6512. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  6513. );
  6514. }
  6515. }
  6516. /**
  6517. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  6518. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  6519. */
  6520. public function export_month_outward()
  6521. {
  6522. $this->request->filter(['strip_tags', 'trim']);
  6523. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  6524. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  6525. $ym = date('Y-m');
  6526. }
  6527. $dbRows = [];
  6528. try {
  6529. $query = Db::table('purchase_order');
  6530. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  6531. $dbRows = $query->select();
  6532. } catch (\Throwable $e) {
  6533. $dbRows = [];
  6534. }
  6535. if (!is_array($dbRows)) {
  6536. $dbRows = [];
  6537. }
  6538. $completeTsMap = [];
  6539. $sidList = [];
  6540. foreach ($dbRows as $dbRow) {
  6541. if (!is_array($dbRow)) {
  6542. continue;
  6543. }
  6544. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  6545. if ($sid > 0) {
  6546. $sidList[$sid] = true;
  6547. }
  6548. }
  6549. if ($sidList !== []) {
  6550. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  6551. }
  6552. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  6553. if (!is_array($dbRow)) {
  6554. return false;
  6555. }
  6556. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  6557. return $done['ts'] > 0 && date('Y-m', $done['ts']) === $ym;
  6558. }));
  6559. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  6560. $filtered = $pool;
  6561. $mainBySid = [];
  6562. foreach ($filtered as $rw) {
  6563. if (!is_array($rw)) {
  6564. continue;
  6565. }
  6566. $rid = (int)($rw['ID'] ?? 0);
  6567. if ($rid > 0) {
  6568. $mainBySid[$rid] = $rw;
  6569. }
  6570. }
  6571. if ($mainBySid === []) {
  6572. $detailRows = [];
  6573. } else {
  6574. try {
  6575. $detailRows = Db::table('purchase_order_detail')
  6576. ->where('scydgy_id', 'in', array_keys($mainBySid))
  6577. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  6578. ->order('status', 'desc')
  6579. ->order('CCYDH', 'asc')
  6580. ->order('company_name', 'asc')
  6581. ->order('id', 'asc')
  6582. ->select();
  6583. } catch (\Throwable $e) {
  6584. try {
  6585. $detailRows = Db::table('purchase_order_detail')
  6586. ->where('scydgy_id', 'in', array_keys($mainBySid))
  6587. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  6588. ->order('status', 'desc')
  6589. ->order('CCYDH', 'asc')
  6590. ->order('company_name', 'asc')
  6591. ->order('ID', 'asc')
  6592. ->select();
  6593. } catch (\Throwable $e2) {
  6594. $detailRows = [];
  6595. }
  6596. }
  6597. }
  6598. if (!is_array($detailRows)) {
  6599. $detailRows = [];
  6600. }
  6601. $exportLines = [];
  6602. $detailSidSeen = [];
  6603. foreach ($detailRows as $dr) {
  6604. if (!is_array($dr)) {
  6605. continue;
  6606. }
  6607. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  6608. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  6609. continue;
  6610. }
  6611. if (isset($detailSidSeen[$sid])) {
  6612. continue;
  6613. }
  6614. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  6615. continue;
  6616. }
  6617. $detailSidSeen[$sid] = true;
  6618. $m = $mainBySid[$sid];
  6619. $exportLines[] = [
  6620. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  6621. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  6622. 'company_name' => (string)($dr['company_name'] ?? ''),
  6623. 'CDF' => (string)($m['CDF'] ?? ''),
  6624. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  6625. 'gx' => $this->procuremenExportGxText($m),
  6626. 'detail' => $dr,
  6627. ];
  6628. }
  6629. foreach ($detailRows as $dr) {
  6630. if (!is_array($dr)) {
  6631. continue;
  6632. }
  6633. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  6634. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  6635. continue;
  6636. }
  6637. $detailSidSeen[$sid] = true;
  6638. $m = $mainBySid[$sid];
  6639. $exportLines[] = [
  6640. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  6641. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  6642. 'company_name' => (string)($dr['company_name'] ?? ''),
  6643. 'CDF' => (string)($m['CDF'] ?? ''),
  6644. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  6645. 'gx' => $this->procuremenExportGxText($m),
  6646. 'detail' => $dr,
  6647. ];
  6648. }
  6649. foreach ($mainBySid as $sid => $m) {
  6650. if (isset($detailSidSeen[$sid])) {
  6651. continue;
  6652. }
  6653. $company = trim((string)($m['pick_company_name'] ?? ''));
  6654. $exportLines[] = [
  6655. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  6656. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  6657. 'company_name' => $company,
  6658. 'CDF' => (string)($m['CDF'] ?? ''),
  6659. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  6660. 'gx' => $this->procuremenExportGxText($m),
  6661. 'detail' => [],
  6662. ];
  6663. }
  6664. $groups = [];
  6665. foreach ($exportLines as $line) {
  6666. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  6667. if (!isset($groups[$k])) {
  6668. $groups[$k] = [];
  6669. }
  6670. $groups[$k][] = $line;
  6671. }
  6672. ksort($groups, SORT_STRING);
  6673. $spreadsheet = new Spreadsheet();
  6674. $sheet = $spreadsheet->getActiveSheet();
  6675. $sheet->setTitle('协助明细');
  6676. $mon = (int)substr($ym, 5, 2);
  6677. $sheet->mergeCells('A1:H1');
  6678. $sheet->setCellValue('A1', $mon . '月协助明细');
  6679. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  6680. $sheet->getStyle('A1')->getAlignment()
  6681. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  6682. ->setVertical(Alignment::VERTICAL_CENTER);
  6683. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  6684. $col = 'A';
  6685. foreach ($headers as $h) {
  6686. $sheet->setCellValue($col . '2', $h);
  6687. $col++;
  6688. }
  6689. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  6690. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  6691. $rowNum = 3;
  6692. $sumSubtotalCounts = 0;
  6693. $grandAmount = 0.0;
  6694. if ($groups === []) {
  6695. $sheet->mergeCells('A3:H3');
  6696. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  6697. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  6698. $rowNum = 4;
  6699. } else {
  6700. foreach ($groups as $items) {
  6701. if ($items === []) {
  6702. continue;
  6703. }
  6704. $groupLineCount = count($items);
  6705. $subAmount = 0.0;
  6706. $i = 0;
  6707. foreach ($items as $line) {
  6708. $i++;
  6709. $dr = $line['detail'];
  6710. $amt = $this->procuremenExportAmount($dr);
  6711. $subAmount += $amt;
  6712. $sheet->setCellValue('A' . $rowNum, $i);
  6713. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  6714. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  6715. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  6716. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  6717. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  6718. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  6719. $sheet->setCellValue('H' . $rowNum, $amt);
  6720. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  6721. $rowNum++;
  6722. }
  6723. $sumSubtotalCounts += $groupLineCount;
  6724. $grandAmount += $subAmount;
  6725. $sheet->setCellValue('A' . $rowNum, $groupLineCount);
  6726. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  6727. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  6728. $sheet->getStyle('G' . $rowNum)->getAlignment()
  6729. ->setHorizontal(Alignment::HORIZONTAL_RIGHT)
  6730. ->setVertical(Alignment::VERTICAL_CENTER);
  6731. $rowNum++;
  6732. }
  6733. }
  6734. $sheet->setCellValue('A' . $rowNum, '总计');
  6735. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  6736. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  6737. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  6738. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  6739. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
  6740. $lastRow = $rowNum;
  6741. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  6742. 'borders' => [
  6743. 'allBorders' => [
  6744. 'borderStyle' => Border::BORDER_THIN,
  6745. 'color' => ['rgb' => '000000'],
  6746. ],
  6747. ],
  6748. ]);
  6749. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  6750. if ($lastRow >= 3) {
  6751. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6752. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6753. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6754. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6755. }
  6756. $sheet->getColumnDimension('A')->setWidth(7);
  6757. $sheet->getColumnDimension('B')->setWidth(16);
  6758. $sheet->getColumnDimension('C')->setWidth(52);
  6759. $sheet->getColumnDimension('D')->setWidth(32);
  6760. $sheet->getColumnDimension('E')->setWidth(12);
  6761. $sheet->getColumnDimension('F')->setWidth(44);
  6762. $sheet->getColumnDimension('G')->setWidth(26);
  6763. $sheet->getColumnDimension('H')->setWidth(13);
  6764. $sheet->getRowDimension(1)->setRowHeight(28);
  6765. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  6766. $quoteStartRow = $lastRow + 3;
  6767. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, $quoteStartRow);
  6768. if ($quoteLastRow >= $quoteStartRow) {
  6769. $sheet->getColumnDimension('E')->setWidth(28);
  6770. }
  6771. $fileBase = '协助明细_' . str_replace('-', '', $ym);
  6772. $filename = $fileBase . '.xlsx';
  6773. try {
  6774. $this->ensurePurchaseMonthExportLogTable();
  6775. list($adminId, $adminName) = $this->GetUseName();
  6776. Db::table('purchase_month_export_log')->insert([
  6777. 'ym' => $ym,
  6778. 'admin_id' => (int)$adminId,
  6779. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  6780. 'row_count' => count($exportLines),
  6781. 'total_amount' => round($grandAmount, 2),
  6782. 'createtime' => time(),
  6783. ]);
  6784. } catch (\Throwable $e) {
  6785. Log::write('month export log: ' . $e->getMessage(), 'error');
  6786. }
  6787. if (ob_get_length()) {
  6788. ob_end_clean();
  6789. }
  6790. $asciiName = 'outward_' . str_replace('-', '', $ym) . '.xlsx';
  6791. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  6792. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  6793. header('Cache-Control: max-age=0');
  6794. $writer = new Xlsx($spreadsheet);
  6795. $writer->save('php://output');
  6796. $spreadsheet->disconnectWorksheets();
  6797. unset($spreadsheet);
  6798. exit;
  6799. }
  6800. /**
  6801. * 导出用:工序列文案
  6802. */
  6803. protected function procuremenExportGxText(array $r)
  6804. {
  6805. $a = trim((string)($r['CDXMC'] ?? ''));
  6806. $b = trim((string)($r['CGYMC'] ?? ''));
  6807. if ($a !== '' && $b !== '') {
  6808. return $a . ':' . $b;
  6809. }
  6810. return $a !== '' ? $a : $b;
  6811. }
  6812. /**
  6813. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  6814. */
  6815. protected function procuremenExportAmount(array $r)
  6816. {
  6817. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  6818. if (!array_key_exists($k, $r)) {
  6819. continue;
  6820. }
  6821. $v = $r[$k];
  6822. if ($v === null || $v === '') {
  6823. continue;
  6824. }
  6825. if (is_numeric($v)) {
  6826. return (float)$v;
  6827. }
  6828. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  6829. if ($v !== '' && is_numeric($v)) {
  6830. return (float)$v;
  6831. }
  6832. }
  6833. return 0.0;
  6834. }
  6835. /**
  6836. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  6837. *
  6838. * @param array<int, array<string, mixed>> $detailRows
  6839. * @param array<int, array<string, mixed>> $mainBySid
  6840. * @return array<int, array<string, mixed>>
  6841. */
  6842. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  6843. {
  6844. $lines = [];
  6845. foreach ($detailRows as $dr) {
  6846. if (!is_array($dr)) {
  6847. continue;
  6848. }
  6849. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  6850. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  6851. continue;
  6852. }
  6853. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  6854. continue;
  6855. }
  6856. $cn = trim((string)($dr['company_name'] ?? ''));
  6857. if ($cn === '') {
  6858. continue;
  6859. }
  6860. $m = $mainBySid[$sid];
  6861. $am = trim((string)($dr['amount'] ?? ''));
  6862. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  6863. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  6864. $amountText = $amountFilled
  6865. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  6866. : '未填写';
  6867. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  6868. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  6869. if ($deliveryShow === '' && $deliveryRaw !== '') {
  6870. $deliveryShow = $deliveryRaw;
  6871. }
  6872. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  6873. ? $deliveryShow
  6874. : '未填写';
  6875. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  6876. $lines[] = [
  6877. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  6878. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  6879. 'gx' => $this->procuremenExportGxText($m),
  6880. 'company_name' => $cn,
  6881. 'amount_text' => $amountText,
  6882. 'amount_num' => $amountFilled ? $amountNum : null,
  6883. 'delivery_text' => $deliveryText,
  6884. 'picked_text' => $picked ? '中标' : '未中标',
  6885. 'picked' => $picked,
  6886. ];
  6887. }
  6888. usort($lines, function ($a, $b) {
  6889. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  6890. if ($c !== 0) {
  6891. return $c;
  6892. }
  6893. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  6894. if ($c !== 0) {
  6895. return $c;
  6896. }
  6897. if (!empty($a['picked']) !== !empty($b['picked'])) {
  6898. return !empty($a['picked']) ? -1 : 1;
  6899. }
  6900. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  6901. });
  6902. return $lines;
  6903. }
  6904. /**
  6905. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  6906. *
  6907. * @param array<int, array<string, mixed>> $quoteLines
  6908. */
  6909. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  6910. {
  6911. $mon = (int)substr($ym, 5, 2);
  6912. $titleRow = $startRow;
  6913. $headerRow = $startRow + 1;
  6914. $dataStartRow = $startRow + 2;
  6915. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  6916. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  6917. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  6918. $sheet->getStyle('A' . $titleRow)->getAlignment()
  6919. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  6920. ->setVertical(Alignment::VERTICAL_CENTER);
  6921. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  6922. $col = 'A';
  6923. foreach ($headers as $h) {
  6924. $sheet->setCellValue($col . $headerRow, $h);
  6925. $col++;
  6926. }
  6927. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  6928. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  6929. $rowNum = $dataStartRow;
  6930. if ($quoteLines === []) {
  6931. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  6932. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  6933. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  6934. $rowNum = $dataStartRow + 1;
  6935. } else {
  6936. $i = 0;
  6937. foreach ($quoteLines as $line) {
  6938. $i++;
  6939. $sheet->setCellValue('A' . $rowNum, $i);
  6940. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  6941. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  6942. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  6943. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  6944. if ($line['amount_num'] !== null) {
  6945. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  6946. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  6947. } else {
  6948. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  6949. }
  6950. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  6951. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  6952. if (!empty($line['picked'])) {
  6953. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  6954. }
  6955. $rowNum++;
  6956. }
  6957. }
  6958. $lastRow = $rowNum - 1;
  6959. if ($lastRow >= $headerRow) {
  6960. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  6961. 'borders' => [
  6962. 'allBorders' => [
  6963. 'borderStyle' => Border::BORDER_THIN,
  6964. 'color' => ['rgb' => '000000'],
  6965. ],
  6966. ],
  6967. ]);
  6968. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  6969. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6970. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6971. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  6972. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  6973. }
  6974. return $lastRow;
  6975. }
  6976. /**
  6977. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  6978. */
  6979. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  6980. {
  6981. $s = trim($ccydh);
  6982. if ($s === '') {
  6983. return 'ORDER';
  6984. }
  6985. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  6986. $s = trim($s, '._-');
  6987. if ($s === '') {
  6988. return 'ORDER';
  6989. }
  6990. if (function_exists('mb_substr')) {
  6991. return mb_substr($s, 0, 80, 'UTF-8');
  6992. }
  6993. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  6994. }
  6995. /**
  6996. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  6997. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  6998. *
  6999. * @return array{objectKey: string, webPath: string}
  7000. */
  7001. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  7002. {
  7003. $sid = (int)$scydgyId;
  7004. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  7005. $y = date('Y');
  7006. $m = date('m');
  7007. $d = date('d');
  7008. $basename = $safeOrder . '_' . $sid . '.pdf';
  7009. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  7010. return [
  7011. 'objectKey' => $objectKey,
  7012. 'webPath' => '/' . $objectKey,
  7013. ];
  7014. }
  7015. /**
  7016. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  7017. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  7018. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  7019. *
  7020. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  7021. */
  7022. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  7023. {
  7024. if (!$this->isValidScydgyRowId($scydgyId)) {
  7025. return '';
  7026. }
  7027. $ids = trim((string)$scydgyId);
  7028. $prep = $this->prepareProcuremenDetailsView($ids);
  7029. if (!$prep['ok']) {
  7030. return '';
  7031. }
  7032. $ccydh = $prep['ccydh'];
  7033. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  7034. $objectKey = $paths['objectKey'];
  7035. $webPath = $paths['webPath'];
  7036. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  7037. $this->view->assign([
  7038. 'pdf_export' => 1,
  7039. 'pdfMetaLine' => $meta,
  7040. ]);
  7041. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  7042. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  7043. $this->view->engine->layout(false);
  7044. try {
  7045. $html = $this->view->fetch('procuremen/details_pdf_shell');
  7046. } catch (\Throwable $e) {
  7047. if ($restoreLayout) {
  7048. $this->view->engine->layout($restoreLayout);
  7049. }
  7050. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  7051. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  7052. return '';
  7053. }
  7054. if ($restoreLayout) {
  7055. $this->view->engine->layout($restoreLayout);
  7056. }
  7057. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  7058. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  7059. if (!is_dir($tempDir)) {
  7060. @mkdir($tempDir, 0755, true);
  7061. }
  7062. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  7063. try {
  7064. $mpdf = new \Mpdf\Mpdf([
  7065. 'mode' => 'utf-8',
  7066. 'format' => 'A4',
  7067. 'margin_left' => 12,
  7068. 'margin_right' => 12,
  7069. 'margin_top' => 14,
  7070. 'margin_bottom' => 14,
  7071. 'tempDir' => $tempDir,
  7072. 'autoScriptToLang' => true,
  7073. 'autoLangToFont' => true,
  7074. ]);
  7075. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  7076. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  7077. $mpdf->SetBasePath('http://127.0.0.1/');
  7078. $mpdf->WriteHTML($html);
  7079. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  7080. } catch (\Throwable $e) {
  7081. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  7082. if (is_file($tempPdf)) {
  7083. @unlink($tempPdf);
  7084. }
  7085. return '';
  7086. }
  7087. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  7088. if ($ossUrl !== '') {
  7089. @unlink($tempPdf);
  7090. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  7091. return $ossUrl;
  7092. }
  7093. $pi = pathinfo($objectKey);
  7094. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  7095. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  7096. if ($baseFile === '') {
  7097. @unlink($tempPdf);
  7098. return '';
  7099. }
  7100. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  7101. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  7102. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  7103. @unlink($tempPdf);
  7104. return '';
  7105. }
  7106. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  7107. if (!@copy($tempPdf, $fullPath)) {
  7108. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  7109. @unlink($tempPdf);
  7110. return '';
  7111. }
  7112. @unlink($tempPdf);
  7113. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  7114. return $webPath;
  7115. }
  7116. /**
  7117. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  7118. */
  7119. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  7120. {
  7121. if ($scydgyId <= 0 || $webPath === '') {
  7122. return;
  7123. }
  7124. try {
  7125. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  7126. } catch (\Throwable $e) {
  7127. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  7128. }
  7129. }
  7130. /**
  7131. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  7132. *
  7133. * @param array<string, string> $vars
  7134. * @return array<string, string>
  7135. */
  7136. protected function normalizeSmsTemplateVars(array $vars): array
  7137. {
  7138. $out = [];
  7139. foreach ($vars as $k => $v) {
  7140. $out[(string)$k] = trim((string)$v);
  7141. }
  7142. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  7143. $out['contact_name'] = $out['company_name'];
  7144. }
  7145. return $out;
  7146. }
  7147. /**
  7148. * 按手机号或公司名称查 customer 表联系人姓名
  7149. */
  7150. protected function resolveCustomerContactName(string $phone, string $companyName): string
  7151. {
  7152. $phone = trim($phone);
  7153. $companyName = trim($companyName);
  7154. try {
  7155. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  7156. $row = Db::table('customer')
  7157. ->where(function ($q) use ($phone) {
  7158. $q->where('phone', $phone)->whereOr('account', $phone);
  7159. })
  7160. ->order('id', 'asc')
  7161. ->find();
  7162. if (is_array($row)) {
  7163. $nm = trim((string)($row['username'] ?? ''));
  7164. if ($nm !== '') {
  7165. return $nm;
  7166. }
  7167. }
  7168. }
  7169. if ($companyName !== '') {
  7170. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  7171. if (is_array($row)) {
  7172. return trim((string)($row['username'] ?? ''));
  7173. }
  7174. }
  7175. } catch (\Throwable $e) {
  7176. }
  7177. return '';
  7178. }
  7179. /**
  7180. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  7181. */
  7182. protected function plainTextToHtmlEmailBody(string $text): string
  7183. {
  7184. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  7185. $parts = explode("\n", $text);
  7186. $out = [];
  7187. foreach ($parts as $line) {
  7188. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  7189. $out[] = $line;
  7190. } else {
  7191. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  7192. }
  7193. }
  7194. return implode("<br>\n", $out);
  7195. }
  7196. /**
  7197. * 短信场景:去掉链接类变量,避免误填 URL
  7198. *
  7199. * @param array<string, string> $vars
  7200. * @return array<string, string>
  7201. */
  7202. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  7203. {
  7204. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  7205. return $vars;
  7206. }
  7207. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  7208. $vars[$k] = '';
  7209. }
  7210. return $vars;
  7211. }
  7212. /**
  7213. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  7214. *
  7215. * @param array<string, string> $vars
  7216. */
  7217. protected function renderNotifyTemplate(string $scene, array $vars): string
  7218. {
  7219. $vars = $this->normalizeSmsTemplateVars($vars);
  7220. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  7221. $row = $this->loadNotifyTemplateRow($scene);
  7222. if ($row === null) {
  7223. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  7224. }
  7225. $tpl = trim((string)($row['content'] ?? ''));
  7226. if ($tpl === '') {
  7227. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  7228. }
  7229. foreach ($vars as $k => $v) {
  7230. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  7231. }
  7232. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  7233. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  7234. return $tpl;
  7235. }
  7236. protected function resolveProcuremenEmailSubject(string $scene): string
  7237. {
  7238. $map = [
  7239. 'review_email' => '您有新的协助加工订单',
  7240. ];
  7241. $subject = trim((string)($map[$scene] ?? ''));
  7242. if ($subject === '') {
  7243. $this->error('未配置邮件主题:' . $scene);
  7244. }
  7245. return $subject;
  7246. }
  7247. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  7248. {
  7249. $map = [
  7250. 'review_email' => '协助下发-邮箱',
  7251. 'review_sms' => '协助下发-短信',
  7252. 'confirm_ok' => '采购确认-通过',
  7253. 'confirm_fail' => '采购确认-未通过',
  7254. ];
  7255. $label = $map[$scene] ?? $scene;
  7256. if ($titleRequired) {
  7257. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  7258. }
  7259. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  7260. }
  7261. /**
  7262. * 是否开启协助通知演练(不发真实短信/邮件)
  7263. */
  7264. protected function isProcuremenNotifyDryRun(): bool
  7265. {
  7266. return (bool)Config::get('procuremen_notify_dry_run');
  7267. }
  7268. /**
  7269. * @param array<string, mixed> $payload
  7270. */
  7271. protected function recordNotifyDryRunPreview(array $payload): void
  7272. {
  7273. $this->notifyDryRunPreview[] = $payload;
  7274. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  7275. }
  7276. /**
  7277. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  7278. * @throws \Exception
  7279. */
  7280. protected function smsbao($phone, $content)
  7281. {
  7282. if ($this->isProcuremenNotifyDryRun()) {
  7283. $this->recordNotifyDryRunPreview([
  7284. 'scene' => 'sms_only',
  7285. 'phone' => $phone,
  7286. 'sms_content' => $content,
  7287. ]);
  7288. return;
  7289. }
  7290. $statusStr = [
  7291. '0' => '短信发送成功',
  7292. '-1' => '参数不全',
  7293. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  7294. '30' => '密码错误',
  7295. '40' => '账号不存在',
  7296. '41' => '余额不足',
  7297. '42' => '帐户已过期',
  7298. '43' => 'IP地址限制',
  7299. '50' => '内容含有敏感词',
  7300. ];
  7301. $smsapi = 'http://api.smsbao.com/';
  7302. $user = 'zhuwei123';
  7303. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  7304. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  7305. $result = @file_get_contents($sendurl);
  7306. if ($result === false) {
  7307. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  7308. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  7309. }
  7310. $result = trim((string)$result);
  7311. if ($result !== '0') {
  7312. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  7313. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  7314. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  7315. }
  7316. }
  7317. }