Procuremen.php 339 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenGuard;
  6. use app\common\library\ProcuremenOperLog;
  7. use app\common\library\ProcuremenStatus;
  8. use app\common\library\ProcuremenTime;
  9. use PHPMailer\PHPMailer\PHPMailer;
  10. use think\Config;
  11. use think\Cache;
  12. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  13. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  14. use PhpOffice\PhpSpreadsheet\Style\Border;
  15. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  16. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  17. use think\Db;
  18. use think\Log;
  19. class Procuremen extends Backend
  20. {
  21. /**
  22. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  23. */
  24. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  25. /**
  26. * Procuremen模型对象
  27. * @var \app\admin\model\Procuremen
  28. */
  29. protected $model = null;
  30. /**
  31. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  32. */
  33. protected $notifyDryRunPreview = [];
  34. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  35. protected $procuremenRedisCache = null;
  36. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  37. protected $pickHiddenScydgySetCache = null;
  38. /** 邮件发送日志表结构已就绪缓存键 */
  39. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  40. /**
  41. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  42. * @var array
  43. */
  44. protected $noNeedRight = [
  45. 'pickreview', 'review', 'reviewcompanies',
  46. ];
  47. public function _initialize()
  48. {
  49. parent::_initialize();
  50. $this->model = new \app\admin\model\Procuremen;
  51. $this->maybeMigrateLegacyWflowStatusText();
  52. $this->assignProcuremenAuthConfig();
  53. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  54. $this->ensurePurchaseEmailSendLogTableOnce();
  55. }
  56. }
  57. /**
  58. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  59. */
  60. protected function maybeMigrateLegacyWflowStatusText(): void
  61. {
  62. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  63. if (is_file($flagFile)) {
  64. return;
  65. }
  66. $map = [
  67. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  68. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  69. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  70. '3' => ProcuremenStatus::WFLOW_APPROVED,
  71. ];
  72. try {
  73. foreach ($map as $num => $text) {
  74. Db::table('purchase_order')
  75. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  76. ->update(['wflow_status' => $text]);
  77. }
  78. @file_put_contents($flagFile, date('c'));
  79. } catch (\Throwable $e) {
  80. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  81. }
  82. }
  83. /**
  84. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  85. *
  86. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  87. */
  88. protected function hasProcuremenPerm(array $actions): bool
  89. {
  90. foreach ($actions as $action) {
  91. $action = strtolower(trim((string)$action));
  92. if ($action === '') {
  93. continue;
  94. }
  95. if (strpos($action, 'procuremen/') !== 0) {
  96. $action = 'procuremen/' . $action;
  97. }
  98. if ($this->auth->check($action)) {
  99. return true;
  100. }
  101. }
  102. $suffixes = [];
  103. foreach ($actions as $action) {
  104. $action = strtolower(trim((string)$action));
  105. $action = preg_replace('#^procuremen/#', '', $action);
  106. if ($action !== '') {
  107. $suffixes[$action] = true;
  108. }
  109. }
  110. if ($suffixes === []) {
  111. return false;
  112. }
  113. try {
  114. foreach ($this->auth->getRuleList() as $rule) {
  115. $rule = strtolower((string)$rule);
  116. if (strpos($rule, 'procuremen/') !== 0) {
  117. continue;
  118. }
  119. foreach (array_keys($suffixes) as $suffix) {
  120. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  121. return true;
  122. }
  123. }
  124. }
  125. } catch (\Throwable $e) {
  126. }
  127. return false;
  128. }
  129. /**
  130. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  131. *
  132. * @param string[] $actions
  133. */
  134. protected function hasProcuremenPermStrict(array $actions): bool
  135. {
  136. foreach ($actions as $action) {
  137. $action = strtolower(trim((string)$action));
  138. if ($action === '') {
  139. continue;
  140. }
  141. if (strpos($action, 'procuremen/') !== 0) {
  142. $action = 'procuremen/' . $action;
  143. }
  144. if ($this->auth->check($action)) {
  145. return true;
  146. }
  147. }
  148. return false;
  149. }
  150. /**
  151. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  152. *
  153. * @param string[] $titles
  154. */
  155. protected function authHasAssignedRuleTitle(array $titles): bool
  156. {
  157. $titles = array_values(array_filter(array_map('trim', $titles)));
  158. if ($titles === []) {
  159. return false;
  160. }
  161. try {
  162. $ids = $this->auth->getRuleIds();
  163. if (in_array('*', $ids, true)) {
  164. return true;
  165. }
  166. if ($ids === []) {
  167. return false;
  168. }
  169. $rows = Db::name('auth_rule')
  170. ->where('status', 'normal')
  171. ->whereIn('id', $ids)
  172. ->column('title');
  173. foreach ($rows as $title) {
  174. $t = trim((string)$title);
  175. if ($t !== '' && in_array($t, $titles, true)) {
  176. return true;
  177. }
  178. }
  179. } catch (\Throwable $e) {
  180. }
  181. return false;
  182. }
  183. protected function procuremenCanPickDelete(): bool
  184. {
  185. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  186. return true;
  187. }
  188. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  189. }
  190. protected function procuremenCanComplete(): bool
  191. {
  192. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  193. return true;
  194. }
  195. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  196. }
  197. protected function procuremenCanDispatch(): bool
  198. {
  199. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  200. }
  201. /**
  202. * 前端按钮显隐(Config.procuremenAuth)
  203. */
  204. protected function assignProcuremenAuthConfig(): void
  205. {
  206. $authMap = [
  207. 'pickreview' => $this->procuremenCanDispatch(),
  208. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  209. 'pickdelete' => $this->procuremenCanPickDelete(),
  210. 'completedirectly' => $this->procuremenCanComplete(),
  211. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  212. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  213. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  214. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  215. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  216. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  217. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  218. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  219. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  220. 'details' => $this->hasProcuremenPerm(['details']),
  221. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  222. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  223. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  224. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  225. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  226. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  227. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  228. 'add' => $this->hasProcuremenPerm(['add']),
  229. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  230. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  231. ];
  232. $this->assignconfig('procuremenAuth', $authMap);
  233. }
  234. /**
  235. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  236. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  237. *
  238. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  239. */
  240. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  241. {
  242. static $mprocCfgLoaded = false;
  243. if (!$mprocCfgLoaded) {
  244. $mprocCfgLoaded = true;
  245. if (is_file(APP_PATH . 'extra/mproc.php')) {
  246. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  247. }
  248. }
  249. $eid = (int)$purchaseOrderDetailId;
  250. $base = $this->resolveMprocMobilePublicBaseUrl();
  251. if ($base === '') {
  252. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  253. }
  254. $path = trim((string)Config::get('mproc.mobile_index_path'));
  255. if ($path === '') {
  256. $path = '/index.php/index/index/index';
  257. } else {
  258. $path = '/' . ltrim($path, '/');
  259. }
  260. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  261. if ($eid > 0) {
  262. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  263. }
  264. return $base . $path . '?main_tab=orders';
  265. }
  266. /**
  267. * 邮件/短信外链:须为带点的公网域名
  268. */
  269. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  270. {
  271. $u = trim((string)$baseUrl);
  272. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  273. return false;
  274. }
  275. $host = parse_url($u, PHP_URL_HOST);
  276. if (!is_string($host) || $host === '') {
  277. return false;
  278. }
  279. if (strcasecmp($host, 'localhost') === 0) {
  280. return false;
  281. }
  282. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  283. return false;
  284. }
  285. if (strpos($host, '.') === false) {
  286. return false;
  287. }
  288. return true;
  289. }
  290. /**
  291. * 解析用于协助邮件/短信的手机端站点根
  292. */
  293. protected function resolveMprocMobilePublicBaseUrl()
  294. {
  295. $candidates = [];
  296. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  297. $candidates[] = trim((string)Config::get('site.indexurl'));
  298. $cdn = trim((string)Config::get('site.cdnurl'));
  299. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  300. $candidates[] = rtrim($cdn, '/');
  301. }
  302. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  303. $candidates[] = $reqBase;
  304. foreach ($candidates as $c) {
  305. if ($c === '') {
  306. continue;
  307. }
  308. $c = rtrim($c, '/');
  309. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  310. return $c;
  311. }
  312. }
  313. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  314. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  315. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  316. return $reqBase;
  317. }
  318. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  319. return '';
  320. }
  321. /**
  322. * 获取 Redis 中 procuremen_redis
  323. */
  324. protected function ProcuremenRedis(): array
  325. {
  326. if ($this->procuremenRedisCache !== null) {
  327. return $this->procuremenRedisCache;
  328. }
  329. try {
  330. $redis = redis();
  331. $raw = $redis->get('procuremen_redis');
  332. if ($raw === false || $raw === '') {
  333. $this->procuremenRedisCache = [];
  334. return $this->procuremenRedisCache;
  335. }
  336. $decoded = json_decode($raw, true);
  337. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  338. $this->procuremenRedisCache = [];
  339. return $this->procuremenRedisCache;
  340. }
  341. $this->procuremenRedisCache = $decoded['data'];
  342. return $this->procuremenRedisCache;
  343. } catch (\Throwable $e) {
  344. $this->procuremenRedisCache = [];
  345. return $this->procuremenRedisCache;
  346. }
  347. }
  348. /**
  349. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  350. *
  351. * @return array<int, array<string, mixed>>
  352. */
  353. protected function procuremenFetchErpPoolFromDb(): array
  354. {
  355. try {
  356. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  357. $endTime = date('Y-m-d 23:59:59');
  358. $list = Db::table('scydgy')
  359. ->alias('a')
  360. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  361. ->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')
  362. ->where([
  363. 'a.bwjg' => 1,
  364. 'a.iEndBz' => 0,
  365. 'a.iType' => 0,
  366. 'a.iStatus' => 10,
  367. ])
  368. ->where('a.dStamp', '>=', $startTime)
  369. ->where('a.dStamp', '<=', $endTime)
  370. ->order('a.dStamp', 'desc')
  371. ->select();
  372. if (!is_array($list)) {
  373. return [];
  374. }
  375. try {
  376. $redis = redis();
  377. $payload = [
  378. 'code' => 200,
  379. 'msg' => 'success',
  380. 'data' => $list,
  381. ];
  382. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  383. $this->procuremenRedisCache = $list;
  384. } catch (\Throwable $e) {
  385. }
  386. return $list;
  387. } catch (\Throwable $e) {
  388. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  389. return [];
  390. }
  391. }
  392. /**
  393. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  394. *
  395. * @return array<int, array<string, mixed>>
  396. */
  397. protected function procuremenEnsureRedisPool(): array
  398. {
  399. $pool = $this->ProcuremenRedis();
  400. if (is_array($pool) && $pool !== []) {
  401. return $pool;
  402. }
  403. static $warmed = false;
  404. if ($warmed) {
  405. return is_array($pool) ? $pool : [];
  406. }
  407. $warmed = true;
  408. return $this->procuremenFetchErpPoolFromDb();
  409. }
  410. /**
  411. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  412. *
  413. * @param array<string, mixed> $row
  414. */
  415. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  416. {
  417. $t = $this->procuremenRowListSortTime($row, $primary);
  418. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  419. return null;
  420. }
  421. $mo = (int)$m[2];
  422. if ($mo < 1 || $mo > 12) {
  423. return null;
  424. }
  425. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  426. }
  427. /**
  428. * @param array<int, array{year:string, months:array}> $sidebar
  429. * @return array<int, array{year:string, months:array}>
  430. */
  431. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  432. {
  433. $ym = trim($ym);
  434. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  435. return $sidebar;
  436. }
  437. foreach ($sidebar as $block) {
  438. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  439. continue;
  440. }
  441. foreach ($block['months'] as $item) {
  442. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  443. return $sidebar;
  444. }
  445. }
  446. }
  447. $y = substr($ym, 0, 4);
  448. $mo = (int)substr($ym, 5, 2);
  449. $sidebar[] = [
  450. 'year' => $y,
  451. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  452. ];
  453. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  454. }
  455. /**
  456. * @param array<int, array{year:string, months:array}> $sidebar
  457. * @return string[]
  458. */
  459. protected function flattenProcuremenSidebarYms(array $sidebar): array
  460. {
  461. $yms = [];
  462. foreach ($sidebar as $block) {
  463. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  464. continue;
  465. }
  466. foreach ($block['months'] as $item) {
  467. if (!is_array($item)) {
  468. continue;
  469. }
  470. $ym = trim((string)($item['ym'] ?? ''));
  471. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  472. $yms[$ym] = true;
  473. }
  474. }
  475. }
  476. return array_keys($yms);
  477. }
  478. /**
  479. * 左侧菜单(协助初选:Redis/ERP 工序按提交日期分组;与列表月份筛选字段一致)
  480. */
  481. protected function GetIndexYearMonths()
  482. {
  483. $ymSet = [];
  484. $pool = $this->procuremenEnsureRedisPool();
  485. foreach ($pool as $r) {
  486. if (!is_array($r)) {
  487. continue;
  488. }
  489. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  490. if ($ym !== null) {
  491. $ymSet[$ym] = true;
  492. }
  493. }
  494. foreach ($this->loadPickManualOrderRows() as $r) {
  495. if (!is_array($r)) {
  496. continue;
  497. }
  498. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  499. if ($ym !== null) {
  500. $ymSet[$ym] = true;
  501. }
  502. }
  503. $ymList = array_keys($ymSet);
  504. if ($ymList === []) {
  505. $ymList[] = $this->resolveProcuremenDefaultYm('pick');
  506. }
  507. return $this->buildYearMonthSidebar($ymList);
  508. }
  509. /**
  510. * @param string[] $ymList 形如 2026-06
  511. * @return array<int, array{year:string, months:array}>
  512. */
  513. protected function buildYearMonthSidebar(array $ymList): array
  514. {
  515. rsort($ymList, SORT_STRING);
  516. $byYear = [];
  517. foreach ($ymList as $ym) {
  518. $y = substr($ym, 0, 4);
  519. $mo = (int)substr($ym, 5, 2);
  520. if (!isset($byYear[$y])) {
  521. $byYear[$y] = [];
  522. }
  523. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  524. }
  525. krsort($byYear, SORT_NUMERIC);
  526. foreach ($byYear as $y => $items) {
  527. usort($byYear[$y], function ($a, $b) {
  528. return strcmp($b['ym'], $a['ym']);
  529. });
  530. }
  531. $sidebar = [];
  532. foreach ($byYear as $y => $months) {
  533. $sidebar[] = ['year' => $y, 'months' => $months];
  534. }
  535. return $sidebar;
  536. }
  537. /**
  538. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  539. */
  540. protected function GetIssuedOrderYearMonths(string $stage): array
  541. {
  542. $ymSet = [];
  543. try {
  544. $query = Db::table('purchase_order');
  545. $this->applyPurchaseOrderNotDeletedWhere($query);
  546. if ($stage === 'audit') {
  547. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  548. } elseif ($stage === 'confirm') {
  549. $this->applyPurchaseOrderConfirmStageWhere($query);
  550. } else {
  551. return $this->GetIndexYearMonths();
  552. }
  553. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  554. if (is_array($rows)) {
  555. foreach ($rows as $r) {
  556. if (!is_array($r)) {
  557. continue;
  558. }
  559. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  560. if ($ym !== null) {
  561. $ymSet[$ym] = true;
  562. }
  563. }
  564. }
  565. } catch (\Throwable $e) {
  566. $ymSet = [];
  567. }
  568. $ymList = array_keys($ymSet);
  569. if ($ymList === []) {
  570. $def = $this->resolveProcuremenDefaultYm($stage);
  571. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  572. }
  573. return $this->buildYearMonthSidebar($ymList);
  574. }
  575. /**
  576. * 列表默认月份:已下发类取最近有数据的月份,初选仍用当月
  577. */
  578. protected function resolveProcuremenDefaultYm(string $stage): string
  579. {
  580. if ($stage === 'pick') {
  581. return date('Y-m');
  582. }
  583. try {
  584. $query = Db::table('purchase_order');
  585. $this->applyPurchaseOrderNotDeletedWhere($query);
  586. if ($stage === 'audit') {
  587. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  588. } elseif ($stage === 'confirm') {
  589. $this->applyPurchaseOrderConfirmStageWhere($query);
  590. } else {
  591. return date('Y-m');
  592. }
  593. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  594. if ($latest === null || $latest === '') {
  595. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  596. }
  597. $t = $this->formatProcuremenDetailTime($latest);
  598. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  599. return $m[1] . '-' . $m[2];
  600. }
  601. } catch (\Throwable $e) {
  602. }
  603. return date('Y-m');
  604. }
  605. protected function applyPurchaseOrderNotDeletedWhere($query): void
  606. {
  607. $query->whereRaw(
  608. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  609. );
  610. }
  611. /**
  612. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  613. */
  614. protected function applyPurchaseOrderConfirmStageWhere($query): void
  615. {
  616. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  617. $quoted = [];
  618. foreach ($vals as $v) {
  619. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  620. }
  621. if ($quoted === []) {
  622. $query->whereRaw('1 = 0');
  623. return;
  624. }
  625. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  626. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  627. }
  628. /**
  629. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  630. *
  631. * @param array<string, mixed> $row
  632. * @return array<string, mixed>
  633. */
  634. protected function normalizePurchaseOrderListTimeRow(array $row): array
  635. {
  636. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  637. $pick = trim((string)($row['pick_time'] ?? ''));
  638. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  639. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  640. $t = trim((string)($row[$key] ?? ''));
  641. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  642. $row['pick_time'] = $t;
  643. break;
  644. }
  645. }
  646. }
  647. return $row;
  648. }
  649. /**
  650. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  651. */
  652. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  653. {
  654. if (!in_array($stage, ['audit', 'confirm'], true)) {
  655. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  656. }
  657. if ($pool === []) {
  658. $def = $this->resolveProcuremenDefaultYm($stage);
  659. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  660. }
  661. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  662. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  663. return false;
  664. }
  665. $monthStart = $ym . '-01 00:00:00';
  666. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  667. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  668. return $probe !== [];
  669. };
  670. if ($tryYm($requestedYm)) {
  671. return $requestedYm;
  672. }
  673. $fallback = $this->resolveProcuremenDefaultYm($stage);
  674. if ($tryYm($fallback)) {
  675. return $fallback;
  676. }
  677. $bestYm = '';
  678. $bestTime = '';
  679. foreach ($pool as $row) {
  680. if (!is_array($row)) {
  681. continue;
  682. }
  683. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  684. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  685. continue;
  686. }
  687. $ymRow = $m[1];
  688. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  689. $bestTime = $t;
  690. $bestYm = $ymRow;
  691. }
  692. }
  693. if ($bestYm !== '') {
  694. return $bestYm;
  695. }
  696. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  697. }
  698. protected function isPurchaseOrderDetailVoid(array $row): bool
  699. {
  700. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  701. return true;
  702. }
  703. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  704. }
  705. /**
  706. * 仅当前有效下发明细(排除废弃归档)
  707. */
  708. protected function applyActivePurchaseOrderDetailWhere($query): void
  709. {
  710. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  711. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  712. }
  713. /**
  714. * @param array<string, mixed> $detailRow
  715. */
  716. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  717. {
  718. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  719. return false;
  720. }
  721. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  722. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  723. }
  724. /**
  725. * 废弃退回初选:下发明细标记归档,不物理删除
  726. *
  727. * @param array<int, int|string> $scydgyIds
  728. */
  729. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  730. {
  731. $ids = [];
  732. foreach ($scydgyIds as $sid) {
  733. $n = (int)$sid;
  734. if ($this->isValidScydgyRowId($n) || $n < 0) {
  735. $ids[$n] = true;
  736. }
  737. }
  738. if ($ids === []) {
  739. return;
  740. }
  741. $void = ProcuremenStatus::POD_VOID;
  742. Db::table('purchase_order_detail')
  743. ->where('scydgy_id', 'in', array_keys($ids))
  744. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  745. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  746. ->update([
  747. 'status' => $void,
  748. 'status_name' => $void,
  749. ]);
  750. }
  751. /**
  752. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  753. */
  754. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  755. {
  756. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  757. $norm = function (string $col) use ($p): string {
  758. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  759. };
  760. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  761. $parts = [];
  762. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  763. if ($key === 'createtime') {
  764. $parts[] = $createtime;
  765. } else {
  766. $parts[] = $norm($key);
  767. }
  768. }
  769. return 'COALESCE(' . implode(', ', $parts) . ')';
  770. }
  771. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  772. {
  773. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  774. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  775. }
  776. /**
  777. * @return array<int, array<string, mixed>>
  778. */
  779. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  780. {
  781. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  782. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  783. try {
  784. $query = Db::table('purchase_order')->field($fields);
  785. $this->applyPurchaseOrderNotDeletedWhere($query);
  786. if ($stage === 'audit') {
  787. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  788. } elseif ($stage === 'confirm') {
  789. $this->applyPurchaseOrderConfirmStageWhere($query);
  790. } else {
  791. return [];
  792. }
  793. $query->order('pick_time', 'desc')->order('id', 'desc');
  794. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  795. $monthStart = $ym . '-01 00:00:00';
  796. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  797. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  798. }
  799. $rows = $query->select();
  800. } catch (\Throwable $e) {
  801. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  802. $rows = [];
  803. }
  804. return is_array($rows) ? $rows : [];
  805. }
  806. /**
  807. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  808. */
  809. protected function resolveProcuremenListStage(): string
  810. {
  811. $tab = trim((string)$this->request->request('wff_tab', ''));
  812. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  813. return $tab;
  814. }
  815. $action = strtolower((string)$this->request->action());
  816. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  817. return $action;
  818. }
  819. return 'pick';
  820. }
  821. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  822. {
  823. $rootTrue = rtrim((string)$this->request->root(true), '/');
  824. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  825. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  826. $indexPhpRoot = $rootTrue . '/index.php';
  827. }
  828. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  829. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  830. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  831. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  832. $this->view->assign('defaultYm', $defaultYm);
  833. $this->view->assign('sidebarYearMonths', $sidebar);
  834. $this->view->assign('procuremenStage', $stage);
  835. $this->view->assign('procuremenPageTitle', $pageTitle);
  836. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  837. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  838. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  839. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  840. }
  841. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  842. public function pick()
  843. {
  844. $this->request->filter(['strip_tags', 'trim']);
  845. if (!$this->request->isAjax()) {
  846. $this->assignProcuremenListPage('pick', '协助下发');
  847. return $this->view->fetch('procuremen/index');
  848. }
  849. return $this->index();
  850. }
  851. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  852. public function audit()
  853. {
  854. $this->request->filter(['strip_tags', 'trim']);
  855. if (!$this->request->isAjax()) {
  856. $this->assignProcuremenListPage('audit', '确认供应商');
  857. return $this->view->fetch('procuremen/index');
  858. }
  859. return $this->index();
  860. }
  861. /** 采购确认(定标) */
  862. public function confirm()
  863. {
  864. $this->request->filter(['strip_tags', 'trim']);
  865. if (!$this->request->isAjax()) {
  866. $this->assignProcuremenListPage('confirm', '采购确认');
  867. return $this->view->fetch('procuremen/index');
  868. }
  869. return $this->index();
  870. }
  871. /**
  872. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  873. */
  874. public function index()
  875. {
  876. $this->request->filter(['strip_tags', 'trim']);
  877. if (!$this->request->isAjax()) {
  878. $this->assignProcuremenListPage('pick', '协助下发');
  879. return $this->view->fetch('procuremen/index');
  880. }
  881. if ($this->request->request('keyField')) {
  882. return $this->selectpage();
  883. }
  884. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  885. $limit = max(10, min(500, (int)$limit));
  886. $ym = $this->request->request('ym', '');
  887. $ym = is_string($ym) ? trim($ym) : '';
  888. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  889. $wffTab = $this->resolveProcuremenListStage();
  890. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  891. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  892. ? $this->resolveProcuremenDefaultYm($wffTab)
  893. : date('Y-m');
  894. }
  895. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  896. $ym = date('Y-m');
  897. }
  898. $monthStart = $ym . '-01 00:00:00';
  899. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  900. $search = trim((string)$this->request->get('search', ''));
  901. $hasActiveSearch = ($search !== '');
  902. if (!$hasActiveSearch) {
  903. $filterStr = $this->request->get('filter', '');
  904. if ($filterStr !== '' && $filterStr !== '[]' && $filterStr !== '{}') {
  905. $arr = json_decode($filterStr, true);
  906. if (is_array($arr) && count($arr) > 0) {
  907. foreach ($arr as $v) {
  908. if (is_array($v)) {
  909. if (array_filter($v, function ($x) {
  910. return $x !== '' && $x !== null;
  911. })) {
  912. $hasActiveSearch = true;
  913. break;
  914. }
  915. } elseif ($v !== '' && $v !== null) {
  916. $hasActiveSearch = true;
  917. break;
  918. }
  919. }
  920. }
  921. }
  922. }
  923. $applyMonthRange = !$hasActiveSearch;
  924. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  925. $opArr = (array)json_decode($this->request->get('op', ''), true);
  926. try {
  927. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  928. if ($wffTab === 'audit') {
  929. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  930. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  931. );
  932. } elseif ($wffTab === 'confirm') {
  933. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  934. if ($dbRows === []) {
  935. try {
  936. $dbRows = Db::table('purchase_order')
  937. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,'
  938. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  939. ->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%\')')
  940. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  941. ->order('pick_time', 'desc')->order('id', 'desc')
  942. ->select();
  943. } catch (\Throwable $e) {
  944. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  945. $dbRows = [];
  946. }
  947. }
  948. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  949. if ($pool === []) {
  950. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  951. }
  952. } else {
  953. $pool = $this->procuremenEnsureRedisPool();
  954. if (!is_array($pool)) {
  955. $pool = [];
  956. }
  957. // 下发列表:已通知供应商(有明细)或已进入审核/确认/完结的工序不再显示
  958. $hideSet = $this->loadPickHiddenScydgySet();
  959. if ($pool !== [] && $hideSet !== []) {
  960. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  961. if (!is_array($r)) {
  962. return false;
  963. }
  964. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  965. return $id <= 0 || !isset($hideSet[$id]);
  966. }));
  967. }
  968. $manualPool = $this->loadPickManualOrderRows();
  969. if ($manualPool !== []) {
  970. $pool = array_merge($pool, $manualPool);
  971. }
  972. if ($pool === []) {
  973. return json([
  974. 'total' => 0,
  975. 'rows' => [],
  976. ]);
  977. }
  978. }
  979. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  980. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  981. $monthStart = $ym . '-01 00:00:00';
  982. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  983. }
  984. $filtered = $this->filterProcuremenIndexPool(
  985. $pool,
  986. $monthStart,
  987. $monthEnd,
  988. $applyMonthRange,
  989. $search,
  990. $filterArr,
  991. $opArr,
  992. $listTimePrimary
  993. );
  994. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  995. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  996. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  997. }
  998. $sortField = 'ID';
  999. if (is_string($sort) && $sort !== '') {
  1000. $parts = explode(',', $sort);
  1001. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1002. if ($sortField === '') {
  1003. $sortField = 'ID';
  1004. }
  1005. }
  1006. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1007. $nFiltered = count($filtered);
  1008. if ($nFiltered > 1) {
  1009. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1010. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1011. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1012. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1013. if ($ta === $tb) {
  1014. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1015. }
  1016. if ($ta === '') {
  1017. return 1;
  1018. }
  1019. if ($tb === '') {
  1020. return -1;
  1021. }
  1022. return strcmp($ta, $tb) * $ord;
  1023. });
  1024. } elseif ($sortField === 'ID') {
  1025. $sortKeys = [];
  1026. foreach ($filtered as $i => $row) {
  1027. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1028. }
  1029. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1030. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1031. } elseif ($sortField === 'CCYDH') {
  1032. usort($filtered, function ($a, $b) use ($ord) {
  1033. $sa = trim((string)($a['CCYDH'] ?? ''));
  1034. $sb = trim((string)($b['CCYDH'] ?? ''));
  1035. if ($sa === $sb) {
  1036. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1037. }
  1038. if ($sa === '') {
  1039. return 1;
  1040. }
  1041. if ($sb === '') {
  1042. return -1;
  1043. }
  1044. return strcmp($sa, $sb) * $ord;
  1045. });
  1046. } else {
  1047. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1048. $va = $a[$sortField] ?? null;
  1049. $vb = $b[$sortField] ?? null;
  1050. $sa = (string)$va;
  1051. $sb = (string)$vb;
  1052. if ($sa === $sb) {
  1053. return 0;
  1054. }
  1055. return strcmp($sa, $sb) * $ord;
  1056. });
  1057. }
  1058. }
  1059. $offset = max(0, (int)$offset);
  1060. $limit = max(1, (int)$limit);
  1061. $rows = array_slice($filtered, $offset, $limit);
  1062. foreach ($rows as &$rw) {
  1063. if (!is_array($rw)) {
  1064. continue;
  1065. }
  1066. $rid = (int)($rw['ID'] ?? 0);
  1067. $rw['_iss_out'] = ($wffTab !== 'pick');
  1068. }
  1069. unset($rw);
  1070. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1071. $idList = [];
  1072. foreach ($rows as $rw) {
  1073. if (!is_array($rw)) {
  1074. continue;
  1075. }
  1076. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1077. foreach ($rw['_order_merge_rows'] as $mr) {
  1078. $mid = (int)($mr['ID'] ?? 0);
  1079. if ($this->isValidScydgyRowId($mid)) {
  1080. $idList[$mid] = true;
  1081. }
  1082. }
  1083. }
  1084. $id = (int)($rw['ID'] ?? 0);
  1085. if ($this->isValidScydgyRowId($id)) {
  1086. $idList[$id] = true;
  1087. }
  1088. }
  1089. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1090. foreach ($rows as &$rw) {
  1091. if (!is_array($rw)) {
  1092. continue;
  1093. }
  1094. $mergeIds = [];
  1095. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1096. foreach ($rw['_order_merge_rows'] as $mr) {
  1097. $mid = (int)($mr['ID'] ?? 0);
  1098. if ($this->isValidScydgyRowId($mid)) {
  1099. $mergeIds[$mid] = true;
  1100. }
  1101. }
  1102. }
  1103. $rid = (int)($rw['ID'] ?? 0);
  1104. if ($this->isValidScydgyRowId($rid)) {
  1105. $mergeIds[$rid] = true;
  1106. }
  1107. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1108. $rw['po_detail_count'] = $s['cnt'];
  1109. $rw['po_amount_fill_cnt'] = $s['amt'];
  1110. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1111. }
  1112. unset($rw);
  1113. }
  1114. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1115. $idList = [];
  1116. foreach ($rows as $rw) {
  1117. if (!is_array($rw)) {
  1118. continue;
  1119. }
  1120. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1121. foreach ($rw['_order_merge_rows'] as $mr) {
  1122. $mid = (int)($mr['ID'] ?? 0);
  1123. if ($this->isValidScydgyRowId($mid)) {
  1124. $idList[$mid] = true;
  1125. }
  1126. }
  1127. }
  1128. $id = (int)($rw['ID'] ?? 0);
  1129. if ($this->isValidScydgyRowId($id)) {
  1130. $idList[$id] = true;
  1131. }
  1132. }
  1133. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1134. $bidOpenSet = [];
  1135. if ($wffTab === 'audit') {
  1136. $ccydhList = [];
  1137. foreach ($rows as $rw0) {
  1138. if (!is_array($rw0)) {
  1139. continue;
  1140. }
  1141. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1142. if ($c0 !== '') {
  1143. $ccydhList[] = $c0;
  1144. }
  1145. }
  1146. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1147. }
  1148. foreach ($rows as &$rw) {
  1149. if (!is_array($rw)) {
  1150. continue;
  1151. }
  1152. $mergeIds = [];
  1153. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1154. foreach ($rw['_order_merge_rows'] as $mr) {
  1155. $mid = (int)($mr['ID'] ?? 0);
  1156. if ($this->isValidScydgyRowId($mid)) {
  1157. $mergeIds[$mid] = true;
  1158. }
  1159. }
  1160. }
  1161. $rid = (int)($rw['ID'] ?? 0);
  1162. if ($this->isValidScydgyRowId($rid)) {
  1163. $mergeIds[$rid] = true;
  1164. }
  1165. $buckets = [];
  1166. foreach (array_keys($mergeIds) as $mid) {
  1167. if (isset($quoteBucket[$mid])) {
  1168. $buckets[] = $quoteBucket[$mid];
  1169. }
  1170. }
  1171. $supplierText = $buckets !== []
  1172. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1173. : '';
  1174. if ($wffTab === 'confirm') {
  1175. $rw['picked_supplier_name'] = $supplierText;
  1176. } else {
  1177. $rw['notify_supplier_text'] = $supplierText;
  1178. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1179. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1180. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1181. $rw['bid_open_status_text'] = $verified ? '已开标' : '待开标';
  1182. }
  1183. }
  1184. unset($rw);
  1185. }
  1186. if ($wffTab === 'all' && count($rows) > 0) {
  1187. $this->mergePurchaseOrder($rows);
  1188. }
  1189. if ($wffTab === 'pick' && count($rows) > 0) {
  1190. $this->mergePurchaseOrder($rows);
  1191. }
  1192. foreach ($rows as &$rwClean) {
  1193. if (is_array($rwClean)) {
  1194. unset($rwClean['_order_merge_rows']);
  1195. if (array_key_exists('NGZL', $rwClean)) {
  1196. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1197. }
  1198. }
  1199. }
  1200. unset($rwClean);
  1201. return json([
  1202. 'total' => count($filtered),
  1203. 'rows' => $rows,
  1204. 'activeYm' => $ym,
  1205. ]);
  1206. } catch (\Throwable $e) {
  1207. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1208. return json([
  1209. 'total' => 0,
  1210. 'rows' => [],
  1211. ]);
  1212. }
  1213. }
  1214. /**
  1215. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1216. *
  1217. * @return array<int, true>
  1218. */
  1219. protected function loadPickHiddenScydgySet(): array
  1220. {
  1221. if ($this->pickHiddenScydgySetCache !== null) {
  1222. return $this->pickHiddenScydgySetCache;
  1223. }
  1224. $hideSet = [];
  1225. try {
  1226. $poIds = Db::table('purchase_order')
  1227. ->where(function ($q) {
  1228. $q->whereIn('wflow_status', array_merge(
  1229. ProcuremenStatus::wflowPendingConfirmValues(),
  1230. ProcuremenStatus::wflowPendingApprovalValues()
  1231. ))
  1232. ->whereOr(function ($q1) {
  1233. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1234. })
  1235. ->whereOr(function ($q2) {
  1236. $q2->whereNotNull('pick_time')
  1237. ->where('pick_time', '<>', '')
  1238. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1239. })
  1240. ->whereOr(function ($q3) {
  1241. $q3->whereNotNull('mod_rq')
  1242. ->where('mod_rq', '<>', '')
  1243. ->where('mod_rq', 'not like', '0000-00-00%');
  1244. });
  1245. })
  1246. ->column('scydgy_id');
  1247. if (is_array($poIds)) {
  1248. foreach ($poIds as $pid) {
  1249. $k = (int)$pid;
  1250. if ($k !== 0) {
  1251. $hideSet[$k] = true;
  1252. }
  1253. }
  1254. }
  1255. } catch (\Throwable $e) {
  1256. }
  1257. try {
  1258. $detIdsQuery = Db::table('purchase_order_detail');
  1259. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1260. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1261. if (is_array($detIds)) {
  1262. foreach ($detIds as $pid) {
  1263. $k = (int)$pid;
  1264. if ($this->isValidScydgyRowId($k)) {
  1265. $hideSet[$k] = true;
  1266. }
  1267. }
  1268. }
  1269. } catch (\Throwable $e) {
  1270. }
  1271. $this->pickHiddenScydgySetCache = $hideSet;
  1272. return $hideSet;
  1273. }
  1274. /**
  1275. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1276. *
  1277. * @return array<int, array<string, mixed>>
  1278. */
  1279. protected function loadPickManualOrderRows(): array
  1280. {
  1281. try {
  1282. $dbRows = Db::table('purchase_order')
  1283. ->where('scydgy_id', '<', 0)
  1284. ->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%\')')
  1285. ->order('scydgy_id', 'asc')
  1286. ->select();
  1287. } catch (\Throwable $e) {
  1288. try {
  1289. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1290. } catch (\Throwable $e2) {
  1291. return [];
  1292. }
  1293. }
  1294. if (!is_array($dbRows) || $dbRows === []) {
  1295. return [];
  1296. }
  1297. $detailSidSet = [];
  1298. try {
  1299. $negIds = [];
  1300. foreach ($dbRows as $dbRow) {
  1301. if (!is_array($dbRow)) {
  1302. continue;
  1303. }
  1304. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1305. if ($sid < 0) {
  1306. $negIds[$sid] = true;
  1307. }
  1308. }
  1309. if ($negIds !== []) {
  1310. $detQuery = Db::table('purchase_order_detail')
  1311. ->where('scydgy_id', 'in', array_keys($negIds));
  1312. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  1313. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  1314. if (is_array($detRows)) {
  1315. foreach ($detRows as $did) {
  1316. $detailSidSet[(int)$did] = true;
  1317. }
  1318. }
  1319. }
  1320. } catch (\Throwable $e) {
  1321. }
  1322. $pool = [];
  1323. foreach ($dbRows as $dbRow) {
  1324. if (!is_array($dbRow)) {
  1325. continue;
  1326. }
  1327. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1328. if ($sid >= 0) {
  1329. continue;
  1330. }
  1331. $wf = ProcuremenStatus::normalizeWflowStatus($dbRow['wflow_status'] ?? '');
  1332. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  1333. continue;
  1334. }
  1335. $st = ProcuremenStatus::normalizePoStatus($dbRow['status'] ?? '');
  1336. if ($st === ProcuremenStatus::PO_COMPLETED || $st === ProcuremenStatus::PO_IN_PROGRESS) {
  1337. continue;
  1338. }
  1339. if (isset($detailSidSet[$sid])) {
  1340. continue;
  1341. }
  1342. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  1343. $r['_is_manual'] = 1;
  1344. $pool[] = $r;
  1345. }
  1346. return $pool;
  1347. }
  1348. /**
  1349. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  1350. */
  1351. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  1352. {
  1353. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  1354. foreach ($keys as $k) {
  1355. $t = trim((string)($row[$k] ?? ''));
  1356. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1357. return $t;
  1358. }
  1359. }
  1360. return '';
  1361. }
  1362. /**
  1363. * 分配手工新增工序行 ID(负数递减)
  1364. */
  1365. protected function allocateManualScydgyId(): int
  1366. {
  1367. try {
  1368. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  1369. $min = (int)$min;
  1370. return $min < 0 ? $min - 1 : -1;
  1371. } catch (\Throwable $e) {
  1372. return -1;
  1373. }
  1374. }
  1375. /**
  1376. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  1377. */
  1378. protected function allocateManualOrderCcydh(): string
  1379. {
  1380. $prefix = 'YW' . date('Ymd');
  1381. $maxSeq = 0;
  1382. try {
  1383. $rows = Db::table('purchase_order')
  1384. ->where('CCYDH', 'like', $prefix . '%')
  1385. ->column('CCYDH');
  1386. if (is_array($rows)) {
  1387. foreach ($rows as $ccydh) {
  1388. $ccydh = trim((string)$ccydh);
  1389. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  1390. $maxSeq = max($maxSeq, (int)$m[1]);
  1391. }
  1392. }
  1393. }
  1394. } catch (\Throwable $e) {
  1395. }
  1396. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  1397. }
  1398. /**
  1399. * purchase_order.mod_rq 是否有有效软删除时间
  1400. */
  1401. protected function isPurchaseOrderSoftDeleted($modRq): bool
  1402. {
  1403. $t = trim((string)$modRq);
  1404. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  1405. }
  1406. /**
  1407. * 列表行 → purchase_order 写入字段
  1408. *
  1409. * @return array<string, mixed>
  1410. */
  1411. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  1412. {
  1413. return [
  1414. 'scydgy_id' => $scydgyId,
  1415. 'CCYDH' => $row['CCYDH'] ?? null,
  1416. 'CYJMC' => $row['CYJMC'] ?? null,
  1417. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  1418. 'CDXMC' => $row['CDXMC'] ?? null,
  1419. 'CGYBH' => $row['CGYBH'] ?? null,
  1420. 'CGYMC' => $row['CGYMC'] ?? null,
  1421. 'CDW' => $row['CDW'] ?? null,
  1422. 'NGZL' => $row['NGZL'] ?? null,
  1423. 'CDF' => $row['CDF'] ?? null,
  1424. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  1425. 'MBZ' => $row['MBZ'] ?? null,
  1426. 'bwjg' => $row['bwjg'] ?? null,
  1427. 'iStatus' => $row['iStatus'] ?? null,
  1428. 'dStamp' => $row['dStamp'] ?? null,
  1429. 'dputrecord' => $row['dputrecord'] ?? null,
  1430. 'cywyxm' => $row['cywyxm'] ?? null,
  1431. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  1432. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  1433. ];
  1434. }
  1435. /**
  1436. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  1437. *
  1438. * @return array{po:?array<string,mixed>, hidden:bool}
  1439. */
  1440. protected function resolvePickRowPoContext(int $sid): array
  1441. {
  1442. $po = null;
  1443. try {
  1444. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1445. if (is_array($found)) {
  1446. $po = $found;
  1447. }
  1448. } catch (\Throwable $e) {
  1449. }
  1450. $hideSet = $this->loadPickHiddenScydgySet();
  1451. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  1452. }
  1453. /**
  1454. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  1455. */
  1456. protected function assertPickRowCanDelete(int $sid, array $row): void
  1457. {
  1458. $ctx = $this->resolvePickRowPoContext($sid);
  1459. $po = $ctx['po'];
  1460. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1461. return;
  1462. }
  1463. if (is_array($po)) {
  1464. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1465. throw new \InvalidArgumentException('该工序已完结,无法删除');
  1466. }
  1467. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1468. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  1469. }
  1470. }
  1471. if ($ctx['hidden']) {
  1472. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  1473. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  1474. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  1475. }
  1476. }
  1477. /**
  1478. * 初选直接完结前校验
  1479. */
  1480. protected function assertPickRowCanComplete(int $sid, array $row): void
  1481. {
  1482. $ctx = $this->resolvePickRowPoContext($sid);
  1483. $po = $ctx['po'];
  1484. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  1485. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  1486. }
  1487. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1488. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  1489. }
  1490. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  1491. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  1492. }
  1493. }
  1494. /**
  1495. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  1496. */
  1497. protected function softDeleteProcuremenPickRow(array $row): void
  1498. {
  1499. $sid = $this->extractScydgyRowId($row);
  1500. if (!$this->isValidScydgyRowId($sid)) {
  1501. throw new \InvalidArgumentException('无效的行主键');
  1502. }
  1503. $this->assertPickRowCanDelete($sid, $row);
  1504. $po = $this->resolvePickRowPoContext($sid)['po'];
  1505. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  1506. return;
  1507. }
  1508. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  1509. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  1510. }
  1511. $now = date('Y-m-d H:i:s');
  1512. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1513. if (is_array($exists)) {
  1514. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  1515. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  1516. } else {
  1517. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  1518. $data['mod_rq'] = $now;
  1519. $data['createtime'] = $now;
  1520. Db::table('purchase_order')->insert($data);
  1521. $poIdLog = (int)Db::getLastInsID();
  1522. }
  1523. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  1524. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  1525. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  1526. if ($gymcLog !== '') {
  1527. $logTail .= ' / ' . $gymcLog;
  1528. }
  1529. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  1530. }
  1531. /**
  1532. * 手工新增协助工序(写入 purchase_order)
  1533. *
  1534. * @param array<string, mixed> $params
  1535. * @return int scydgy_id
  1536. */
  1537. protected function saveManualPickOrder(array $params): int
  1538. {
  1539. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  1540. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  1541. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  1542. if ($ccydh === '') {
  1543. $ccydh = $this->allocateManualOrderCcydh();
  1544. }
  1545. $now = date('Y-m-d H:i:s');
  1546. $sid = $this->allocateManualScydgyId();
  1547. $data = [
  1548. 'scydgy_id' => $sid,
  1549. 'CCYDH' => $ccydh,
  1550. 'CYJMC' => $cyjmc,
  1551. 'CGYMC' => $cgymc,
  1552. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  1553. 'CDW' => trim((string)($params['CDW'] ?? '')),
  1554. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  1555. 'CDF' => trim((string)($params['CDF'] ?? '')),
  1556. 'cGzzxMc' => trim((string)($params['cGzzxMc'] ?? '')),
  1557. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  1558. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  1559. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  1560. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  1561. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  1562. 'createtime' => $now,
  1563. 'dStamp' => $now,
  1564. 'dputrecord' => $now,
  1565. ];
  1566. Db::table('purchase_order')->insert($data);
  1567. $poId = (int)Db::getLastInsID();
  1568. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  1569. return $sid;
  1570. }
  1571. protected function formatProcuremenRowLabel(array $row): string
  1572. {
  1573. $dh = trim((string)($row['CCYDH'] ?? ''));
  1574. $gymc = trim((string)($row['CGYMC'] ?? ''));
  1575. if ($dh !== '' && $gymc !== '') {
  1576. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  1577. }
  1578. if ($dh !== '') {
  1579. return '订单「' . $dh . '」';
  1580. }
  1581. if ($gymc !== '') {
  1582. return '工序「' . $gymc . '」';
  1583. }
  1584. $id = $this->extractScydgyRowId($row);
  1585. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  1586. }
  1587. /**
  1588. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  1589. */
  1590. protected function extractScydgyRowId(array $row): int
  1591. {
  1592. return (int)($row['ID'] ?? $row['id'] ?? $row['scydgy_id'] ?? 0);
  1593. }
  1594. protected function isValidScydgyRowId(int $id): bool
  1595. {
  1596. return ProcuremenGuard::isValidScydgyId($id);
  1597. }
  1598. protected function isManualScydgyRowId(int $id): bool
  1599. {
  1600. return $id < 0;
  1601. }
  1602. /**
  1603. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  1604. *
  1605. * @param int[] $scydgyIds
  1606. * @return array<int, string[]>
  1607. */
  1608. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  1609. {
  1610. $out = [];
  1611. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1612. if ($scydgyIds === []) {
  1613. return $out;
  1614. }
  1615. try {
  1616. $rows = Db::table('purchase_order_detail')
  1617. ->where('scydgy_id', 'in', $scydgyIds)
  1618. ->field('scydgy_id,company_name')
  1619. ->order('company_name', 'asc')
  1620. ->select();
  1621. } catch (\Throwable $e) {
  1622. $rows = [];
  1623. }
  1624. if (!is_array($rows)) {
  1625. return $out;
  1626. }
  1627. foreach ($rows as $r) {
  1628. if (!is_array($r)) {
  1629. continue;
  1630. }
  1631. $sid = (int)($r['scydgy_id'] ?? 0);
  1632. $cn = trim((string)($r['company_name'] ?? ''));
  1633. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1634. continue;
  1635. }
  1636. if (!isset($out[$sid])) {
  1637. $out[$sid] = [];
  1638. }
  1639. if (!in_array($cn, $out[$sid], true)) {
  1640. $out[$sid][] = $cn;
  1641. }
  1642. }
  1643. return $out;
  1644. }
  1645. /**
  1646. * 列表展示通知供应商(完整列表,前端单行省略展开)
  1647. *
  1648. * @param string[] $names
  1649. */
  1650. protected function formatNotifySupplierDisplay(array $names): string
  1651. {
  1652. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  1653. return trim((string)$n);
  1654. }, $names))));
  1655. if ($names === []) {
  1656. return '';
  1657. }
  1658. sort($names, SORT_STRING);
  1659. return implode("\n", $names);
  1660. }
  1661. /**
  1662. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  1663. *
  1664. * @param int[] $scydgyIds
  1665. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  1666. */
  1667. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  1668. {
  1669. $out = [];
  1670. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  1671. if ($scydgyIds === []) {
  1672. return $out;
  1673. }
  1674. try {
  1675. $rows = Db::table('purchase_order_detail')
  1676. ->where('scydgy_id', 'in', $scydgyIds)
  1677. ->field('scydgy_id,company_name,amount')
  1678. ->select();
  1679. } catch (\Throwable $e) {
  1680. $rows = [];
  1681. }
  1682. if (!is_array($rows)) {
  1683. return $out;
  1684. }
  1685. foreach ($rows as $r) {
  1686. if (!is_array($r)) {
  1687. continue;
  1688. }
  1689. $sid = (int)($r['scydgy_id'] ?? 0);
  1690. $cn = trim((string)($r['company_name'] ?? ''));
  1691. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  1692. continue;
  1693. }
  1694. if (!isset($out[$sid])) {
  1695. $out[$sid] = ['all' => [], 'quoted' => []];
  1696. }
  1697. $out[$sid]['all'][$cn] = true;
  1698. $am = trim((string)($r['amount'] ?? ''));
  1699. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  1700. $out[$sid]['quoted'][$cn] = true;
  1701. }
  1702. }
  1703. return $out;
  1704. }
  1705. /**
  1706. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  1707. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  1708. */
  1709. protected function mergeQuotedSupplierBuckets(array $buckets): array
  1710. {
  1711. $merged = ['all' => [], 'quoted' => []];
  1712. foreach ($buckets as $b) {
  1713. if (!is_array($b)) {
  1714. continue;
  1715. }
  1716. foreach ($b['all'] ?? [] as $cn => $_) {
  1717. $merged['all'][$cn] = true;
  1718. }
  1719. foreach ($b['quoted'] ?? [] as $cn => $_) {
  1720. $merged['quoted'][$cn] = true;
  1721. }
  1722. }
  1723. return $merged;
  1724. }
  1725. /**
  1726. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  1727. */
  1728. protected function formatQuotedSupplierLines(array $bucket): string
  1729. {
  1730. $all = array_keys($bucket['all'] ?? []);
  1731. if ($all === []) {
  1732. return '';
  1733. }
  1734. sort($all, SORT_STRING);
  1735. $lines = [];
  1736. foreach ($all as $cn) {
  1737. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  1738. $lines[] = $cn . '(' . $status . ')';
  1739. }
  1740. return implode("\n", $lines);
  1741. }
  1742. /**
  1743. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  1744. */
  1745. protected function resolveBundleSysRq(array $bundle): string
  1746. {
  1747. foreach ($bundle['pos'] ?? [] as $po) {
  1748. if (!is_array($po)) {
  1749. continue;
  1750. }
  1751. $sr = trim((string)($po['sys_rq'] ?? ''));
  1752. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  1753. return $sr;
  1754. }
  1755. }
  1756. return '';
  1757. }
  1758. /**
  1759. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  1760. */
  1761. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  1762. {
  1763. $raw = trim((string)$sysRq);
  1764. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  1765. return true;
  1766. }
  1767. $ts = strtotime(str_replace('T', ' ', $raw));
  1768. if ($ts === false || $ts <= 0) {
  1769. return true;
  1770. }
  1771. return time() >= $ts;
  1772. }
  1773. /**
  1774. * 开标前校验:必须已过报价截止时间
  1775. *
  1776. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  1777. */
  1778. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  1779. {
  1780. $sysRq = $this->resolveBundleSysRq($bundle);
  1781. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  1782. $this->error('未到截止时间');
  1783. }
  1784. }
  1785. /**
  1786. * 截止时间前:隐藏单价/交期真实值,统一展示文案
  1787. *
  1788. * @param array<string, mixed> $line
  1789. */
  1790. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  1791. {
  1792. $amountFilled = !empty($line['amount_filled']);
  1793. $deliveryFilled = !empty($line['delivery_filled']);
  1794. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  1795. $line['amount_show'] = '';
  1796. if (array_key_exists('amount_text', $line)) {
  1797. $line['amount_text'] = $line['unit_price_text'];
  1798. }
  1799. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  1800. $line['delivery_show'] = $deliveryText;
  1801. if (array_key_exists('delivery_text', $line)) {
  1802. $line['delivery_text'] = $deliveryText;
  1803. }
  1804. $line['delivery_ymd'] = '';
  1805. $line['subtotal_text'] = $amountFilled ? '' : '';
  1806. $line['subtotal_num'] = null;
  1807. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  1808. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  1809. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled) ? 1 : 0;
  1810. $line['amount_filled'] = false;
  1811. $line['delivery_filled'] = false;
  1812. $line['is_quoted'] = false;
  1813. if (array_key_exists('quote_label', $line)) {
  1814. $line['quote_label'] = ($amountFilled || $deliveryFilled) ? '未开标验证' : '未报价';
  1815. }
  1816. }
  1817. protected function ensurePurchaseOrderBidOpenTable(): void
  1818. {
  1819. try {
  1820. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  1821. } catch (\Throwable $e) {
  1822. Db::execute(
  1823. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  1824. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  1825. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  1826. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  1827. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  1828. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  1829. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  1830. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  1831. `operator_name` varchar(64) NOT NULL DEFAULT '',
  1832. `createtime` datetime DEFAULT NULL,
  1833. PRIMARY KEY (`id`),
  1834. UNIQUE KEY `uk_ccydh` (`ccydh`)
  1835. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  1836. );
  1837. }
  1838. }
  1839. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  1840. {
  1841. $ccydh = trim($ccydh);
  1842. if ($ccydh === '') {
  1843. return false;
  1844. }
  1845. $this->ensurePurchaseOrderBidOpenTable();
  1846. try {
  1847. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  1848. return is_array($row);
  1849. } catch (\Throwable $e) {
  1850. return false;
  1851. }
  1852. }
  1853. /**
  1854. * 批量查询订单是否已开标验证
  1855. *
  1856. * @param array<int, string> $ccydhs
  1857. * @return array<string, bool> ccydh => true
  1858. */
  1859. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  1860. {
  1861. $set = [];
  1862. $list = [];
  1863. foreach ($ccydhs as $c) {
  1864. $c = trim((string)$c);
  1865. if ($c !== '') {
  1866. $list[$c] = true;
  1867. }
  1868. }
  1869. if ($list === []) {
  1870. return $set;
  1871. }
  1872. $this->ensurePurchaseOrderBidOpenTable();
  1873. try {
  1874. $rows = Db::table('purchase_order_bid_open')
  1875. ->where('ccydh', 'in', array_keys($list))
  1876. ->field('ccydh')
  1877. ->select();
  1878. foreach ($rows as $row) {
  1879. if (!is_array($row)) {
  1880. continue;
  1881. }
  1882. $c = trim((string)($row['ccydh'] ?? ''));
  1883. if ($c !== '') {
  1884. $set[$c] = true;
  1885. }
  1886. }
  1887. } catch (\Throwable $e) {
  1888. return [];
  1889. }
  1890. return $set;
  1891. }
  1892. /**
  1893. * 未开标验证时掩码供应商备注(与单价/交货日期一致)
  1894. *
  1895. * @param array<string, mixed> $group
  1896. */
  1897. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  1898. {
  1899. $remarkRaw = trim((string)($group['remark'] ?? ''));
  1900. if ($quoteVisible || $remarkRaw === '') {
  1901. $group['remark_quote_pending'] = 0;
  1902. return;
  1903. }
  1904. $group['remark'] = '开标验证后查看';
  1905. $group['remark_quote_pending'] = 1;
  1906. }
  1907. /**
  1908. * @param array{ccydh?:string} $bundle
  1909. */
  1910. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  1911. {
  1912. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  1913. }
  1914. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  1915. {
  1916. return $this->isProcuremenBidOpenVerifiedForBundle($bundle);
  1917. }
  1918. protected function loadBidOpenAdminUser(int $adminId): ?array
  1919. {
  1920. if ($adminId <= 0) {
  1921. return null;
  1922. }
  1923. try {
  1924. $row = Db::name('admin')->where('id', $adminId)->find();
  1925. } catch (\Throwable $e) {
  1926. return null;
  1927. }
  1928. if (!is_array($row)) {
  1929. return null;
  1930. }
  1931. $status = strtolower(trim((string)($row['status'] ?? '')));
  1932. if ($status !== '' && $status !== 'normal') {
  1933. return null;
  1934. }
  1935. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  1936. return null;
  1937. }
  1938. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  1939. if (!preg_match('/^1\d{10}$/', $phone)) {
  1940. return null;
  1941. }
  1942. $name = trim((string)($row['nickname'] ?? ''));
  1943. if ($name === '') {
  1944. $name = trim((string)($row['username'] ?? ''));
  1945. }
  1946. return [
  1947. 'id' => (int)$row['id'],
  1948. 'username' => trim((string)($row['username'] ?? '')),
  1949. 'nickname' => $name,
  1950. 'mobile' => $phone,
  1951. ];
  1952. }
  1953. /**
  1954. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  1955. */
  1956. protected function bidOpenVerifierAuthGroupRootId(): int
  1957. {
  1958. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  1959. return $id > 0 ? $id : 10;
  1960. }
  1961. /**
  1962. * @return int[]
  1963. */
  1964. protected function loadBidOpenVerifierAuthGroupIds(): array
  1965. {
  1966. static $memo = [];
  1967. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  1968. if (isset($memo[$rootId])) {
  1969. return $memo[$rootId];
  1970. }
  1971. try {
  1972. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  1973. } catch (\Throwable $e) {
  1974. $memo[$rootId] = [$rootId];
  1975. return $memo[$rootId];
  1976. }
  1977. if (!is_array($groups) || $groups === []) {
  1978. $memo[$rootId] = [$rootId];
  1979. return $memo[$rootId];
  1980. }
  1981. $groupList = [];
  1982. foreach ($groups as $g) {
  1983. if (is_array($g)) {
  1984. $groupList[] = $g;
  1985. }
  1986. }
  1987. if ($groupList === []) {
  1988. $memo[$rootId] = [$rootId];
  1989. return $memo[$rootId];
  1990. }
  1991. $tree = \fast\Tree::instance();
  1992. $tree->init($groupList);
  1993. $ids = $tree->getChildrenIds($rootId, true);
  1994. if (!is_array($ids) || $ids === []) {
  1995. $memo[$rootId] = [$rootId];
  1996. return $memo[$rootId];
  1997. }
  1998. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  1999. return $memo[$rootId];
  2000. }
  2001. protected function isBidOpenVerifierAdmin(int $adminId): bool
  2002. {
  2003. if ($adminId <= 0) {
  2004. return false;
  2005. }
  2006. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2007. if ($groupIds === []) {
  2008. return false;
  2009. }
  2010. try {
  2011. return (bool)Db::name('auth_group_access')
  2012. ->where('uid', $adminId)
  2013. ->where('group_id', 'in', $groupIds)
  2014. ->count();
  2015. } catch (\Throwable $e) {
  2016. return false;
  2017. }
  2018. }
  2019. /**
  2020. * @return array<int, array<string, mixed>>
  2021. */
  2022. protected function listBidOpenVerifierCandidates(): array
  2023. {
  2024. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2025. if ($groupIds === []) {
  2026. return [];
  2027. }
  2028. try {
  2029. $adminIds = Db::name('auth_group_access')
  2030. ->where('group_id', 'in', $groupIds)
  2031. ->column('uid');
  2032. } catch (\Throwable $e) {
  2033. $adminIds = [];
  2034. }
  2035. $adminIds = is_array($adminIds)
  2036. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  2037. : [];
  2038. if ($adminIds === []) {
  2039. return [];
  2040. }
  2041. try {
  2042. $rows = Db::name('admin')
  2043. ->where('status', 'normal')
  2044. ->where('id', 'in', $adminIds)
  2045. ->where('mobile', '<>', '')
  2046. ->order('id', 'asc')
  2047. ->select();
  2048. } catch (\Throwable $e) {
  2049. return [];
  2050. }
  2051. if (!is_array($rows)) {
  2052. return [];
  2053. }
  2054. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  2055. $out = [];
  2056. foreach ($rows as $row) {
  2057. if (!is_array($row)) {
  2058. continue;
  2059. }
  2060. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  2061. if ($one === null) {
  2062. continue;
  2063. }
  2064. $out[] = [
  2065. 'id' => $one['id'],
  2066. 'username' => $one['username'],
  2067. 'nickname' => $one['nickname'],
  2068. 'group_name' => $groupNameMap[$one['id']] ?? '',
  2069. 'mobile' => mask_phone($one['mobile']),
  2070. ];
  2071. }
  2072. return $out;
  2073. }
  2074. /**
  2075. * @param int[] $adminIds
  2076. * @return array<int, string>
  2077. */
  2078. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  2079. {
  2080. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  2081. if ($adminIds === []) {
  2082. return [];
  2083. }
  2084. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2085. try {
  2086. $rows = Db::name('auth_group_access')
  2087. ->alias('aga')
  2088. ->join('auth_group ag', 'aga.group_id = ag.id')
  2089. ->where('aga.uid', 'in', $adminIds)
  2090. ->where('aga.group_id', 'in', $groupIds)
  2091. ->field('aga.uid,ag.name')
  2092. ->order('aga.uid', 'asc')
  2093. ->order('aga.group_id', 'asc')
  2094. ->select();
  2095. } catch (\Throwable $e) {
  2096. return [];
  2097. }
  2098. if (!is_array($rows)) {
  2099. return [];
  2100. }
  2101. $out = [];
  2102. foreach ($rows as $row) {
  2103. if (!is_array($row)) {
  2104. continue;
  2105. }
  2106. $uid = (int)($row['uid'] ?? 0);
  2107. $name = trim((string)($row['name'] ?? ''));
  2108. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  2109. continue;
  2110. }
  2111. $out[$uid] = $name;
  2112. }
  2113. return $out;
  2114. }
  2115. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  2116. {
  2117. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  2118. }
  2119. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  2120. {
  2121. return 'procuremen_bidopen_wait_' . $adminId;
  2122. }
  2123. protected function renderBidOpenVerifySms(string $code): string
  2124. {
  2125. $tpl = '';
  2126. try {
  2127. $row = $this->loadNotifyTemplateRow('bid_open');
  2128. if (is_array($row)) {
  2129. $tpl = trim((string)($row['content'] ?? ''));
  2130. }
  2131. } catch (\Throwable $e) {
  2132. $tpl = '';
  2133. }
  2134. if ($tpl === '') {
  2135. $tpl = '【可集达】您的短信验证码是{code}';
  2136. }
  2137. return str_replace('{code}', $code, $tpl);
  2138. }
  2139. protected function sendBidOpenVerifySms(string $phone, string $code): void
  2140. {
  2141. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  2142. }
  2143. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  2144. {
  2145. $code = trim($code);
  2146. if (!preg_match('/^\d{6}$/', $code)) {
  2147. return false;
  2148. }
  2149. $mock = Config::get('mproc.mock_sms_code');
  2150. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  2151. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2152. return true;
  2153. }
  2154. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2155. if ($cached === false || $cached === null || (string)$cached !== $code) {
  2156. return false;
  2157. }
  2158. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  2159. return true;
  2160. }
  2161. /**
  2162. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2163. */
  2164. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  2165. {
  2166. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2167. if ($ccydh === '') {
  2168. throw new \InvalidArgumentException('订单号无效');
  2169. }
  2170. $this->ensurePurchaseOrderBidOpenTable();
  2171. list($operatorId, $operatorName) = $this->GetUseName();
  2172. $now = date('Y-m-d H:i:s');
  2173. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2174. $payload = [
  2175. 'ccydh' => $ccydh,
  2176. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  2177. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  2178. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  2179. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  2180. 'operator_id' => (int)$operatorId,
  2181. 'operator_name' => trim((string)$operatorName),
  2182. 'createtime' => $now,
  2183. ];
  2184. if (is_array($exists)) {
  2185. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  2186. } else {
  2187. Db::table('purchase_order_bid_open')->insert($payload);
  2188. }
  2189. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  2190. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  2191. $orderPart = '(订单' . $ccydh . ')';
  2192. $logMsg = '开标验证' . $orderPart . ':' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证,可查看供应商报价信息';
  2193. $seenSid = [];
  2194. foreach ($bundle['pos'] ?? [] as $poRow) {
  2195. if (!is_array($poRow)) {
  2196. continue;
  2197. }
  2198. $sid = (int)($poRow['scydgy_id'] ?? 0);
  2199. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  2200. continue;
  2201. }
  2202. $seenSid[$sid] = true;
  2203. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  2204. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  2205. }
  2206. if ($seenSid === []) {
  2207. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  2208. if ($this->isValidScydgyRowId($anchor)) {
  2209. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  2210. }
  2211. }
  2212. }
  2213. /**
  2214. * 报价行展示字段默认值(模板安全访问)
  2215. *
  2216. * @param array<string, mixed> $line
  2217. * @return array<string, mixed>
  2218. */
  2219. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  2220. {
  2221. if (!array_key_exists('amount_quote_pending', $line)) {
  2222. $line['amount_quote_pending'] = 0;
  2223. }
  2224. if (!array_key_exists('delivery_quote_pending', $line)) {
  2225. $line['delivery_quote_pending'] = 0;
  2226. }
  2227. if (!array_key_exists('quote_before_deadline', $line)) {
  2228. $line['quote_before_deadline'] = 0;
  2229. }
  2230. if (!array_key_exists('amount_filled', $line)) {
  2231. $line['amount_filled'] = 0;
  2232. }
  2233. if (!array_key_exists('delivery_filled', $line)) {
  2234. $line['delivery_filled'] = 0;
  2235. }
  2236. return $line;
  2237. }
  2238. /**
  2239. * 审核弹窗:按供应商汇总报价明细
  2240. *
  2241. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2242. * @return array<int, array<string, mixed>>
  2243. */
  2244. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  2245. {
  2246. $sids = [];
  2247. foreach ($bundle['pos'] ?? [] as $po) {
  2248. if (!is_array($po)) {
  2249. continue;
  2250. }
  2251. $sid = (int)($po['scydgy_id'] ?? 0);
  2252. if ($this->isValidScydgyRowId($sid)) {
  2253. $sids[$sid] = true;
  2254. }
  2255. }
  2256. if ($sids === []) {
  2257. return [];
  2258. }
  2259. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2260. $gymcMap = [];
  2261. $qtyBySid = [];
  2262. $orderedSids = [];
  2263. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2264. if (!is_array($mr)) {
  2265. continue;
  2266. }
  2267. $gid = $this->extractScydgyRowId($mr);
  2268. if ($this->isValidScydgyRowId($gid)) {
  2269. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2270. $orderedSids[] = $gid;
  2271. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2272. if ($qty === '') {
  2273. $qty = trim((string)($mr['NGZL'] ?? ''));
  2274. }
  2275. $qtyBySid[$gid] = $qty;
  2276. }
  2277. }
  2278. foreach ($bundle['pos'] ?? [] as $po) {
  2279. if (!is_array($po)) {
  2280. continue;
  2281. }
  2282. $gid = (int)($po['scydgy_id'] ?? 0);
  2283. if ($this->isValidScydgyRowId($gid)) {
  2284. $nm = trim((string)($po['CGYMC'] ?? ''));
  2285. if ($nm !== '') {
  2286. $gymcMap[$gid] = $nm;
  2287. }
  2288. if (!in_array($gid, $orderedSids, true)) {
  2289. $orderedSids[] = $gid;
  2290. }
  2291. }
  2292. }
  2293. try {
  2294. $detailsQuery = Db::table('purchase_order_detail')
  2295. ->where('scydgy_id', 'in', array_keys($sids));
  2296. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2297. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  2298. } catch (\Throwable $e) {
  2299. try {
  2300. $detailsQuery = Db::table('purchase_order_detail')
  2301. ->where('scydgy_id', 'in', array_keys($sids));
  2302. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  2303. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  2304. } catch (\Throwable $e2) {
  2305. $details = [];
  2306. }
  2307. }
  2308. if (!is_array($details)) {
  2309. $details = [];
  2310. }
  2311. $byCompany = [];
  2312. foreach ($details as $d) {
  2313. if (!is_array($d)) {
  2314. continue;
  2315. }
  2316. $cn = trim((string)($d['company_name'] ?? ''));
  2317. if ($cn === '') {
  2318. continue;
  2319. }
  2320. if (!isset($byCompany[$cn])) {
  2321. $ph = trim((string)($d['phone'] ?? ''));
  2322. $username = trim((string)($d['username'] ?? ''));
  2323. if ($username === '') {
  2324. $username = $this->resolveCustomerContactName($ph, $cn);
  2325. }
  2326. $byCompany[$cn] = [
  2327. 'name' => $cn,
  2328. 'email' => trim((string)($d['email'] ?? '')),
  2329. 'phone' => $ph,
  2330. 'username' => $username,
  2331. 'remark' => '',
  2332. 'has_quote' => false,
  2333. 'lines_map' => [],
  2334. ];
  2335. }
  2336. if ($byCompany[$cn]['remark'] === '') {
  2337. $rm = '';
  2338. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2339. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2340. $rm = trim((string)$d[$rk]);
  2341. break;
  2342. }
  2343. }
  2344. if ($rm !== '') {
  2345. $byCompany[$cn]['remark'] = $rm;
  2346. }
  2347. }
  2348. $sid = (int)($d['scydgy_id'] ?? 0);
  2349. $am = trim((string)($d['amount'] ?? ''));
  2350. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2351. if ($gymc === '') {
  2352. $gymc = '工序';
  2353. }
  2354. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2355. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2356. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2357. $deliveryShow = $deliveryRaw;
  2358. }
  2359. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2360. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2361. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2362. $subtotal = null;
  2363. if ($amountNum !== null) {
  2364. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2365. }
  2366. $unitPriceText = $amountFilled
  2367. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2368. : '未填写';
  2369. $lineRow = [
  2370. 'cgymc' => $gymc,
  2371. 'amount' => $am,
  2372. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  2373. 'amount_filled' => $amountFilled,
  2374. 'unit_price_text' => $unitPriceText,
  2375. 'delivery' => $deliveryRaw,
  2376. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  2377. 'delivery_filled' => $deliveryFilled,
  2378. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  2379. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2380. 'subtotal_num' => $subtotal,
  2381. 'status_name' => trim((string)($d['status_name'] ?? '')),
  2382. 'is_quoted' => $amountFilled,
  2383. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  2384. ];
  2385. if (!$quoteVisible) {
  2386. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  2387. }
  2388. // 按工序 id 暂存,下面再按上方工序表顺序输出
  2389. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  2390. }
  2391. foreach ($byCompany as $cn => $g) {
  2392. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  2393. $lines = [];
  2394. $usedSids = [];
  2395. foreach ($orderedSids as $sid) {
  2396. if (!isset($linesMap[$sid])) {
  2397. continue;
  2398. }
  2399. $lines[] = $linesMap[$sid];
  2400. $usedSids[$sid] = true;
  2401. }
  2402. foreach ($linesMap as $sid => $ln) {
  2403. if (isset($usedSids[$sid])) {
  2404. continue;
  2405. }
  2406. $lines[] = $ln;
  2407. }
  2408. $total = count($lines);
  2409. $quoted = 0;
  2410. $groupTotal = 0.0;
  2411. $groupHasTotal = false;
  2412. if ($quoteVisible) {
  2413. foreach ($lines as $ln) {
  2414. $am = trim((string)($ln['amount'] ?? ''));
  2415. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2416. $quoted++;
  2417. }
  2418. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2419. $groupTotal += (float)$ln['subtotal_num'];
  2420. $groupHasTotal = true;
  2421. }
  2422. }
  2423. }
  2424. unset($byCompany[$cn]['lines_map']);
  2425. $byCompany[$cn]['lines'] = $lines;
  2426. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  2427. $byCompany[$cn]['line_count'] = $total;
  2428. $byCompany[$cn]['has_total'] = $total > 0;
  2429. $byCompany[$cn]['has_remark'] = $total > 0;
  2430. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  2431. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2432. // 工序行 + 备注行 + 总计行
  2433. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  2434. }
  2435. return array_values($byCompany);
  2436. }
  2437. /**
  2438. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  2439. *
  2440. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  2441. * @return array<int, array<string, mixed>>
  2442. */
  2443. protected function loadConfirmSupplierPickGroups(array $bundle): array
  2444. {
  2445. $sids = [];
  2446. $poIdMap = [];
  2447. foreach ($bundle['pos'] ?? [] as $po) {
  2448. if (!is_array($po)) {
  2449. continue;
  2450. }
  2451. $sid = (int)($po['scydgy_id'] ?? 0);
  2452. if ($this->isValidScydgyRowId($sid)) {
  2453. $sids[$sid] = true;
  2454. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  2455. }
  2456. }
  2457. if ($sids === []) {
  2458. return [];
  2459. }
  2460. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  2461. $gymcMap = [];
  2462. $qtyBySid = [];
  2463. $orderedSids = [];
  2464. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  2465. if (!is_array($mr)) {
  2466. continue;
  2467. }
  2468. $gid = $this->extractScydgyRowId($mr);
  2469. if ($this->isValidScydgyRowId($gid)) {
  2470. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  2471. $orderedSids[] = $gid;
  2472. $qty = trim((string)($mr['This_quantity'] ?? ''));
  2473. if ($qty === '') {
  2474. $qty = trim((string)($mr['NGZL'] ?? ''));
  2475. }
  2476. $qtyBySid[$gid] = $qty;
  2477. }
  2478. }
  2479. foreach ($bundle['pos'] ?? [] as $po) {
  2480. if (!is_array($po)) {
  2481. continue;
  2482. }
  2483. $gid = (int)($po['scydgy_id'] ?? 0);
  2484. if ($this->isValidScydgyRowId($gid)) {
  2485. $nm = trim((string)($po['CGYMC'] ?? ''));
  2486. if ($nm !== '') {
  2487. $gymcMap[$gid] = $nm;
  2488. }
  2489. }
  2490. }
  2491. try {
  2492. $details = Db::table('purchase_order_detail')
  2493. ->where('scydgy_id', 'in', array_keys($sids))
  2494. ->order('company_name', 'asc')
  2495. ->order('id', 'asc')
  2496. ->select();
  2497. } catch (\Throwable $e) {
  2498. try {
  2499. $details = Db::table('purchase_order_detail')
  2500. ->where('scydgy_id', 'in', array_keys($sids))
  2501. ->order('company_name', 'asc')
  2502. ->order('ID', 'asc')
  2503. ->select();
  2504. } catch (\Throwable $e2) {
  2505. $details = [];
  2506. }
  2507. }
  2508. if (!is_array($details)) {
  2509. $details = [];
  2510. }
  2511. $byCompany = [];
  2512. foreach ($details as $d) {
  2513. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2514. continue;
  2515. }
  2516. $cn = trim((string)($d['company_name'] ?? ''));
  2517. if ($cn === '') {
  2518. continue;
  2519. }
  2520. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  2521. $sid = (int)($d['scydgy_id'] ?? 0);
  2522. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  2523. continue;
  2524. }
  2525. if (!isset($byCompany[$cn])) {
  2526. $ph = trim((string)($d['phone'] ?? ''));
  2527. $username = trim((string)($d['username'] ?? ''));
  2528. if ($username === '') {
  2529. $username = $this->resolveCustomerContactName($ph, $cn);
  2530. }
  2531. $byCompany[$cn] = [
  2532. 'name' => $cn,
  2533. 'email' => trim((string)($d['email'] ?? '')),
  2534. 'phone' => $ph,
  2535. 'username' => $username,
  2536. 'remark' => '',
  2537. 'pick_lines' => [],
  2538. 'detail_picks' => [],
  2539. ];
  2540. }
  2541. if ($byCompany[$cn]['remark'] === '') {
  2542. $rm = '';
  2543. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  2544. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  2545. $rm = trim((string)$d[$rk]);
  2546. break;
  2547. }
  2548. }
  2549. if ($rm !== '') {
  2550. $byCompany[$cn]['remark'] = $rm;
  2551. }
  2552. }
  2553. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  2554. if ($gymc === '') {
  2555. $gymc = '工序';
  2556. }
  2557. $am = trim((string)($d['amount'] ?? ''));
  2558. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  2559. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  2560. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  2561. if ($deliveryShow === '' && $deliveryRaw !== '') {
  2562. $deliveryShow = $deliveryRaw;
  2563. }
  2564. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  2565. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  2566. $subtotal = null;
  2567. if ($amountNum !== null) {
  2568. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  2569. }
  2570. $unitPriceText = $amountFilled
  2571. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  2572. : '未填写';
  2573. $pickLine = [
  2574. 'cgymc' => $gymc,
  2575. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  2576. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  2577. 'amount_filled' => $amountFilled,
  2578. 'delivery_filled' => $deliveryFilled,
  2579. 'unit_price_text' => $unitPriceText,
  2580. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  2581. 'subtotal_num' => $subtotal,
  2582. 'is_quoted' => $amountFilled,
  2583. ];
  2584. if (!$quoteVisible) {
  2585. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  2586. }
  2587. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  2588. $byCompany[$cn]['detail_picks'][$sid] = [
  2589. 'scydgy_id' => $sid,
  2590. 'detail_id' => $detailId,
  2591. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  2592. 'cgymc' => $gymc,
  2593. ];
  2594. }
  2595. $out = [];
  2596. foreach ($byCompany as $g) {
  2597. $pickLinesMap = $g['pick_lines'] ?? [];
  2598. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  2599. continue;
  2600. }
  2601. $pickLines = [];
  2602. $usedLineSids = [];
  2603. foreach ($orderedSids as $sid) {
  2604. if (!isset($pickLinesMap[$sid])) {
  2605. continue;
  2606. }
  2607. $pickLines[] = $pickLinesMap[$sid];
  2608. $usedLineSids[$sid] = true;
  2609. }
  2610. foreach ($pickLinesMap as $sid => $ln) {
  2611. if (isset($usedLineSids[$sid])) {
  2612. continue;
  2613. }
  2614. $pickLines[] = $ln;
  2615. }
  2616. $groupTotal = 0.0;
  2617. $groupHasTotal = false;
  2618. if ($quoteVisible) {
  2619. foreach ($pickLines as $ln) {
  2620. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  2621. $groupTotal += (float)$ln['subtotal_num'];
  2622. $groupHasTotal = true;
  2623. }
  2624. }
  2625. }
  2626. $lineCount = count($pickLines);
  2627. $g['pick_lines'] = $pickLines;
  2628. $g['line_count'] = $lineCount;
  2629. $g['has_total'] = $lineCount > 0;
  2630. $g['has_remark'] = $lineCount > 0;
  2631. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  2632. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  2633. // 工序行 + 备注行 + 总计行
  2634. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  2635. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  2636. $detailPicks = [];
  2637. $usedPickSids = [];
  2638. foreach ($orderedSids as $sid) {
  2639. if (!isset($detailPicksMap[$sid])) {
  2640. continue;
  2641. }
  2642. $detailPicks[] = $detailPicksMap[$sid];
  2643. $usedPickSids[$sid] = true;
  2644. }
  2645. foreach ($detailPicksMap as $sid => $dp) {
  2646. if (isset($usedPickSids[$sid])) {
  2647. continue;
  2648. }
  2649. $detailPicks[] = $dp;
  2650. }
  2651. $g['detail_picks'] = $detailPicks;
  2652. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  2653. unset($g['detail_picks']);
  2654. $out[] = $g;
  2655. }
  2656. return $out;
  2657. }
  2658. /**
  2659. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  2660. * @return array<int, int[]> scydgy_id => detail_id[]
  2661. */
  2662. protected function mapDetailIdsByScydgyId(array $details): array
  2663. {
  2664. $out = [];
  2665. foreach ($details as $d) {
  2666. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  2667. continue;
  2668. }
  2669. $sid = (int)($d['scydgy_id'] ?? 0);
  2670. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  2671. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  2672. continue;
  2673. }
  2674. if (!isset($out[$sid])) {
  2675. $out[$sid] = [];
  2676. }
  2677. $out[$sid][] = $pk;
  2678. }
  2679. foreach ($out as $sid => $ids) {
  2680. $out[$sid] = array_values(array_unique($ids));
  2681. }
  2682. return $out;
  2683. }
  2684. /**
  2685. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  2686. *
  2687. * @param array<string, mixed> $dbRow
  2688. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  2689. */
  2690. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  2691. {
  2692. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2693. $r = [
  2694. 'ID' => $sid,
  2695. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  2696. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  2697. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  2698. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  2699. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  2700. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  2701. 'CDW' => $dbRow['CDW'] ?? '',
  2702. 'NGZL' => $dbRow['NGZL'] ?? '',
  2703. 'CDF' => $dbRow['CDF'] ?? '',
  2704. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  2705. 'MBZ' => $dbRow['MBZ'] ?? '',
  2706. 'bwjg' => $dbRow['bwjg'] ?? '',
  2707. 'iStatus' => $dbRow['iStatus'] ?? '',
  2708. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  2709. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  2710. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  2711. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  2712. 'dStamp' => $dbRow['dStamp'] ?? '',
  2713. 'pick_time' => $dbRow['pick_time'] ?? '',
  2714. ];
  2715. if ($sid > 0 && isset($dStampMap[$sid])) {
  2716. $t = trim((string)$dStampMap[$sid]);
  2717. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2718. $r['dStamp'] = $dStampMap[$sid];
  2719. }
  2720. }
  2721. $dsOut = trim((string)($r['dStamp'] ?? ''));
  2722. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  2723. $ct = $dbRow['createtime'];
  2724. if (is_numeric($ct) && (int)$ct > 946684800) {
  2725. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  2726. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  2727. $r['dStamp'] = trim($ct);
  2728. }
  2729. }
  2730. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  2731. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  2732. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  2733. $fallback = trim((string)($r['dStamp'] ?? ''));
  2734. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  2735. $r['dputrecord'] = $fallback;
  2736. }
  2737. }
  2738. if (array_key_exists('id', $dbRow)) {
  2739. $r['purchase_order_id'] = (int)$dbRow['id'];
  2740. }
  2741. if ($sid < 0) {
  2742. $r['_is_manual'] = 1;
  2743. }
  2744. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  2745. $pickOut = trim((string)($r['pick_time'] ?? ''));
  2746. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  2747. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  2748. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  2749. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  2750. $r['pick_time'] = $pickFallback;
  2751. break;
  2752. }
  2753. }
  2754. }
  2755. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  2756. if ($pickNm !== '') {
  2757. $r['pick_company_name'] = $pickNm;
  2758. $r['picked_supplier_name'] = $pickNm;
  2759. }
  2760. return $r;
  2761. }
  2762. /**
  2763. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  2764. *
  2765. * @return array<int, array<string, mixed>>
  2766. */
  2767. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  2768. {
  2769. $pool = [];
  2770. if (!is_array($dbRows) || $dbRows === []) {
  2771. return $pool;
  2772. }
  2773. $dStampMap = [];
  2774. $sidList = [];
  2775. foreach ($dbRows as $tmpRow) {
  2776. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  2777. $sid = (int)$tmpRow['scydgy_id'];
  2778. if ($sid > 0) {
  2779. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  2780. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2781. $sidList[$sid] = true;
  2782. }
  2783. }
  2784. }
  2785. }
  2786. if ($sidList !== []) {
  2787. try {
  2788. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  2789. } catch (\Throwable $e) {
  2790. $dStampMap = [];
  2791. }
  2792. }
  2793. foreach ($dbRows as $dbRow) {
  2794. if (!is_array($dbRow)) {
  2795. continue;
  2796. }
  2797. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  2798. }
  2799. return $pool;
  2800. }
  2801. /**
  2802. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  2803. *
  2804. * @param int[] $scydgyIds
  2805. * @return array<int, array<string, mixed>>
  2806. */
  2807. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  2808. {
  2809. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2810. if ($scydgyIds === []) {
  2811. return [];
  2812. }
  2813. try {
  2814. $list = Db::table('purchase_order_detail')
  2815. ->where('scydgy_id', 'in', $scydgyIds)
  2816. ->field('scydgy_id,company_name,amount,delivery')
  2817. ->select();
  2818. } catch (\Throwable $e) {
  2819. $list = [];
  2820. }
  2821. return is_array($list) ? $list : [];
  2822. }
  2823. /**
  2824. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  2825. *
  2826. * @param int[] $scydgyIds
  2827. * @param array<int, array<string, mixed>> $allRows
  2828. * @return array{cnt:int, amt:int, deliv:int}
  2829. */
  2830. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  2831. {
  2832. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2833. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2834. if ($scydgyIds === [] || $allRows === []) {
  2835. return $out;
  2836. }
  2837. $idSet = array_flip($scydgyIds);
  2838. $all = [];
  2839. $withAmt = [];
  2840. $withDeliv = [];
  2841. foreach ($allRows as $r) {
  2842. if (!is_array($r)) {
  2843. continue;
  2844. }
  2845. $sid = (int)($r['scydgy_id'] ?? 0);
  2846. if (!isset($idSet[$sid])) {
  2847. continue;
  2848. }
  2849. $cn = trim((string)($r['company_name'] ?? ''));
  2850. if ($cn === '') {
  2851. continue;
  2852. }
  2853. $all[$cn] = true;
  2854. $am = $r['amount'] ?? null;
  2855. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  2856. $withAmt[$cn] = true;
  2857. }
  2858. $dv = $r['delivery'] ?? null;
  2859. if ($dv !== null && trim((string)$dv) !== '') {
  2860. $withDeliv[$cn] = true;
  2861. }
  2862. }
  2863. return [
  2864. 'cnt' => count($all),
  2865. 'amt' => count($withAmt),
  2866. 'deliv' => count($withDeliv),
  2867. ];
  2868. }
  2869. /**
  2870. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  2871. *
  2872. * @param int[] $scydgyIds
  2873. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  2874. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  2875. */
  2876. protected function OrderDetailSummary(array $scydgyIds)
  2877. {
  2878. $out = [];
  2879. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2880. if ($scydgyIds === []) {
  2881. return $out;
  2882. }
  2883. $list = [];
  2884. try {
  2885. $list = Db::table('purchase_order_detail')
  2886. ->where('scydgy_id', 'in', $scydgyIds)
  2887. ->field('id,scydgy_id,amount,delivery')
  2888. ->select();
  2889. } catch (\Throwable $e) {
  2890. $list = [];
  2891. }
  2892. if (!is_array($list)) {
  2893. return $out;
  2894. }
  2895. foreach ($list as $r) {
  2896. if (!is_array($r)) {
  2897. continue;
  2898. }
  2899. $ids = (int)($r['scydgy_id'] ?? 0);
  2900. if (!$this->isValidScydgyRowId($ids)) {
  2901. continue;
  2902. }
  2903. if (!isset($out[$ids])) {
  2904. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  2905. }
  2906. $out[$ids]['cnt']++;
  2907. $am = $r['amount'] ?? null;
  2908. if ($am !== null && $am !== '') {
  2909. if (!(is_string($am) && trim($am) === '')) {
  2910. $out[$ids]['amt']++;
  2911. }
  2912. }
  2913. $dv = $r['delivery'] ?? null;
  2914. if ($dv !== null && trim((string)$dv) !== '') {
  2915. $out[$ids]['deliv']++;
  2916. }
  2917. }
  2918. return $out;
  2919. }
  2920. /**
  2921. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  2922. *
  2923. * @return array
  2924. */
  2925. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  2926. {
  2927. $strContains = function ($haystack, $needle) {
  2928. if ($needle === '') {
  2929. return false;
  2930. }
  2931. $haystack = (string)$haystack;
  2932. if (function_exists('mb_stripos')) {
  2933. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  2934. }
  2935. return stripos($haystack, $needle) !== false;
  2936. };
  2937. $stripAlias = function ($f) {
  2938. return preg_replace('/^[ab]\./i', '', (string)$f);
  2939. };
  2940. $searchColNames = [];
  2941. foreach (explode(',', $this->searchFields) as $colRaw) {
  2942. $c = $stripAlias(trim($colRaw));
  2943. if ($c !== '') {
  2944. $searchColNames[] = $c;
  2945. }
  2946. }
  2947. $filtered = [];
  2948. foreach ($pool as $r) {
  2949. if (!is_array($r)) {
  2950. continue;
  2951. }
  2952. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  2953. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  2954. if (!$isManual) {
  2955. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  2956. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  2957. continue;
  2958. }
  2959. if ($applyMonthRange) {
  2960. $mo = (int)$m[2];
  2961. if ($mo < 1 || $mo > 12) {
  2962. continue;
  2963. }
  2964. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2965. $rowMonthStart = $ymRow . '-01 00:00:00';
  2966. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2967. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2968. continue;
  2969. }
  2970. }
  2971. } elseif ($applyMonthRange) {
  2972. $ds = isset($r['dputrecord']) ? trim((string)$r['dputrecord']) : '';
  2973. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  2974. $ds = $listTime;
  2975. }
  2976. if ($ds === '' || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $ds, $m)) {
  2977. continue;
  2978. }
  2979. $mo = (int)$m[2];
  2980. if ($mo < 1 || $mo > 12) {
  2981. continue;
  2982. }
  2983. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  2984. $rowMonthStart = $ymRow . '-01 00:00:00';
  2985. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  2986. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  2987. continue;
  2988. }
  2989. }
  2990. if ($search !== '') {
  2991. $hitSearch = false;
  2992. foreach ($searchColNames as $c) {
  2993. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  2994. if ($cell !== '' && $strContains($cell, $search)) {
  2995. $hitSearch = true;
  2996. break;
  2997. }
  2998. }
  2999. if (!$hitSearch) {
  3000. continue;
  3001. }
  3002. }
  3003. foreach ($filterArr as $fk => $fv) {
  3004. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  3005. continue;
  3006. }
  3007. if (is_array($fv)) {
  3008. continue;
  3009. }
  3010. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  3011. continue;
  3012. }
  3013. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  3014. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  3015. $field = $stripAlias($fk);
  3016. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  3017. $cellStr = trim((string)$cell);
  3018. switch ($sym) {
  3019. case '=':
  3020. if ((string)$cell !== (string)$fv) {
  3021. continue 3;
  3022. }
  3023. break;
  3024. case '<>':
  3025. if ((string)$cell === (string)$fv) {
  3026. continue 3;
  3027. }
  3028. break;
  3029. case 'LIKE':
  3030. case 'NOT LIKE':
  3031. $needle = trim((string)$fv);
  3032. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  3033. if ($sym === 'LIKE' && !$hit) {
  3034. continue 3;
  3035. }
  3036. if ($sym === 'NOT LIKE' && $hit) {
  3037. continue 3;
  3038. }
  3039. break;
  3040. case '>':
  3041. case '>=':
  3042. case '<':
  3043. case '<=':
  3044. if (!is_numeric($cell) && $cellStr === '') {
  3045. continue 3;
  3046. }
  3047. $cv = is_numeric($cell) ? (float)$cell : (float)$cellStr;
  3048. $vv = (float)$fv;
  3049. if ($sym === '>' && !($cv > $vv)) {
  3050. continue 3;
  3051. }
  3052. if ($sym === '>=' && !($cv >= $vv)) {
  3053. continue 3;
  3054. }
  3055. if ($sym === '<' && !($cv < $vv)) {
  3056. continue 3;
  3057. }
  3058. if ($sym === '<=' && !($cv <= $vv)) {
  3059. continue 3;
  3060. }
  3061. break;
  3062. case 'RANGE':
  3063. case 'NOT RANGE':
  3064. case 'BETWEEN':
  3065. case 'NOT BETWEEN':
  3066. case 'BETWEEN TIME':
  3067. case 'NOT BETWEEN TIME':
  3068. $rawR = is_array($fv) ? implode(',', $fv) : (string)$fv;
  3069. $rawR = str_replace(' - ', ',', $rawR);
  3070. $arr = array_slice(array_map('trim', explode(',', $rawR)), 0, 2);
  3071. if (count($arr) < 2) {
  3072. break;
  3073. }
  3074. $lo = $arr[0];
  3075. $hi = $arr[1];
  3076. if ($lo === '' && $hi === '') {
  3077. break;
  3078. }
  3079. $isNot = (strpos($sym, 'NOT') !== false);
  3080. if ($lo === '') {
  3081. $in = ($cellStr !== '' && $cellStr <= $hi);
  3082. if ($isNot ? $in : !$in) {
  3083. continue 3;
  3084. }
  3085. break;
  3086. }
  3087. if ($hi === '') {
  3088. $in = ($cellStr !== '' && $cellStr >= $lo);
  3089. if ($isNot ? $in : !$in) {
  3090. continue 3;
  3091. }
  3092. break;
  3093. }
  3094. $in = ($cellStr >= $lo && $cellStr <= $hi);
  3095. if ($isNot ? $in : !$in) {
  3096. continue 3;
  3097. }
  3098. break;
  3099. case 'NULL':
  3100. case 'IS NULL':
  3101. if ($cell !== null && $cell !== '') {
  3102. continue 3;
  3103. }
  3104. break;
  3105. case 'NOT NULL':
  3106. case 'IS NOT NULL':
  3107. if ($cell === null || $cell === '') {
  3108. continue 3;
  3109. }
  3110. break;
  3111. default:
  3112. break;
  3113. }
  3114. }
  3115. $filtered[] = $r;
  3116. }
  3117. return $filtered;
  3118. }
  3119. /**
  3120. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  3121. */
  3122. public function snapshotToProcure()
  3123. {
  3124. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3125. $this->error(__('Invalid parameters'));
  3126. }
  3127. $row = json_decode($this->request->post('row_json', ''), true);
  3128. if (!is_array($row)) {
  3129. $this->error(__('Invalid parameters'));
  3130. }
  3131. try {
  3132. $ids = $this->extractScydgyRowId($row);
  3133. if (!$this->isValidScydgyRowId($ids)) {
  3134. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3135. }
  3136. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3137. $data = [
  3138. 'scydgy_id' => $ids,
  3139. 'CCYDH' => $row['CCYDH'] ?? null,
  3140. 'CYJMC' => $row['CYJMC'] ?? null,
  3141. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3142. 'CDXMC' => $row['CDXMC'] ?? null,
  3143. 'CGYBH' => $row['CGYBH'] ?? null,
  3144. 'CGYMC' => $row['CGYMC'] ?? null,
  3145. 'CDW' => $row['CDW'] ?? null,
  3146. 'NGZL' => $row['NGZL'] ?? null,
  3147. 'CDF' => $row['CDF'] ?? null,
  3148. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3149. 'MBZ' => $row['MBZ'] ?? null,
  3150. 'bwjg' => $row['bwjg'] ?? null,
  3151. 'iStatus' => $row['iStatus'] ?? null,
  3152. 'dStamp' => $row['dStamp'] ?? null,
  3153. 'dputrecord' => $row['dputrecord'] ?? null,
  3154. 'cywyxm' => $row['cywyxm'] ?? null,
  3155. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3156. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3157. ];
  3158. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  3159. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  3160. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  3161. $this->success('操作成功');
  3162. return;
  3163. }
  3164. if ($exists) {
  3165. $upd = $data;
  3166. unset($upd['scydgy_id'], $upd['status']);
  3167. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3168. } else {
  3169. // 新增:不写 status(空/走库默认);仅写创建时间
  3170. $data['createtime'] = date('Y-m-d H:i:s');
  3171. Db::table('purchase_order')->insert($data);
  3172. }
  3173. } catch (\Throwable $e) {
  3174. $this->error($e->getMessage());
  3175. }
  3176. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  3177. $this->success('操作成功');
  3178. }
  3179. /**
  3180. * 未发列表
  3181. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  3182. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  3183. */
  3184. public function completeDirectly()
  3185. {
  3186. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3187. $this->error(__('参数错误'));
  3188. }
  3189. if (!$this->procuremenCanComplete()) {
  3190. $this->error(__('You have no permission'));
  3191. }
  3192. $row = json_decode($this->request->post('row_json', ''), true);
  3193. if (!is_array($row)) {
  3194. $this->error(__('Invalid parameters'));
  3195. }
  3196. $finishRaw = $this->request->post('finish', '1');
  3197. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  3198. $poIdLog = null;
  3199. try {
  3200. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  3201. $ids = $this->extractScydgyRowId($row);
  3202. if (!$this->isValidScydgyRowId($ids)) {
  3203. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  3204. }
  3205. if ($asComplete) {
  3206. $this->assertPickRowCanComplete($ids, $row);
  3207. }
  3208. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3209. $data = [
  3210. 'scydgy_id' => $ids,
  3211. 'CCYDH' => $row['CCYDH'] ?? null,
  3212. 'CYJMC' => $row['CYJMC'] ?? null,
  3213. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  3214. 'CDXMC' => $row['CDXMC'] ?? null,
  3215. 'CGYBH' => $row['CGYBH'] ?? null,
  3216. 'CGYMC' => $row['CGYMC'] ?? null,
  3217. 'CDW' => $row['CDW'] ?? null,
  3218. 'NGZL' => $row['NGZL'] ?? null,
  3219. 'CDF' => $row['CDF'] ?? null,
  3220. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  3221. 'MBZ' => $row['MBZ'] ?? null,
  3222. 'bwjg' => $row['bwjg'] ?? null,
  3223. 'iStatus' => $row['iStatus'] ?? null,
  3224. 'dStamp' => $row['dStamp'] ?? null,
  3225. 'dputrecord' => $row['dputrecord'] ?? null,
  3226. 'cywyxm' => $row['cywyxm'] ?? null,
  3227. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  3228. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  3229. ];
  3230. if ($asComplete) {
  3231. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  3232. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  3233. }
  3234. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  3235. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  3236. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  3237. $this->success('操作成功');
  3238. return;
  3239. }
  3240. if ($exists) {
  3241. $upd = $data;
  3242. unset($upd['scydgy_id']);
  3243. if (!$asComplete) {
  3244. unset($upd['status']);
  3245. }
  3246. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  3247. } else {
  3248. // 新增:不写 status;完结时 $data 已含 status=1
  3249. $data['createtime'] = date('Y-m-d H:i:s');
  3250. Db::table('purchase_order')->insert($data);
  3251. }
  3252. } catch (\Throwable $e) {
  3253. $this->error($e->getMessage());
  3254. }
  3255. try {
  3256. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  3257. if (is_array($rpo)) {
  3258. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3259. $poIdLog = $tid > 0 ? $tid : null;
  3260. }
  3261. } catch (\Throwable $e) {
  3262. $poIdLog = null;
  3263. }
  3264. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  3265. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  3266. if ($asComplete) {
  3267. $this->addOrderLog(
  3268. $ids,
  3269. 'mark_complete',
  3270. '点击「完结」,已标记为已完结',
  3271. $poIdLog
  3272. );
  3273. try {
  3274. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  3275. if ($pdfPublicPath === '') {
  3276. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  3277. }
  3278. } catch (\Throwable $e) {
  3279. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  3280. }
  3281. } else {
  3282. $this->addOrderLog(
  3283. $ids,
  3284. 'save_qty_price',
  3285. '保存本次数量、最高限价:本次数量「' . ($q !== '' ? $q : '') . '」,最高限价「' . ($p !== '' ? $p : '') . '」',
  3286. $poIdLog
  3287. );
  3288. }
  3289. $this->pickHiddenScydgySetCache = null;
  3290. $this->success("操作成功");
  3291. }
  3292. /**
  3293. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  3294. *
  3295. * @param array<int, array> $rows 引用传递当前页行
  3296. */
  3297. protected function mergePurchaseOrder(array &$rows)
  3298. {
  3299. if ($rows === []) {
  3300. return;
  3301. }
  3302. $ids = [];
  3303. foreach ($rows as $rw) {
  3304. if (!is_array($rw)) {
  3305. continue;
  3306. }
  3307. $id = (int)($rw['ID'] ?? 0);
  3308. if ($id > 0) {
  3309. $ids[$id] = true;
  3310. }
  3311. }
  3312. $idList = array_keys($ids);
  3313. if ($idList === []) {
  3314. return;
  3315. }
  3316. try {
  3317. $list = Db::table('purchase_order')
  3318. ->where('scydgy_id', 'in', $idList)
  3319. ->field('scydgy_id,This_quantity,ceilingPrice')
  3320. ->select();
  3321. } catch (\Throwable $e) {
  3322. return;
  3323. }
  3324. if (!is_array($list)) {
  3325. return;
  3326. }
  3327. $byId = [];
  3328. foreach ($list as $dbRow) {
  3329. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  3330. continue;
  3331. }
  3332. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  3333. }
  3334. foreach ($rows as &$rw) {
  3335. if (!is_array($rw)) {
  3336. continue;
  3337. }
  3338. $sid = (int)($rw['ID'] ?? 0);
  3339. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  3340. continue;
  3341. }
  3342. $db = $byId[$sid];
  3343. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  3344. if (array_key_exists('This_quantity', $db)) {
  3345. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  3346. }
  3347. if (array_key_exists('ceilingPrice', $db)) {
  3348. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  3349. } elseif (array_key_exists('ceiling_price', $db)) {
  3350. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  3351. }
  3352. }
  3353. unset($rw);
  3354. }
  3355. /**
  3356. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  3357. */
  3358. public function purchaseConfirmPick()
  3359. {
  3360. if (!$this->request->isPost() || !$this->request->isAjax()) {
  3361. $this->error(__('Invalid parameters'));
  3362. }
  3363. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  3364. $this->error(__('You have no permission'));
  3365. }
  3366. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  3367. if ($batchRaw !== '') {
  3368. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  3369. return;
  3370. }
  3371. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  3372. $sid = (int)$scydgyId;
  3373. if (!$this->isValidScydgyRowId($sid)) {
  3374. $this->error('参数无效');
  3375. }
  3376. $parseIdList = function ($raw) {
  3377. if (is_array($raw)) {
  3378. $arr = $raw;
  3379. } else {
  3380. $decoded = json_decode((string)$raw, true);
  3381. $arr = is_array($decoded) ? $decoded : [];
  3382. }
  3383. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  3384. };
  3385. $selectedRaw = $this->request->post('selected_ids', null);
  3386. if ($selectedRaw === null || $selectedRaw === '') {
  3387. $legacy = (int)$this->request->post('selected_id', 0);
  3388. $selectedIds = $legacy > 0 ? [$legacy] : [];
  3389. } else {
  3390. $selectedIds = $parseIdList($selectedRaw);
  3391. }
  3392. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  3393. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  3394. try {
  3395. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  3396. } catch (\InvalidArgumentException $e) {
  3397. $this->error($e->getMessage());
  3398. } catch (\Throwable $e) {
  3399. $this->error($e->getMessage());
  3400. }
  3401. $this->pickHiddenScydgySetCache = null;
  3402. $this->success('操作成功', '', $result);
  3403. }
  3404. /**
  3405. * 整单采购确认(多道工序一次提交)
  3406. */
  3407. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  3408. {
  3409. $decoded = json_decode($batchRaw, true);
  3410. if (!is_array($decoded) || $decoded === []) {
  3411. $this->error('提交数据无效');
  3412. }
  3413. $picks = [];
  3414. foreach ($decoded as $item) {
  3415. if (!is_array($item)) {
  3416. continue;
  3417. }
  3418. $sid = (int)($item['scydgy_id'] ?? 0);
  3419. if (!$this->isValidScydgyRowId($sid)) {
  3420. continue;
  3421. }
  3422. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  3423. if (!is_array($sel)) {
  3424. $sel = [(int)$sel];
  3425. }
  3426. $unsel = $item['unselected_ids'] ?? [];
  3427. if (!is_array($unsel)) {
  3428. $unsel = json_decode((string)$unsel, true);
  3429. $unsel = is_array($unsel) ? $unsel : [];
  3430. }
  3431. $picks[] = [
  3432. 'scydgy_id' => $sid,
  3433. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  3434. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  3435. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  3436. ];
  3437. }
  3438. if ($picks === []) {
  3439. $this->error('提交数据无效');
  3440. }
  3441. Db::startTrans();
  3442. $results = [];
  3443. try {
  3444. foreach ($picks as $pick) {
  3445. $results[] = $this->runPurchaseConfirmPick(
  3446. (int)$pick['scydgy_id'],
  3447. $pick['selected_ids'],
  3448. $pick['unselected_ids'],
  3449. (int)$pick['purchase_order_id'],
  3450. false,
  3451. false
  3452. );
  3453. }
  3454. Db::commit();
  3455. } catch (\Throwable $e) {
  3456. Db::rollback();
  3457. $msg = $e->getMessage();
  3458. $this->error($msg !== '' ? $msg : '提交失败');
  3459. }
  3460. try {
  3461. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  3462. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  3463. } catch (\Throwable $e) {
  3464. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  3465. }
  3466. $this->pickHiddenScydgySetCache = null;
  3467. $this->success('操作成功', '', ['batch' => $results]);
  3468. }
  3469. /**
  3470. * @return array<string, mixed>
  3471. */
  3472. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  3473. {
  3474. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  3475. ProcuremenGuard::assertWflowPendingApproval($poRow);
  3476. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  3477. $scydgyId = (string)$sid;
  3478. if ($selectedIds === []) {
  3479. throw new \InvalidArgumentException('请至少勾选一条明细');
  3480. }
  3481. $inter = array_intersect($selectedIds, $unselectedIds);
  3482. if ($inter !== []) {
  3483. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  3484. }
  3485. $allIds = $this->purchaseOrderDetail($sid);
  3486. if ($allIds === []) {
  3487. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  3488. }
  3489. foreach ($selectedIds as $id) {
  3490. if (!in_array($id, $allIds, true)) {
  3491. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  3492. }
  3493. }
  3494. foreach ($unselectedIds as $id) {
  3495. if (!in_array($id, $allIds, true)) {
  3496. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  3497. }
  3498. }
  3499. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  3500. sort($union, SORT_NUMERIC);
  3501. $expect = $allIds;
  3502. sort($expect, SORT_NUMERIC);
  3503. if ($union !== $expect) {
  3504. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  3505. }
  3506. if ($manageTransaction) {
  3507. Db::startTrans();
  3508. }
  3509. try {
  3510. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  3511. $aff = 0;
  3512. try {
  3513. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3514. } catch (\Throwable $e) {
  3515. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  3516. }
  3517. if ($aff < 1) {
  3518. throw new \Exception('更新选中状态失败');
  3519. }
  3520. $poPayload = [
  3521. 'status' => ProcuremenStatus::PO_COMPLETED,
  3522. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  3523. ];
  3524. if ($purchaseOrderId > 0) {
  3525. $poAff = (int)Db::table('purchase_order')
  3526. ->where('id', $purchaseOrderId)
  3527. ->where('scydgy_id', $sid)
  3528. ->update($poPayload);
  3529. if ($poAff < 1) {
  3530. throw new \Exception('主表订单不存在或与工序行不匹配');
  3531. }
  3532. } else {
  3533. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  3534. if ($poAff < 1) {
  3535. throw new \Exception('未找到');
  3536. }
  3537. }
  3538. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  3539. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  3540. if ($manageTransaction) {
  3541. Db::commit();
  3542. }
  3543. } catch (\Throwable $e) {
  3544. if ($manageTransaction) {
  3545. Db::rollback();
  3546. }
  3547. throw $e;
  3548. }
  3549. $poIdFinal = $purchaseOrderId;
  3550. if ($poIdFinal <= 0) {
  3551. try {
  3552. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3553. if (is_array($rpo)) {
  3554. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  3555. }
  3556. } catch (\Throwable $e) {
  3557. $poIdFinal = 0;
  3558. }
  3559. }
  3560. $pickNames = [];
  3561. foreach ($selectedIds as $pid) {
  3562. $dr = $this->purchaseOrderDetai($sid, $pid);
  3563. $nm = trim((string)($dr['company_name'] ?? ''));
  3564. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  3565. }
  3566. $this->addOrderLog(
  3567. $sid,
  3568. 'purchase_confirm',
  3569. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  3570. $poIdFinal > 0 ? $poIdFinal : null
  3571. );
  3572. if ($sendNotifications) {
  3573. try {
  3574. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  3575. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  3576. 'scydgy_id' => $sid,
  3577. 'selected_ids' => $selectedIds,
  3578. 'unselected_ids' => $unselectedIds,
  3579. 'purchase_order_id' => $purchaseOrderId,
  3580. ]]);
  3581. } catch (\Throwable $e) {
  3582. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  3583. }
  3584. }
  3585. Log::write(sprintf(
  3586. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  3587. $scydgyId,
  3588. $purchaseOrderId,
  3589. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  3590. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  3591. ), 'notice');
  3592. $pdfPublicPath = '';
  3593. try {
  3594. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  3595. } catch (\Throwable $e) {
  3596. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  3597. }
  3598. return [
  3599. 'scydgy_id' => $scydgyId,
  3600. 'purchase_order_id' => $purchaseOrderId,
  3601. 'selected_ids' => $selectedIds,
  3602. 'unselected_ids' => $unselectedIds,
  3603. 'purchase_confirm_pdf' => $pdfPublicPath,
  3604. ];
  3605. }
  3606. /**
  3607. * 审批通过短信:按本次涉及的工序汇总 process_lines
  3608. *
  3609. * @param int[]|string[] $scydgyIds
  3610. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  3611. */
  3612. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  3613. {
  3614. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  3615. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3616. if ($scydgyIds === []) {
  3617. return $empty;
  3618. }
  3619. $pos = [];
  3620. try {
  3621. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  3622. } catch (\Throwable $e) {
  3623. $rows = [];
  3624. }
  3625. if (is_array($rows)) {
  3626. foreach ($rows as $po) {
  3627. if (is_array($po)) {
  3628. $pos[] = $po;
  3629. }
  3630. }
  3631. }
  3632. if ($pos === []) {
  3633. return $empty;
  3634. }
  3635. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  3636. return [
  3637. 'ccydh' => $ccydh,
  3638. 'pos' => $pos,
  3639. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  3640. ];
  3641. }
  3642. /**
  3643. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  3644. *
  3645. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3646. * @param array<int, array<string, mixed>> $picks
  3647. */
  3648. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  3649. {
  3650. if ($picks === []) {
  3651. return;
  3652. }
  3653. $fallbackDetailId = 0;
  3654. $winners = [];
  3655. $losers = [];
  3656. foreach ($picks as $pick) {
  3657. if (!is_array($pick)) {
  3658. continue;
  3659. }
  3660. $sid = (int)($pick['scydgy_id'] ?? 0);
  3661. if (!$this->isValidScydgyRowId($sid)) {
  3662. continue;
  3663. }
  3664. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  3665. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  3666. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  3667. $fallbackDetailId = (int)$selectedIds[0];
  3668. }
  3669. foreach ($selectedIds as $pid) {
  3670. $dr = $this->purchaseOrderDetai($sid, $pid);
  3671. if (!is_array($dr)) {
  3672. continue;
  3673. }
  3674. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  3675. }
  3676. foreach ($unselectedIds as $pid) {
  3677. $dr = $this->purchaseOrderDetai($sid, $pid);
  3678. if (!is_array($dr)) {
  3679. continue;
  3680. }
  3681. $key = $this->notifySupplierDedupeKey($dr);
  3682. if (!isset($winners[$key])) {
  3683. $losers[$key] = $dr;
  3684. }
  3685. }
  3686. }
  3687. if ($winners === [] && $losers === []) {
  3688. return;
  3689. }
  3690. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  3691. $sendSmsSafe = function ($phone, $content) {
  3692. $phone = trim((string)$phone);
  3693. if ($phone === '') {
  3694. return;
  3695. }
  3696. try {
  3697. $this->smsbao($phone, $content);
  3698. } catch (\Throwable $e) {
  3699. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  3700. }
  3701. };
  3702. foreach ($winners as $dr) {
  3703. $cname = trim((string)($dr['company_name'] ?? ''));
  3704. $ph = trim((string)($dr['phone'] ?? ''));
  3705. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  3706. 'company_name' => $cname,
  3707. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3708. 'phone' => $ph,
  3709. ]));
  3710. $sendSmsSafe($ph, $sms);
  3711. }
  3712. foreach ($losers as $dr) {
  3713. $cname = trim((string)($dr['company_name'] ?? ''));
  3714. $ph = trim((string)($dr['phone'] ?? ''));
  3715. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  3716. 'company_name' => $cname,
  3717. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  3718. 'phone' => $ph,
  3719. ]));
  3720. $sendSmsSafe($ph, $sms);
  3721. }
  3722. }
  3723. /**
  3724. * 短信去重键:优先手机号,否则公司名
  3725. */
  3726. protected function notifySupplierDedupeKey(array $detailRow): string
  3727. {
  3728. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  3729. if ($ph !== '') {
  3730. return 'p:' . $ph;
  3731. }
  3732. $cn = trim((string)($detailRow['company_name'] ?? ''));
  3733. return 'c:' . $cn;
  3734. }
  3735. /**
  3736. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  3737. *
  3738. * @param int[] $detailIds
  3739. */
  3740. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  3741. {
  3742. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  3743. if ($detailIds === []) {
  3744. return;
  3745. }
  3746. $payload = ['status_name' => $statusName];
  3747. try {
  3748. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  3749. } catch (\Throwable $e) {
  3750. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  3751. }
  3752. }
  3753. /**
  3754. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  3755. */
  3756. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  3757. {
  3758. try {
  3759. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  3760. } catch (\Throwable $e) {
  3761. return;
  3762. }
  3763. if (!is_array($rows)) {
  3764. return;
  3765. }
  3766. foreach ($rows as $dr) {
  3767. if (!is_array($dr)) {
  3768. continue;
  3769. }
  3770. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  3771. if ($id <= 0) {
  3772. continue;
  3773. }
  3774. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  3775. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  3776. try {
  3777. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  3778. } catch (\Throwable $e) {
  3779. }
  3780. }
  3781. }
  3782. /**
  3783. * @param array<string, mixed> $detailRow
  3784. */
  3785. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  3786. {
  3787. $am = $detailRow['amount'] ?? null;
  3788. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  3789. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  3790. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  3791. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  3792. }
  3793. /**
  3794. * @return int[]
  3795. */
  3796. protected function purchaseOrderDetail(int $scydgyId): array
  3797. {
  3798. if (!$this->isValidScydgyRowId($scydgyId)) {
  3799. return [];
  3800. }
  3801. try {
  3802. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  3803. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  3804. $list = $listQuery->select();
  3805. } catch (\Throwable $e) {
  3806. return [];
  3807. }
  3808. if (!is_array($list)) {
  3809. return [];
  3810. }
  3811. $ids = [];
  3812. foreach ($list as $r) {
  3813. if (!is_array($r)) {
  3814. continue;
  3815. }
  3816. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  3817. if ($pk > 0) {
  3818. $ids[] = $pk;
  3819. }
  3820. }
  3821. return array_values(array_unique($ids));
  3822. }
  3823. /**
  3824. * 获取当前登录用户信息 [id, 展示名]
  3825. */
  3826. protected function GetUseName(): array
  3827. {
  3828. $id = 0;
  3829. $name = '';
  3830. try {
  3831. if ($this->auth && $this->auth->isLogin()) {
  3832. $u = $this->auth->getUserInfo();
  3833. if (is_array($u)) {
  3834. $id = (int)($u['id'] ?? 0);
  3835. $name = trim((string)($u['nickname'] ?? ''));
  3836. if ($name === '') {
  3837. $name = trim((string)($u['username'] ?? ''));
  3838. }
  3839. }
  3840. }
  3841. } catch (\Throwable $e) {
  3842. }
  3843. if ($name === '') {
  3844. $name = '未知用户';
  3845. }
  3846. return [$id, $name];
  3847. }
  3848. /**
  3849. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  3850. */
  3851. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  3852. {
  3853. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  3854. }
  3855. /**
  3856. * 按主键取一条
  3857. */
  3858. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  3859. {
  3860. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  3861. return [];
  3862. }
  3863. try {
  3864. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  3865. if (is_array($one)) {
  3866. return $one;
  3867. }
  3868. } catch (\Throwable $e) {
  3869. }
  3870. try {
  3871. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  3872. if (is_array($one)) {
  3873. return $one;
  3874. }
  3875. } catch (\Throwable $e) {
  3876. }
  3877. return [];
  3878. }
  3879. /**
  3880. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  3881. */
  3882. protected function formatProcuremenDetailTime($v): string
  3883. {
  3884. if ($v === null || $v === '') {
  3885. return '';
  3886. }
  3887. if (is_numeric($v) && (int)$v > 946684800) {
  3888. return date('Y-m-d H:i:s', (int)$v);
  3889. }
  3890. return ProcuremenTime::formatDisplayDateTime($v);
  3891. }
  3892. /**
  3893. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  3894. */
  3895. protected function formatDeliveryYmd($v): string
  3896. {
  3897. if ($v === null || $v === '') {
  3898. return '';
  3899. }
  3900. $s = trim((string)$v);
  3901. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  3902. return '';
  3903. }
  3904. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  3905. return $m[1];
  3906. }
  3907. $ts = strtotime($s);
  3908. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  3909. }
  3910. /**
  3911. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  3912. */
  3913. protected function detailRowSupplierOperated(array $r): bool
  3914. {
  3915. $am = $r['amount'] ?? null;
  3916. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3917. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3918. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3919. return $okAmt || $okDel;
  3920. }
  3921. /**
  3922. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  3923. */
  3924. protected function resolveDetailSupplierOperTime(array $r): string
  3925. {
  3926. if (!$this->detailRowSupplierOperated($r)) {
  3927. return '';
  3928. }
  3929. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  3930. if ($t !== '') {
  3931. return $t;
  3932. }
  3933. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  3934. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  3935. continue;
  3936. }
  3937. $t = $this->formatProcuremenDetailTime($r[$col]);
  3938. if ($t !== '') {
  3939. return $t;
  3940. }
  3941. }
  3942. return '';
  3943. }
  3944. /**
  3945. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  3946. */
  3947. protected function detailRowSupplierAccepted(array $r): bool
  3948. {
  3949. $am = $r['amount'] ?? null;
  3950. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  3951. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  3952. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  3953. return $okAmt && $okDel;
  3954. }
  3955. /**
  3956. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  3957. */
  3958. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  3959. {
  3960. if ($detailCount > 0) {
  3961. return true;
  3962. }
  3963. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  3964. return true;
  3965. }
  3966. $pickTime = trim((string)($main['pick_time'] ?? ''));
  3967. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  3968. return true;
  3969. }
  3970. return false;
  3971. }
  3972. /**
  3973. * 下发时间:优先 pick_time,其次首条下发明细时间
  3974. */
  3975. protected function resolveProcuremenIssueTime(array $main, array $details): string
  3976. {
  3977. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  3978. if ($issueTime !== '') {
  3979. return $issueTime;
  3980. }
  3981. foreach ($details as $dr) {
  3982. if (!is_array($dr)) {
  3983. continue;
  3984. }
  3985. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  3986. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  3987. $issueTime = $t;
  3988. }
  3989. }
  3990. if ($issueTime !== '') {
  3991. return $issueTime;
  3992. }
  3993. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  3994. }
  3995. /**
  3996. * 直接点「完结」时间:优先操作记录 mark_complete
  3997. */
  3998. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  3999. {
  4000. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  4001. }
  4002. /**
  4003. * 操作记录时间(取指定 action 最近一条)
  4004. *
  4005. * @param string|array<int, string> $actions
  4006. */
  4007. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  4008. {
  4009. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  4010. }
  4011. /**
  4012. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  4013. *
  4014. * @param array $main purchase_order 一行
  4015. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  4016. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  4017. */
  4018. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  4019. {
  4020. $issueCnt = count($details);
  4021. $acceptCnt = 0;
  4022. $pickedName = '';
  4023. $pickedTime = '';
  4024. foreach ($details as $dr) {
  4025. if (!is_array($dr)) {
  4026. continue;
  4027. }
  4028. if ($this->detailRowSupplierAccepted($dr)) {
  4029. $acceptCnt++;
  4030. }
  4031. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  4032. if ($pickedName === '') {
  4033. $pickedName = trim((string)($dr['company_name'] ?? ''));
  4034. }
  4035. if ($pickedTime === '') {
  4036. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  4037. if ($pickedTime === '') {
  4038. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  4039. }
  4040. }
  4041. }
  4042. }
  4043. $hasMain = $main !== [];
  4044. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  4045. if ($poTime === '') {
  4046. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  4047. }
  4048. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  4049. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  4050. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  4051. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  4052. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  4053. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  4054. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  4055. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  4056. $supplierTime = '';
  4057. if ($acceptCnt > 0) {
  4058. foreach ($details as $dr) {
  4059. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  4060. continue;
  4061. }
  4062. $t = $this->resolveDetailSupplierOperTime($dr);
  4063. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  4064. $supplierTime = $t;
  4065. }
  4066. }
  4067. }
  4068. $directComplete = ($mainCompleted && !$issued);
  4069. $doneTime = '';
  4070. if ($mainCompleted) {
  4071. if ($directComplete) {
  4072. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  4073. }
  4074. if ($doneTime === '') {
  4075. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  4076. }
  4077. if ($doneTime === '') {
  4078. foreach ($details as $dr) {
  4079. if (!is_array($dr)) {
  4080. continue;
  4081. }
  4082. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  4083. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  4084. $doneTime = $t;
  4085. }
  4086. }
  4087. }
  4088. if ($doneTime === '') {
  4089. $doneTime = $poTime;
  4090. }
  4091. if ($confirmApproveTime !== '') {
  4092. $doneTime = $confirmApproveTime;
  4093. }
  4094. }
  4095. if ($directComplete) {
  4096. // 未下发直接完结:仅「未发」「已完结」两步完成,中间环节保持未进行
  4097. $step1Done = $hasMain;
  4098. $step2Done = false;
  4099. $step3Done = false;
  4100. $step4Done = false;
  4101. $step5Done = false;
  4102. $step6Done = true;
  4103. } else {
  4104. $step1Done = $issued;
  4105. $step2Done = $issued;
  4106. $step3Done = $acceptCnt > 0;
  4107. $step4Done = $wflowPendingApproval;
  4108. if (!$step4Done) {
  4109. foreach ($details as $dr) {
  4110. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  4111. $step4Done = true;
  4112. break;
  4113. }
  4114. }
  4115. }
  4116. $step5Done = $confirmApproveTime !== '' || $mainCompleted;
  4117. $step6Done = $mainCompleted;
  4118. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  4119. if ($mainCompleted && $issued) {
  4120. $step3Done = true;
  4121. $step4Done = true;
  4122. $step5Done = true;
  4123. if ($supplierTime === '') {
  4124. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4125. if ($fillT !== '') {
  4126. $supplierTime = $fillT;
  4127. }
  4128. }
  4129. if ($pickedTime === '') {
  4130. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4131. if ($fillT !== '') {
  4132. $pickedTime = $fillT;
  4133. }
  4134. }
  4135. if ($auditSelectTime === '') {
  4136. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4137. if ($fillT !== '') {
  4138. $auditSelectTime = $fillT;
  4139. }
  4140. }
  4141. if ($confirmApproveTime === '') {
  4142. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  4143. if ($fillT !== '') {
  4144. $confirmApproveTime = $fillT;
  4145. }
  4146. }
  4147. }
  4148. }
  4149. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  4150. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  4151. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  4152. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  4153. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  4154. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  4155. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  4156. $deadlineText = '';
  4157. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  4158. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  4159. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  4160. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  4161. $deadlineText = '截止 ' . $deadlineDisp;
  4162. }
  4163. }
  4164. $steps = [
  4165. [
  4166. 'title' => '未发',
  4167. 'subtitle' => '',
  4168. 'time' => $issued ? '—' : ($hasMain ? $poTime : ''),
  4169. 'done' => $step1Done,
  4170. ],
  4171. [
  4172. 'title' => '下发',
  4173. 'subtitle' => $deadlineText,
  4174. 'time' => $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '',
  4175. 'done' => $step2Done,
  4176. ],
  4177. [
  4178. 'title' => '供应商接单',
  4179. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  4180. 'time' => '',
  4181. 'done' => $step3Done,
  4182. ],
  4183. [
  4184. 'title' => '待确认',
  4185. 'subtitle' => $step4Done
  4186. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  4187. : ($issued ? '待选供应商' : ''),
  4188. 'time' => $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '',
  4189. 'done' => $step4Done,
  4190. ],
  4191. [
  4192. 'title' => '待审批',
  4193. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  4194. 'time' => $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : $doneTime) : '',
  4195. 'done' => $step5Done,
  4196. ],
  4197. [
  4198. 'title' => '已完结',
  4199. 'subtitle' => '',
  4200. 'time' => $step6Done ? $doneTime : '',
  4201. 'done' => $step6Done,
  4202. ],
  4203. ];
  4204. $currentIdx = count($steps) - 1;
  4205. if (!$directComplete) {
  4206. foreach ($steps as $i => $s) {
  4207. if (!$s['done']) {
  4208. $currentIdx = $i;
  4209. break;
  4210. }
  4211. }
  4212. }
  4213. $nSteps = count($steps);
  4214. foreach ($steps as $idx => &$s) {
  4215. $s['current'] = ($idx === $currentIdx);
  4216. if ($idx === 0) {
  4217. $s['pdf_left_bg'] = '';
  4218. } else {
  4219. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  4220. }
  4221. if ($idx >= $nSteps - 1) {
  4222. $s['pdf_right_bg'] = '';
  4223. } else {
  4224. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  4225. }
  4226. }
  4227. unset($s);
  4228. $labelMap = [
  4229. 'CCYDH' => '订单号',
  4230. 'CYJMC' => '印件名称',
  4231. 'CCLBMMC' => '承揽部门',
  4232. 'CGYMC' => '工序名称',
  4233. 'CDW' => '单位',
  4234. 'NGZL' => '工作量',
  4235. 'CDF' => '单价',
  4236. 'cGzzxMc' => '工作中心',
  4237. 'MBZ' => '备注',
  4238. 'This_quantity' => '本次数量',
  4239. 'ceilingPrice' => '最高限价',
  4240. ];
  4241. $orderSummary = [];
  4242. foreach ($labelMap as $key => $lab) {
  4243. if (!array_key_exists($key, $main)) {
  4244. continue;
  4245. }
  4246. $val = $main[$key];
  4247. if ($val === null) {
  4248. $val = '';
  4249. } elseif (!is_scalar($val)) {
  4250. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  4251. } else {
  4252. $val = (string)$val;
  4253. }
  4254. $orderSummary[] = ['label' => $lab, 'value' => $val];
  4255. }
  4256. $orderSummaryGrid = [];
  4257. $n = count($orderSummary);
  4258. for ($i = 0; $i < $n; $i += 2) {
  4259. $left = $orderSummary[$i];
  4260. $hasRight = ($i + 1) < $n;
  4261. $orderSummaryGrid[] = [
  4262. 'l1' => $left['label'],
  4263. 'v1' => $left['value'],
  4264. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  4265. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  4266. ];
  4267. }
  4268. return [
  4269. 'steps' => $steps,
  4270. 'orderSummary' => $orderSummary,
  4271. 'orderSummaryGrid' => $orderSummaryGrid,
  4272. 'detailRows' => $details,
  4273. ];
  4274. }
  4275. /**
  4276. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  4277. *
  4278. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  4279. */
  4280. protected function prepareProcuremenDetailsView(string $ids): array
  4281. {
  4282. $main = [];
  4283. try {
  4284. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4285. $main = is_array($one) ? $one : [];
  4286. } catch (\Throwable $e) {
  4287. $main = [];
  4288. }
  4289. $details = [];
  4290. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  4291. if ($mergeRows === []) {
  4292. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  4293. if ($mergeRows === [] && $main !== []) {
  4294. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  4295. }
  4296. }
  4297. $detailSidList = [];
  4298. $anchorSid = (int)$ids;
  4299. if ($anchorSid !== 0) {
  4300. $detailSidList[$anchorSid] = true;
  4301. }
  4302. foreach ($mergeRows as $mr) {
  4303. if (!is_array($mr)) {
  4304. continue;
  4305. }
  4306. $sid = $this->extractScydgyRowId($mr);
  4307. if ($sid !== 0) {
  4308. $detailSidList[$sid] = true;
  4309. }
  4310. }
  4311. try {
  4312. if ($detailSidList !== []) {
  4313. $details = Db::table('purchase_order_detail')
  4314. ->where('scydgy_id', 'in', array_keys($detailSidList))
  4315. ->order('id', 'asc')
  4316. ->select();
  4317. }
  4318. } catch (\Throwable $e) {
  4319. $details = [];
  4320. }
  4321. if (!is_array($details)) {
  4322. $details = [];
  4323. }
  4324. foreach ($details as &$r) {
  4325. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  4326. $r['id'] = $r['ID'];
  4327. }
  4328. if (isset($r['createtime'])) {
  4329. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  4330. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  4331. } else {
  4332. $r['createtime_text'] = (string)$r['createtime'];
  4333. }
  4334. } else {
  4335. $r['createtime_text'] = '';
  4336. }
  4337. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  4338. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  4339. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  4340. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  4341. if (is_array($r)) {
  4342. $r = $this->maskSupplierContactFields($r);
  4343. }
  4344. }
  4345. unset($r);
  4346. $activeDetails = [];
  4347. foreach ($details as $r) {
  4348. if (is_array($r) && empty($r['is_void'])) {
  4349. $activeDetails[] = $r;
  4350. }
  4351. }
  4352. $operLogs = [];
  4353. try {
  4354. $operLogs = Db::table('purchase_order_oper_log')->where('scydgy_id', $ids)->order('id', 'asc')->select();
  4355. } catch (\Throwable $e) {
  4356. $operLogs = [];
  4357. }
  4358. if (!is_array($operLogs)) {
  4359. $operLogs = [];
  4360. }
  4361. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs);
  4362. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails);
  4363. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  4364. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  4365. if ($ccydh === '') {
  4366. foreach ($details as $r) {
  4367. if (!is_array($r)) {
  4368. continue;
  4369. }
  4370. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  4371. if ($ccydh !== '') {
  4372. break;
  4373. }
  4374. }
  4375. }
  4376. $this->view->assign('ccydh', $ccydh);
  4377. $this->view->assign('steps', $bundle['steps']);
  4378. $this->view->assign('orderSummary', $bundle['orderSummary']);
  4379. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  4380. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  4381. $this->view->assign('processCount', count($mergeRows));
  4382. $this->view->assign('detailRows', $details);
  4383. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  4384. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  4385. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  4386. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  4387. $showSupplierBidResult = (trim((string)($quoteView['selected_company'] ?? '')) !== '')
  4388. || ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  4389. if (!$showSupplierBidResult) {
  4390. foreach ($details as $dr) {
  4391. if (is_array($dr) && !empty($dr['is_picked'])) {
  4392. $showSupplierBidResult = true;
  4393. break;
  4394. }
  4395. }
  4396. }
  4397. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  4398. $this->view->assign('operLogs', $operLogs);
  4399. return [
  4400. 'ok' => $main !== [] || $details !== [],
  4401. 'ccydh' => $ccydh,
  4402. ];
  4403. }
  4404. /**
  4405. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  4406. */
  4407. public function details()
  4408. {
  4409. $ids = $this->request->param('ids', $this->request->param('id', ''));
  4410. if (is_array($ids)) {
  4411. $ids = isset($ids[0]) ? $ids[0] : '';
  4412. }
  4413. $ids = trim((string)$ids);
  4414. if ($ids === '') {
  4415. $this->error(__('Invalid parameters'));
  4416. }
  4417. $this->assertManualOrderDetailsViewable((int)$ids);
  4418. $this->prepareProcuremenDetailsView($ids);
  4419. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  4420. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  4421. $this->view->engine->layout(false);
  4422. try {
  4423. return $this->view->fetch('procuremen/details_dialog_shell');
  4424. } finally {
  4425. if ($restoreLayout) {
  4426. $this->view->engine->layout($restoreLayout);
  4427. }
  4428. }
  4429. }
  4430. /**
  4431. * 解析合并审核工序行(订单号须一致,且均未协助)
  4432. *
  4433. * @return array<int, array<string, mixed>>
  4434. */
  4435. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  4436. {
  4437. $primary = json_decode($rowJson, true);
  4438. if (!is_array($primary)) {
  4439. $this->error(__('Invalid parameters'));
  4440. }
  4441. $merge = json_decode($mergeRowsJson, true);
  4442. if (!is_array($merge) || $merge === []) {
  4443. $merge = [$primary];
  4444. }
  4445. $seen = [];
  4446. $out = [];
  4447. foreach ($merge as $r) {
  4448. if (!is_array($r)) {
  4449. continue;
  4450. }
  4451. $id = $this->extractScydgyRowId($r);
  4452. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  4453. continue;
  4454. }
  4455. $seen[$id] = true;
  4456. $out[] = $r;
  4457. }
  4458. if ($out === []) {
  4459. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  4460. }
  4461. $ccydh = null;
  4462. foreach ($out as $r) {
  4463. $dh = trim((string)($r['CCYDH'] ?? ''));
  4464. if ($ccydh === null) {
  4465. $ccydh = $dh;
  4466. } elseif ($dh !== $ccydh) {
  4467. $this->error('合并审核要求所选行的订单号一致');
  4468. }
  4469. }
  4470. $ids = [];
  4471. foreach ($out as $r) {
  4472. $id = $this->extractScydgyRowId($r);
  4473. if ($this->isValidScydgyRowId($id)) {
  4474. $ids[$id] = true;
  4475. }
  4476. }
  4477. $poBySid = [];
  4478. $detCntBySid = [];
  4479. if ($ids !== []) {
  4480. $idList = array_keys($ids);
  4481. try {
  4482. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  4483. if (is_array($poList)) {
  4484. foreach ($poList as $po) {
  4485. if (!is_array($po)) {
  4486. continue;
  4487. }
  4488. $sid = (int)($po['scydgy_id'] ?? 0);
  4489. if ($this->isValidScydgyRowId($sid)) {
  4490. $poBySid[$sid] = $po;
  4491. }
  4492. }
  4493. }
  4494. } catch (\Throwable $e) {
  4495. }
  4496. try {
  4497. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  4498. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  4499. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  4500. if (is_array($detRows)) {
  4501. foreach ($detRows as $dr) {
  4502. if (!is_array($dr)) {
  4503. continue;
  4504. }
  4505. $sid = (int)($dr['scydgy_id'] ?? 0);
  4506. if ($this->isValidScydgyRowId($sid)) {
  4507. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  4508. }
  4509. }
  4510. }
  4511. } catch (\Throwable $e) {
  4512. }
  4513. }
  4514. foreach ($out as $r) {
  4515. $id = $this->extractScydgyRowId($r);
  4516. if (!$this->isValidScydgyRowId($id)) {
  4517. continue;
  4518. }
  4519. $po = $poBySid[$id] ?? null;
  4520. if (!is_array($po)) {
  4521. continue;
  4522. }
  4523. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4524. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4525. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  4526. }
  4527. $detCnt = (int)($detCntBySid[$id] ?? 0);
  4528. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  4529. $gymc = trim((string)($r['CGYMC'] ?? ''));
  4530. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  4531. }
  4532. }
  4533. return $out;
  4534. }
  4535. /**
  4536. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  4537. */
  4538. protected function maskSupplierContactFields(array $item): array
  4539. {
  4540. if (array_key_exists('email', $item)) {
  4541. $item['email'] = mask_email((string)$item['email']);
  4542. }
  4543. if (array_key_exists('phone', $item)) {
  4544. $item['phone'] = mask_phone((string)$item['phone']);
  4545. }
  4546. return $item;
  4547. }
  4548. /**
  4549. * @param array<int, array<string, mixed>> $list
  4550. * @return array<int, array<string, mixed>>
  4551. */
  4552. protected function maskSupplierContactList(array $list): array
  4553. {
  4554. $out = [];
  4555. foreach ($list as $item) {
  4556. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  4557. }
  4558. return $out;
  4559. }
  4560. /**
  4561. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  4562. *
  4563. * @return array<string, string>|null
  4564. */
  4565. protected function buildCustomerContactPayloadFromRow($row): ?array
  4566. {
  4567. if (!is_array($row)) {
  4568. return null;
  4569. }
  4570. $norm = [];
  4571. foreach ($row as $k => $v) {
  4572. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  4573. }
  4574. $row = $norm;
  4575. $st = $row['status'] ?? '';
  4576. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  4577. return null;
  4578. }
  4579. $companyName = '';
  4580. foreach (['company_name', 'name'] as $nk) {
  4581. if (!empty($row[$nk])) {
  4582. $companyName = trim((string)$row[$nk]);
  4583. break;
  4584. }
  4585. }
  4586. if ($companyName === '') {
  4587. return null;
  4588. }
  4589. $username = '';
  4590. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  4591. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  4592. $username = trim((string)$row[$uk]);
  4593. break;
  4594. }
  4595. }
  4596. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  4597. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  4598. if ($phone === '' && isset($row['account'])) {
  4599. $phone = trim((string)$row['account']);
  4600. }
  4601. if ($phone === '' && isset($row['mobile'])) {
  4602. $phone = trim((string)$row['mobile']);
  4603. }
  4604. if ($email === '' && $phone === '') {
  4605. return null;
  4606. }
  4607. $category = '';
  4608. foreach (['company_type', 'category', 'type_name'] as $ck) {
  4609. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  4610. $category = trim((string)$row[$ck]);
  4611. break;
  4612. }
  4613. }
  4614. return [
  4615. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  4616. 'name' => $companyName,
  4617. 'company_name' => $companyName,
  4618. 'username' => $username,
  4619. 'email' => $email,
  4620. 'phone' => $phone,
  4621. 'category' => $category,
  4622. 'company_type' => $category,
  4623. ];
  4624. }
  4625. /**
  4626. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  4627. */
  4628. protected function resolveCustomerContactById(string $id): ?array
  4629. {
  4630. $id = trim($id);
  4631. if ($id === '' || !ctype_digit($id)) {
  4632. return null;
  4633. }
  4634. try {
  4635. $row = Db::table('customer')->where('id', (int)$id)->find();
  4636. } catch (\Throwable $e) {
  4637. return null;
  4638. }
  4639. return $this->buildCustomerContactPayloadFromRow($row);
  4640. }
  4641. /**
  4642. * 按供应商名称解析联系信息(兼容旧提交数据)
  4643. */
  4644. protected function resolveCustomerContactByCompanyName(string $name): ?array
  4645. {
  4646. $name = trim($name);
  4647. if ($name === '') {
  4648. return null;
  4649. }
  4650. try {
  4651. $row = Db::table('customer')
  4652. ->where(function ($q) use ($name) {
  4653. $q->where('company_name', $name)->whereOr('name', $name);
  4654. })
  4655. ->order('id', 'desc')
  4656. ->find();
  4657. } catch (\Throwable $e) {
  4658. return null;
  4659. }
  4660. return $this->buildCustomerContactPayloadFromRow($row);
  4661. }
  4662. /**
  4663. * 规范化下发/确认时勾选的供应商
  4664. *
  4665. * @param array<int, mixed> $companies
  4666. * @return array<int, array<string, string>>
  4667. */
  4668. protected function normalizePickCompanies(array $companies): array
  4669. {
  4670. $out = [];
  4671. foreach ($companies as $c) {
  4672. if (!is_array($c)) {
  4673. continue;
  4674. }
  4675. $resolved = null;
  4676. $cid = trim((string)($c['id'] ?? ''));
  4677. if ($cid !== '') {
  4678. $resolved = $this->resolveCustomerContactById($cid);
  4679. }
  4680. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  4681. if ($resolved === null && $name !== '') {
  4682. $resolved = $this->resolveCustomerContactByCompanyName($name);
  4683. }
  4684. if ($resolved === null) {
  4685. continue;
  4686. }
  4687. $out[] = $resolved;
  4688. }
  4689. return $out;
  4690. }
  4691. /**
  4692. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  4693. *
  4694. * @param array<int, array<string, mixed>> $pool
  4695. * @return array<int, array<string, mixed>>
  4696. */
  4697. protected function collapseProcuremenPoolByOrder(array $pool): array
  4698. {
  4699. if ($pool === []) {
  4700. return [];
  4701. }
  4702. $groups = [];
  4703. foreach ($pool as $row) {
  4704. if (!is_array($row)) {
  4705. continue;
  4706. }
  4707. $dh = trim((string)($row['CCYDH'] ?? ''));
  4708. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  4709. if (!isset($groups[$key])) {
  4710. $groups[$key] = [];
  4711. }
  4712. $groups[$key][] = $row;
  4713. }
  4714. $out = [];
  4715. foreach ($groups as $ccydh => $rows) {
  4716. if ($rows === []) {
  4717. continue;
  4718. }
  4719. usort($rows, function ($a, $b) {
  4720. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  4721. });
  4722. $head = $rows[0];
  4723. $gymcList = [];
  4724. foreach ($rows as $r) {
  4725. $g = trim((string)($r['CGYMC'] ?? ''));
  4726. if ($g !== '' && !in_array($g, $gymcList, true)) {
  4727. $gymcList[] = $g;
  4728. }
  4729. }
  4730. $merged = $head;
  4731. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  4732. $merged['process_count'] = count($rows);
  4733. $merged['_order_merge_rows'] = $rows;
  4734. if (count($rows) > 1) {
  4735. $merged['CGYMC'] = implode('、', $gymcList);
  4736. }
  4737. $mergedPickTime = '';
  4738. foreach ($rows as $r) {
  4739. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  4740. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  4741. $mergedPickTime = $t;
  4742. }
  4743. }
  4744. if ($mergedPickTime !== '') {
  4745. $merged['pick_time'] = $mergedPickTime;
  4746. }
  4747. $out[] = $merged;
  4748. }
  4749. usort($out, function ($a, $b) {
  4750. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  4751. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  4752. if ($ta === $tb) {
  4753. $ida = (int)($a['purchase_order_id'] ?? 0);
  4754. $idb = (int)($b['purchase_order_id'] ?? 0);
  4755. if ($ida !== $idb) {
  4756. return $idb <=> $ida;
  4757. }
  4758. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  4759. }
  4760. if ($ta === '') {
  4761. return 1;
  4762. }
  4763. if ($tb === '') {
  4764. return -1;
  4765. }
  4766. return strcmp($tb, $ta);
  4767. });
  4768. return $out;
  4769. }
  4770. /**
  4771. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  4772. *
  4773. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4774. */
  4775. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  4776. {
  4777. $scydgyId = trim($scydgyId);
  4778. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4779. if ($scydgyId === '') {
  4780. return $empty;
  4781. }
  4782. try {
  4783. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4784. } catch (\Throwable $e) {
  4785. $anchor = null;
  4786. }
  4787. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  4788. return $empty;
  4789. }
  4790. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4791. if ($ccydh === '') {
  4792. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  4793. }
  4794. try {
  4795. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  4796. } catch (\Throwable $e) {
  4797. $pos = [$anchor];
  4798. }
  4799. if (!is_array($pos) || $pos === []) {
  4800. $pos = [$anchor];
  4801. }
  4802. return [
  4803. 'ccydh' => $ccydh,
  4804. 'pos' => $pos,
  4805. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4806. ];
  4807. }
  4808. /**
  4809. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  4810. */
  4811. protected function purchaseOrderRowInConfirmStage(array $po): bool
  4812. {
  4813. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  4814. return false;
  4815. }
  4816. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  4817. return false;
  4818. }
  4819. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  4820. return true;
  4821. }
  4822. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  4823. $sid = (int)($po['scydgy_id'] ?? 0);
  4824. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  4825. }
  4826. return false;
  4827. }
  4828. /**
  4829. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  4830. *
  4831. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4832. */
  4833. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  4834. {
  4835. $scydgyId = trim($scydgyId);
  4836. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4837. if ($scydgyId === '') {
  4838. return $empty;
  4839. }
  4840. try {
  4841. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4842. } catch (\Throwable $e) {
  4843. $anchor = null;
  4844. }
  4845. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  4846. return $empty;
  4847. }
  4848. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4849. if ($ccydh === '') {
  4850. return [
  4851. 'ccydh' => '',
  4852. 'pos' => [$anchor],
  4853. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  4854. ];
  4855. }
  4856. try {
  4857. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  4858. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  4859. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  4860. } catch (\Throwable $e) {
  4861. $pos = [$anchor];
  4862. }
  4863. if (!is_array($pos) || $pos === []) {
  4864. $pos = [$anchor];
  4865. }
  4866. $pos = array_values(array_filter($pos, function ($po) {
  4867. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  4868. }));
  4869. if ($pos === []) {
  4870. $pos = [$anchor];
  4871. }
  4872. return [
  4873. 'ccydh' => $ccydh,
  4874. 'pos' => $pos,
  4875. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4876. ];
  4877. }
  4878. /**
  4879. * @param array<int, array<string, mixed>> $purchaseOrders
  4880. * @return array<int, array<string, mixed>>
  4881. */
  4882. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  4883. {
  4884. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  4885. $byId = [];
  4886. foreach ($pool as $r) {
  4887. if (!is_array($r)) {
  4888. continue;
  4889. }
  4890. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  4891. if ($this->isValidScydgyRowId($sid)) {
  4892. $byId[$sid] = $r;
  4893. }
  4894. }
  4895. $out = [];
  4896. foreach ($purchaseOrders as $po) {
  4897. if (!is_array($po)) {
  4898. continue;
  4899. }
  4900. $sid = (int)($po['scydgy_id'] ?? 0);
  4901. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  4902. $out[] = $byId[$sid];
  4903. }
  4904. }
  4905. return $out;
  4906. }
  4907. /**
  4908. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  4909. *
  4910. * @return array<int, array<string, mixed>>
  4911. */
  4912. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  4913. {
  4914. $scydgyId = trim($scydgyId);
  4915. if ($scydgyId === '') {
  4916. return [];
  4917. }
  4918. try {
  4919. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  4920. } catch (\Throwable $e) {
  4921. $anchor = null;
  4922. }
  4923. if (!is_array($anchor)) {
  4924. return [];
  4925. }
  4926. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  4927. return [];
  4928. }
  4929. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  4930. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  4931. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  4932. try {
  4933. $q = Db::table('purchase_order');
  4934. if ($ccydh !== '') {
  4935. $q->where('CCYDH', $ccydh);
  4936. } else {
  4937. $q->where('scydgy_id', $scydgyId);
  4938. }
  4939. if ($isValidPick) {
  4940. $q->where('pick_time', $pickTime);
  4941. }
  4942. $pos = $q->order('scydgy_id', 'asc')->select();
  4943. } catch (\Throwable $e) {
  4944. $pos = [$anchor];
  4945. }
  4946. if (!is_array($pos) || $pos === []) {
  4947. $pos = [$anchor];
  4948. }
  4949. $pos = array_values(array_filter($pos, function ($po) {
  4950. if (!is_array($po)) {
  4951. return false;
  4952. }
  4953. $mr = $po['mod_rq'] ?? null;
  4954. if ($mr === null || $mr === '') {
  4955. return true;
  4956. }
  4957. $mrs = trim((string)$mr);
  4958. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  4959. }));
  4960. if ($pos === []) {
  4961. $pos = [$anchor];
  4962. }
  4963. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  4964. if ($rows === []) {
  4965. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  4966. }
  4967. return $rows;
  4968. }
  4969. /**
  4970. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  4971. *
  4972. * @param array<int, array<string, mixed>> $mergeRows
  4973. * @return array<int, array<string, mixed>>
  4974. */
  4975. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  4976. {
  4977. $list = array_values($mergeRows);
  4978. $n = count($list);
  4979. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  4980. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  4981. $mergeSame = $n > 1 && $orderKey0 !== '';
  4982. if ($mergeSame) {
  4983. foreach ($list as $rr) {
  4984. if (!is_array($rr)) {
  4985. $mergeSame = false;
  4986. break;
  4987. }
  4988. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  4989. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  4990. $mergeSame = false;
  4991. break;
  4992. }
  4993. }
  4994. }
  4995. $out = [];
  4996. foreach ($list as $idx => $r) {
  4997. if (!is_array($r)) {
  4998. continue;
  4999. }
  5000. $qty = $r['This_quantity'] ?? $r['this_quantity'] ?? '';
  5001. if (is_scalar($qty)) {
  5002. $qty = trim((string)$qty);
  5003. } else {
  5004. $qty = '';
  5005. }
  5006. if ($qty === '') {
  5007. $gzl = $r['NGZL'] ?? '';
  5008. if (is_scalar($gzl)) {
  5009. $qty = trim((string)$gzl);
  5010. }
  5011. }
  5012. $price = $r['ceilingPrice'] ?? $r['ceiling_price'] ?? '';
  5013. $sid = $this->extractScydgyRowId($r);
  5014. $out[] = [
  5015. 'seq' => $idx + 1,
  5016. 'scydgy_id' => $sid,
  5017. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  5018. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  5019. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  5020. 'CDW' => trim((string)($r['CDW'] ?? '')),
  5021. 'NGZL' => $r['NGZL'] ?? '',
  5022. 'This_quantity' => is_scalar($qty) ? trim((string)$qty) : '',
  5023. 'ceilingPrice' => is_scalar($price) ? trim((string)$price) : '',
  5024. 'CDF' => trim((string)($r['CDF'] ?? '')),
  5025. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  5026. 'show_order_cells' => !$mergeSame || $idx === 0,
  5027. 'order_rowspan' => $mergeSame ? $n : 1,
  5028. ];
  5029. }
  5030. return $out;
  5031. }
  5032. /**
  5033. * 解析金额/数量(去千分位等非数字字符)
  5034. */
  5035. protected function parseProcuremenMoneyNumber($value): ?float
  5036. {
  5037. if ($value === null || $value === '') {
  5038. return null;
  5039. }
  5040. if (is_numeric($value)) {
  5041. return (float)$value;
  5042. }
  5043. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  5044. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  5045. }
  5046. protected function formatProcuremenMoneyDisplay(?float $amount): string
  5047. {
  5048. if ($amount === null) {
  5049. return '';
  5050. }
  5051. return (string)(int)round($amount);
  5052. }
  5053. /**
  5054. * 列表/详情展示:工作量为 0 时显示空
  5055. */
  5056. protected function formatProcuremenWorkloadDisplay($value): string
  5057. {
  5058. if ($value === null || $value === '') {
  5059. return '';
  5060. }
  5061. $s = trim((string)$value);
  5062. if ($s === '') {
  5063. return '';
  5064. }
  5065. if (is_numeric($s) && (float)$s == 0) {
  5066. return '';
  5067. }
  5068. return $s;
  5069. }
  5070. /**
  5071. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  5072. */
  5073. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  5074. {
  5075. foreach ($details as $d) {
  5076. if (!is_array($d)) {
  5077. continue;
  5078. }
  5079. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  5080. $cn = trim((string)($d['company_name'] ?? ''));
  5081. if ($cn !== '') {
  5082. return $cn;
  5083. }
  5084. }
  5085. }
  5086. return trim((string)($main['pick_company_name'] ?? ''));
  5087. }
  5088. /**
  5089. * 详情报价小计:单价 × 本工序本次数量
  5090. */
  5091. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  5092. {
  5093. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  5094. if ($unit === null) {
  5095. return null;
  5096. }
  5097. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  5098. if ($qty === null || $qty <= 0) {
  5099. return null;
  5100. }
  5101. return $unit * $qty;
  5102. }
  5103. /**
  5104. * 详情页:工序小计 + 供应商分组报价与总计
  5105. *
  5106. * @param array<int, array<string, mixed>> $mergeRows
  5107. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  5108. * @return array{
  5109. * process_rows: array,
  5110. * supplier_groups: array,
  5111. * order_total_text: string,
  5112. * order_total_has: bool,
  5113. * selected_company: string
  5114. * }
  5115. */
  5116. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  5117. {
  5118. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  5119. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  5120. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh);
  5121. $qtyBySid = [];
  5122. $gymcBySid = [];
  5123. $orderedSids = [];
  5124. foreach ($mergeRows as $mr) {
  5125. if (!is_array($mr)) {
  5126. continue;
  5127. }
  5128. $sid = $this->extractScydgyRowId($mr);
  5129. if ($this->isValidScydgyRowId($sid)) {
  5130. $orderedSids[] = $sid;
  5131. }
  5132. $qty = trim((string)($mr['This_quantity'] ?? ''));
  5133. if ($qty === '') {
  5134. $qty = trim((string)($mr['NGZL'] ?? ''));
  5135. }
  5136. $qtyBySid[$sid] = $qty;
  5137. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  5138. }
  5139. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  5140. $detailByCompanySid = [];
  5141. foreach ($details as $d) {
  5142. if (!is_array($d)) {
  5143. continue;
  5144. }
  5145. $cn = trim((string)($d['company_name'] ?? ''));
  5146. $sid = (int)($d['scydgy_id'] ?? 0);
  5147. if ($cn === '' || $sid === 0) {
  5148. continue;
  5149. }
  5150. if (!isset($detailByCompanySid[$cn])) {
  5151. $detailByCompanySid[$cn] = [];
  5152. }
  5153. $detailByCompanySid[$cn][$sid] = $d;
  5154. }
  5155. $supplierGroups = [];
  5156. foreach ($detailByCompanySid as $cn => $bySid) {
  5157. $lines = [];
  5158. $groupTotal = 0.0;
  5159. $groupHas = false;
  5160. $groupVoid = true;
  5161. $usedSids = [];
  5162. $appendLine = function (int $sid, array $d) use (
  5163. &$lines,
  5164. &$groupTotal,
  5165. &$groupHas,
  5166. &$groupVoid,
  5167. $qtyBySid,
  5168. $gymcBySid,
  5169. $quoteVisible
  5170. ) {
  5171. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  5172. if (!$isVoid) {
  5173. $groupVoid = false;
  5174. }
  5175. $qtyStr = $qtyBySid[$sid] ?? '';
  5176. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  5177. $am = trim((string)($d['amount'] ?? ''));
  5178. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  5179. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  5180. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  5181. $sub = null;
  5182. if (!$isVoid && $amountNum !== null) {
  5183. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  5184. }
  5185. $ct = $this->resolveDetailSupplierOperTime($d);
  5186. $line = [
  5187. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  5188. 'unit_price_text' => $amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am,
  5189. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  5190. 'delivery_ymd' => $deliveryYmd,
  5191. 'amount_filled' => $amountFilled,
  5192. 'delivery_filled' => $deliveryFilled,
  5193. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  5194. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  5195. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  5196. 'is_void' => $isVoid,
  5197. 'oper_time_text' => $ct,
  5198. ];
  5199. if (!$quoteVisible && !$isVoid) {
  5200. $this->maskSupplierQuoteLineBeforeDeadline($line);
  5201. } elseif ($sub !== null) {
  5202. $groupTotal += $sub;
  5203. $groupHas = true;
  5204. }
  5205. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  5206. };
  5207. foreach ($orderedSids as $sid) {
  5208. if (!isset($bySid[$sid])) {
  5209. continue;
  5210. }
  5211. $usedSids[$sid] = true;
  5212. $appendLine($sid, $bySid[$sid]);
  5213. }
  5214. foreach ($bySid as $sid => $d) {
  5215. if (isset($usedSids[$sid])) {
  5216. continue;
  5217. }
  5218. $appendLine((int)$sid, $d);
  5219. }
  5220. $firstDetail = null;
  5221. foreach ($bySid as $d) {
  5222. if (is_array($d)) {
  5223. $firstDetail = $d;
  5224. break;
  5225. }
  5226. }
  5227. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  5228. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  5229. if ($username === '' && $ph !== '') {
  5230. $username = $this->resolveCustomerContactName($ph, $cn);
  5231. }
  5232. $remark = '';
  5233. foreach ($bySid as $d) {
  5234. if (!is_array($d)) {
  5235. continue;
  5236. }
  5237. $rm = '';
  5238. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  5239. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  5240. $rm = trim((string)$d[$rk]);
  5241. break;
  5242. }
  5243. }
  5244. if ($rm !== '') {
  5245. $remark = $rm;
  5246. break;
  5247. }
  5248. }
  5249. $lineCount = count($lines);
  5250. $hasRemark = $lineCount > 0;
  5251. $supplierGroup = [
  5252. 'company_name' => $cn,
  5253. 'username' => $username,
  5254. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  5255. 'phone' => $ph,
  5256. 'remark' => $remark,
  5257. 'has_remark' => $hasRemark,
  5258. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  5259. 'is_void' => $groupVoid,
  5260. 'lines' => $lines,
  5261. 'line_count' => $lineCount,
  5262. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  5263. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  5264. 'has_total' => $lineCount > 0,
  5265. ];
  5266. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  5267. $supplierGroups[] = $supplierGroup;
  5268. }
  5269. usort($supplierGroups, function ($a, $b) {
  5270. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  5271. return ($a['is_void'] ?? false) ? 1 : -1;
  5272. }
  5273. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  5274. return ($a['is_selected'] ?? false) ? -1 : 1;
  5275. }
  5276. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  5277. });
  5278. return [
  5279. 'process_rows' => $processRows,
  5280. 'supplier_groups' => $supplierGroups,
  5281. 'order_total_text' => '',
  5282. 'order_total_has' => false,
  5283. 'selected_company' => $selectedCompany,
  5284. ];
  5285. }
  5286. /**
  5287. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  5288. */
  5289. protected function buildProcessLinesPlain(array $mergeRows): string
  5290. {
  5291. $lines = [];
  5292. $i = 1;
  5293. foreach ($mergeRows as $r) {
  5294. if (!is_array($r)) {
  5295. continue;
  5296. }
  5297. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5298. $dw = trim((string)($r['CDW'] ?? ''));
  5299. $gzl = trim((string)($r['NGZL'] ?? ''));
  5300. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5301. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  5302. if ($dw !== '') {
  5303. $parts[] = '单位:' . $dw;
  5304. }
  5305. if ($gzl !== '') {
  5306. $parts[] = '工作量:' . $gzl;
  5307. }
  5308. if ($qty !== '') {
  5309. $parts[] = '本次数量:' . $qty;
  5310. }
  5311. $lines[] = implode(' ', $parts);
  5312. $i++;
  5313. }
  5314. return implode("\n", $lines);
  5315. }
  5316. /**
  5317. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  5318. *
  5319. * @return array<string, string>
  5320. */
  5321. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  5322. {
  5323. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  5324. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  5325. }
  5326. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  5327. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  5328. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  5329. $cyjmc = '';
  5330. foreach ($mergeRows as $mr) {
  5331. if (!is_array($mr)) {
  5332. continue;
  5333. }
  5334. if ($ccydh === '') {
  5335. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  5336. }
  5337. if ($cyjmc === '') {
  5338. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  5339. }
  5340. }
  5341. if ($pos !== []) {
  5342. $firstPo = $pos[0];
  5343. if (is_array($firstPo)) {
  5344. if ($ccydh === '') {
  5345. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  5346. }
  5347. if ($cyjmc === '') {
  5348. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  5349. }
  5350. }
  5351. }
  5352. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  5353. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  5354. if (is_array($any)) {
  5355. if ($ccydh === '') {
  5356. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  5357. }
  5358. if ($cyjmc === '') {
  5359. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  5360. }
  5361. }
  5362. }
  5363. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  5364. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  5365. $cgymc = '';
  5366. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  5367. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  5368. }
  5369. return [
  5370. 'ccydh' => $ccydh,
  5371. 'cyjmc' => $cyjmc,
  5372. 'cgymc' => $cgymc,
  5373. 'process_lines' => $processLines,
  5374. 'process_lines_html' => '',
  5375. ];
  5376. }
  5377. /**
  5378. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  5379. */
  5380. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  5381. {
  5382. $lines = [];
  5383. if ($ccydh !== '') {
  5384. $lines[] = '订单号:' . $ccydh;
  5385. }
  5386. if ($cyjmc !== '') {
  5387. $lines[] = '印件名称:' . $cyjmc;
  5388. }
  5389. if ($processPlain !== '') {
  5390. $lines[] = $processPlain;
  5391. }
  5392. return implode("\n", $lines);
  5393. }
  5394. /**
  5395. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  5396. *
  5397. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5398. */
  5399. protected function buildPlatformLinksPlain(array $detailLinks): string
  5400. {
  5401. $lines = [];
  5402. $i = 1;
  5403. foreach ($detailLinks as $lk) {
  5404. if (!is_array($lk)) {
  5405. continue;
  5406. }
  5407. $url = trim((string)($lk['url'] ?? ''));
  5408. if ($url === '') {
  5409. continue;
  5410. }
  5411. $label = trim((string)($lk['cgymc'] ?? ''));
  5412. if ($label === '') {
  5413. $label = '工序' . $i;
  5414. }
  5415. $lines[] = $label . ':' . $url;
  5416. $i++;
  5417. }
  5418. return implode("\n", $lines);
  5419. }
  5420. /**
  5421. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  5422. *
  5423. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  5424. */
  5425. protected function buildPlatformLinksHtml(array $detailLinks): string
  5426. {
  5427. $parts = [];
  5428. $i = 1;
  5429. foreach ($detailLinks as $lk) {
  5430. if (!is_array($lk)) {
  5431. continue;
  5432. }
  5433. $url = trim((string)($lk['url'] ?? ''));
  5434. if ($url === '') {
  5435. continue;
  5436. }
  5437. $label = trim((string)($lk['cgymc'] ?? ''));
  5438. if ($label === '') {
  5439. $label = '工序' . $i;
  5440. }
  5441. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  5442. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  5443. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  5444. $i++;
  5445. }
  5446. return implode("<br>\n", $parts);
  5447. }
  5448. /**
  5449. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  5450. *
  5451. * @return array<string, mixed>
  5452. */
  5453. protected function loadMailerConfig(): array
  5454. {
  5455. try {
  5456. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  5457. } catch (\Throwable $e) {
  5458. $cfg = [];
  5459. }
  5460. return is_array($cfg) ? $cfg : [];
  5461. }
  5462. protected function loadNotifyTemplateRow(string $scene): ?array
  5463. {
  5464. try {
  5465. $row = Db::table('purchase_sms_template')
  5466. ->where('scene', $scene)
  5467. ->where(function ($q) {
  5468. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  5469. })
  5470. ->order('id', 'asc')
  5471. ->find();
  5472. } catch (\Throwable $e) {
  5473. return null;
  5474. }
  5475. if (!is_array($row) || $row === []) {
  5476. return null;
  5477. }
  5478. return [
  5479. 'title' => trim((string)($row['title'] ?? '')),
  5480. 'content' => trim((string)($row['content'] ?? '')),
  5481. ];
  5482. }
  5483. /**
  5484. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  5485. */
  5486. protected function buildProcessLinesHtml(array $mergeRows): string
  5487. {
  5488. if (count($mergeRows) <= 1) {
  5489. $r = $mergeRows[0] ?? [];
  5490. if (!is_array($r)) {
  5491. return '';
  5492. }
  5493. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5494. $dw = trim((string)($r['CDW'] ?? ''));
  5495. $gzl = trim((string)($r['NGZL'] ?? ''));
  5496. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  5497. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  5498. if ($dw !== '') {
  5499. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  5500. }
  5501. if ($gzl !== '') {
  5502. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  5503. }
  5504. if ($qty !== '') {
  5505. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  5506. }
  5507. return $html;
  5508. }
  5509. $rows = '';
  5510. $i = 1;
  5511. foreach ($mergeRows as $r) {
  5512. if (!is_array($r)) {
  5513. continue;
  5514. }
  5515. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  5516. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  5517. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  5518. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  5519. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  5520. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  5521. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  5522. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  5523. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  5524. $i++;
  5525. }
  5526. if ($rows === '') {
  5527. return '';
  5528. }
  5529. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  5530. . '<thead><tr style="background:#f5f5f5;">'
  5531. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  5532. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  5533. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  5534. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  5535. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  5536. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  5537. }
  5538. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true): string
  5539. {
  5540. $sysRq = trim($sysRq);
  5541. if ($sysRq === '') {
  5542. if ($required) {
  5543. $this->error('请选择截止时间');
  5544. }
  5545. return '';
  5546. }
  5547. $ts = strtotime($sysRq);
  5548. if ($ts === false || $ts <= 0) {
  5549. $this->error('截止时间格式无效');
  5550. }
  5551. return date('Y-m-d H:i:s', $ts);
  5552. }
  5553. protected function formatProcuremenSysRqForInput($sysRq): string
  5554. {
  5555. $sr = trim((string)$sysRq);
  5556. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  5557. return '';
  5558. }
  5559. $ts = strtotime($sr);
  5560. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  5561. }
  5562. protected function formatProcuremenSysRqForDisplay($sysRq): string
  5563. {
  5564. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  5565. if ($sr === '') {
  5566. return '—';
  5567. }
  5568. $ts = strtotime($sr);
  5569. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  5570. }
  5571. /**
  5572. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  5573. *
  5574. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  5575. * @return array{ccydh?:string,pos:array,merge_rows:array}
  5576. */
  5577. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  5578. {
  5579. return $bundle;
  5580. }
  5581. /**
  5582. * 写入/更新 purchase_order(单道工序行)
  5583. */
  5584. protected function upsertPurchaseOrderFromRow(
  5585. array $row,
  5586. string $sysRqDb,
  5587. $wflowStatus = null,
  5588. ?string $pickTime = null,
  5589. ?array $exists = null
  5590. ): void {
  5591. $ids = $this->extractScydgyRowId($row);
  5592. if (!$this->isValidScydgyRowId($ids)) {
  5593. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  5594. }
  5595. if ($exists === null) {
  5596. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5597. }
  5598. $data = [
  5599. 'scydgy_id' => $ids,
  5600. 'CCYDH' => $row['CCYDH'] ?? null,
  5601. 'CYJMC' => $row['CYJMC'] ?? null,
  5602. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  5603. 'CDXMC' => $row['CDXMC'] ?? null,
  5604. 'CGYBH' => $row['CGYBH'] ?? null,
  5605. 'CGYMC' => $row['CGYMC'] ?? null,
  5606. 'CDW' => $row['CDW'] ?? null,
  5607. 'NGZL' => $row['NGZL'] ?? null,
  5608. 'CDF' => $row['CDF'] ?? null,
  5609. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  5610. 'MBZ' => $row['MBZ'] ?? null,
  5611. 'bwjg' => $row['bwjg'] ?? null,
  5612. 'iStatus' => $row['iStatus'] ?? null,
  5613. 'dStamp' => $row['dStamp'] ?? null,
  5614. 'dputrecord' => $row['dputrecord'] ?? null,
  5615. 'cywyxm' => $row['cywyxm'] ?? null,
  5616. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  5617. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  5618. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  5619. 'sys_rq' => $sysRqDb,
  5620. ];
  5621. if ($wflowStatus !== null && $wflowStatus !== '') {
  5622. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  5623. }
  5624. if ($pickTime !== null && $pickTime !== '') {
  5625. $data['pick_time'] = $pickTime;
  5626. $data['pick_company_name'] = '';
  5627. }
  5628. if ($exists) {
  5629. $upd = $data;
  5630. unset($upd['scydgy_id']);
  5631. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  5632. } else {
  5633. $data['createtime'] = date('Y-m-d H:i:s');
  5634. Db::table('purchase_order')->insert($data);
  5635. }
  5636. }
  5637. /**
  5638. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  5639. *
  5640. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  5641. */
  5642. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false): array
  5643. {
  5644. $toDb = function ($value) {
  5645. if ($value === null) {
  5646. return null;
  5647. }
  5648. if (is_scalar($value)) {
  5649. return $value;
  5650. }
  5651. return json_encode($value, JSON_UNESCAPED_UNICODE);
  5652. };
  5653. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5654. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5655. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5656. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  5657. if ($username === '') {
  5658. $username = $this->resolveCustomerContactName($phone, $companyName);
  5659. }
  5660. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5661. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  5662. }
  5663. if ($phone === '') {
  5664. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  5665. }
  5666. $detailLinks = [];
  5667. foreach ($mergeRows as $row) {
  5668. if (!is_array($row)) {
  5669. continue;
  5670. }
  5671. $sid = $this->extractScydgyRowId($row);
  5672. $detailId = 0;
  5673. if ($skipExisting) {
  5674. try {
  5675. $existsQuery = Db::table('purchase_order_detail')
  5676. ->where('scydgy_id', $sid)
  5677. ->where('company_name', $companyName);
  5678. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  5679. $exists = $existsQuery->find();
  5680. } catch (\Throwable $e) {
  5681. $exists = null;
  5682. }
  5683. if (is_array($exists)) {
  5684. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  5685. }
  5686. }
  5687. if ($detailId <= 0) {
  5688. $one = [
  5689. 'scydgy_id' => $toDb($sid),
  5690. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  5691. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  5692. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  5693. 'username' => $username !== '' ? $username : null,
  5694. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  5695. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  5696. 'createtime' => date('Y-m-d H:i:s'),
  5697. 'status' => ProcuremenStatus::POD_UNPICKED,
  5698. 'status_name' => '未提交',
  5699. ];
  5700. Db::table('purchase_order_detail')->insert($one);
  5701. $detailId = (int)Db::getLastInsID();
  5702. }
  5703. $mprocUrl = '';
  5704. if ($buildMobileLinks && $detailId > 0) {
  5705. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  5706. }
  5707. $detailLinks[] = [
  5708. 'detail_id' => $detailId,
  5709. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  5710. 'url' => $mprocUrl,
  5711. ];
  5712. }
  5713. return $detailLinks;
  5714. }
  5715. /**
  5716. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  5717. * @return array<string, mixed>
  5718. */
  5719. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  5720. {
  5721. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  5722. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  5723. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  5724. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  5725. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  5726. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  5727. $isMerge = !empty($ctx['is_merge']);
  5728. $contactName = trim((string)($c['username'] ?? ''));
  5729. if ($contactName === '') {
  5730. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  5731. }
  5732. $notifyVars = [
  5733. 'company_name' => $companyName,
  5734. 'contact_name' => $contactName,
  5735. 'phone' => $phone,
  5736. 'email' => $toEmail,
  5737. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  5738. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  5739. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  5740. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  5741. 'deadline' => (string)($ctx['deadline'] ?? ''),
  5742. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  5743. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  5744. 'platform_url' => $platformUrl,
  5745. 'platform_links' => $platformLinksPlain,
  5746. 'platform_links_html' => $platformLinksHtml,
  5747. ];
  5748. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  5749. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  5750. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  5751. return [
  5752. 'company_name' => $companyName,
  5753. 'phone' => $phone,
  5754. 'email' => $toEmail,
  5755. 'sms_content' => $smsContent,
  5756. 'mail_plain' => $mailPlain,
  5757. 'mail_body' => $mailBody,
  5758. 'notify_vars' => $notifyVars,
  5759. 'detail_links' => $detailLinks,
  5760. ];
  5761. }
  5762. /**
  5763. * @param array<string, mixed> $chosen
  5764. * @param array<int, array<string, mixed>> $mergeRows
  5765. * @param array{ccydh:string, pos:array} $bundle
  5766. */
  5767. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue'): void
  5768. {
  5769. if (!$sendSms && !$sendEmail) {
  5770. return;
  5771. }
  5772. $companyName = trim((string)($chosen['name'] ?? ''));
  5773. $phone = trim((string)($chosen['phone'] ?? ''));
  5774. $toEmail = trim((string)($chosen['email'] ?? ''));
  5775. if ($companyName === '') {
  5776. throw new \Exception('供应商名称无效');
  5777. }
  5778. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  5779. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  5780. }
  5781. if ($sendSms && $phone === '') {
  5782. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  5783. }
  5784. $sids = [];
  5785. foreach ($mergeRows as $mr) {
  5786. if (!is_array($mr)) {
  5787. continue;
  5788. }
  5789. $sid = $this->extractScydgyRowId($mr);
  5790. if ($this->isValidScydgyRowId($sid)) {
  5791. $sids[$sid] = true;
  5792. }
  5793. }
  5794. if ($sids === []) {
  5795. throw new \Exception('未找到工序行,无法发送通知');
  5796. }
  5797. $sysRqNotify = '';
  5798. $pos = $bundle['pos'] ?? [];
  5799. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  5800. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  5801. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  5802. $ts = strtotime($sr);
  5803. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  5804. }
  5805. }
  5806. try {
  5807. $detailsQuery = Db::table('purchase_order_detail')
  5808. ->where('scydgy_id', 'in', array_keys($sids))
  5809. ->where('company_name', $companyName);
  5810. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  5811. $details = $detailsQuery->order('id', 'asc')->select();
  5812. } catch (\Throwable $e) {
  5813. $details = [];
  5814. }
  5815. if (!is_array($details) || $details === []) {
  5816. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  5817. try {
  5818. $detailsQuery = Db::table('purchase_order_detail')
  5819. ->where('scydgy_id', 'in', array_keys($sids))
  5820. ->where('company_name', $companyName);
  5821. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  5822. $details = $detailsQuery->order('id', 'asc')->select();
  5823. } catch (\Throwable $e) {
  5824. $details = [];
  5825. }
  5826. }
  5827. if (!is_array($details) || $details === []) {
  5828. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  5829. }
  5830. $detailLinks = [];
  5831. foreach ($details as $d) {
  5832. if (!is_array($d)) {
  5833. continue;
  5834. }
  5835. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  5836. if ($detailId <= 0) {
  5837. continue;
  5838. }
  5839. $sid = (int)($d['scydgy_id'] ?? 0);
  5840. $gymc = '';
  5841. foreach ($mergeRows as $mr) {
  5842. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  5843. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5844. break;
  5845. }
  5846. }
  5847. $detailLinks[] = [
  5848. 'detail_id' => $detailId,
  5849. 'cgymc' => $gymc,
  5850. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  5851. ];
  5852. }
  5853. if ($detailLinks === []) {
  5854. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  5855. }
  5856. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  5857. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  5858. $notifyBundle['email_log_scene'] = $emailLogScene;
  5859. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  5860. $poIdLog = 0;
  5861. $pos = $bundle['pos'] ?? [];
  5862. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  5863. $poIdLog = (int)($pos[0]['id'] ?? 0);
  5864. }
  5865. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  5866. if ($sendEmail) {
  5867. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  5868. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  5869. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  5870. }
  5871. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  5872. $mailConfig = $this->loadMailerConfig();
  5873. if (!$this->isProcuremenNotifyDryRun()) {
  5874. if (empty($mailConfig['host'])) {
  5875. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  5876. }
  5877. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  5878. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  5879. }
  5880. }
  5881. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  5882. }
  5883. if ($sendSms) {
  5884. $this->issueSendSupplierSms($notifyBundle);
  5885. }
  5886. }
  5887. /**
  5888. * @param array<int, array<string, mixed>> $quoteGroups
  5889. * @return array<int, array<string, mixed>>
  5890. */
  5891. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  5892. {
  5893. $names = [];
  5894. if (is_string($companiesJson) && $companiesJson !== '') {
  5895. $decoded = json_decode($companiesJson, true);
  5896. if (is_array($decoded)) {
  5897. foreach ($decoded as $nm) {
  5898. $nm = trim((string)$nm);
  5899. if ($nm !== '') {
  5900. $names[] = $nm;
  5901. }
  5902. }
  5903. }
  5904. }
  5905. $names = array_values(array_unique($names));
  5906. if ($names === [] && $selectedCompany !== '') {
  5907. $names = [$selectedCompany];
  5908. }
  5909. if ($names === []) {
  5910. return $quoteGroups;
  5911. }
  5912. $targets = [];
  5913. foreach ($quoteGroups as $g) {
  5914. if (!is_array($g)) {
  5915. continue;
  5916. }
  5917. $cn = trim((string)($g['name'] ?? ''));
  5918. if ($cn !== '' && in_array($cn, $names, true)) {
  5919. $targets[] = $g;
  5920. }
  5921. }
  5922. return $targets;
  5923. }
  5924. /**
  5925. * @return array{pos:array, merge_rows:array, bundle:array}
  5926. */
  5927. protected function loadAuditResendBundle(string $scydgyId): array
  5928. {
  5929. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  5930. $pos = $bundle['pos'];
  5931. $mergeRows = $bundle['merge_rows'];
  5932. if ($pos === [] || $mergeRows === []) {
  5933. $this->error('该订单不在待确认供应商状态');
  5934. }
  5935. $sysRqDb = '';
  5936. if (isset($pos[0]) && is_array($pos[0])) {
  5937. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  5938. }
  5939. foreach ($pos as $i => $poRow) {
  5940. if (is_array($pos[$i]) && $sysRqDb !== '') {
  5941. $pos[$i]['sys_rq'] = $sysRqDb;
  5942. }
  5943. }
  5944. $bundle['pos'] = $pos;
  5945. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  5946. }
  5947. /**
  5948. * @param array<int, array<string, mixed>> $targets
  5949. */
  5950. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  5951. {
  5952. if ($targets === []) {
  5953. $this->error('未找到可通知的供应商');
  5954. }
  5955. $notifyErrors = [];
  5956. try {
  5957. $this->notifyDryRunPreview = [];
  5958. foreach ($targets as $g) {
  5959. if (!is_array($g)) {
  5960. continue;
  5961. }
  5962. $cname = trim((string)($g['name'] ?? ''));
  5963. if ($cname === '') {
  5964. continue;
  5965. }
  5966. $chosen = [
  5967. 'name' => $cname,
  5968. 'company_name' => $cname,
  5969. 'email' => trim((string)($g['email'] ?? '')),
  5970. 'phone' => trim((string)($g['phone'] ?? '')),
  5971. 'username' => trim((string)($g['username'] ?? '')),
  5972. ];
  5973. try {
  5974. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  5975. } catch (\Throwable $e) {
  5976. $notifyErrors[] = $cname . ':' . $e->getMessage();
  5977. }
  5978. }
  5979. } catch (\Throwable $e) {
  5980. $this->error('通知发送失败:' . $e->getMessage());
  5981. }
  5982. if ($notifyErrors !== []) {
  5983. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  5984. }
  5985. if ($this->isProcuremenNotifyDryRun()) {
  5986. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  5987. 'notify_dry_run' => true,
  5988. 'notify_preview' => $this->notifyDryRunPreview,
  5989. ]);
  5990. }
  5991. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  5992. }
  5993. /**
  5994. * 协助下发 — 发送短信(一家供应商)
  5995. *
  5996. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  5997. */
  5998. protected function issueSendSupplierSms(array $bundle): void
  5999. {
  6000. $companyName = (string)($bundle['company_name'] ?? '');
  6001. $phone = (string)($bundle['phone'] ?? '');
  6002. $smsContent = (string)($bundle['sms_content'] ?? '');
  6003. $this->logIssueNotifyDebug('短信', [
  6004. 'company' => $companyName,
  6005. 'phone' => $phone,
  6006. 'sms_content' => $smsContent,
  6007. ]);
  6008. if ($this->isProcuremenNotifyDryRun()) {
  6009. $this->recordNotifyDryRunPreview([
  6010. 'scene' => 'issue_sms',
  6011. 'company_name' => $companyName,
  6012. 'phone' => $phone,
  6013. 'sms_content' => $smsContent,
  6014. ]);
  6015. return;
  6016. }
  6017. $this->smsbao($phone, $smsContent);
  6018. }
  6019. /**
  6020. * 协助下发 — 发送邮件(一家供应商)
  6021. *
  6022. * @param array<string, mixed> $bundle
  6023. * @param array<string, mixed> $mailConfig
  6024. */
  6025. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  6026. {
  6027. $companyName = (string)($bundle['company_name'] ?? '');
  6028. $toEmail = (string)($bundle['email'] ?? '');
  6029. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  6030. $mailBody = (string)($bundle['mail_body'] ?? '');
  6031. $this->logIssueNotifyDebug('邮件', [
  6032. 'company' => $companyName,
  6033. 'email' => $toEmail,
  6034. 'mail_subject' => $mailSubject,
  6035. 'mail_body' => $mailPlain,
  6036. ]);
  6037. if ($this->isProcuremenNotifyDryRun()) {
  6038. $this->recordNotifyDryRunPreview([
  6039. 'scene' => 'issue_email',
  6040. 'company_name' => $companyName,
  6041. 'email' => $toEmail,
  6042. 'mail_subject' => $mailSubject,
  6043. 'mail_body' => $mailPlain,
  6044. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  6045. 'notify_vars' => $bundle['notify_vars'] ?? [],
  6046. 'detail_links' => $bundle['detail_links'] ?? [],
  6047. ]);
  6048. return;
  6049. }
  6050. $mail = new PHPMailer(true);
  6051. $mail->isSMTP();
  6052. $mail->Host = $mailConfig['host'];
  6053. $mail->SMTPAuth = true;
  6054. $mail->Username = $mailConfig['addr'];
  6055. $mail->Password = $mailConfig['pass'];
  6056. $mail->SMTPSecure = $mailConfig['security'];
  6057. $mail->Port = $mailConfig['port'];
  6058. $mail->CharSet = $mailConfig['charset'];
  6059. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  6060. $mail->addAddress($toEmail, $companyName);
  6061. $mail->isHTML(true);
  6062. $mail->Subject = $mailSubject;
  6063. $mail->Body = $mailBody;
  6064. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  6065. $sendOk = true;
  6066. $failReason = '';
  6067. try {
  6068. $mail->send();
  6069. } catch (\Throwable $e) {
  6070. $sendOk = false;
  6071. $failReason = $e->getMessage();
  6072. $this->persistEmailSendLog([
  6073. 'from_email' => $fromEmail,
  6074. 'to_email' => $toEmail,
  6075. 'send_time' => date('Y-m-d H:i:s'),
  6076. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6077. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6078. 'company_name' => $companyName,
  6079. 'mail_subject' => $mailSubject,
  6080. 'status' => 0,
  6081. 'fail_reason' => $failReason,
  6082. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6083. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6084. ]);
  6085. throw $e;
  6086. }
  6087. $this->persistEmailSendLog([
  6088. 'from_email' => $fromEmail,
  6089. 'to_email' => $toEmail,
  6090. 'send_time' => date('Y-m-d H:i:s'),
  6091. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  6092. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  6093. 'company_name' => $companyName,
  6094. 'mail_subject' => $mailSubject,
  6095. 'status' => 1,
  6096. 'fail_reason' => '',
  6097. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  6098. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  6099. ]);
  6100. }
  6101. /**
  6102. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  6103. *
  6104. * @param array<int, array<string, mixed>> $mergeRows
  6105. * @return array<string, mixed>
  6106. */
  6107. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  6108. {
  6109. $head = $mergeRows[0] ?? [];
  6110. $isMerge = count($mergeRows) > 1;
  6111. return [
  6112. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  6113. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  6114. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  6115. 'is_merge' => $isMerge,
  6116. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  6117. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  6118. 'deadline' => $sysRqNotify,
  6119. ];
  6120. }
  6121. /**
  6122. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  6123. *
  6124. * @param array<string, mixed> $data
  6125. */
  6126. protected function logIssueNotifyDebug(string $type, array $data): void
  6127. {
  6128. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  6129. return;
  6130. }
  6131. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  6132. }
  6133. protected function ensurePurchaseEmailSendLogTableOnce(): void
  6134. {
  6135. try {
  6136. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  6137. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6138. return;
  6139. } catch (\Throwable $e) {
  6140. }
  6141. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  6142. if (is_file($sqlFile)) {
  6143. $sql = file_get_contents($sqlFile);
  6144. if (is_string($sql) && $sql !== '') {
  6145. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  6146. $stmt = trim($stmt);
  6147. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  6148. continue;
  6149. }
  6150. try {
  6151. Db::execute($stmt);
  6152. } catch (\Throwable $ignore) {
  6153. }
  6154. }
  6155. }
  6156. }
  6157. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  6158. }
  6159. /**
  6160. * @param array<string, mixed> $row
  6161. */
  6162. protected function persistEmailSendLog(array $row): void
  6163. {
  6164. try {
  6165. $this->ensurePurchaseEmailSendLogTableOnce();
  6166. } catch (\Throwable $e) {
  6167. return;
  6168. }
  6169. list($adminId, $adminName) = $this->GetUseName();
  6170. $cut = function ($s, $max) {
  6171. $s = (string)$s;
  6172. if (function_exists('mb_substr')) {
  6173. return mb_substr($s, 0, $max, 'UTF-8');
  6174. }
  6175. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  6176. };
  6177. $data = [
  6178. 'from_email' => $cut($row['from_email'] ?? '', 128),
  6179. 'to_email' => $cut($row['to_email'] ?? '', 128),
  6180. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  6181. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  6182. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  6183. 'company_name' => $cut($row['company_name'] ?? '', 128),
  6184. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  6185. 'status' => !empty($row['status']) ? 1 : 0,
  6186. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  6187. 'admin_id' => (int)$adminId,
  6188. 'admin_name' => $cut($adminName, 64),
  6189. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  6190. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  6191. 'createtime' => date('Y-m-d H:i:s'),
  6192. ];
  6193. try {
  6194. Db::table('purchase_email_send_log')->insert($data);
  6195. } catch (\Throwable $e) {
  6196. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  6197. }
  6198. }
  6199. protected function formatEmailLogSceneText(string $scene): string
  6200. {
  6201. $map = [
  6202. 'pick_issue' => '初选下发',
  6203. 'audit_resend' => '确认页重发',
  6204. ];
  6205. return $map[$scene] ?? $scene;
  6206. }
  6207. /**
  6208. * 邮件发送日志列表
  6209. */
  6210. public function emailLog()
  6211. {
  6212. $this->relationSearch = false;
  6213. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  6214. $this->request->filter(['strip_tags', 'trim']);
  6215. $bakModel = $this->model;
  6216. $this->model = new \app\admin\model\Purchaseemailsendlog;
  6217. if ($this->request->isAjax()) {
  6218. $this->ensurePurchaseEmailSendLogTableOnce();
  6219. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6220. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6221. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6222. $list = $this->model
  6223. ->where($where)
  6224. ->order($sortField, $orderDir)
  6225. ->paginate($limit);
  6226. $rows = [];
  6227. foreach ($list->items() as $item) {
  6228. $row = is_array($item) ? $item : $item->toArray();
  6229. $scene = trim((string)($row['scene'] ?? ''));
  6230. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  6231. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  6232. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  6233. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  6234. $rows[] = $row;
  6235. }
  6236. $this->model = $bakModel;
  6237. return json(['total' => $list->total(), 'rows' => $rows]);
  6238. }
  6239. $this->model = $bakModel;
  6240. return $this->view->fetch('procuremen/emaillog');
  6241. }
  6242. /**
  6243. * 协助下发弹窗(选多家供应商并通知)
  6244. */
  6245. public function pickReview()
  6246. {
  6247. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  6248. $this->error(__('You have no permission'));
  6249. }
  6250. if ($this->request->isPost()) {
  6251. $this->error('请使用弹窗内「确认下发」提交');
  6252. }
  6253. $this->view->assign('pickMode', 1);
  6254. return $this->view->fetch('procuremen/review');
  6255. }
  6256. /**
  6257. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  6258. */
  6259. public function add()
  6260. {
  6261. if ($this->request->isPost()) {
  6262. $params = $this->request->post('row/a');
  6263. if (!is_array($params)) {
  6264. $this->error(__('Parameter %s can not be empty', ''));
  6265. }
  6266. [, $adminName] = $this->GetUseName();
  6267. $params['cywyxm'] = $adminName;
  6268. try {
  6269. $sid = $this->saveManualPickOrder($params);
  6270. } catch (\InvalidArgumentException $e) {
  6271. $this->error($e->getMessage());
  6272. } catch (\Throwable $e) {
  6273. $this->error($e->getMessage());
  6274. }
  6275. $this->success('新增成功', '', [
  6276. 'scydgy_id' => $sid,
  6277. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  6278. ]);
  6279. }
  6280. [, $adminName] = $this->GetUseName();
  6281. $this->view->assign('adminNickname', $adminName);
  6282. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  6283. $this->view->assign('defaultCclbmmc', '营销中心');
  6284. return $this->view->fetch();
  6285. }
  6286. /**
  6287. * 业务员新增进度查询(仅手工新增工序;普通用户只看 cywyxm=本人,超管看全部)
  6288. */
  6289. public function rfqlist()
  6290. {
  6291. $this->relationSearch = false;
  6292. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm';
  6293. $this->request->filter(['strip_tags', 'trim']);
  6294. if ($this->request->isAjax()) {
  6295. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  6296. $limit = max(10, min(500, (int)$limit));
  6297. $applyFilters = function ($query) use ($where) {
  6298. $query->where('scydgy_id', '<', 0);
  6299. $query->whereRaw(
  6300. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  6301. );
  6302. if (!$this->auth->isSuperAdmin()) {
  6303. [, $adminName] = $this->GetUseName();
  6304. $query->where('cywyxm', $adminName);
  6305. }
  6306. if (!empty($where)) {
  6307. $query->where($where);
  6308. }
  6309. };
  6310. $countQuery = Db::table('purchase_order');
  6311. $applyFilters($countQuery);
  6312. $total = (int)$countQuery->count();
  6313. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  6314. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  6315. $listQuery = Db::table('purchase_order');
  6316. $applyFilters($listQuery);
  6317. $rows = $listQuery
  6318. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,cywyxm,createtime,dStamp,status,wflow_status')
  6319. ->order($sortField, $orderDir)
  6320. ->limit($offset, $limit)
  6321. ->select();
  6322. if (!is_array($rows)) {
  6323. $rows = [];
  6324. }
  6325. $out = [];
  6326. foreach ($rows as $r) {
  6327. if (!is_array($r)) {
  6328. continue;
  6329. }
  6330. $sid = (int)($r['scydgy_id'] ?? 0);
  6331. if ($sid >= 0) {
  6332. continue;
  6333. }
  6334. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  6335. if ($createdText === '') {
  6336. $createdText = trim((string)($r['dStamp'] ?? ''));
  6337. }
  6338. $out[] = [
  6339. 'id' => (int)($r['id'] ?? 0),
  6340. 'scydgy_id' => $sid,
  6341. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6342. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6343. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  6344. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6345. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  6346. 'progress_text' => $this->formatProcuremenRfqProgressText($r),
  6347. 'createtime' => $r['createtime'] ?? null,
  6348. 'createtime_text' => $createdText,
  6349. ];
  6350. }
  6351. return json(['total' => $total, 'rows' => $out]);
  6352. }
  6353. [, $adminName] = $this->GetUseName();
  6354. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  6355. $this->view->assign('adminNickname', $adminName);
  6356. return $this->view->fetch('procuremen/rfqlist');
  6357. }
  6358. /**
  6359. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  6360. */
  6361. public function rfqlistDetails()
  6362. {
  6363. return $this->details();
  6364. }
  6365. /**
  6366. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  6367. */
  6368. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  6369. {
  6370. if ($scydgyId >= 0) {
  6371. return;
  6372. }
  6373. try {
  6374. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6375. } catch (\Throwable $e) {
  6376. $po = null;
  6377. }
  6378. if (!is_array($po)) {
  6379. $this->error('订单不存在');
  6380. }
  6381. $modRq = trim((string)($po['mod_rq'] ?? ''));
  6382. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  6383. $this->error('订单不存在');
  6384. }
  6385. if ($this->auth->isSuperAdmin()) {
  6386. return;
  6387. }
  6388. [, $adminName] = $this->GetUseName();
  6389. $cywy = trim((string)($po['cywyxm'] ?? ''));
  6390. if ($cywy !== '' && $cywy === $adminName) {
  6391. return;
  6392. }
  6393. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  6394. try {
  6395. if ($this->auth->check($rule)) {
  6396. return;
  6397. }
  6398. } catch (\Throwable $e) {
  6399. }
  6400. }
  6401. $this->error('无权查看该订单');
  6402. }
  6403. /**
  6404. * 手工新增协助工序进度文案
  6405. */
  6406. protected function formatProcuremenRfqProgressText(array $row): string
  6407. {
  6408. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  6409. return ProcuremenStatus::PO_COMPLETED;
  6410. }
  6411. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  6412. return '待采购确认';
  6413. }
  6414. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  6415. return '待确认供应商';
  6416. }
  6417. $sid = (int)($row['scydgy_id'] ?? 0);
  6418. if ($sid < 0) {
  6419. try {
  6420. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  6421. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  6422. $detCnt = (int)$detCntQuery->count();
  6423. if ($detCnt > 0) {
  6424. return '已下发待确认';
  6425. }
  6426. } catch (\Throwable $e) {
  6427. }
  6428. }
  6429. return '待协助下发';
  6430. }
  6431. /**
  6432. * 协助初选列表 — 批量软删除
  6433. */
  6434. public function pickDelete()
  6435. {
  6436. if (!$this->request->isPost() || !$this->request->isAjax()) {
  6437. $this->error(__('Invalid parameters'));
  6438. }
  6439. if (!$this->procuremenCanPickDelete()) {
  6440. $this->error(__('You have no permission'));
  6441. }
  6442. $rowsRaw = $this->request->post('rows_json', '[]');
  6443. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  6444. if (!is_array($rows) || $rows === []) {
  6445. $this->error('请至少勾选一条工序');
  6446. }
  6447. $done = 0;
  6448. Db::startTrans();
  6449. try {
  6450. foreach ($rows as $row) {
  6451. if (!is_array($row)) {
  6452. continue;
  6453. }
  6454. $this->softDeleteProcuremenPickRow($row);
  6455. $done++;
  6456. }
  6457. if ($done < 1) {
  6458. throw new \Exception('没有可删除的工序');
  6459. }
  6460. Db::commit();
  6461. } catch (\InvalidArgumentException $e) {
  6462. Db::rollback();
  6463. $this->error($e->getMessage());
  6464. } catch (\Throwable $e) {
  6465. Db::rollback();
  6466. $this->error($e->getMessage());
  6467. }
  6468. $this->pickHiddenScydgySetCache = null;
  6469. $this->success('已删除 ' . $done . ' 条工序');
  6470. }
  6471. /**
  6472. * 下发 — 手工新增工序(弹窗)
  6473. */
  6474. public function pickAdd()
  6475. {
  6476. if ($this->request->isPost()) {
  6477. $params = $this->request->post('row/a');
  6478. if (!is_array($params)) {
  6479. $this->error(__('Parameter %s can not be empty', ''));
  6480. }
  6481. try {
  6482. $sid = $this->saveManualPickOrder($params);
  6483. } catch (\InvalidArgumentException $e) {
  6484. $this->error($e->getMessage());
  6485. } catch (\Throwable $e) {
  6486. $this->error($e->getMessage());
  6487. }
  6488. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  6489. }
  6490. return $this->view->fetch('procuremen/pick_add');
  6491. }
  6492. /**
  6493. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  6494. */
  6495. public function pickSubmit()
  6496. {
  6497. if (!$this->request->isPost()) {
  6498. $this->error(__('Invalid parameters'));
  6499. }
  6500. // ---------- 接口订单数据 ----------
  6501. $rowJson = $this->request->post('row_json', '');
  6502. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  6503. $companiesJson = $this->request->post('companies_json', '[]');
  6504. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  6505. $companies = json_decode($companiesJson, true);
  6506. if (!is_array($companies)) {
  6507. $this->error('供应商数据无效');
  6508. }
  6509. $issueCompanies = $this->normalizePickCompanies($companies);
  6510. if ($issueCompanies === []) {
  6511. $this->error('请至少选择一家合作供应商');
  6512. }
  6513. $issueNameLabels = [];
  6514. foreach ($issueCompanies as $pc) {
  6515. $issueNameLabels[] = $pc['name'];
  6516. }
  6517. $issueNamesSummary = implode('、', $issueNameLabels);
  6518. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  6519. if ($sysRq === '') {
  6520. $this->error('请选择截止时间');
  6521. }
  6522. $sysRqTs = strtotime($sysRq);
  6523. if ($sysRqTs === false || $sysRqTs <= 0) {
  6524. $this->error('截止时间格式无效');
  6525. }
  6526. $sysRqDb = date('Y-m-d H:i:s', $sysRqTs);
  6527. $isMerge = count($mergeRows) > 1;
  6528. $ccydhLog = '';
  6529. foreach ($mergeRows as $row) {
  6530. if (!is_array($row)) {
  6531. continue;
  6532. }
  6533. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  6534. if ($ccydhLog !== '') {
  6535. break;
  6536. }
  6537. }
  6538. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  6539. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  6540. $logMsg = '下发' . $orderPart . $procPart
  6541. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  6542. $issueTime = date('Y-m-d H:i:s');
  6543. $logSidList = [];
  6544. foreach ($mergeRows as $row) {
  6545. if (!is_array($row)) {
  6546. continue;
  6547. }
  6548. $sid = $this->extractScydgyRowId($row);
  6549. if ($this->isValidScydgyRowId($sid)) {
  6550. $logSidList[$sid] = true;
  6551. }
  6552. }
  6553. $existingBySid = [];
  6554. if ($logSidList !== []) {
  6555. try {
  6556. $existingRows = Db::table('purchase_order')
  6557. ->where('scydgy_id', 'in', array_keys($logSidList))
  6558. ->select();
  6559. if (is_array($existingRows)) {
  6560. foreach ($existingRows as $poRow) {
  6561. if (!is_array($poRow)) {
  6562. continue;
  6563. }
  6564. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6565. if ($this->isValidScydgyRowId($sid)) {
  6566. $existingBySid[$sid] = $poRow;
  6567. }
  6568. }
  6569. }
  6570. } catch (\Throwable $e) {
  6571. $existingBySid = [];
  6572. }
  6573. }
  6574. Db::startTrans();
  6575. try {
  6576. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  6577. foreach ($mergeRows as $row) {
  6578. if (!is_array($row)) {
  6579. continue;
  6580. }
  6581. $sid = $this->extractScydgyRowId($row);
  6582. $this->upsertPurchaseOrderFromRow(
  6583. $row,
  6584. $sysRqDb,
  6585. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  6586. $issueTime,
  6587. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null
  6588. );
  6589. }
  6590. foreach ($issueCompanies as $c) {
  6591. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  6592. }
  6593. Db::commit();
  6594. } catch (\Throwable $e) {
  6595. Db::rollback();
  6596. $this->error($e->getMessage());
  6597. }
  6598. $poIdBySid = [];
  6599. if ($logSidList !== []) {
  6600. try {
  6601. $poIdBySid = Db::table('purchase_order')
  6602. ->where('scydgy_id', 'in', array_keys($logSidList))
  6603. ->column('id', 'scydgy_id');
  6604. } catch (\Throwable $e) {
  6605. $poIdBySid = [];
  6606. }
  6607. }
  6608. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  6609. if ($logSidList !== []) {
  6610. list($adminId, $adminName) = $this->GetUseName();
  6611. $cut = function ($s, $max) {
  6612. if (function_exists('mb_substr')) {
  6613. return mb_substr($s, 0, $max, 'UTF-8');
  6614. }
  6615. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  6616. };
  6617. $logRows = [];
  6618. $seenLogSid = [];
  6619. foreach ($mergeRows as $row) {
  6620. if (!is_array($row)) {
  6621. continue;
  6622. }
  6623. $ids = $this->extractScydgyRowId($row);
  6624. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  6625. continue;
  6626. }
  6627. $seenLogSid[$ids] = true;
  6628. $poIdLog = null;
  6629. if (isset($poIdBySid[$ids])) {
  6630. $tid = (int)$poIdBySid[$ids];
  6631. $poIdLog = $tid > 0 ? $tid : null;
  6632. }
  6633. $logRows[] = [
  6634. 'scydgy_id' => $ids,
  6635. 'purchase_order_id' => $poIdLog,
  6636. 'admin_id' => $adminId,
  6637. 'admin_name' => $cut($adminName, 64),
  6638. 'action' => $cut('issue_submit', 64),
  6639. 'content' => $cut($logMsg, 1000),
  6640. 'createtime' => ProcuremenTime::nowDateTime(),
  6641. ];
  6642. }
  6643. if ($logRows !== []) {
  6644. try {
  6645. Db::table('purchase_order_oper_log')->insertAll($logRows);
  6646. } catch (\Throwable $e) {
  6647. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  6648. }
  6649. }
  6650. }
  6651. $notifyErrors = [];
  6652. $posNotify = [];
  6653. if ($logSidList !== []) {
  6654. try {
  6655. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  6656. } catch (\Throwable $e) {
  6657. $posNotify = [];
  6658. }
  6659. }
  6660. if (!is_array($posNotify)) {
  6661. $posNotify = [];
  6662. }
  6663. foreach ($posNotify as $i => $prow) {
  6664. if (is_array($posNotify[$i])) {
  6665. $posNotify[$i]['sys_rq'] = $sysRqDb;
  6666. }
  6667. }
  6668. $ccydhPick = '';
  6669. foreach ($mergeRows as $row) {
  6670. if (!is_array($row)) {
  6671. continue;
  6672. }
  6673. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  6674. if ($ccydhPick !== '') {
  6675. break;
  6676. }
  6677. }
  6678. $notifyBundleBase = [
  6679. 'ccydh' => $ccydhPick,
  6680. 'pos' => $posNotify,
  6681. 'merge_rows' => $mergeRows,
  6682. ];
  6683. try {
  6684. $this->notifyDryRunPreview = [];
  6685. foreach ($issueCompanies as $c) {
  6686. if (!is_array($c)) {
  6687. continue;
  6688. }
  6689. $cname = trim((string)($c['name'] ?? ''));
  6690. if ($cname === '') {
  6691. continue;
  6692. }
  6693. try {
  6694. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  6695. } catch (\Throwable $e) {
  6696. $notifyErrors[] = $cname . ':' . $e->getMessage();
  6697. }
  6698. }
  6699. } catch (\Throwable $e) {
  6700. $this->error('通知发送失败:' . $e->getMessage());
  6701. }
  6702. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  6703. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  6704. }
  6705. if ($this->isProcuremenNotifyDryRun()) {
  6706. $this->success('【演练模式】已保存并生成通知预览', '', [
  6707. 'notify_dry_run' => true,
  6708. 'notify_preview' => $this->notifyDryRunPreview,
  6709. ]);
  6710. }
  6711. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  6712. }
  6713. /**
  6714. * 确认供应商弹窗
  6715. */
  6716. public function auditIssue()
  6717. {
  6718. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6719. if (is_array($ids)) {
  6720. $ids = isset($ids[0]) ? $ids[0] : '';
  6721. }
  6722. $ids = trim((string)$ids);
  6723. if ($ids === '') {
  6724. $this->error(__('Invalid parameters'));
  6725. }
  6726. if ($this->request->isPost()) {
  6727. $this->error('请使用弹窗内「确认」提交');
  6728. }
  6729. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  6730. $pos = $bundle['pos'];
  6731. if ($pos === []) {
  6732. $this->error('该订单不在待确认供应商状态');
  6733. }
  6734. $po = $pos[0];
  6735. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6736. if ($quoteGroups === []) {
  6737. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  6738. }
  6739. $pickedName = '';
  6740. foreach ($pos as $poRow) {
  6741. if (!is_array($poRow)) {
  6742. continue;
  6743. }
  6744. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  6745. if ($pn !== '') {
  6746. $pickedName = $pn;
  6747. break;
  6748. }
  6749. }
  6750. $this->view->assign('po', $po);
  6751. $this->view->assign('scydgyId', $ids);
  6752. $this->view->assign('orderCcydh', $bundle['ccydh']);
  6753. $mergeRows = $bundle['merge_rows'];
  6754. $this->view->assign('processRows', $mergeRows);
  6755. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  6756. $this->view->assign('processCount', count($mergeRows));
  6757. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  6758. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  6759. $this->view->assign('pickedCompanyName', $pickedName);
  6760. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  6761. if ($sysRqForView === '') {
  6762. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  6763. }
  6764. $this->view->assign('sysRq', $sysRqForView);
  6765. $this->view->assign('bidOpenVerified', $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0);
  6766. $this->view->assign('quoteDeadlineReached', $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0);
  6767. return $this->view->fetch('procuremen/audit_issue');
  6768. }
  6769. /**
  6770. * 开标双重验证 — 可选验证人列表
  6771. */
  6772. public function bidOpenUsers()
  6773. {
  6774. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  6775. $this->error('无权限');
  6776. }
  6777. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  6778. if ($scydgyId !== '') {
  6779. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6780. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6781. $this->success('已完成开标验证', null, [
  6782. 'verified' => 1,
  6783. 'users' => [],
  6784. ]);
  6785. }
  6786. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  6787. }
  6788. $this->success('', null, [
  6789. 'verified' => 0,
  6790. 'users' => $this->listBidOpenVerifierCandidates(),
  6791. ]);
  6792. }
  6793. /**
  6794. * 开标双重验证 — 向指定管理员发送短信验证码
  6795. */
  6796. public function bidOpenSendCode()
  6797. {
  6798. if (!$this->request->isPost()) {
  6799. $this->error(__('Invalid parameters'));
  6800. }
  6801. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  6802. $this->error('无权限');
  6803. }
  6804. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6805. $adminId = (int)$this->request->post('admin_id', 0);
  6806. if ($scydgyId === '' || $adminId <= 0) {
  6807. $this->error('参数无效');
  6808. }
  6809. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6810. if ($bundle['pos'] === []) {
  6811. $this->error('该订单不在待确认供应商状态');
  6812. }
  6813. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6814. $this->success('已完成开标验证,无需重复发送');
  6815. }
  6816. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  6817. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6818. if ($ccydh === '') {
  6819. $this->error('订单号无效');
  6820. }
  6821. $admin = $this->loadBidOpenAdminUser($adminId);
  6822. if ($admin === null) {
  6823. $this->error('验证人无效或未绑定手机号');
  6824. }
  6825. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  6826. $cd = max(30, min(120, $cd));
  6827. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  6828. $this->error('发送过于频繁,请稍后再试');
  6829. }
  6830. $code = (string)random_int(100000, 999999);
  6831. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  6832. $ttl = max(60, min(600, $ttl));
  6833. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  6834. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  6835. try {
  6836. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  6837. } catch (\Throwable $e) {
  6838. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  6839. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  6840. $this->error($e->getMessage());
  6841. }
  6842. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  6843. }
  6844. /**
  6845. * 开标双重验证 — 两人验证码校验并记录
  6846. */
  6847. public function bidOpenVerify()
  6848. {
  6849. if (!$this->request->isPost()) {
  6850. $this->error(__('Invalid parameters'));
  6851. }
  6852. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  6853. $this->error('无权限');
  6854. }
  6855. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6856. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  6857. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  6858. $code1 = trim((string)$this->request->post('code1', ''));
  6859. $code2 = trim((string)$this->request->post('code2', ''));
  6860. if ($scydgyId === '') {
  6861. $this->error('参数无效');
  6862. }
  6863. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  6864. $this->error('请选择两位验证人');
  6865. }
  6866. if ($verifier1Id === $verifier2Id) {
  6867. $this->error('两位验证人不能相同');
  6868. }
  6869. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  6870. $this->error('请输入6位短信验证码');
  6871. }
  6872. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6873. if ($bundle['pos'] === []) {
  6874. $this->error('该订单不在待确认供应商状态');
  6875. }
  6876. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6877. if ($ccydh === '') {
  6878. $this->error('订单号无效');
  6879. }
  6880. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6881. $this->success('已完成开标验证');
  6882. }
  6883. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  6884. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  6885. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  6886. if ($verifier1 === null || $verifier2 === null) {
  6887. $this->error('验证人无效或未绑定手机号');
  6888. }
  6889. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  6890. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  6891. }
  6892. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  6893. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  6894. }
  6895. try {
  6896. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  6897. } catch (\Throwable $e) {
  6898. $this->error($e->getMessage());
  6899. }
  6900. $this->success('开标验证成功,可查看供应商报价与交货日期');
  6901. }
  6902. /**
  6903. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  6904. */
  6905. public function auditSubmit()
  6906. {
  6907. if (!$this->request->isPost()) {
  6908. $this->error(__('Invalid parameters'));
  6909. }
  6910. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6911. if ($scydgyId === '') {
  6912. $this->error('参数无效');
  6913. }
  6914. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  6915. $pos = $bundle['pos'];
  6916. $mergeRows = $bundle['merge_rows'];
  6917. if ($pos === [] || $mergeRows === []) {
  6918. $this->error('该订单不在待确认供应商状态');
  6919. }
  6920. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  6921. if ($quoteGroups === []) {
  6922. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  6923. }
  6924. $companyName = trim((string)$this->request->post('selected_company', ''));
  6925. if ($companyName === '') {
  6926. $this->error('请选择一家供应商');
  6927. }
  6928. $matched = null;
  6929. foreach ($quoteGroups as $g) {
  6930. if (!is_array($g)) {
  6931. continue;
  6932. }
  6933. if (trim((string)($g['name'] ?? '')) === $companyName) {
  6934. $matched = $g;
  6935. break;
  6936. }
  6937. }
  6938. if ($matched === null) {
  6939. $this->error('所选供应商不在本单报价列表中');
  6940. }
  6941. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  6942. if ($sysRqDb === '') {
  6943. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true);
  6944. } else {
  6945. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true);
  6946. }
  6947. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  6948. $this->error('请先完成开标双重验证后再确认供应商');
  6949. }
  6950. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  6951. $procCnt = count($mergeRows);
  6952. $orderPart = $ccydhLog !== '' ? '(订单' . $ccydhLog . ')' : '';
  6953. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  6954. $logMsg = '确认供应商' . $orderPart . $procPart . ':已选定「' . $companyName . '」';
  6955. Db::startTrans();
  6956. try {
  6957. foreach ($pos as $poRow) {
  6958. if (!is_array($poRow)) {
  6959. continue;
  6960. }
  6961. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6962. if (!$this->isValidScydgyRowId($sid)) {
  6963. continue;
  6964. }
  6965. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  6966. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  6967. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6968. 'pick_company_name' => $companyName,
  6969. 'sys_rq' => $sysRqDb,
  6970. ]);
  6971. }
  6972. Db::commit();
  6973. } catch (\Throwable $e) {
  6974. Db::rollback();
  6975. $this->error($e->getMessage());
  6976. }
  6977. foreach ($pos as $poRow) {
  6978. if (!is_array($poRow)) {
  6979. continue;
  6980. }
  6981. $sid = (int)($poRow['scydgy_id'] ?? 0);
  6982. if (!$this->isValidScydgyRowId($sid)) {
  6983. continue;
  6984. }
  6985. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  6986. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  6987. }
  6988. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  6989. }
  6990. /**
  6991. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  6992. */
  6993. public function auditResendSms()
  6994. {
  6995. if (!$this->request->isPost()) {
  6996. $this->error(__('Invalid parameters'));
  6997. }
  6998. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  6999. if ($scydgyId === '') {
  7000. $this->error('参数无效');
  7001. }
  7002. $loaded = $this->loadAuditResendBundle($scydgyId);
  7003. $mergeRows = $loaded['merge_rows'];
  7004. $bundle = $loaded['bundle'];
  7005. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  7006. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7007. if ($quoteGroups === []) {
  7008. $this->error('暂无可通知的供应商');
  7009. }
  7010. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  7011. $companiesJson = (string)$this->request->post('companies_json', '');
  7012. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  7013. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  7014. }
  7015. /**
  7016. * 确认供应商 — 二次发送邮件(可选单家/批量)
  7017. */
  7018. public function auditResendEmail()
  7019. {
  7020. if (!$this->request->isPost()) {
  7021. $this->error(__('Invalid parameters'));
  7022. }
  7023. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  7024. if ($scydgyId === '') {
  7025. $this->error('参数无效');
  7026. }
  7027. $loaded = $this->loadAuditResendBundle($scydgyId);
  7028. $mergeRows = $loaded['merge_rows'];
  7029. $bundle = $loaded['bundle'];
  7030. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  7031. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  7032. if ($quoteGroups === []) {
  7033. $this->error('暂无可通知的供应商');
  7034. }
  7035. $companiesJson = (string)$this->request->post('companies_json', '');
  7036. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  7037. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  7038. if ($companiesJson === '' && $selectedCompany === '') {
  7039. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  7040. }
  7041. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  7042. }
  7043. /**
  7044. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  7045. *
  7046. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  7047. * @return array<int, true> 已处理的 scydgy_id 集合
  7048. */
  7049. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  7050. {
  7051. $pos = $bundle['pos'] ?? [];
  7052. if (!is_array($pos) || $pos === []) {
  7053. return [];
  7054. }
  7055. $sids = [];
  7056. foreach ($pos as $poRow) {
  7057. if (!is_array($poRow)) {
  7058. continue;
  7059. }
  7060. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7061. if ($this->isValidScydgyRowId($sid)) {
  7062. $sids[$sid] = true;
  7063. }
  7064. }
  7065. if ($sids === []) {
  7066. return [];
  7067. }
  7068. $ccydhLog = trim((string)($bundle['ccydh'] ?? ''));
  7069. $logMsg = '重新下发' . ($ccydhLog !== '' ? '(' . $ccydhLog . ')' : '');
  7070. $suffix = trim((string)$logSuffix, ',, ');
  7071. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  7072. $logMsg .= ':从历史存证退回协助初选';
  7073. } else {
  7074. $logMsg .= ':退回协助初选';
  7075. }
  7076. Db::table('purchase_order')
  7077. ->where('scydgy_id', 'in', array_keys($sids))
  7078. ->update([
  7079. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  7080. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7081. 'pick_company_name' => '',
  7082. 'pick_time' => null,
  7083. 'sys_rq' => null,
  7084. 'mod_rq' => null,
  7085. ]);
  7086. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  7087. foreach (array_keys($sids) as $sid) {
  7088. $this->addOrderLog((int)$sid, $logAction, $logMsg, null);
  7089. }
  7090. return $sids;
  7091. }
  7092. /**
  7093. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  7094. *
  7095. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  7096. */
  7097. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  7098. {
  7099. $scydgyId = trim($scydgyId);
  7100. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7101. if ($scydgyId === '') {
  7102. return $empty;
  7103. }
  7104. try {
  7105. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  7106. } catch (\Throwable $e) {
  7107. $anchor = null;
  7108. }
  7109. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  7110. return $empty;
  7111. }
  7112. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  7113. if ($ccydh === '') {
  7114. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  7115. }
  7116. try {
  7117. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  7118. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  7119. $pos = $query->order('scydgy_id', 'asc')->select();
  7120. } catch (\Throwable $e) {
  7121. $pos = [$anchor];
  7122. }
  7123. if (!is_array($pos) || $pos === []) {
  7124. $pos = [$anchor];
  7125. }
  7126. return [
  7127. 'ccydh' => $ccydh,
  7128. 'pos' => $pos,
  7129. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  7130. ];
  7131. }
  7132. protected function purchaseOrderRowIsCompleted(array $po): bool
  7133. {
  7134. $st = $po['status'] ?? null;
  7135. if ($st === 1 || $st === '1') {
  7136. return true;
  7137. }
  7138. if (is_string($st) && trim($st) === '1') {
  7139. return true;
  7140. }
  7141. return is_numeric($st) && (int)$st === 1;
  7142. }
  7143. /**
  7144. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  7145. */
  7146. public function auditAbandon()
  7147. {
  7148. if (!$this->request->isPost()) {
  7149. $this->error(__('Invalid parameters'));
  7150. }
  7151. $anchorIds = [];
  7152. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7153. if ($batchRaw !== '') {
  7154. $decoded = json_decode($batchRaw, true);
  7155. if (is_array($decoded)) {
  7156. foreach ($decoded as $id) {
  7157. $s = trim((string)$id);
  7158. if ($s !== '') {
  7159. $anchorIds[] = $s;
  7160. }
  7161. }
  7162. }
  7163. }
  7164. if ($anchorIds === []) {
  7165. $single = trim((string)$this->request->post('scydgy_id', ''));
  7166. if ($single !== '') {
  7167. $anchorIds[] = $single;
  7168. }
  7169. }
  7170. if ($anchorIds === []) {
  7171. $this->error('请至少选择一条订单');
  7172. }
  7173. $processedCcydh = [];
  7174. $doneOrders = 0;
  7175. $allSids = [];
  7176. Db::startTrans();
  7177. try {
  7178. foreach ($anchorIds as $anchorId) {
  7179. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  7180. if (($bundle['pos'] ?? []) === []) {
  7181. continue;
  7182. }
  7183. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7184. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7185. if (isset($processedCcydh[$dedupeKey])) {
  7186. continue;
  7187. }
  7188. $processedCcydh[$dedupeKey] = true;
  7189. $sids = $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  7190. if ($sids === []) {
  7191. continue;
  7192. }
  7193. $doneOrders++;
  7194. foreach (array_keys($sids) as $sid) {
  7195. $allSids[(int)$sid] = true;
  7196. }
  7197. }
  7198. if ($doneOrders < 1) {
  7199. throw new \Exception('所选订单均不在待确认供应商状态');
  7200. }
  7201. Db::commit();
  7202. } catch (\Throwable $e) {
  7203. Db::rollback();
  7204. $this->error($e->getMessage());
  7205. }
  7206. $this->pickHiddenScydgySetCache = null;
  7207. $msg = $doneOrders > 1
  7208. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  7209. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7210. $this->success($msg);
  7211. }
  7212. /**
  7213. * 历史存证 — 已完结订单重新下发,退回协助初选(支持单条或批量)
  7214. */
  7215. public function archiveAbandon()
  7216. {
  7217. if (!$this->request->isPost()) {
  7218. $this->error(__('Invalid parameters'));
  7219. }
  7220. if (!$this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon'])) {
  7221. $this->error(__('You have no permission'));
  7222. }
  7223. $anchorIds = [];
  7224. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  7225. if ($batchRaw !== '') {
  7226. $decoded = json_decode($batchRaw, true);
  7227. if (is_array($decoded)) {
  7228. foreach ($decoded as $id) {
  7229. $s = trim((string)$id);
  7230. if ($s !== '') {
  7231. $anchorIds[] = $s;
  7232. }
  7233. }
  7234. }
  7235. }
  7236. if ($anchorIds === []) {
  7237. $single = trim((string)$this->request->post('scydgy_id', ''));
  7238. if ($single !== '') {
  7239. $anchorIds[] = $single;
  7240. }
  7241. }
  7242. if ($anchorIds === []) {
  7243. $this->error('请至少选择一条订单');
  7244. }
  7245. $processedCcydh = [];
  7246. $doneOrders = 0;
  7247. Db::startTrans();
  7248. try {
  7249. foreach ($anchorIds as $anchorId) {
  7250. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  7251. if (($bundle['pos'] ?? []) === []) {
  7252. continue;
  7253. }
  7254. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7255. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  7256. if (isset($processedCcydh[$dedupeKey])) {
  7257. continue;
  7258. }
  7259. $processedCcydh[$dedupeKey] = true;
  7260. $sids = $this->abandonOrderBundleToPick(
  7261. $bundle,
  7262. 'archive_abandon',
  7263. ',从历史存证退回协助初选'
  7264. );
  7265. if ($sids === []) {
  7266. continue;
  7267. }
  7268. $doneOrders++;
  7269. }
  7270. if ($doneOrders < 1) {
  7271. throw new \Exception('所选订单均不是已完结状态');
  7272. }
  7273. Db::commit();
  7274. } catch (\Throwable $e) {
  7275. Db::rollback();
  7276. $this->error($e->getMessage());
  7277. }
  7278. $this->pickHiddenScydgySetCache = null;
  7279. $msg = $doneOrders > 1
  7280. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史记录已保留')
  7281. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  7282. $this->success($msg);
  7283. }
  7284. /**
  7285. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  7286. */
  7287. public function purchaseApprovalReject()
  7288. {
  7289. if (!$this->request->isPost() || !$this->request->isAjax()) {
  7290. $this->error(__('Invalid parameters'));
  7291. }
  7292. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  7293. $this->error(__('You have no permission'));
  7294. }
  7295. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  7296. $decoded = json_decode($batchRaw, true);
  7297. if (!is_array($decoded) || $decoded === []) {
  7298. $this->error('提交数据无效');
  7299. }
  7300. $done = 0;
  7301. Db::startTrans();
  7302. try {
  7303. foreach ($decoded as $item) {
  7304. if (!is_array($item)) {
  7305. continue;
  7306. }
  7307. $sid = (int)($item['scydgy_id'] ?? 0);
  7308. if (!$this->isValidScydgyRowId($sid)) {
  7309. continue;
  7310. }
  7311. $this->runPurchaseApprovalRejectForSid($sid);
  7312. $done++;
  7313. }
  7314. if ($done < 1) {
  7315. throw new \Exception('所选订单均不在待审批状态');
  7316. }
  7317. Db::commit();
  7318. } catch (\Throwable $e) {
  7319. Db::rollback();
  7320. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  7321. }
  7322. $this->pickHiddenScydgySetCache = null;
  7323. $this->success('已驳回并退回「协助审批下发」');
  7324. }
  7325. /**
  7326. * @throws \Exception
  7327. */
  7328. protected function runPurchaseApprovalRejectForSid(int $sid): void
  7329. {
  7330. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  7331. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  7332. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  7333. $allIds = $this->purchaseOrderDetail($sid);
  7334. if ($allIds === []) {
  7335. throw new \Exception('未找到下发明细');
  7336. }
  7337. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  7338. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  7339. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7340. 'pick_company_name' => '',
  7341. ]);
  7342. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  7343. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  7344. $poId = 0;
  7345. try {
  7346. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  7347. if (is_array($po)) {
  7348. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7349. }
  7350. } catch (\Throwable $e) {
  7351. }
  7352. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  7353. }
  7354. /**
  7355. * 审核弹窗(旧入口,POST 已关闭)
  7356. */
  7357. public function review()
  7358. {
  7359. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  7360. $this->error(__('You have no permission'));
  7361. }
  7362. if ($this->request->isPost()) {
  7363. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  7364. }
  7365. $this->view->assign('pickMode', 0);
  7366. return $this->view->fetch('procuremen/review');
  7367. }
  7368. /**
  7369. * 审核弹窗获取公司列表
  7370. */
  7371. public function reviewCompanies()
  7372. {
  7373. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review'])) {
  7374. $this->error(__('You have no permission'));
  7375. }
  7376. if (!$this->request->isAjax()) {
  7377. $this->error(__('Invalid parameters'));
  7378. }
  7379. $list = [];
  7380. try {
  7381. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  7382. $rows = Db::table('customer')
  7383. ->where(function ($q) {
  7384. $q->where('status', 1)
  7385. ->whereOr('status', '1')
  7386. ->whereOr('status', '')
  7387. ->whereNull('status');
  7388. })
  7389. ->order('id', 'desc')
  7390. ->select();
  7391. } catch (\Throwable $e) {
  7392. $this->success('', '', []);
  7393. return;
  7394. }
  7395. if (!is_array($rows)) {
  7396. $this->success('', '', []);
  7397. return;
  7398. }
  7399. $detailColCandidates = [
  7400. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  7401. 'company_detail', 'company_desc', 'address',
  7402. ];
  7403. foreach ($rows as $row) {
  7404. if (!is_array($row)) {
  7405. continue;
  7406. }
  7407. $norm = [];
  7408. foreach ($row as $k => $v) {
  7409. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  7410. }
  7411. $row = $norm;
  7412. $st = $row['status'] ?? '';
  7413. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  7414. continue;
  7415. }
  7416. $payload = $this->buildCustomerContactPayloadFromRow($row);
  7417. if ($payload === null) {
  7418. continue;
  7419. }
  7420. $detail = '';
  7421. foreach ($detailColCandidates as $dk) {
  7422. if (!isset($row[$dk])) {
  7423. continue;
  7424. }
  7425. $dv = trim((string)$row[$dk]);
  7426. if ($dv !== '') {
  7427. $detail = $dv;
  7428. break;
  7429. }
  7430. }
  7431. $payload['detail'] = $detail;
  7432. $list[] = $this->maskSupplierContactFields($payload);
  7433. }
  7434. $this->success('', '', $list);
  7435. }
  7436. /**
  7437. * 采购确认-下发明细弹窗:
  7438. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  7439. */
  7440. public function outward_detail()
  7441. {
  7442. $ids = $this->request->param('ids', $this->request->param('id', ''));
  7443. if (is_array($ids)) {
  7444. $ids = isset($ids[0]) ? $ids[0] : '';
  7445. }
  7446. $ids = trim((string)$ids);
  7447. if ($ids === '') {
  7448. $this->error(__('Invalid parameters'));
  7449. }
  7450. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  7451. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  7452. $wffTab = 'all';
  7453. }
  7454. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  7455. $purchaseOrderId = 0;
  7456. $po = null;
  7457. try {
  7458. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7459. if (is_array($po)) {
  7460. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7461. }
  7462. } catch (\Throwable $e) {
  7463. $purchaseOrderId = 0;
  7464. $po = null;
  7465. }
  7466. if (!$isPurchaseConfirm && is_array($po)) {
  7467. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  7468. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  7469. $isPurchaseConfirm = true;
  7470. }
  7471. }
  7472. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  7473. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  7474. $confirmProcessCount = 1;
  7475. $confirmPickGroups = [];
  7476. $processDisplayRows = [];
  7477. $allDetailsBySid = [];
  7478. $requiredSidList = [];
  7479. $sidList = [$ids];
  7480. if ($isPurchaseConfirm) {
  7481. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  7482. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  7483. if ($mergeRows !== []) {
  7484. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  7485. }
  7486. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  7487. if ($confirmBundle['pos'] !== []) {
  7488. $sidList = [];
  7489. foreach ($confirmBundle['pos'] as $poRow) {
  7490. if (!is_array($poRow)) {
  7491. continue;
  7492. }
  7493. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7494. if (!$this->isValidScydgyRowId($sid)) {
  7495. continue;
  7496. }
  7497. $sidList[] = (string)$sid;
  7498. $requiredSidList[] = $sid;
  7499. }
  7500. }
  7501. if ($sidList === []) {
  7502. $sidList = [$ids];
  7503. $requiredSidList = [(int)$ids];
  7504. }
  7505. $confirmProcessCount = max(1, count($requiredSidList));
  7506. if (is_array($po) && $purchaseOrderId <= 0) {
  7507. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  7508. }
  7509. }
  7510. $rows = [];
  7511. try {
  7512. if (count($sidList) === 1) {
  7513. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  7514. } else {
  7515. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  7516. }
  7517. } catch (\Throwable $e) {
  7518. $rows = [];
  7519. }
  7520. if ($isPurchaseConfirm) {
  7521. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  7522. }
  7523. foreach ($rows as &$r) {
  7524. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  7525. $r['id'] = $r['ID'];
  7526. }
  7527. if (isset($r['createtime'])) {
  7528. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  7529. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  7530. } else {
  7531. $r['createtime_text'] = (string)$r['createtime'];
  7532. }
  7533. } else {
  7534. $r['createtime_text'] = '';
  7535. }
  7536. if (is_array($r)) {
  7537. $r = $this->maskSupplierContactFields($r);
  7538. }
  7539. }
  7540. unset($r);
  7541. $pickedCompanyName = '';
  7542. if ($isPurchaseConfirm) {
  7543. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  7544. if (!is_array($poRow)) {
  7545. continue;
  7546. }
  7547. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  7548. if ($pn !== '') {
  7549. $pickedCompanyName = $pn;
  7550. break;
  7551. }
  7552. }
  7553. }
  7554. $this->view->assign('rows', $rows ?: []);
  7555. $this->view->assign('rowCount', count($rows ?: []));
  7556. $this->view->assign('scydgyId', $ids);
  7557. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  7558. $this->view->assign('headTitle', $headTitle);
  7559. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  7560. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  7561. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  7562. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  7563. $this->view->assign('processDisplayRows', $processDisplayRows);
  7564. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  7565. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  7566. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  7567. $sysRqDisplay = '—';
  7568. if ($isPurchaseConfirm) {
  7569. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  7570. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  7571. );
  7572. }
  7573. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  7574. $this->view->assign('sysRq', $isPurchaseConfirm
  7575. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  7576. : '');
  7577. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  7578. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  7579. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  7580. if ($isPurchaseConfirm) {
  7581. return $this->view->fetch();
  7582. }
  7583. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  7584. $this->view->engine->layout(false);
  7585. try {
  7586. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  7587. $this->view->assign('dialogBody', $bodyHtml);
  7588. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  7589. } finally {
  7590. if ($restoreLayout) {
  7591. $this->view->engine->layout($restoreLayout);
  7592. }
  7593. }
  7594. }
  7595. /**
  7596. * 月度导出记录表(不存在时自动创建)
  7597. */
  7598. protected function ensurePurchaseMonthExportLogTable(): void
  7599. {
  7600. try {
  7601. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  7602. } catch (\Throwable $e) {
  7603. Db::execute(
  7604. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  7605. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  7606. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  7607. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  7608. `admin_name` varchar(64) NOT NULL DEFAULT '',
  7609. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  7610. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  7611. `createtime` int(10) unsigned DEFAULT NULL,
  7612. PRIMARY KEY (`id`),
  7613. KEY `idx_ym` (`ym`),
  7614. KEY `idx_ct` (`createtime`)
  7615. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  7616. );
  7617. }
  7618. }
  7619. /**
  7620. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  7621. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  7622. */
  7623. public function export_month_outward()
  7624. {
  7625. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  7626. $this->error(__('You have no permission'));
  7627. }
  7628. $this->request->filter(['strip_tags', 'trim']);
  7629. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  7630. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  7631. $ym = date('Y-m');
  7632. }
  7633. $dbRows = [];
  7634. try {
  7635. $query = Db::table('purchase_order');
  7636. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  7637. $dbRows = $query->select();
  7638. } catch (\Throwable $e) {
  7639. $dbRows = [];
  7640. }
  7641. if (!is_array($dbRows)) {
  7642. $dbRows = [];
  7643. }
  7644. $completeTsMap = [];
  7645. $sidList = [];
  7646. foreach ($dbRows as $dbRow) {
  7647. if (!is_array($dbRow)) {
  7648. continue;
  7649. }
  7650. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  7651. if ($sid > 0) {
  7652. $sidList[$sid] = true;
  7653. }
  7654. }
  7655. if ($sidList !== []) {
  7656. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  7657. }
  7658. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  7659. if (!is_array($dbRow)) {
  7660. return false;
  7661. }
  7662. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  7663. return $done['ts'] > 0 && date('Y-m', $done['ts']) === $ym;
  7664. }));
  7665. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  7666. $filtered = $pool;
  7667. $mainBySid = [];
  7668. foreach ($filtered as $rw) {
  7669. if (!is_array($rw)) {
  7670. continue;
  7671. }
  7672. $rid = (int)($rw['ID'] ?? 0);
  7673. if ($rid > 0) {
  7674. $mainBySid[$rid] = $rw;
  7675. }
  7676. }
  7677. if ($mainBySid === []) {
  7678. $detailRows = [];
  7679. } else {
  7680. try {
  7681. $detailRows = Db::table('purchase_order_detail')
  7682. ->where('scydgy_id', 'in', array_keys($mainBySid))
  7683. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  7684. ->order('status', 'desc')
  7685. ->order('CCYDH', 'asc')
  7686. ->order('company_name', 'asc')
  7687. ->order('id', 'asc')
  7688. ->select();
  7689. } catch (\Throwable $e) {
  7690. try {
  7691. $detailRows = Db::table('purchase_order_detail')
  7692. ->where('scydgy_id', 'in', array_keys($mainBySid))
  7693. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  7694. ->order('status', 'desc')
  7695. ->order('CCYDH', 'asc')
  7696. ->order('company_name', 'asc')
  7697. ->order('ID', 'asc')
  7698. ->select();
  7699. } catch (\Throwable $e2) {
  7700. $detailRows = [];
  7701. }
  7702. }
  7703. }
  7704. if (!is_array($detailRows)) {
  7705. $detailRows = [];
  7706. }
  7707. $exportLines = [];
  7708. $detailSidSeen = [];
  7709. foreach ($detailRows as $dr) {
  7710. if (!is_array($dr)) {
  7711. continue;
  7712. }
  7713. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  7714. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  7715. continue;
  7716. }
  7717. if (isset($detailSidSeen[$sid])) {
  7718. continue;
  7719. }
  7720. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  7721. continue;
  7722. }
  7723. $detailSidSeen[$sid] = true;
  7724. $m = $mainBySid[$sid];
  7725. $exportLines[] = [
  7726. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  7727. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  7728. 'company_name' => (string)($dr['company_name'] ?? ''),
  7729. 'CDF' => (string)($m['CDF'] ?? ''),
  7730. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  7731. 'gx' => $this->procuremenExportGxText($m),
  7732. 'detail' => $dr,
  7733. ];
  7734. }
  7735. foreach ($detailRows as $dr) {
  7736. if (!is_array($dr)) {
  7737. continue;
  7738. }
  7739. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  7740. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  7741. continue;
  7742. }
  7743. $detailSidSeen[$sid] = true;
  7744. $m = $mainBySid[$sid];
  7745. $exportLines[] = [
  7746. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  7747. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  7748. 'company_name' => (string)($dr['company_name'] ?? ''),
  7749. 'CDF' => (string)($m['CDF'] ?? ''),
  7750. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  7751. 'gx' => $this->procuremenExportGxText($m),
  7752. 'detail' => $dr,
  7753. ];
  7754. }
  7755. foreach ($mainBySid as $sid => $m) {
  7756. if (isset($detailSidSeen[$sid])) {
  7757. continue;
  7758. }
  7759. $company = trim((string)($m['pick_company_name'] ?? ''));
  7760. $exportLines[] = [
  7761. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  7762. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  7763. 'company_name' => $company,
  7764. 'CDF' => (string)($m['CDF'] ?? ''),
  7765. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  7766. 'gx' => $this->procuremenExportGxText($m),
  7767. 'detail' => [],
  7768. ];
  7769. }
  7770. $groups = [];
  7771. foreach ($exportLines as $line) {
  7772. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  7773. if (!isset($groups[$k])) {
  7774. $groups[$k] = [];
  7775. }
  7776. $groups[$k][] = $line;
  7777. }
  7778. ksort($groups, SORT_STRING);
  7779. $spreadsheet = new Spreadsheet();
  7780. $sheet = $spreadsheet->getActiveSheet();
  7781. $sheet->setTitle('外协加工明细');
  7782. $mon = (int)substr($ym, 5, 2);
  7783. $sheet->mergeCells('A1:H1');
  7784. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  7785. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  7786. $sheet->getStyle('A1')->getAlignment()
  7787. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  7788. ->setVertical(Alignment::VERTICAL_CENTER);
  7789. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  7790. $col = 'A';
  7791. foreach ($headers as $h) {
  7792. $sheet->setCellValue($col . '2', $h);
  7793. $col++;
  7794. }
  7795. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  7796. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7797. $rowNum = 3;
  7798. $sumSubtotalCounts = 0;
  7799. $grandAmount = 0.0;
  7800. $globalSeq = 0;
  7801. if ($groups === []) {
  7802. $sheet->mergeCells('A3:H3');
  7803. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  7804. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  7805. $rowNum = 4;
  7806. } else {
  7807. foreach ($groups as $items) {
  7808. if ($items === []) {
  7809. continue;
  7810. }
  7811. $groupLineCount = count($items);
  7812. $subAmount = 0.0;
  7813. foreach ($items as $line) {
  7814. $globalSeq++;
  7815. $dr = $line['detail'];
  7816. $amt = $this->procuremenExportAmount($dr);
  7817. $subAmount += $amt;
  7818. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  7819. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  7820. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  7821. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  7822. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  7823. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  7824. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  7825. $sheet->setCellValue('H' . $rowNum, $amt);
  7826. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  7827. $rowNum++;
  7828. }
  7829. $sumSubtotalCounts += $groupLineCount;
  7830. $grandAmount += $subAmount;
  7831. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  7832. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  7833. $sheet->getStyle('G' . $rowNum)->getAlignment()
  7834. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  7835. ->setVertical(Alignment::VERTICAL_CENTER);
  7836. $rowNum++;
  7837. }
  7838. }
  7839. $sheet->setCellValue('A' . $rowNum, '总计');
  7840. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  7841. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  7842. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  7843. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  7844. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  7845. $lastRow = $rowNum;
  7846. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  7847. 'borders' => [
  7848. 'allBorders' => [
  7849. 'borderStyle' => Border::BORDER_THIN,
  7850. 'color' => ['rgb' => '000000'],
  7851. ],
  7852. ],
  7853. ]);
  7854. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  7855. if ($lastRow >= 3) {
  7856. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7857. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7858. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7859. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  7860. }
  7861. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  7862. $sheet->getColumnDimension('A')->setWidth(7);
  7863. $sheet->getColumnDimension('B')->setWidth(16);
  7864. $sheet->getColumnDimension('C')->setWidth(52);
  7865. $sheet->getColumnDimension('D')->setWidth(32);
  7866. $sheet->getColumnDimension('E')->setWidth(12);
  7867. $sheet->getColumnDimension('F')->setWidth(44);
  7868. $sheet->getColumnDimension('G')->setWidth(26);
  7869. $sheet->getColumnDimension('H')->setWidth(13);
  7870. $sheet->getRowDimension(1)->setRowHeight(28);
  7871. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  7872. $quoteStartRow = $lastRow + 3;
  7873. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, $quoteStartRow);
  7874. if ($quoteLastRow >= $quoteStartRow) {
  7875. $sheet->getColumnDimension('E')->setWidth(28);
  7876. }
  7877. $ymCompact = str_replace('-', '', $ym);
  7878. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  7879. $filename = $fileBase . '.xlsx';
  7880. try {
  7881. $this->ensurePurchaseMonthExportLogTable();
  7882. list($adminId, $adminName) = $this->GetUseName();
  7883. Db::table('purchase_month_export_log')->insert([
  7884. 'ym' => $ym,
  7885. 'admin_id' => (int)$adminId,
  7886. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  7887. 'row_count' => count($exportLines),
  7888. 'total_amount' => round($grandAmount, 2),
  7889. 'createtime' => time(),
  7890. ]);
  7891. } catch (\Throwable $e) {
  7892. Log::write('month export log: ' . $e->getMessage(), 'error');
  7893. }
  7894. if (ob_get_length()) {
  7895. ob_end_clean();
  7896. }
  7897. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  7898. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  7899. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  7900. header('Cache-Control: max-age=0');
  7901. $writer = new Xlsx($spreadsheet);
  7902. $writer->save('php://output');
  7903. $spreadsheet->disconnectWorksheets();
  7904. unset($spreadsheet);
  7905. exit;
  7906. }
  7907. /**
  7908. * 导出用:工序列文案
  7909. */
  7910. protected function procuremenExportGxText(array $r)
  7911. {
  7912. $a = trim((string)($r['CDXMC'] ?? ''));
  7913. $b = trim((string)($r['CGYMC'] ?? ''));
  7914. if ($a !== '' && $b !== '') {
  7915. return $a . ':' . $b;
  7916. }
  7917. return $a !== '' ? $a : $b;
  7918. }
  7919. /**
  7920. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  7921. */
  7922. protected function procuremenExportAmount(array $r)
  7923. {
  7924. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  7925. if (!array_key_exists($k, $r)) {
  7926. continue;
  7927. }
  7928. $v = $r[$k];
  7929. if ($v === null || $v === '') {
  7930. continue;
  7931. }
  7932. if (is_numeric($v)) {
  7933. return (float)$v;
  7934. }
  7935. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  7936. if ($v !== '' && is_numeric($v)) {
  7937. return (float)$v;
  7938. }
  7939. }
  7940. return 0.0;
  7941. }
  7942. /**
  7943. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  7944. *
  7945. * @param array<int, array<string, mixed>> $detailRows
  7946. * @param array<int, array<string, mixed>> $mainBySid
  7947. * @return array<int, array<string, mixed>>
  7948. */
  7949. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  7950. {
  7951. $lines = [];
  7952. foreach ($detailRows as $dr) {
  7953. if (!is_array($dr)) {
  7954. continue;
  7955. }
  7956. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  7957. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  7958. continue;
  7959. }
  7960. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  7961. continue;
  7962. }
  7963. $cn = trim((string)($dr['company_name'] ?? ''));
  7964. if ($cn === '') {
  7965. continue;
  7966. }
  7967. $m = $mainBySid[$sid];
  7968. $am = trim((string)($dr['amount'] ?? ''));
  7969. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  7970. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  7971. $amountText = $amountFilled
  7972. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  7973. : '未填写';
  7974. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  7975. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  7976. if ($deliveryShow === '' && $deliveryRaw !== '') {
  7977. $deliveryShow = $deliveryRaw;
  7978. }
  7979. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  7980. ? $deliveryShow
  7981. : '未填写';
  7982. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  7983. $lines[] = [
  7984. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  7985. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  7986. 'gx' => $this->procuremenExportGxText($m),
  7987. 'company_name' => $cn,
  7988. 'amount_text' => $amountText,
  7989. 'amount_num' => $amountFilled ? $amountNum : null,
  7990. 'delivery_text' => $deliveryText,
  7991. 'picked_text' => $picked ? '中标' : '未中标',
  7992. 'picked' => $picked,
  7993. ];
  7994. }
  7995. $winnerSupplierByOrder = [];
  7996. foreach ($lines as $line) {
  7997. $dh = trim((string)($line['CCYDH'] ?? ''));
  7998. $cn = trim((string)($line['company_name'] ?? ''));
  7999. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  8000. $winnerSupplierByOrder[$dh][$cn] = true;
  8001. }
  8002. }
  8003. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  8004. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  8005. if ($c !== 0) {
  8006. return $c;
  8007. }
  8008. $dh = trim((string)($a['CCYDH'] ?? ''));
  8009. $aCn = trim((string)($a['company_name'] ?? ''));
  8010. $bCn = trim((string)($b['company_name'] ?? ''));
  8011. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  8012. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  8013. if ($aSupplierWin !== $bSupplierWin) {
  8014. return $aSupplierWin ? -1 : 1;
  8015. }
  8016. $c = strcmp($aCn, $bCn);
  8017. if ($c !== 0) {
  8018. return $c;
  8019. }
  8020. if (!empty($a['picked']) !== !empty($b['picked'])) {
  8021. return !empty($a['picked']) ? -1 : 1;
  8022. }
  8023. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  8024. if ($c !== 0) {
  8025. return $c;
  8026. }
  8027. return 0;
  8028. });
  8029. return $lines;
  8030. }
  8031. /**
  8032. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  8033. *
  8034. * @param array<int, array<string, mixed>> $quoteLines
  8035. */
  8036. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  8037. {
  8038. $mon = (int)substr($ym, 5, 2);
  8039. $titleRow = $startRow;
  8040. $headerRow = $startRow + 1;
  8041. $dataStartRow = $startRow + 2;
  8042. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  8043. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  8044. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  8045. $sheet->getStyle('A' . $titleRow)->getAlignment()
  8046. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8047. ->setVertical(Alignment::VERTICAL_CENTER);
  8048. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  8049. $col = 'A';
  8050. foreach ($headers as $h) {
  8051. $sheet->setCellValue($col . $headerRow, $h);
  8052. $col++;
  8053. }
  8054. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  8055. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8056. $rowNum = $dataStartRow;
  8057. if ($quoteLines === []) {
  8058. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  8059. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  8060. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  8061. $rowNum = $dataStartRow + 1;
  8062. } else {
  8063. $i = 0;
  8064. foreach ($quoteLines as $line) {
  8065. $i++;
  8066. $sheet->setCellValue('A' . $rowNum, $i);
  8067. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  8068. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  8069. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  8070. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  8071. if ($line['amount_num'] !== null) {
  8072. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  8073. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  8074. } else {
  8075. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  8076. }
  8077. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  8078. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  8079. if (!empty($line['picked'])) {
  8080. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  8081. }
  8082. $rowNum++;
  8083. }
  8084. }
  8085. $lastRow = $rowNum - 1;
  8086. if ($lastRow >= $headerRow) {
  8087. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  8088. 'borders' => [
  8089. 'allBorders' => [
  8090. 'borderStyle' => Border::BORDER_THIN,
  8091. 'color' => ['rgb' => '000000'],
  8092. ],
  8093. ],
  8094. ]);
  8095. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  8096. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8097. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8098. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  8099. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  8100. if ($lastRow >= $dataStartRow) {
  8101. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  8102. }
  8103. }
  8104. return $lastRow;
  8105. }
  8106. /**
  8107. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  8108. */
  8109. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  8110. {
  8111. if ($lastRow < $dataStartRow || $headerRow < 1) {
  8112. return;
  8113. }
  8114. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  8115. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8116. ->setVertical(Alignment::VERTICAL_CENTER);
  8117. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  8118. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  8119. ->setVertical(Alignment::VERTICAL_CENTER);
  8120. if ($lastCol > 'B') {
  8121. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  8122. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  8123. ->setVertical(Alignment::VERTICAL_CENTER);
  8124. }
  8125. }
  8126. /**
  8127. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  8128. */
  8129. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  8130. {
  8131. $s = trim($ccydh);
  8132. if ($s === '') {
  8133. return 'ORDER';
  8134. }
  8135. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  8136. $s = trim($s, '._-');
  8137. if ($s === '') {
  8138. return 'ORDER';
  8139. }
  8140. if (function_exists('mb_substr')) {
  8141. return mb_substr($s, 0, 80, 'UTF-8');
  8142. }
  8143. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  8144. }
  8145. /**
  8146. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  8147. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  8148. *
  8149. * @return array{objectKey: string, webPath: string}
  8150. */
  8151. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  8152. {
  8153. $sid = (int)$scydgyId;
  8154. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  8155. $y = date('Y');
  8156. $m = date('m');
  8157. $d = date('d');
  8158. $basename = $safeOrder . '_' . $sid . '.pdf';
  8159. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  8160. return [
  8161. 'objectKey' => $objectKey,
  8162. 'webPath' => '/' . $objectKey,
  8163. ];
  8164. }
  8165. /**
  8166. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  8167. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  8168. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  8169. *
  8170. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  8171. */
  8172. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  8173. {
  8174. if (!$this->isValidScydgyRowId($scydgyId)) {
  8175. return '';
  8176. }
  8177. $ids = trim((string)$scydgyId);
  8178. $prep = $this->prepareProcuremenDetailsView($ids);
  8179. if (!$prep['ok']) {
  8180. return '';
  8181. }
  8182. $ccydh = $prep['ccydh'];
  8183. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  8184. $objectKey = $paths['objectKey'];
  8185. $webPath = $paths['webPath'];
  8186. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  8187. $this->view->assign([
  8188. 'pdf_export' => 1,
  8189. 'pdfMetaLine' => $meta,
  8190. ]);
  8191. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  8192. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  8193. $this->view->engine->layout(false);
  8194. try {
  8195. $html = $this->view->fetch('procuremen/details_pdf_shell');
  8196. } catch (\Throwable $e) {
  8197. if ($restoreLayout) {
  8198. $this->view->engine->layout($restoreLayout);
  8199. }
  8200. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  8201. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  8202. return '';
  8203. }
  8204. if ($restoreLayout) {
  8205. $this->view->engine->layout($restoreLayout);
  8206. }
  8207. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  8208. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  8209. if (!is_dir($tempDir)) {
  8210. @mkdir($tempDir, 0755, true);
  8211. }
  8212. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  8213. try {
  8214. $mpdf = new \Mpdf\Mpdf([
  8215. 'mode' => 'utf-8',
  8216. 'format' => 'A4',
  8217. 'margin_left' => 12,
  8218. 'margin_right' => 12,
  8219. 'margin_top' => 14,
  8220. 'margin_bottom' => 14,
  8221. 'tempDir' => $tempDir,
  8222. 'autoScriptToLang' => true,
  8223. 'autoLangToFont' => true,
  8224. ]);
  8225. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  8226. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  8227. $mpdf->SetBasePath('http://127.0.0.1/');
  8228. $mpdf->WriteHTML($html);
  8229. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  8230. } catch (\Throwable $e) {
  8231. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  8232. if (is_file($tempPdf)) {
  8233. @unlink($tempPdf);
  8234. }
  8235. return '';
  8236. }
  8237. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  8238. if ($ossUrl !== '') {
  8239. @unlink($tempPdf);
  8240. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8241. return $ossUrl;
  8242. }
  8243. $pi = pathinfo($objectKey);
  8244. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  8245. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  8246. if ($baseFile === '') {
  8247. @unlink($tempPdf);
  8248. return '';
  8249. }
  8250. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  8251. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  8252. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  8253. @unlink($tempPdf);
  8254. return '';
  8255. }
  8256. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  8257. if (!@copy($tempPdf, $fullPath)) {
  8258. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  8259. @unlink($tempPdf);
  8260. return '';
  8261. }
  8262. @unlink($tempPdf);
  8263. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  8264. return $webPath;
  8265. }
  8266. /**
  8267. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  8268. */
  8269. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  8270. {
  8271. if ($scydgyId <= 0 || $webPath === '') {
  8272. return;
  8273. }
  8274. try {
  8275. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  8276. } catch (\Throwable $e) {
  8277. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  8278. }
  8279. }
  8280. /**
  8281. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  8282. *
  8283. * @param array<string, string> $vars
  8284. * @return array<string, string>
  8285. */
  8286. protected function normalizeSmsTemplateVars(array $vars): array
  8287. {
  8288. $out = [];
  8289. foreach ($vars as $k => $v) {
  8290. $out[(string)$k] = trim((string)$v);
  8291. }
  8292. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  8293. $out['contact_name'] = $out['company_name'];
  8294. }
  8295. return $out;
  8296. }
  8297. /**
  8298. * 按手机号或公司名称查 customer 表联系人姓名
  8299. */
  8300. protected function resolveCustomerContactName(string $phone, string $companyName): string
  8301. {
  8302. $phone = trim($phone);
  8303. $companyName = trim($companyName);
  8304. try {
  8305. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  8306. $row = Db::table('customer')
  8307. ->where(function ($q) use ($phone) {
  8308. $q->where('phone', $phone)->whereOr('account', $phone);
  8309. })
  8310. ->order('id', 'asc')
  8311. ->find();
  8312. if (is_array($row)) {
  8313. $nm = trim((string)($row['username'] ?? ''));
  8314. if ($nm !== '') {
  8315. return $nm;
  8316. }
  8317. }
  8318. }
  8319. if ($companyName !== '') {
  8320. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  8321. if (is_array($row)) {
  8322. return trim((string)($row['username'] ?? ''));
  8323. }
  8324. }
  8325. } catch (\Throwable $e) {
  8326. }
  8327. return '';
  8328. }
  8329. /**
  8330. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  8331. */
  8332. protected function plainTextToHtmlEmailBody(string $text): string
  8333. {
  8334. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  8335. $parts = explode("\n", $text);
  8336. $out = [];
  8337. foreach ($parts as $line) {
  8338. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  8339. $out[] = $line;
  8340. } else {
  8341. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  8342. }
  8343. }
  8344. return implode("<br>\n", $out);
  8345. }
  8346. /**
  8347. * 短信场景:去掉链接类变量,避免误填 URL
  8348. *
  8349. * @param array<string, string> $vars
  8350. * @return array<string, string>
  8351. */
  8352. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  8353. {
  8354. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  8355. return $vars;
  8356. }
  8357. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  8358. $vars[$k] = '';
  8359. }
  8360. return $vars;
  8361. }
  8362. /**
  8363. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  8364. *
  8365. * @param array<string, string> $vars
  8366. */
  8367. protected function renderNotifyTemplate(string $scene, array $vars): string
  8368. {
  8369. $vars = $this->normalizeSmsTemplateVars($vars);
  8370. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  8371. $row = $this->loadNotifyTemplateRow($scene);
  8372. if ($row === null) {
  8373. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  8374. }
  8375. $tpl = trim((string)($row['content'] ?? ''));
  8376. if ($tpl === '') {
  8377. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  8378. }
  8379. foreach ($vars as $k => $v) {
  8380. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  8381. }
  8382. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  8383. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  8384. return $tpl;
  8385. }
  8386. protected function resolveProcuremenEmailSubject(string $scene): string
  8387. {
  8388. $map = [
  8389. 'review_email' => '您有新的协助加工订单',
  8390. ];
  8391. $subject = trim((string)($map[$scene] ?? ''));
  8392. if ($subject === '') {
  8393. $this->error('未配置邮件主题:' . $scene);
  8394. }
  8395. return $subject;
  8396. }
  8397. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  8398. {
  8399. $map = [
  8400. 'review_email' => '协助下发-邮箱',
  8401. 'review_sms' => '协助下发-短信',
  8402. 'confirm_ok' => '采购确认-通过',
  8403. 'confirm_fail' => '采购确认-未通过',
  8404. 'bid_open' => '开标双重验证',
  8405. ];
  8406. $label = $map[$scene] ?? $scene;
  8407. if ($titleRequired) {
  8408. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  8409. }
  8410. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  8411. }
  8412. /**
  8413. * 是否开启协助通知演练(不发真实短信/邮件)
  8414. */
  8415. protected function isProcuremenNotifyDryRun(): bool
  8416. {
  8417. return (bool)Config::get('procuremen_notify_dry_run');
  8418. }
  8419. /**
  8420. * @param array<string, mixed> $payload
  8421. */
  8422. protected function recordNotifyDryRunPreview(array $payload): void
  8423. {
  8424. $this->notifyDryRunPreview[] = $payload;
  8425. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  8426. }
  8427. /**
  8428. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  8429. * @throws \Exception
  8430. */
  8431. protected function smsbao($phone, $content)
  8432. {
  8433. if ($this->isProcuremenNotifyDryRun()) {
  8434. $this->recordNotifyDryRunPreview([
  8435. 'scene' => 'sms_only',
  8436. 'phone' => $phone,
  8437. 'sms_content' => $content,
  8438. ]);
  8439. return;
  8440. }
  8441. $statusStr = [
  8442. '0' => '短信发送成功',
  8443. '-1' => '参数不全',
  8444. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  8445. '30' => '密码错误',
  8446. '40' => '账号不存在',
  8447. '41' => '余额不足',
  8448. '42' => '帐户已过期',
  8449. '43' => 'IP地址限制',
  8450. '50' => '内容含有敏感词',
  8451. ];
  8452. $smsapi = 'http://api.smsbao.com/';
  8453. $user = 'zhuwei123';
  8454. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  8455. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  8456. $result = @file_get_contents($sendurl);
  8457. if ($result === false) {
  8458. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  8459. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  8460. }
  8461. $result = trim((string)$result);
  8462. if ($result !== '0') {
  8463. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  8464. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  8465. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  8466. }
  8467. }
  8468. }