Procuremen.php 269 KB

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