Procuremen.php 295 KB

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