Procuremen.php 252 KB

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