Procuremen.php 506 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414
  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\ProcuremenSchema;
  8. use app\common\library\ProcuremenStatus;
  9. use app\common\library\ProcuremenSupplierScore;
  10. use app\common\library\ProcuremenTime;
  11. use PHPMailer\PHPMailer\PHPMailer;
  12. use think\Config;
  13. use think\Cache;
  14. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  15. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  16. use PhpOffice\PhpSpreadsheet\Style\Border;
  17. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  18. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  19. use think\Db;
  20. use think\Log;
  21. class Procuremen extends Backend
  22. {
  23. /**
  24. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  25. */
  26. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,b.czlyq,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  27. /**
  28. * Procuremen模型对象
  29. * @var \app\admin\model\Procuremen
  30. */
  31. protected $model = null;
  32. /**
  33. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  34. */
  35. protected $notifyDryRunPreview = [];
  36. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  37. protected $procuremenRedisCache = null;
  38. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  39. protected $pickHiddenScydgySetCache = null;
  40. /** 邮件发送日志表结构已就绪缓存键 */
  41. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  42. /**
  43. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  44. * @var array
  45. */
  46. protected $noNeedRight = [
  47. 'pickreview', 'review', 'reviewcompanies',
  48. // 方法内用 hasProcuremenPerm 校验(兼容 auditsubmit / auditissue)
  49. 'auditmanualpick',
  50. // 与 rfqlist 同权,方法内校验
  51. 'rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqissuesuppliers', 'rfqissue', 'rfqissuesendmail', 'rfqquotes',
  52. 'rfqappendsuppliers', 'rfqsupplieroptions', 'rfqsalesmanoptions', 'rfqappendsalesmen',
  53. ];
  54. public function _initialize()
  55. {
  56. parent::_initialize();
  57. $this->model = new \app\admin\model\Procuremen;
  58. $this->maybeMigrateLegacyWflowStatusText();
  59. $this->assignProcuremenAuthConfig();
  60. try {
  61. ProcuremenSchema::ensureAll();
  62. } catch (\Throwable $e) {
  63. }
  64. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  65. $this->ensurePurchaseEmailSendLogTableOnce();
  66. }
  67. }
  68. /**
  69. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  70. */
  71. protected function maybeMigrateLegacyWflowStatusText(): void
  72. {
  73. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  74. if (is_file($flagFile)) {
  75. return;
  76. }
  77. $map = [
  78. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  79. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  80. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  81. '3' => ProcuremenStatus::WFLOW_APPROVED,
  82. ];
  83. try {
  84. foreach ($map as $num => $text) {
  85. Db::table('purchase_order')
  86. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  87. ->update(['wflow_status' => $text]);
  88. }
  89. @file_put_contents($flagFile, date('c'));
  90. } catch (\Throwable $e) {
  91. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  92. }
  93. }
  94. /**
  95. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  96. *
  97. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  98. */
  99. protected function hasProcuremenPerm(array $actions): bool
  100. {
  101. foreach ($actions as $action) {
  102. $action = strtolower(trim((string)$action));
  103. if ($action === '') {
  104. continue;
  105. }
  106. if (strpos($action, 'procuremen/') !== 0) {
  107. $action = 'procuremen/' . $action;
  108. }
  109. if ($this->auth->check($action)) {
  110. return true;
  111. }
  112. }
  113. $suffixes = [];
  114. foreach ($actions as $action) {
  115. $action = strtolower(trim((string)$action));
  116. $action = preg_replace('#^procuremen/#', '', $action);
  117. if ($action !== '') {
  118. $suffixes[$action] = true;
  119. }
  120. }
  121. if ($suffixes === []) {
  122. return false;
  123. }
  124. try {
  125. foreach ($this->auth->getRuleList() as $rule) {
  126. $rule = strtolower((string)$rule);
  127. if (strpos($rule, 'procuremen/') !== 0) {
  128. continue;
  129. }
  130. foreach (array_keys($suffixes) as $suffix) {
  131. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  132. return true;
  133. }
  134. }
  135. }
  136. } catch (\Throwable $e) {
  137. }
  138. return false;
  139. }
  140. /**
  141. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  142. *
  143. * @param string[] $actions
  144. */
  145. protected function hasProcuremenPermStrict(array $actions): bool
  146. {
  147. foreach ($actions as $action) {
  148. $action = strtolower(trim((string)$action));
  149. if ($action === '') {
  150. continue;
  151. }
  152. if (strpos($action, 'procuremen/') !== 0) {
  153. $action = 'procuremen/' . $action;
  154. }
  155. if ($this->auth->check($action)) {
  156. return true;
  157. }
  158. }
  159. return false;
  160. }
  161. /**
  162. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  163. *
  164. * @param string[] $titles
  165. */
  166. protected function authHasAssignedRuleTitle(array $titles): bool
  167. {
  168. $titles = array_values(array_filter(array_map('trim', $titles)));
  169. if ($titles === []) {
  170. return false;
  171. }
  172. try {
  173. $ids = $this->auth->getRuleIds();
  174. if (in_array('*', $ids, true)) {
  175. return true;
  176. }
  177. if ($ids === []) {
  178. return false;
  179. }
  180. $rows = Db::name('auth_rule')
  181. ->where('status', 'normal')
  182. ->whereIn('id', $ids)
  183. ->column('title');
  184. foreach ($rows as $title) {
  185. $t = trim((string)$title);
  186. if ($t !== '' && in_array($t, $titles, true)) {
  187. return true;
  188. }
  189. }
  190. } catch (\Throwable $e) {
  191. }
  192. return false;
  193. }
  194. protected function procuremenCanPickDelete(): bool
  195. {
  196. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  197. return true;
  198. }
  199. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  200. }
  201. protected function procuremenCanComplete(): bool
  202. {
  203. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  204. return true;
  205. }
  206. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  207. }
  208. protected function procuremenCanDispatch(): bool
  209. {
  210. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  211. }
  212. /**
  213. * 前端按钮显隐(Config.procuremenAuth)
  214. */
  215. protected function assignProcuremenAuthConfig(): void
  216. {
  217. $authMap = [
  218. 'pickreview' => $this->procuremenCanDispatch(),
  219. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  220. 'pickdelete' => $this->procuremenCanPickDelete(),
  221. 'completedirectly' => $this->procuremenCanComplete(),
  222. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  223. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  224. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  225. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  226. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  227. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  228. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  229. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  230. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  231. 'details' => $this->hasProcuremenPerm(['details']),
  232. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  233. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  234. 'export_month_quote' => $this->hasProcuremenPerm(['export_month_quote', 'exportMonthQuote', 'export_month_outward', 'exportMonthOutward']),
  235. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  236. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  237. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  238. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  239. 'auditmanualpick' => $this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue']),
  240. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  241. 'add' => $this->hasProcuremenPerm(['add']),
  242. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  243. // 查询询价三个操作按钮:各自独立,不再因有 rfqlist 就全部放开
  244. 'rfqissue' => $this->hasProcuremenPerm(['rfqissue']),
  245. 'rfqquotes' => $this->hasProcuremenPerm(['rfqquotes']),
  246. 'rfqnotifysalesman' => $this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen']),
  247. 'rfqnotifysalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman']),
  248. // 询价附属接口:有「询价」按钮权限即可(无需再单独勾选)
  249. 'rfqissuesuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers']),
  250. 'rfqissuesendmail' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail']),
  251. 'rfqappendsuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers']),
  252. 'rfqsupplieroptions' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions']),
  253. 'rfqsalesmanoptions' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen']),
  254. 'rfqappendsalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen']),
  255. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  256. ];
  257. $this->assignconfig('procuremenAuth', $authMap);
  258. }
  259. /**
  260. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  261. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  262. *
  263. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  264. */
  265. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  266. {
  267. static $mprocCfgLoaded = false;
  268. if (!$mprocCfgLoaded) {
  269. $mprocCfgLoaded = true;
  270. if (is_file(APP_PATH . 'extra/mproc.php')) {
  271. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  272. }
  273. }
  274. $eid = (int)$purchaseOrderDetailId;
  275. $base = $this->resolveMprocMobilePublicBaseUrl();
  276. if ($base === '') {
  277. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  278. }
  279. $path = trim((string)Config::get('mproc.mobile_index_path'));
  280. if ($path === '') {
  281. $path = '/index.php/index/index/index';
  282. } else {
  283. $path = '/' . ltrim($path, '/');
  284. }
  285. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  286. if ($eid > 0) {
  287. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  288. }
  289. return $base . $path . '?main_tab=orders';
  290. }
  291. /**
  292. * 邮件/短信外链:须为带点的公网域名
  293. */
  294. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  295. {
  296. $u = trim((string)$baseUrl);
  297. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  298. return false;
  299. }
  300. $host = parse_url($u, PHP_URL_HOST);
  301. if (!is_string($host) || $host === '') {
  302. return false;
  303. }
  304. if (strcasecmp($host, 'localhost') === 0) {
  305. return false;
  306. }
  307. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  308. return false;
  309. }
  310. if (strpos($host, '.') === false) {
  311. return false;
  312. }
  313. return true;
  314. }
  315. /**
  316. * 解析用于协助邮件/短信的手机端站点根
  317. */
  318. protected function resolveMprocMobilePublicBaseUrl()
  319. {
  320. $candidates = [];
  321. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  322. $candidates[] = trim((string)Config::get('site.indexurl'));
  323. $cdn = trim((string)Config::get('site.cdnurl'));
  324. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  325. $candidates[] = rtrim($cdn, '/');
  326. }
  327. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  328. $candidates[] = $reqBase;
  329. foreach ($candidates as $c) {
  330. if ($c === '') {
  331. continue;
  332. }
  333. $c = rtrim($c, '/');
  334. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  335. return $c;
  336. }
  337. }
  338. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  339. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  340. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  341. return $reqBase;
  342. }
  343. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  344. return '';
  345. }
  346. /**
  347. * 获取 Redis 中 procuremen_redis
  348. */
  349. protected function ProcuremenRedis(): array
  350. {
  351. if ($this->procuremenRedisCache !== null) {
  352. return $this->procuremenRedisCache;
  353. }
  354. try {
  355. $redis = redis();
  356. $raw = $redis->get('procuremen_redis');
  357. if ($raw === false || $raw === '') {
  358. $this->procuremenRedisCache = [];
  359. return $this->procuremenRedisCache;
  360. }
  361. $decoded = json_decode($raw, true);
  362. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  363. $this->procuremenRedisCache = [];
  364. return $this->procuremenRedisCache;
  365. }
  366. $this->procuremenRedisCache = $decoded['data'];
  367. // 整包已解码时顺带补齐侧栏小键,避免下次首屏再扫库
  368. if ($this->loadProcuremenSidebarYmList() === []) {
  369. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($this->procuremenRedisCache));
  370. }
  371. return $this->procuremenRedisCache;
  372. } catch (\Throwable $e) {
  373. $this->procuremenRedisCache = [];
  374. return $this->procuremenRedisCache;
  375. }
  376. }
  377. /**
  378. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  379. *
  380. * @return array<int, array<string, mixed>>
  381. */
  382. protected function procuremenFetchErpPoolFromDb(): array
  383. {
  384. try {
  385. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  386. $endTime = date('Y-m-d 23:59:59');
  387. $list = Db::table('scydgy')
  388. ->alias('a')
  389. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  390. ->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, b.czlyq, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  391. ->where([
  392. 'a.bwjg' => 1,
  393. 'a.iEndBz' => 0,
  394. 'a.iType' => 0,
  395. 'a.iStatus' => 10,
  396. ])
  397. ->where('a.dStamp', '>=', $startTime)
  398. ->where('a.dStamp', '<=', $endTime)
  399. ->order('a.dStamp', 'desc')
  400. ->select();
  401. if (!is_array($list)) {
  402. return [];
  403. }
  404. try {
  405. $redis = redis();
  406. $payload = [
  407. 'code' => 200,
  408. 'msg' => 'success',
  409. 'data' => $list,
  410. ];
  411. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  412. $this->procuremenRedisCache = $list;
  413. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($list));
  414. $this->clearPickMonthPoolCaches();
  415. $this->warmPickMonthPoolCachesFromPool($list);
  416. } catch (\Throwable $e) {
  417. }
  418. return $list;
  419. } catch (\Throwable $e) {
  420. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  421. return [];
  422. }
  423. }
  424. /**
  425. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  426. *
  427. * @return array<int, array<string, mixed>>
  428. */
  429. protected function procuremenEnsureRedisPool(): array
  430. {
  431. $pool = $this->ProcuremenRedis();
  432. if (is_array($pool) && $pool !== []) {
  433. return $pool;
  434. }
  435. static $warmed = false;
  436. if ($warmed) {
  437. return is_array($pool) ? $pool : [];
  438. }
  439. $warmed = true;
  440. return $this->procuremenFetchErpPoolFromDb();
  441. }
  442. /**
  443. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  444. *
  445. * @param array<string, mixed> $row
  446. */
  447. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  448. {
  449. $t = $this->procuremenRowListSortTime($row, $primary);
  450. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  451. return null;
  452. }
  453. $mo = (int)$m[2];
  454. if ($mo < 1 || $mo > 12) {
  455. return null;
  456. }
  457. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  458. }
  459. /**
  460. * @param array<int, array{year:string, months:array}> $sidebar
  461. * @return array<int, array{year:string, months:array}>
  462. */
  463. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  464. {
  465. $ym = trim($ym);
  466. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  467. return $sidebar;
  468. }
  469. foreach ($sidebar as $block) {
  470. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  471. continue;
  472. }
  473. foreach ($block['months'] as $item) {
  474. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  475. return $sidebar;
  476. }
  477. }
  478. }
  479. $y = substr($ym, 0, 4);
  480. $mo = (int)substr($ym, 5, 2);
  481. $sidebar[] = [
  482. 'year' => $y,
  483. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  484. ];
  485. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  486. }
  487. /**
  488. * @param array<int, array{year:string, months:array}> $sidebar
  489. * @return string[]
  490. */
  491. protected function flattenProcuremenSidebarYms(array $sidebar): array
  492. {
  493. $yms = [];
  494. foreach ($sidebar as $block) {
  495. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  496. continue;
  497. }
  498. foreach ($block['months'] as $item) {
  499. if (!is_array($item)) {
  500. continue;
  501. }
  502. $ym = trim((string)($item['ym'] ?? ''));
  503. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  504. $yms[$ym] = true;
  505. }
  506. }
  507. }
  508. return array_keys($yms);
  509. }
  510. /**
  511. * 左侧菜单(协助初选)
  512. * 优先 Redis 月份小键;为空时用轻量 DISTINCT 查库补齐(避免只显示空当月、漏掉有数据的月份)。
  513. */
  514. protected function GetIndexYearMonths()
  515. {
  516. $ymList = $this->ensureProcuremenPickSidebarYmList();
  517. if ($ymList === []) {
  518. $def = date('Y-m');
  519. $ymList = [preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m')];
  520. }
  521. return $this->buildYearMonthSidebar($ymList);
  522. }
  523. /**
  524. * 初选侧栏月份:以轻量 DISTINCT 查库为准(有数据才显示),并写回 Redis 小键。
  525. *
  526. * @return string[]
  527. */
  528. protected function ensureProcuremenPickSidebarYmList(bool $forceRefresh = false): array
  529. {
  530. static $memo = null;
  531. if (!$forceRefresh && is_array($memo)) {
  532. return $memo;
  533. }
  534. $fromDb = $this->queryProcuremenPickSidebarYmListLight();
  535. if ($fromDb !== []) {
  536. $this->saveProcuremenSidebarYmList($fromDb);
  537. $memo = $fromDb;
  538. return $memo;
  539. }
  540. // 库侧暂无初选数据时,再回退 Redis / 当月,避免侧栏空白
  541. $cached = $this->loadProcuremenSidebarYmList();
  542. if ($cached !== []) {
  543. $memo = $cached;
  544. return $memo;
  545. }
  546. $memo = [date('Y-m')];
  547. return $memo;
  548. }
  549. /**
  550. * @return string[] 形如 2026-07
  551. */
  552. protected function loadProcuremenSidebarYmList(): array
  553. {
  554. try {
  555. $raw = redis()->get('procuremen_redis_yms');
  556. if ($raw === false || $raw === null || $raw === '') {
  557. return [];
  558. }
  559. $decoded = json_decode((string)$raw, true);
  560. if (!is_array($decoded)) {
  561. return [];
  562. }
  563. $out = [];
  564. foreach ($decoded as $ym) {
  565. $ym = trim((string)$ym);
  566. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  567. $out[$ym] = true;
  568. }
  569. }
  570. return array_keys($out);
  571. } catch (\Throwable $e) {
  572. return [];
  573. }
  574. }
  575. /**
  576. * @param string[] $ymList
  577. */
  578. protected function saveProcuremenSidebarYmList(array $ymList): void
  579. {
  580. $out = [];
  581. foreach ($ymList as $ym) {
  582. $ym = trim((string)$ym);
  583. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  584. $out[$ym] = true;
  585. }
  586. }
  587. if ($out === []) {
  588. return;
  589. }
  590. try {
  591. redis()->set('procuremen_redis_yms', json_encode(array_keys($out), JSON_UNESCAPED_UNICODE));
  592. } catch (\Throwable $e) {
  593. }
  594. }
  595. /**
  596. * @param array<int, array<string, mixed>> $pool
  597. * @return string[]
  598. */
  599. protected function extractYearMonthsFromPoolRows(array $pool): array
  600. {
  601. $ymSet = [];
  602. foreach ($pool as $r) {
  603. if (!is_array($r)) {
  604. continue;
  605. }
  606. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  607. continue;
  608. }
  609. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  610. if ($ym !== null) {
  611. $ymSet[$ym] = true;
  612. }
  613. }
  614. return array_keys($ymSet);
  615. }
  616. /**
  617. * 轻量查询初选侧栏月份(只取 DISTINCT 年月,不拉整包工序)
  618. *
  619. * @return string[]
  620. */
  621. protected function queryProcuremenPickSidebarYmListLight(): array
  622. {
  623. try {
  624. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  625. $endTime = date('Y-m-d 23:59:59');
  626. $sql = 'SELECT DISTINCT DATE_FORMAT('
  627. . 'IF(b.dputrecord IS NOT NULL AND TRIM(CAST(b.dputrecord AS CHAR(32))) <> \'\''
  628. . ' AND TRIM(CAST(b.dputrecord AS CHAR(32))) NOT LIKE \'0000-00-00%\','
  629. . ' b.dputrecord, a.dStamp), \'%Y-%m\') AS ym'
  630. . ' FROM scydgy a'
  631. . ' INNER JOIN mcyd b ON b.ICYDID = a.ICYDID AND b.iStatus >= 10'
  632. . ' WHERE a.bwjg = 1 AND a.iEndBz = 0 AND a.iType = 0 AND a.iStatus = 10'
  633. . ' AND a.dStamp >= ? AND a.dStamp <= ?';
  634. $rows = Db::query($sql, [$startTime, $endTime]);
  635. if (!is_array($rows)) {
  636. return [];
  637. }
  638. $out = [];
  639. foreach ($rows as $r) {
  640. $ym = trim((string)($r['ym'] ?? ''));
  641. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  642. $out[$ym] = true;
  643. }
  644. }
  645. return array_keys($out);
  646. } catch (\Throwable $e) {
  647. Log::write('初选侧栏月份轻量查询失败:' . $e->getMessage(), 'warning');
  648. return [];
  649. }
  650. }
  651. /**
  652. * @return string[] 含当月在内的近 N 个自然月
  653. */
  654. protected function buildRecentCalendarYmList(int $months = 12): array
  655. {
  656. $months = max(1, min(24, $months));
  657. $out = [];
  658. $base = strtotime(date('Y-m-01'));
  659. for ($i = 0; $i < $months; $i++) {
  660. $out[] = date('Y-m', strtotime('-' . $i . ' month', $base));
  661. }
  662. return $out;
  663. }
  664. /**
  665. * 初选按月工序池:优先月缓存;未命中则直接按月查 ERP。
  666. * 禁止为列表去解近一年整包 Redis(解包/连接异常会造成长时间转圈)。
  667. *
  668. * @return array<int, array<string, mixed>>
  669. */
  670. protected function loadPickPoolForYm(string $ym): array
  671. {
  672. $ym = trim($ym);
  673. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  674. return [];
  675. }
  676. $hit = $this->readPickMonthPoolCache($ym);
  677. if ($hit !== null) {
  678. return $hit;
  679. }
  680. return $this->queryPickPoolForYmFromDb($ym);
  681. }
  682. /**
  683. * @return array<int, array<string, mixed>>|null null=无有效缓存(含旧版空数组误缓存)
  684. */
  685. protected function readPickMonthPoolCache(string $ym): ?array
  686. {
  687. try {
  688. $raw = redis()->get('procuremen_pick_pool:' . $ym);
  689. if ($raw === false || $raw === null || $raw === '') {
  690. return null;
  691. }
  692. $decoded = json_decode((string)$raw, true);
  693. if (!is_array($decoded)) {
  694. return null;
  695. }
  696. // 新格式:{ok:1, rows:[...]},空月也算有效(已从整包确认)
  697. if (isset($decoded['ok']) && (int)$decoded['ok'] === 1 && isset($decoded['rows']) && is_array($decoded['rows'])) {
  698. return $decoded['rows'];
  699. }
  700. // 旧格式:仅非空行列表可命中;[] 多半是错误 SQL 写入,视为未命中
  701. if ($decoded === []) {
  702. try {
  703. redis()->del('procuremen_pick_pool:' . $ym);
  704. } catch (\Throwable $e) {
  705. }
  706. return null;
  707. }
  708. if (isset($decoded[0]) && is_array($decoded[0])) {
  709. return $decoded;
  710. }
  711. return null;
  712. } catch (\Throwable $e) {
  713. return null;
  714. }
  715. }
  716. /**
  717. * @param array<int, array<string, mixed>> $rows
  718. */
  719. protected function writePickMonthPoolCache(string $ym, array $rows): void
  720. {
  721. try {
  722. redis()->setex(
  723. 'procuremen_pick_pool:' . $ym,
  724. 600,
  725. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  726. );
  727. } catch (\Throwable $e) {
  728. }
  729. }
  730. /**
  731. * @param array<int, array<string, mixed>> $pool
  732. * @return array<int, array<string, mixed>>
  733. */
  734. protected function filterPoolRowsByYm(array $pool, string $ym): array
  735. {
  736. $out = [];
  737. foreach ($pool as $r) {
  738. if (!is_array($r)) {
  739. continue;
  740. }
  741. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  742. continue;
  743. }
  744. if ($this->procuremenRowYearMonth($r, 'dputrecord') === $ym) {
  745. $out[] = $r;
  746. }
  747. }
  748. return $out;
  749. }
  750. /**
  751. * 按 dStamp 取当月附近数据,再用列表规则(dputrecord 优先)精确到 ym
  752. *
  753. * @return array<int, array<string, mixed>>
  754. */
  755. protected function queryPickPoolForYmFromDb(string $ym): array
  756. {
  757. $monthStart = $ym . '-01 00:00:00';
  758. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  759. // 略放大窗口,避免 dStamp 与 dputrecord 跨月导致漏数;最终仍按 ym 精确过滤
  760. $queryStart = date('Y-m-d 00:00:00', strtotime($monthStart . ' -7 days'));
  761. $queryEnd = date('Y-m-d 23:59:59', strtotime($monthEnd . ' +7 days'));
  762. try {
  763. $list = Db::table('scydgy')
  764. ->alias('a')
  765. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  766. ->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, b.czlyq, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  767. ->where([
  768. 'a.bwjg' => 1,
  769. 'a.iEndBz' => 0,
  770. 'a.iType' => 0,
  771. 'a.iStatus' => 10,
  772. ])
  773. ->where('a.dStamp', '>=', $queryStart)
  774. ->where('a.dStamp', '<=', $queryEnd)
  775. ->order('a.dStamp', 'desc')
  776. ->select();
  777. } catch (\Throwable $e) {
  778. Log::write('初选按月取数失败 ym=' . $ym . ':' . $e->getMessage(), 'error');
  779. return [];
  780. }
  781. if (!is_array($list)) {
  782. $list = [];
  783. }
  784. $out = $this->filterPoolRowsByYm($list, $ym);
  785. // 新格式缓存(含空月),避免重复打库;读侧只认 ok=1
  786. $this->writePickMonthPoolCache($ym, $out);
  787. try {
  788. $yms = $this->loadProcuremenSidebarYmList();
  789. if ($out !== [] && ($yms === [] || !in_array($ym, $yms, true))) {
  790. $yms[] = $ym;
  791. $this->saveProcuremenSidebarYmList($yms);
  792. }
  793. } catch (\Throwable $e) {
  794. }
  795. return $out;
  796. }
  797. /**
  798. * 整包写入后拆成按月小缓存,供初选列表秒开
  799. *
  800. * @param array<int, array<string, mixed>> $pool
  801. */
  802. protected function warmPickMonthPoolCachesFromPool(array $pool): void
  803. {
  804. if ($pool === []) {
  805. return;
  806. }
  807. $byYm = [];
  808. foreach ($pool as $r) {
  809. if (!is_array($r)) {
  810. continue;
  811. }
  812. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  813. continue;
  814. }
  815. $rowYm = $this->procuremenRowYearMonth($r, 'dputrecord');
  816. if ($rowYm === null) {
  817. continue;
  818. }
  819. $byYm[$rowYm][] = $r;
  820. }
  821. if ($byYm === []) {
  822. return;
  823. }
  824. try {
  825. $redis = redis();
  826. foreach ($byYm as $rowYm => $rows) {
  827. $redis->setex(
  828. 'procuremen_pick_pool:' . $rowYm,
  829. 600,
  830. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  831. );
  832. }
  833. try {
  834. $redis->del('procuremen_pick_hidden_scydgy_v1');
  835. } catch (\Throwable $e) {
  836. }
  837. } catch (\Throwable $e) {
  838. }
  839. }
  840. /**
  841. * 刷新整包后清理近月缓存,避免脏读
  842. */
  843. protected function clearPickMonthPoolCaches(int $months = 24): void
  844. {
  845. try {
  846. $redis = redis();
  847. foreach ($this->buildRecentCalendarYmList($months) as $ym) {
  848. try {
  849. $redis->del('procuremen_pick_pool:' . $ym);
  850. } catch (\Throwable $e) {
  851. }
  852. }
  853. } catch (\Throwable $e) {
  854. }
  855. $this->invalidatePickHiddenScydgyCache();
  856. }
  857. /**
  858. * 下发/完结后清隐藏集缓存,避免初选列表最多 90 秒仍显示已下发行
  859. */
  860. protected function invalidatePickHiddenScydgyCache(): void
  861. {
  862. $this->pickHiddenScydgySetCache = null;
  863. try {
  864. redis()->del('procuremen_pick_hidden_scydgy_v1');
  865. } catch (\Throwable $e) {
  866. }
  867. }
  868. /** 列表/首屏读完鉴权后尽早释放 session,避免多 iframe 串行卡死 */
  869. protected function procuremenReleaseSessionLock(): void
  870. {
  871. if (session_status() === PHP_SESSION_ACTIVE) {
  872. @session_write_close();
  873. }
  874. }
  875. /**
  876. * @param string[] $ymList 形如 2026-06
  877. * @return array<int, array{year:string, months:array}>
  878. */
  879. protected function buildYearMonthSidebar(array $ymList): array
  880. {
  881. rsort($ymList, SORT_STRING);
  882. $byYear = [];
  883. foreach ($ymList as $ym) {
  884. $y = substr($ym, 0, 4);
  885. $mo = (int)substr($ym, 5, 2);
  886. if (!isset($byYear[$y])) {
  887. $byYear[$y] = [];
  888. }
  889. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  890. }
  891. krsort($byYear, SORT_NUMERIC);
  892. foreach ($byYear as $y => $items) {
  893. usort($byYear[$y], function ($a, $b) {
  894. return strcmp($b['ym'], $a['ym']);
  895. });
  896. }
  897. $sidebar = [];
  898. foreach ($byYear as $y => $months) {
  899. $sidebar[] = ['year' => $y, 'months' => $months];
  900. }
  901. return $sidebar;
  902. }
  903. /**
  904. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  905. */
  906. protected function GetIssuedOrderYearMonths(string $stage): array
  907. {
  908. $ymSet = [];
  909. try {
  910. $query = Db::table('purchase_order');
  911. $this->applyPurchaseOrderNotDeletedWhere($query);
  912. if ($stage === 'audit') {
  913. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  914. } elseif ($stage === 'confirm') {
  915. $this->applyPurchaseOrderConfirmStageWhere($query);
  916. } else {
  917. return $this->GetIndexYearMonths();
  918. }
  919. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  920. if (is_array($rows)) {
  921. foreach ($rows as $r) {
  922. if (!is_array($r)) {
  923. continue;
  924. }
  925. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  926. if ($ym !== null) {
  927. $ymSet[$ym] = true;
  928. }
  929. }
  930. }
  931. } catch (\Throwable $e) {
  932. $ymSet = [];
  933. }
  934. $ymList = array_keys($ymSet);
  935. if ($ymList === []) {
  936. $def = $this->resolveProcuremenDefaultYm($stage);
  937. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  938. }
  939. return $this->buildYearMonthSidebar($ymList);
  940. }
  941. /**
  942. * 列表默认月份:已下发类取最近有数据的月份;初选也取最近有数据月份(避免跨月后落到空当月)
  943. */
  944. protected function resolveProcuremenDefaultYm(string $stage): string
  945. {
  946. if ($stage === 'pick') {
  947. $yms = $this->ensureProcuremenPickSidebarYmList();
  948. if ($yms !== []) {
  949. rsort($yms, SORT_STRING);
  950. return $yms[0];
  951. }
  952. return date('Y-m');
  953. }
  954. try {
  955. $query = Db::table('purchase_order');
  956. $this->applyPurchaseOrderNotDeletedWhere($query);
  957. if ($stage === 'audit') {
  958. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  959. } elseif ($stage === 'confirm') {
  960. $this->applyPurchaseOrderConfirmStageWhere($query);
  961. } else {
  962. return date('Y-m');
  963. }
  964. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  965. if ($latest === null || $latest === '') {
  966. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  967. }
  968. $t = $this->formatProcuremenDetailTime($latest);
  969. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  970. return $m[1] . '-' . $m[2];
  971. }
  972. } catch (\Throwable $e) {
  973. }
  974. return date('Y-m');
  975. }
  976. protected function applyPurchaseOrderNotDeletedWhere($query): void
  977. {
  978. $query->whereRaw(
  979. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  980. );
  981. }
  982. /**
  983. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  984. */
  985. protected function applyPurchaseOrderConfirmStageWhere($query): void
  986. {
  987. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  988. $quoted = [];
  989. foreach ($vals as $v) {
  990. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  991. }
  992. if ($quoted === []) {
  993. $query->whereRaw('1 = 0');
  994. return;
  995. }
  996. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  997. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  998. }
  999. /**
  1000. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  1001. *
  1002. * @param array<string, mixed> $row
  1003. * @return array<string, mixed>
  1004. */
  1005. protected function normalizePurchaseOrderListTimeRow(array $row): array
  1006. {
  1007. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  1008. $pick = trim((string)($row['pick_time'] ?? ''));
  1009. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  1010. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  1011. $t = trim((string)($row[$key] ?? ''));
  1012. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1013. $row['pick_time'] = $t;
  1014. break;
  1015. }
  1016. }
  1017. }
  1018. return $row;
  1019. }
  1020. /**
  1021. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  1022. */
  1023. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  1024. {
  1025. if (!in_array($stage, ['audit', 'confirm'], true)) {
  1026. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1027. }
  1028. if ($pool === []) {
  1029. $def = $this->resolveProcuremenDefaultYm($stage);
  1030. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  1031. }
  1032. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  1033. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1034. return false;
  1035. }
  1036. $monthStart = $ym . '-01 00:00:00';
  1037. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1038. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  1039. return $probe !== [];
  1040. };
  1041. if ($tryYm($requestedYm)) {
  1042. return $requestedYm;
  1043. }
  1044. $fallback = $this->resolveProcuremenDefaultYm($stage);
  1045. if ($tryYm($fallback)) {
  1046. return $fallback;
  1047. }
  1048. $bestYm = '';
  1049. $bestTime = '';
  1050. foreach ($pool as $row) {
  1051. if (!is_array($row)) {
  1052. continue;
  1053. }
  1054. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  1055. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  1056. continue;
  1057. }
  1058. $ymRow = $m[1];
  1059. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  1060. $bestTime = $t;
  1061. $bestYm = $ymRow;
  1062. }
  1063. }
  1064. if ($bestYm !== '') {
  1065. return $bestYm;
  1066. }
  1067. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1068. }
  1069. protected function isPurchaseOrderDetailVoid(array $row): bool
  1070. {
  1071. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  1072. return true;
  1073. }
  1074. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  1075. }
  1076. /**
  1077. * 仅当前有效下发明细(排除废弃归档)
  1078. */
  1079. protected function applyActivePurchaseOrderDetailWhere($query): void
  1080. {
  1081. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1082. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  1083. }
  1084. /**
  1085. * @param array<string, mixed> $detailRow
  1086. */
  1087. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  1088. {
  1089. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  1090. return false;
  1091. }
  1092. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  1093. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  1094. }
  1095. /**
  1096. * 废弃退回初选:下发明细标记归档,不物理删除
  1097. *
  1098. * @param array<int, int|string> $scydgyIds
  1099. */
  1100. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  1101. {
  1102. $ids = [];
  1103. foreach ($scydgyIds as $sid) {
  1104. $n = (int)$sid;
  1105. if ($this->isValidScydgyRowId($n) || $n < 0) {
  1106. $ids[$n] = true;
  1107. }
  1108. }
  1109. if ($ids === []) {
  1110. return;
  1111. }
  1112. $void = ProcuremenStatus::POD_VOID;
  1113. Db::table('purchase_order_detail')
  1114. ->where('scydgy_id', 'in', array_keys($ids))
  1115. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1116. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  1117. ->update([
  1118. 'status' => $void,
  1119. 'status_name' => $void,
  1120. ]);
  1121. }
  1122. /**
  1123. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  1124. */
  1125. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  1126. {
  1127. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  1128. $norm = function (string $col) use ($p): string {
  1129. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  1130. };
  1131. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  1132. $parts = [];
  1133. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  1134. if ($key === 'createtime') {
  1135. $parts[] = $createtime;
  1136. } else {
  1137. $parts[] = $norm($key);
  1138. }
  1139. }
  1140. return 'COALESCE(' . implode(', ', $parts) . ')';
  1141. }
  1142. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  1143. {
  1144. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  1145. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  1146. }
  1147. /**
  1148. * @return array<int, array<string, mixed>>
  1149. */
  1150. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  1151. {
  1152. $this->ensurePurchaseOrderCzlyqColumn();
  1153. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1154. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  1155. try {
  1156. $query = Db::table('purchase_order')->field($fields);
  1157. $this->applyPurchaseOrderNotDeletedWhere($query);
  1158. if ($stage === 'audit') {
  1159. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1160. } elseif ($stage === 'confirm') {
  1161. $this->applyPurchaseOrderConfirmStageWhere($query);
  1162. } else {
  1163. return [];
  1164. }
  1165. $query->order('pick_time', 'desc')->order('id', 'desc');
  1166. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  1167. $monthStart = $ym . '-01 00:00:00';
  1168. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1169. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  1170. }
  1171. $rows = $query->select();
  1172. } catch (\Throwable $e) {
  1173. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  1174. $rows = [];
  1175. }
  1176. return is_array($rows) ? $rows : [];
  1177. }
  1178. /**
  1179. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  1180. */
  1181. protected function resolveProcuremenListStage(): string
  1182. {
  1183. $tab = trim((string)$this->request->request('wff_tab', ''));
  1184. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  1185. return $tab;
  1186. }
  1187. $action = strtolower((string)$this->request->action());
  1188. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  1189. return $action;
  1190. }
  1191. return 'pick';
  1192. }
  1193. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  1194. {
  1195. $this->procuremenReleaseSessionLock();
  1196. $rootTrue = rtrim((string)$this->request->root(true), '/');
  1197. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  1198. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  1199. $indexPhpRoot = $rootTrue . '/index.php';
  1200. }
  1201. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  1202. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  1203. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  1204. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  1205. $this->view->assign('defaultYm', $defaultYm);
  1206. $this->view->assign('sidebarYearMonths', $sidebar);
  1207. $this->view->assign('procuremenStage', $stage);
  1208. $this->view->assign('procuremenPageTitle', $pageTitle);
  1209. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  1210. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  1211. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  1212. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  1213. $this->assignconfig('procuremenFilterOptions', $this->buildProcuremenFilterOptions($stage));
  1214. }
  1215. /**
  1216. * 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
  1217. *
  1218. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1219. */
  1220. protected function buildProcuremenFilterOptions(string $stage): array
  1221. {
  1222. $buckets = [
  1223. 'czlyq' => [],
  1224. 'CCLBMMC' => [],
  1225. 'cywyxm' => [],
  1226. 'CGYMC' => [],
  1227. ];
  1228. $maxPerField = 300;
  1229. try {
  1230. if ($stage === 'pick') {
  1231. // 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
  1232. return $buckets;
  1233. }
  1234. if (in_array($stage, ['audit', 'confirm'], true)) {
  1235. $this->ensurePurchaseOrderCzlyqColumn();
  1236. foreach (array_keys($buckets) as $field) {
  1237. try {
  1238. $query = Db::table('purchase_order')->field($field);
  1239. $this->applyPurchaseOrderNotDeletedWhere($query);
  1240. if ($stage === 'audit') {
  1241. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1242. } else {
  1243. $this->applyPurchaseOrderConfirmStageWhere($query);
  1244. }
  1245. $query->where($field, '<>', '')->whereNotNull($field);
  1246. $vals = $query->distinct(true)->limit($maxPerField)->column($field);
  1247. if (!is_array($vals)) {
  1248. continue;
  1249. }
  1250. foreach ($vals as $v) {
  1251. $v = trim((string)$v);
  1252. if ($v !== '') {
  1253. $buckets[$field][$v] = $v;
  1254. }
  1255. }
  1256. } catch (\Throwable $e) {
  1257. // 单字段失败不影响其它
  1258. }
  1259. }
  1260. }
  1261. } catch (\Throwable $e) {
  1262. Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
  1263. }
  1264. foreach ($buckets as &$set) {
  1265. if ($set !== []) {
  1266. ksort($set, SORT_STRING);
  1267. }
  1268. }
  1269. unset($set);
  1270. return $buckets;
  1271. }
  1272. /**
  1273. * filter JSON 是否含有效条件
  1274. *
  1275. * @param array<string, mixed> $filterArr
  1276. */
  1277. protected function procuremenFilterArrHasValue(array $filterArr): bool
  1278. {
  1279. foreach ($filterArr as $v) {
  1280. if (is_array($v)) {
  1281. if (array_filter($v, function ($x) {
  1282. return $x !== '' && $x !== null;
  1283. })) {
  1284. return true;
  1285. }
  1286. } elseif ($v !== '' && $v !== null) {
  1287. return true;
  1288. }
  1289. }
  1290. return false;
  1291. }
  1292. /**
  1293. * 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
  1294. *
  1295. * @param array<string, mixed> $filterArr
  1296. * @param array<string, mixed> $opArr
  1297. */
  1298. protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
  1299. {
  1300. if ($search !== '') {
  1301. return false;
  1302. }
  1303. foreach ($filterArr as $fk => $fv) {
  1304. if (is_array($fv)) {
  1305. continue;
  1306. }
  1307. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  1308. continue;
  1309. }
  1310. if ($fv === null) {
  1311. continue;
  1312. }
  1313. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  1314. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  1315. if ($sym === '' || $sym === '=') {
  1316. continue;
  1317. }
  1318. return false;
  1319. }
  1320. return true;
  1321. }
  1322. /**
  1323. * 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
  1324. *
  1325. * @param array<int, mixed> $rows
  1326. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1327. */
  1328. protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
  1329. {
  1330. $buckets = [
  1331. 'czlyq' => [],
  1332. 'CCLBMMC' => [],
  1333. 'cywyxm' => [],
  1334. 'CGYMC' => [],
  1335. ];
  1336. foreach ($rows as $r) {
  1337. if (!is_array($r)) {
  1338. continue;
  1339. }
  1340. foreach ($buckets as $field => &$set) {
  1341. if (count($set) >= $maxPerField) {
  1342. continue;
  1343. }
  1344. $v = trim((string)($r[$field] ?? ''));
  1345. if ($v !== '') {
  1346. $set[$v] = $v;
  1347. }
  1348. }
  1349. unset($set);
  1350. $full = true;
  1351. foreach ($buckets as $set) {
  1352. if (count($set) < $maxPerField) {
  1353. $full = false;
  1354. break;
  1355. }
  1356. }
  1357. if ($full) {
  1358. break;
  1359. }
  1360. }
  1361. foreach ($buckets as &$set) {
  1362. if ($set !== []) {
  1363. // 保证 json 编码为对象(避免 list 下标 0,1,2… 被前端当选项)
  1364. $normalized = [];
  1365. foreach ($set as $k => $v) {
  1366. $s = trim((string)(is_scalar($v) ? $v : $k));
  1367. if ($s === '') {
  1368. continue;
  1369. }
  1370. $normalized[$s] = $s;
  1371. }
  1372. ksort($normalized, SORT_STRING);
  1373. $set = $normalized;
  1374. }
  1375. }
  1376. unset($set);
  1377. return $buckets;
  1378. }
  1379. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  1380. public function pick()
  1381. {
  1382. $this->request->filter(['strip_tags', 'trim']);
  1383. if (!$this->request->isAjax()) {
  1384. $this->assignProcuremenListPage('pick', '协助下发');
  1385. return $this->view->fetch('procuremen/index');
  1386. }
  1387. return $this->index();
  1388. }
  1389. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  1390. public function audit()
  1391. {
  1392. $this->request->filter(['strip_tags', 'trim']);
  1393. if (!$this->request->isAjax()) {
  1394. $this->assignProcuremenListPage('audit', '确认供应商');
  1395. return $this->view->fetch('procuremen/index');
  1396. }
  1397. return $this->index();
  1398. }
  1399. /** 采购确认(定标) */
  1400. public function confirm()
  1401. {
  1402. $this->request->filter(['strip_tags', 'trim']);
  1403. if (!$this->request->isAjax()) {
  1404. $this->assignProcuremenListPage('confirm', '采购确认');
  1405. return $this->view->fetch('procuremen/index');
  1406. }
  1407. return $this->index();
  1408. }
  1409. /**
  1410. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  1411. */
  1412. public function index()
  1413. {
  1414. $this->request->filter(['strip_tags', 'trim']);
  1415. if (!$this->request->isAjax()) {
  1416. $this->assignProcuremenListPage('pick', '协助下发');
  1417. return $this->view->fetch('procuremen/index');
  1418. }
  1419. if ($this->request->request('keyField')) {
  1420. return $this->selectpage();
  1421. }
  1422. $this->procuremenReleaseSessionLock();
  1423. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  1424. $limit = max(10, min(500, (int)$limit));
  1425. $ym = $this->request->request('ym', '');
  1426. $ym = is_string($ym) ? trim($ym) : '';
  1427. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  1428. $wffTab = $this->resolveProcuremenListStage();
  1429. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1430. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  1431. ? $this->resolveProcuremenDefaultYm($wffTab)
  1432. : date('Y-m');
  1433. }
  1434. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1435. $ym = date('Y-m');
  1436. }
  1437. $monthStart = $ym . '-01 00:00:00';
  1438. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1439. $search = trim((string)$this->request->get('search', ''));
  1440. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  1441. $opArr = (array)json_decode($this->request->get('op', ''), true);
  1442. if (!is_array($filterArr)) {
  1443. $filterArr = [];
  1444. }
  1445. if (!is_array($opArr)) {
  1446. $opArr = [];
  1447. }
  1448. // 开标状态为计算字段,不能进池内等值筛选;单独抽出后在合并后再滤
  1449. $bidOpenStatusFilter = '';
  1450. foreach (['bid_open_status_text', 'a.bid_open_status_text'] as $bidFk) {
  1451. if (!array_key_exists($bidFk, $filterArr)) {
  1452. continue;
  1453. }
  1454. $bidOpenStatusFilter = trim((string)$filterArr[$bidFk]);
  1455. unset($filterArr[$bidFk], $opArr[$bidFk]);
  1456. }
  1457. // 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
  1458. $applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
  1459. $hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
  1460. try {
  1461. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  1462. if ($wffTab === 'audit') {
  1463. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  1464. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  1465. );
  1466. } elseif ($wffTab === 'confirm') {
  1467. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  1468. if ($dbRows === []) {
  1469. try {
  1470. $dbRows = Db::table('purchase_order')
  1471. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1472. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  1473. ->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%\')')
  1474. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  1475. ->order('pick_time', 'desc')->order('id', 'desc')
  1476. ->select();
  1477. } catch (\Throwable $e) {
  1478. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  1479. $dbRows = [];
  1480. }
  1481. }
  1482. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  1483. if ($pool === []) {
  1484. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1485. }
  1486. } else {
  1487. // 初选:按月直查 ERP(不解整包 Redis,避免长时间转圈)
  1488. if ($applyMonthRange) {
  1489. $pool = $this->loadPickPoolForYm($ym);
  1490. } else {
  1491. $pool = $this->procuremenEnsureRedisPool();
  1492. }
  1493. if (!is_array($pool)) {
  1494. $pool = [];
  1495. }
  1496. // 只针对本页候选 ID 查隐藏集,避免全表扫 purchase_order_detail
  1497. $hideSet = $this->loadPickHiddenScydgySetForIds($this->extractScydgyIdsFromPool($pool));
  1498. if ($pool !== [] && $hideSet !== []) {
  1499. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1500. if (!is_array($r)) {
  1501. return false;
  1502. }
  1503. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1504. return $id <= 0 || !isset($hideSet[$id]);
  1505. }));
  1506. }
  1507. // 手工新增(YW / scydgy_id<0)只走「新增询价/查询询价」,不进初选表格
  1508. if ($pool === []) {
  1509. return json([
  1510. 'total' => 0,
  1511. 'rows' => [],
  1512. 'activeYm' => $ym,
  1513. 'filterOptions' => (
  1514. (int)$offset === 0
  1515. && !$hasActiveSearch
  1516. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1517. )
  1518. ? $this->extractProcuremenFilterOptionsFromRows([])
  1519. : new \stdClass(),
  1520. ]);
  1521. }
  1522. }
  1523. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  1524. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  1525. $monthStart = $ym . '-01 00:00:00';
  1526. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1527. }
  1528. $filtered = $this->filterProcuremenIndexPool(
  1529. $pool,
  1530. $monthStart,
  1531. $monthEnd,
  1532. $applyMonthRange,
  1533. $search,
  1534. $filterArr,
  1535. $opArr,
  1536. $listTimePrimary
  1537. );
  1538. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1539. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1540. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1541. }
  1542. if ($wffTab === 'audit' && $bidOpenStatusFilter !== '') {
  1543. $filtered = $this->filterProcuremenPoolByBidOpenStatus($filtered, $bidOpenStatusFilter);
  1544. }
  1545. $sortField = 'ID';
  1546. if (is_string($sort) && $sort !== '') {
  1547. $parts = explode(',', $sort);
  1548. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1549. if ($sortField === '') {
  1550. $sortField = 'ID';
  1551. }
  1552. }
  1553. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1554. $nFiltered = count($filtered);
  1555. if ($nFiltered > 1) {
  1556. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1557. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1558. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1559. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1560. if ($ta === $tb) {
  1561. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1562. }
  1563. if ($ta === '') {
  1564. return 1;
  1565. }
  1566. if ($tb === '') {
  1567. return -1;
  1568. }
  1569. return strcmp($ta, $tb) * $ord;
  1570. });
  1571. } elseif ($sortField === 'ID') {
  1572. $sortKeys = [];
  1573. foreach ($filtered as $i => $row) {
  1574. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1575. }
  1576. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1577. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1578. } elseif ($sortField === 'CCYDH') {
  1579. usort($filtered, function ($a, $b) use ($ord) {
  1580. $sa = trim((string)($a['CCYDH'] ?? ''));
  1581. $sb = trim((string)($b['CCYDH'] ?? ''));
  1582. if ($sa === $sb) {
  1583. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1584. }
  1585. if ($sa === '') {
  1586. return 1;
  1587. }
  1588. if ($sb === '') {
  1589. return -1;
  1590. }
  1591. return strcmp($sa, $sb) * $ord;
  1592. });
  1593. } else {
  1594. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1595. $va = $a[$sortField] ?? null;
  1596. $vb = $b[$sortField] ?? null;
  1597. $sa = (string)$va;
  1598. $sb = (string)$vb;
  1599. if ($sa === $sb) {
  1600. return 0;
  1601. }
  1602. return strcmp($sa, $sb) * $ord;
  1603. });
  1604. }
  1605. }
  1606. $offset = max(0, (int)$offset);
  1607. $limit = max(1, (int)$limit);
  1608. $rows = array_slice($filtered, $offset, $limit);
  1609. foreach ($rows as &$rw) {
  1610. if (!is_array($rw)) {
  1611. continue;
  1612. }
  1613. $rid = (int)($rw['ID'] ?? 0);
  1614. $rw['_iss_out'] = ($wffTab !== 'pick');
  1615. }
  1616. unset($rw);
  1617. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1618. $idList = [];
  1619. foreach ($rows as $rw) {
  1620. if (!is_array($rw)) {
  1621. continue;
  1622. }
  1623. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1624. foreach ($rw['_order_merge_rows'] as $mr) {
  1625. $mid = (int)($mr['ID'] ?? 0);
  1626. if ($this->isValidScydgyRowId($mid)) {
  1627. $idList[$mid] = true;
  1628. }
  1629. }
  1630. }
  1631. $id = (int)($rw['ID'] ?? 0);
  1632. if ($this->isValidScydgyRowId($id)) {
  1633. $idList[$id] = true;
  1634. }
  1635. }
  1636. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1637. foreach ($rows as &$rw) {
  1638. if (!is_array($rw)) {
  1639. continue;
  1640. }
  1641. $mergeIds = [];
  1642. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1643. foreach ($rw['_order_merge_rows'] as $mr) {
  1644. $mid = (int)($mr['ID'] ?? 0);
  1645. if ($this->isValidScydgyRowId($mid)) {
  1646. $mergeIds[$mid] = true;
  1647. }
  1648. }
  1649. }
  1650. $rid = (int)($rw['ID'] ?? 0);
  1651. if ($this->isValidScydgyRowId($rid)) {
  1652. $mergeIds[$rid] = true;
  1653. }
  1654. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1655. $rw['po_detail_count'] = $s['cnt'];
  1656. $rw['po_amount_fill_cnt'] = $s['amt'];
  1657. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1658. }
  1659. unset($rw);
  1660. }
  1661. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1662. $idList = [];
  1663. foreach ($rows as $rw) {
  1664. if (!is_array($rw)) {
  1665. continue;
  1666. }
  1667. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1668. foreach ($rw['_order_merge_rows'] as $mr) {
  1669. $mid = (int)($mr['ID'] ?? 0);
  1670. if ($this->isValidScydgyRowId($mid)) {
  1671. $idList[$mid] = true;
  1672. }
  1673. }
  1674. }
  1675. $id = (int)($rw['ID'] ?? 0);
  1676. if ($this->isValidScydgyRowId($id)) {
  1677. $idList[$id] = true;
  1678. }
  1679. }
  1680. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1681. $bidOpenSet = [];
  1682. $manualPickSet = [];
  1683. if ($wffTab === 'audit') {
  1684. $ccydhList = [];
  1685. foreach ($rows as $rw0) {
  1686. if (!is_array($rw0)) {
  1687. continue;
  1688. }
  1689. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1690. if ($c0 !== '') {
  1691. $ccydhList[] = $c0;
  1692. }
  1693. }
  1694. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1695. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  1696. }
  1697. foreach ($rows as &$rw) {
  1698. if (!is_array($rw)) {
  1699. continue;
  1700. }
  1701. $mergeIds = [];
  1702. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1703. foreach ($rw['_order_merge_rows'] as $mr) {
  1704. $mid = (int)($mr['ID'] ?? 0);
  1705. if ($this->isValidScydgyRowId($mid)) {
  1706. $mergeIds[$mid] = true;
  1707. }
  1708. }
  1709. }
  1710. $rid = (int)($rw['ID'] ?? 0);
  1711. if ($this->isValidScydgyRowId($rid)) {
  1712. $mergeIds[$rid] = true;
  1713. }
  1714. $buckets = [];
  1715. foreach (array_keys($mergeIds) as $mid) {
  1716. if (isset($quoteBucket[$mid])) {
  1717. $buckets[] = $quoteBucket[$mid];
  1718. }
  1719. }
  1720. $supplierText = $buckets !== []
  1721. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1722. : '';
  1723. if ($wffTab === 'confirm') {
  1724. $picked = trim((string)($rw['pick_company_name'] ?? $rw['picked_supplier_name'] ?? ''));
  1725. if ($picked === '') {
  1726. // 兜底:从合并工序行取
  1727. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1728. foreach ($rw['_order_merge_rows'] as $mr) {
  1729. if (!is_array($mr)) {
  1730. continue;
  1731. }
  1732. $pn = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  1733. if ($pn !== '') {
  1734. $picked = $pn;
  1735. break;
  1736. }
  1737. }
  1738. }
  1739. }
  1740. $rw['picked_supplier_name'] = $picked;
  1741. } else {
  1742. $rw['notify_supplier_text'] = $supplierText;
  1743. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1744. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1745. $manualPicked = ($ccydh !== '' && isset($manualPickSet[$ccydh]));
  1746. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1747. $rw['manual_picked'] = $manualPicked ? 1 : 0;
  1748. if ($verified) {
  1749. $rw['bid_open_status_text'] = '已开标';
  1750. } elseif ($manualPicked) {
  1751. $rw['bid_open_status_text'] = '已指定供应商';
  1752. } else {
  1753. $rw['bid_open_status_text'] = '待开标';
  1754. }
  1755. }
  1756. }
  1757. unset($rw);
  1758. }
  1759. if (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
  1760. $this->enrichProcuremenListMilestoneTimes($rows);
  1761. $this->syncCollapsedOrderQtyPriceForList($rows);
  1762. }
  1763. if ($wffTab === 'all' && count($rows) > 0) {
  1764. $this->mergePurchaseOrder($rows);
  1765. }
  1766. if ($wffTab === 'pick' && count($rows) > 0) {
  1767. $this->mergePurchaseOrder($rows);
  1768. }
  1769. foreach ($rows as &$rwClean) {
  1770. if (is_array($rwClean)) {
  1771. unset($rwClean['_order_merge_rows']);
  1772. if (array_key_exists('NGZL', $rwClean)) {
  1773. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1774. }
  1775. }
  1776. }
  1777. unset($rwClean);
  1778. return json([
  1779. 'total' => count($filtered),
  1780. 'rows' => $rows,
  1781. 'activeYm' => $ym,
  1782. // 初选:把有数据的月份带回,替换「空月份日历」侧栏
  1783. 'sidebarYms' => ($wffTab === 'pick' && (int)$offset === 0)
  1784. ? $this->ensureProcuremenPickSidebarYmList()
  1785. : [],
  1786. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1787. 'filterOptions' => (
  1788. (int)$offset === 0
  1789. && !$hasActiveSearch
  1790. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1791. )
  1792. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1793. : new \stdClass(),
  1794. ]);
  1795. } catch (\Throwable $e) {
  1796. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1797. return json([
  1798. 'total' => 0,
  1799. 'rows' => [],
  1800. ]);
  1801. }
  1802. }
  1803. /**
  1804. * @param array<int, array<string, mixed>> $pool
  1805. * @return int[]
  1806. */
  1807. protected function extractScydgyIdsFromPool(array $pool): array
  1808. {
  1809. $ids = [];
  1810. foreach ($pool as $r) {
  1811. if (!is_array($r)) {
  1812. continue;
  1813. }
  1814. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1815. if ($id > 0) {
  1816. $ids[$id] = $id;
  1817. }
  1818. }
  1819. return array_values($ids);
  1820. }
  1821. /**
  1822. * 仅查询指定工序 ID 是否已下发/进入后续流程(初选列表加速)
  1823. *
  1824. * @param int[] $scydgyIds
  1825. * @return array<int, true>
  1826. */
  1827. protected function loadPickHiddenScydgySetForIds(array $scydgyIds): array
  1828. {
  1829. $hideSet = [];
  1830. $scydgyIds = array_values(array_filter(array_map('intval', $scydgyIds), function ($id) {
  1831. return $id > 0;
  1832. }));
  1833. if ($scydgyIds === []) {
  1834. return $hideSet;
  1835. }
  1836. // 分批,避免 whereIn 过长
  1837. foreach (array_chunk($scydgyIds, 500) as $chunk) {
  1838. try {
  1839. $poIds = Db::table('purchase_order')
  1840. ->where('scydgy_id', 'in', $chunk)
  1841. ->where(function ($q) {
  1842. $q->whereIn('wflow_status', array_merge(
  1843. ProcuremenStatus::wflowPendingConfirmValues(),
  1844. ProcuremenStatus::wflowPendingApprovalValues()
  1845. ))
  1846. ->whereOr(function ($q1) {
  1847. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1848. })
  1849. ->whereOr(function ($q2) {
  1850. $q2->whereNotNull('pick_time')
  1851. ->where('pick_time', '<>', '')
  1852. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1853. })
  1854. ->whereOr(function ($q3) {
  1855. $q3->whereNotNull('mod_rq')
  1856. ->where('mod_rq', '<>', '')
  1857. ->where('mod_rq', 'not like', '0000-00-00%');
  1858. });
  1859. })
  1860. ->column('scydgy_id');
  1861. if (is_array($poIds)) {
  1862. foreach ($poIds as $pid) {
  1863. $k = (int)$pid;
  1864. if ($k !== 0) {
  1865. $hideSet[$k] = true;
  1866. }
  1867. }
  1868. }
  1869. } catch (\Throwable $e) {
  1870. }
  1871. try {
  1872. $detIdsQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $chunk);
  1873. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1874. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1875. if (is_array($detIds)) {
  1876. foreach ($detIds as $pid) {
  1877. $k = (int)$pid;
  1878. if ($this->isValidScydgyRowId($k)) {
  1879. $hideSet[$k] = true;
  1880. }
  1881. }
  1882. }
  1883. } catch (\Throwable $e) {
  1884. }
  1885. }
  1886. return $hideSet;
  1887. }
  1888. /**
  1889. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1890. *
  1891. * @return array<int, true>
  1892. */
  1893. protected function loadPickHiddenScydgySet(): array
  1894. {
  1895. if ($this->pickHiddenScydgySetCache !== null) {
  1896. return $this->pickHiddenScydgySetCache;
  1897. }
  1898. $cacheKey = 'procuremen_pick_hidden_scydgy_v1';
  1899. try {
  1900. $raw = redis()->get($cacheKey);
  1901. if ($raw !== false && $raw !== null && $raw !== '') {
  1902. $ids = json_decode((string)$raw, true);
  1903. if (is_array($ids)) {
  1904. $hideSet = [];
  1905. foreach ($ids as $pid) {
  1906. $k = (int)$pid;
  1907. if ($k !== 0) {
  1908. $hideSet[$k] = true;
  1909. }
  1910. }
  1911. $this->pickHiddenScydgySetCache = $hideSet;
  1912. return $hideSet;
  1913. }
  1914. }
  1915. } catch (\Throwable $e) {
  1916. }
  1917. $hideSet = [];
  1918. try {
  1919. $poIds = Db::table('purchase_order')
  1920. ->where(function ($q) {
  1921. $q->whereIn('wflow_status', array_merge(
  1922. ProcuremenStatus::wflowPendingConfirmValues(),
  1923. ProcuremenStatus::wflowPendingApprovalValues()
  1924. ))
  1925. ->whereOr(function ($q1) {
  1926. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1927. })
  1928. ->whereOr(function ($q2) {
  1929. $q2->whereNotNull('pick_time')
  1930. ->where('pick_time', '<>', '')
  1931. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1932. })
  1933. ->whereOr(function ($q3) {
  1934. $q3->whereNotNull('mod_rq')
  1935. ->where('mod_rq', '<>', '')
  1936. ->where('mod_rq', 'not like', '0000-00-00%');
  1937. });
  1938. })
  1939. ->column('scydgy_id');
  1940. if (is_array($poIds)) {
  1941. foreach ($poIds as $pid) {
  1942. $k = (int)$pid;
  1943. if ($k !== 0) {
  1944. $hideSet[$k] = true;
  1945. }
  1946. }
  1947. }
  1948. } catch (\Throwable $e) {
  1949. }
  1950. try {
  1951. $detIdsQuery = Db::table('purchase_order_detail');
  1952. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1953. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1954. if (is_array($detIds)) {
  1955. foreach ($detIds as $pid) {
  1956. $k = (int)$pid;
  1957. if ($this->isValidScydgyRowId($k)) {
  1958. $hideSet[$k] = true;
  1959. }
  1960. }
  1961. }
  1962. } catch (\Throwable $e) {
  1963. }
  1964. $this->pickHiddenScydgySetCache = $hideSet;
  1965. try {
  1966. redis()->setex($cacheKey, 90, json_encode(array_map('intval', array_keys($hideSet))));
  1967. } catch (\Throwable $e) {
  1968. }
  1969. return $hideSet;
  1970. }
  1971. /**
  1972. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1973. *
  1974. * @return array<int, array<string, mixed>>
  1975. */
  1976. protected function loadPickManualOrderRows(): array
  1977. {
  1978. try {
  1979. $dbRows = Db::table('purchase_order')
  1980. ->where('scydgy_id', '<', 0)
  1981. ->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%\')')
  1982. ->order('scydgy_id', 'asc')
  1983. ->select();
  1984. } catch (\Throwable $e) {
  1985. try {
  1986. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1987. } catch (\Throwable $e2) {
  1988. return [];
  1989. }
  1990. }
  1991. if (!is_array($dbRows) || $dbRows === []) {
  1992. return [];
  1993. }
  1994. $detailSidSet = [];
  1995. try {
  1996. $negIds = [];
  1997. foreach ($dbRows as $dbRow) {
  1998. if (!is_array($dbRow)) {
  1999. continue;
  2000. }
  2001. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2002. if ($sid < 0) {
  2003. $negIds[$sid] = true;
  2004. }
  2005. }
  2006. if ($negIds !== []) {
  2007. $detQuery = Db::table('purchase_order_detail')
  2008. ->where('scydgy_id', 'in', array_keys($negIds));
  2009. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  2010. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  2011. if (is_array($detRows)) {
  2012. foreach ($detRows as $did) {
  2013. $detailSidSet[(int)$did] = true;
  2014. }
  2015. }
  2016. }
  2017. } catch (\Throwable $e) {
  2018. }
  2019. $pool = [];
  2020. foreach ($dbRows as $dbRow) {
  2021. if (!is_array($dbRow)) {
  2022. continue;
  2023. }
  2024. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2025. if ($sid >= 0) {
  2026. continue;
  2027. }
  2028. // 已进入确认/审批的不进初选;仅废弃明细残留的仍算可下发
  2029. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  2030. continue;
  2031. }
  2032. // 仅排除已完结;空 status / 「进行中」/ 0 均保留(新建手工单)
  2033. if (ProcuremenStatus::isPoCompleted($dbRow['status'] ?? '')) {
  2034. continue;
  2035. }
  2036. if (isset($detailSidSet[$sid])) {
  2037. continue;
  2038. }
  2039. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  2040. $r['_is_manual'] = 1;
  2041. $pool[] = $r;
  2042. }
  2043. return $pool;
  2044. }
  2045. /**
  2046. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  2047. */
  2048. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  2049. {
  2050. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  2051. foreach ($keys as $k) {
  2052. $t = trim((string)($row[$k] ?? ''));
  2053. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2054. return $t;
  2055. }
  2056. }
  2057. return '';
  2058. }
  2059. /**
  2060. * 分配手工新增工序行 ID(负数递减)
  2061. */
  2062. protected function allocateManualScydgyId(): int
  2063. {
  2064. try {
  2065. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  2066. $min = (int)$min;
  2067. return $min < 0 ? $min - 1 : -1;
  2068. } catch (\Throwable $e) {
  2069. return -1;
  2070. }
  2071. }
  2072. /**
  2073. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  2074. */
  2075. protected function allocateManualOrderCcydh(): string
  2076. {
  2077. $prefix = 'YW' . date('Ymd');
  2078. $maxSeq = 0;
  2079. try {
  2080. $rows = Db::table('purchase_order')
  2081. ->where('CCYDH', 'like', $prefix . '%')
  2082. ->column('CCYDH');
  2083. if (is_array($rows)) {
  2084. foreach ($rows as $ccydh) {
  2085. $ccydh = trim((string)$ccydh);
  2086. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  2087. $maxSeq = max($maxSeq, (int)$m[1]);
  2088. }
  2089. }
  2090. }
  2091. } catch (\Throwable $e) {
  2092. }
  2093. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  2094. }
  2095. /**
  2096. * purchase_order.mod_rq 是否有有效软删除时间
  2097. */
  2098. protected function isPurchaseOrderSoftDeleted($modRq): bool
  2099. {
  2100. $t = trim((string)$modRq);
  2101. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  2102. }
  2103. /**
  2104. * 列表行 → purchase_order 写入字段
  2105. *
  2106. * @return array<string, mixed>
  2107. */
  2108. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  2109. {
  2110. return [
  2111. 'scydgy_id' => $scydgyId,
  2112. 'CCYDH' => $row['CCYDH'] ?? null,
  2113. 'CYJMC' => $row['CYJMC'] ?? null,
  2114. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2115. 'CDXMC' => $row['CDXMC'] ?? null,
  2116. 'CGYBH' => $row['CGYBH'] ?? null,
  2117. 'CGYMC' => $row['CGYMC'] ?? null,
  2118. 'CDW' => $row['CDW'] ?? null,
  2119. 'czlyq' => $row['czlyq'] ?? null,
  2120. 'NGZL' => $row['NGZL'] ?? null,
  2121. 'CDF' => $row['CDF'] ?? null,
  2122. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2123. 'MBZ' => $row['MBZ'] ?? null,
  2124. 'bwjg' => $row['bwjg'] ?? null,
  2125. 'iStatus' => $row['iStatus'] ?? null,
  2126. 'dStamp' => $row['dStamp'] ?? null,
  2127. 'dputrecord' => $row['dputrecord'] ?? null,
  2128. 'cywyxm' => $row['cywyxm'] ?? null,
  2129. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2130. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2131. ];
  2132. }
  2133. /**
  2134. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  2135. *
  2136. * @return array{po:?array<string,mixed>, hidden:bool}
  2137. */
  2138. protected function resolvePickRowPoContext(int $sid): array
  2139. {
  2140. $po = null;
  2141. try {
  2142. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2143. if (is_array($found)) {
  2144. $po = $found;
  2145. }
  2146. } catch (\Throwable $e) {
  2147. }
  2148. $hideSet = $this->loadPickHiddenScydgySet();
  2149. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  2150. }
  2151. /**
  2152. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  2153. */
  2154. protected function assertPickRowCanDelete(int $sid, array $row): void
  2155. {
  2156. $ctx = $this->resolvePickRowPoContext($sid);
  2157. $po = $ctx['po'];
  2158. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2159. return;
  2160. }
  2161. if (is_array($po)) {
  2162. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2163. throw new \InvalidArgumentException('该工序已完结,无法删除');
  2164. }
  2165. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2166. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  2167. }
  2168. }
  2169. if ($ctx['hidden']) {
  2170. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2171. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  2172. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  2173. }
  2174. }
  2175. /**
  2176. * 初选直接完结前校验
  2177. */
  2178. protected function assertPickRowCanComplete(int $sid, array $row): void
  2179. {
  2180. $ctx = $this->resolvePickRowPoContext($sid);
  2181. $po = $ctx['po'];
  2182. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2183. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  2184. }
  2185. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2186. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  2187. }
  2188. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  2189. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  2190. }
  2191. }
  2192. /**
  2193. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  2194. */
  2195. protected function softDeleteProcuremenPickRow(array $row): void
  2196. {
  2197. $sid = $this->extractScydgyRowId($row);
  2198. if (!$this->isValidScydgyRowId($sid)) {
  2199. throw new \InvalidArgumentException('无效的行主键');
  2200. }
  2201. $this->assertPickRowCanDelete($sid, $row);
  2202. $po = $this->resolvePickRowPoContext($sid)['po'];
  2203. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2204. return;
  2205. }
  2206. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2207. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  2208. }
  2209. $now = date('Y-m-d H:i:s');
  2210. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2211. if (is_array($exists)) {
  2212. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  2213. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  2214. } else {
  2215. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  2216. $data['mod_rq'] = $now;
  2217. $data['createtime'] = $now;
  2218. Db::table('purchase_order')->insert($data);
  2219. $poIdLog = (int)Db::getLastInsID();
  2220. }
  2221. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  2222. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  2223. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  2224. if ($gymcLog !== '') {
  2225. $logTail .= ' / ' . $gymcLog;
  2226. }
  2227. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  2228. }
  2229. /**
  2230. * 手工新增协助工序(写入 purchase_order)
  2231. *
  2232. * @param array<string, mixed> $params
  2233. * @return int scydgy_id
  2234. */
  2235. protected function saveManualPickOrder(array $params): int
  2236. {
  2237. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  2238. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  2239. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  2240. if ($ccydh === '') {
  2241. $ccydh = $this->allocateManualOrderCcydh();
  2242. }
  2243. $now = date('Y-m-d H:i:s');
  2244. $sid = $this->allocateManualScydgyId();
  2245. $this->ensurePurchaseOrderNotifySalesmanColumn();
  2246. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  2247. // 选择供应商 / 通知业务员:支持多选,落库用顿号拼接
  2248. $supplierName = $this->joinRfqMultiSelectValues($params['cGzzxMc'] ?? ($params['pick_company_name'] ?? ''));
  2249. $notifySalesman = $this->joinRfqMultiSelectValues($params['notify_salesman'] ?? '');
  2250. $data = [
  2251. 'scydgy_id' => $sid,
  2252. 'CCYDH' => $ccydh,
  2253. 'CYJMC' => $cyjmc,
  2254. 'CGYMC' => $cgymc,
  2255. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  2256. 'CDW' => trim((string)($params['CDW'] ?? '')),
  2257. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  2258. 'CDF' => trim((string)($params['CDF'] ?? '')),
  2259. 'cGzzxMc' => $supplierName,
  2260. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  2261. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  2262. 'notify_salesman' => $notifySalesman,
  2263. 'rfq_salesman_notified' => 0,
  2264. 'rfq_salesman_notify_time' => null,
  2265. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  2266. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  2267. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  2268. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  2269. 'createtime' => $now,
  2270. 'dStamp' => $now,
  2271. 'dputrecord' => $now,
  2272. ];
  2273. Db::table('purchase_order')->insert($data);
  2274. $poId = (int)Db::getLastInsID();
  2275. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  2276. return $sid;
  2277. }
  2278. protected function formatProcuremenRowLabel(array $row): string
  2279. {
  2280. $dh = trim((string)($row['CCYDH'] ?? ''));
  2281. $gymc = trim((string)($row['CGYMC'] ?? ''));
  2282. if ($dh !== '' && $gymc !== '') {
  2283. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  2284. }
  2285. if ($dh !== '') {
  2286. return '订单「' . $dh . '」';
  2287. }
  2288. if ($gymc !== '') {
  2289. return '工序「' . $gymc . '」';
  2290. }
  2291. $id = $this->extractScydgyRowId($row);
  2292. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  2293. }
  2294. /**
  2295. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  2296. */
  2297. protected function extractScydgyRowId(array $row): int
  2298. {
  2299. // 优先 scydgy_id,避免明细行 ID(自增主键)被误当成工序主键;手工单为负数
  2300. if (array_key_exists('scydgy_id', $row) && $row['scydgy_id'] !== null && $row['scydgy_id'] !== '') {
  2301. return (int)$row['scydgy_id'];
  2302. }
  2303. if (array_key_exists('SCYDGY_ID', $row) && $row['SCYDGY_ID'] !== null && $row['SCYDGY_ID'] !== '') {
  2304. return (int)$row['SCYDGY_ID'];
  2305. }
  2306. return (int)($row['ID'] ?? $row['id'] ?? 0);
  2307. }
  2308. protected function isValidScydgyRowId(int $id): bool
  2309. {
  2310. return ProcuremenGuard::isValidScydgyId($id);
  2311. }
  2312. protected function isManualScydgyRowId(int $id): bool
  2313. {
  2314. return $id < 0;
  2315. }
  2316. /**
  2317. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  2318. *
  2319. * @param int[] $scydgyIds
  2320. * @return array<int, string[]>
  2321. */
  2322. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  2323. {
  2324. $out = [];
  2325. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2326. if ($scydgyIds === []) {
  2327. return $out;
  2328. }
  2329. try {
  2330. $rows = Db::table('purchase_order_detail')
  2331. ->where('scydgy_id', 'in', $scydgyIds)
  2332. ->field('scydgy_id,company_name')
  2333. ->order('company_name', 'asc')
  2334. ->select();
  2335. } catch (\Throwable $e) {
  2336. $rows = [];
  2337. }
  2338. if (!is_array($rows)) {
  2339. return $out;
  2340. }
  2341. foreach ($rows as $r) {
  2342. if (!is_array($r)) {
  2343. continue;
  2344. }
  2345. $sid = (int)($r['scydgy_id'] ?? 0);
  2346. $cn = trim((string)($r['company_name'] ?? ''));
  2347. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2348. continue;
  2349. }
  2350. if (!isset($out[$sid])) {
  2351. $out[$sid] = [];
  2352. }
  2353. if (!in_array($cn, $out[$sid], true)) {
  2354. $out[$sid][] = $cn;
  2355. }
  2356. }
  2357. return $out;
  2358. }
  2359. /**
  2360. * 列表展示通知供应商(完整列表,前端单行省略展开)
  2361. *
  2362. * @param string[] $names
  2363. */
  2364. protected function formatNotifySupplierDisplay(array $names): string
  2365. {
  2366. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  2367. return trim((string)$n);
  2368. }, $names))));
  2369. if ($names === []) {
  2370. return '';
  2371. }
  2372. sort($names, SORT_STRING);
  2373. return implode("\n", $names);
  2374. }
  2375. /**
  2376. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  2377. *
  2378. * @param int[] $scydgyIds
  2379. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  2380. */
  2381. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  2382. {
  2383. $out = [];
  2384. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2385. if ($scydgyIds === []) {
  2386. return $out;
  2387. }
  2388. try {
  2389. $rows = Db::table('purchase_order_detail')
  2390. ->where('scydgy_id', 'in', $scydgyIds)
  2391. ->field('scydgy_id,company_name,amount')
  2392. ->select();
  2393. } catch (\Throwable $e) {
  2394. $rows = [];
  2395. }
  2396. if (!is_array($rows)) {
  2397. return $out;
  2398. }
  2399. foreach ($rows as $r) {
  2400. if (!is_array($r)) {
  2401. continue;
  2402. }
  2403. $sid = (int)($r['scydgy_id'] ?? 0);
  2404. $cn = trim((string)($r['company_name'] ?? ''));
  2405. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2406. continue;
  2407. }
  2408. if (!isset($out[$sid])) {
  2409. $out[$sid] = ['all' => [], 'quoted' => []];
  2410. }
  2411. $out[$sid]['all'][$cn] = true;
  2412. $am = trim((string)($r['amount'] ?? ''));
  2413. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2414. $out[$sid]['quoted'][$cn] = true;
  2415. }
  2416. }
  2417. return $out;
  2418. }
  2419. /**
  2420. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  2421. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  2422. */
  2423. protected function mergeQuotedSupplierBuckets(array $buckets): array
  2424. {
  2425. $merged = ['all' => [], 'quoted' => []];
  2426. foreach ($buckets as $b) {
  2427. if (!is_array($b)) {
  2428. continue;
  2429. }
  2430. foreach ($b['all'] ?? [] as $cn => $_) {
  2431. $merged['all'][$cn] = true;
  2432. }
  2433. foreach ($b['quoted'] ?? [] as $cn => $_) {
  2434. $merged['quoted'][$cn] = true;
  2435. }
  2436. }
  2437. return $merged;
  2438. }
  2439. /**
  2440. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  2441. */
  2442. protected function formatQuotedSupplierLines(array $bucket): string
  2443. {
  2444. $all = array_keys($bucket['all'] ?? []);
  2445. if ($all === []) {
  2446. return '';
  2447. }
  2448. sort($all, SORT_STRING);
  2449. $lines = [];
  2450. foreach ($all as $cn) {
  2451. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  2452. $lines[] = $cn . '(' . $status . ')';
  2453. }
  2454. return implode("\n", $lines);
  2455. }
  2456. /**
  2457. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  2458. */
  2459. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  2460. {
  2461. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2462. $this->view->engine->layout(false);
  2463. try {
  2464. $bodyHtml = $this->view->fetch($view);
  2465. $this->view->assign('dialogBody', $bodyHtml);
  2466. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  2467. return $this->view->fetch('procuremen/dialog_lite_shell');
  2468. } finally {
  2469. if ($restoreLayout) {
  2470. $this->view->engine->layout($restoreLayout);
  2471. }
  2472. }
  2473. }
  2474. /**
  2475. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  2476. */
  2477. protected function resolveBundleSysRq(array $bundle): string
  2478. {
  2479. foreach ($bundle['pos'] ?? [] as $po) {
  2480. if (!is_array($po)) {
  2481. continue;
  2482. }
  2483. $sr = trim((string)($po['sys_rq'] ?? ''));
  2484. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  2485. return $sr;
  2486. }
  2487. }
  2488. return '';
  2489. }
  2490. /**
  2491. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  2492. */
  2493. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  2494. {
  2495. $raw = trim((string)$sysRq);
  2496. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  2497. return true;
  2498. }
  2499. $ts = strtotime(str_replace('T', ' ', $raw));
  2500. if ($ts === false || $ts <= 0) {
  2501. return true;
  2502. }
  2503. return time() >= $ts;
  2504. }
  2505. /**
  2506. * 开标前校验:必须已过报价截止时间
  2507. *
  2508. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2509. */
  2510. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  2511. {
  2512. $sysRq = $this->resolveBundleSysRq($bundle);
  2513. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  2514. $this->error('未到招标截止日期');
  2515. }
  2516. }
  2517. /**
  2518. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  2519. *
  2520. * @param array<string, mixed> $d
  2521. * @param string $deliveryYmd
  2522. */
  2523. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  2524. {
  2525. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  2526. return max(0, (int)$d['lead_days']);
  2527. }
  2528. if ($deliveryYmd === '') {
  2529. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  2530. }
  2531. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  2532. return null;
  2533. }
  2534. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2535. $t2 = strtotime($m[1] . ' 00:00:00');
  2536. if ($t1 === false || $t2 === false) {
  2537. return null;
  2538. }
  2539. return max(0, (int)round(($t2 - $t1) / 86400));
  2540. }
  2541. /**
  2542. * @param int|null $days
  2543. */
  2544. protected function formatProcuremenLeadDaysText($days): string
  2545. {
  2546. if ($days === null || $days === '') {
  2547. return '未填写';
  2548. }
  2549. if (!is_numeric($days)) {
  2550. return '未填写';
  2551. }
  2552. return ((int)$days) . '天';
  2553. }
  2554. /**
  2555. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2556. *
  2557. * @param array<string, mixed> $line
  2558. */
  2559. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2560. {
  2561. $amountFilled = !empty($line['amount_filled']);
  2562. $deliveryFilled = !empty($line['delivery_filled']);
  2563. $leadFilled = !empty($line['lead_days_filled']);
  2564. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2565. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2566. $line['amount_show'] = '';
  2567. if (array_key_exists('amount_text', $line)) {
  2568. $line['amount_text'] = $line['unit_price_text'];
  2569. }
  2570. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2571. $line['delivery_show'] = $deliveryText;
  2572. if (array_key_exists('delivery_text', $line)) {
  2573. $line['delivery_text'] = $deliveryText;
  2574. }
  2575. $line['delivery_ymd'] = '';
  2576. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2577. $line['lead_days_show'] = $leadText;
  2578. $line['lead_days_text'] = $leadText;
  2579. $line['lead_days'] = '';
  2580. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2581. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2582. $line['subtotal_num'] = null;
  2583. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2584. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2585. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2586. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2587. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2588. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2589. $line['amount_filled'] = false;
  2590. $line['delivery_filled'] = false;
  2591. $line['lead_days_filled'] = false;
  2592. $line['is_quoted'] = false;
  2593. if (array_key_exists('quote_label', $line)) {
  2594. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2595. }
  2596. }
  2597. protected function ensurePurchaseOrderBidOpenTable(): void
  2598. {
  2599. static $ready = false;
  2600. if ($ready) {
  2601. return;
  2602. }
  2603. $cacheKey = 'procuremen_bid_open_table_ok_v1';
  2604. try {
  2605. if (Cache::get($cacheKey)) {
  2606. $ready = true;
  2607. return;
  2608. }
  2609. } catch (\Throwable $e) {
  2610. }
  2611. try {
  2612. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2613. $ready = true;
  2614. try {
  2615. Cache::set($cacheKey, 1, 86400);
  2616. } catch (\Throwable $e) {
  2617. }
  2618. } catch (\Throwable $e) {
  2619. Db::execute(
  2620. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2621. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2622. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2623. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2624. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2625. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2626. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2627. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2628. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2629. `createtime` datetime DEFAULT NULL,
  2630. PRIMARY KEY (`id`),
  2631. UNIQUE KEY `uk_ccydh` (`ccydh`)
  2632. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2633. );
  2634. $ready = true;
  2635. try {
  2636. Cache::set($cacheKey, 1, 86400);
  2637. } catch (\Throwable $e2) {
  2638. }
  2639. }
  2640. }
  2641. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  2642. {
  2643. $ccydh = trim($ccydh);
  2644. if ($ccydh === '') {
  2645. return false;
  2646. }
  2647. $this->ensurePurchaseOrderBidOpenTable();
  2648. try {
  2649. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2650. return is_array($row);
  2651. } catch (\Throwable $e) {
  2652. return false;
  2653. }
  2654. }
  2655. /**
  2656. * 批量查询订单是否已开标验证
  2657. *
  2658. * @param array<int, string> $ccydhs
  2659. * @return array<string, bool> ccydh => true
  2660. */
  2661. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  2662. {
  2663. $set = [];
  2664. $list = [];
  2665. foreach ($ccydhs as $c) {
  2666. $c = trim((string)$c);
  2667. if ($c !== '') {
  2668. $list[$c] = true;
  2669. }
  2670. }
  2671. if ($list === []) {
  2672. return $set;
  2673. }
  2674. $this->ensurePurchaseOrderBidOpenTable();
  2675. try {
  2676. $rows = Db::table('purchase_order_bid_open')
  2677. ->where('ccydh', 'in', array_keys($list))
  2678. ->field('ccydh')
  2679. ->select();
  2680. foreach ($rows as $row) {
  2681. if (!is_array($row)) {
  2682. continue;
  2683. }
  2684. $c = trim((string)($row['ccydh'] ?? ''));
  2685. if ($c !== '') {
  2686. $set[$c] = true;
  2687. }
  2688. }
  2689. } catch (\Throwable $e) {
  2690. return [];
  2691. }
  2692. return $set;
  2693. }
  2694. /**
  2695. * 批量查询订单是否已指定供应商(免开标)
  2696. *
  2697. * @param array<int, string> $ccydhs
  2698. * @return array<string, bool> ccydh => true
  2699. */
  2700. protected function loadProcuremenManualPickedCcydhSet(array $ccydhs): array
  2701. {
  2702. $set = [];
  2703. $list = [];
  2704. foreach ($ccydhs as $c) {
  2705. $c = trim((string)$c);
  2706. if ($c !== '') {
  2707. $list[$c] = true;
  2708. }
  2709. }
  2710. if ($list === []) {
  2711. return $set;
  2712. }
  2713. $this->ensurePurchaseOrderManualPickColumns();
  2714. try {
  2715. $rows = Db::table('purchase_order')
  2716. ->where('CCYDH', 'in', array_keys($list))
  2717. ->where('manual_pick', 1)
  2718. ->field('CCYDH')
  2719. ->select();
  2720. foreach ($rows as $row) {
  2721. if (!is_array($row)) {
  2722. continue;
  2723. }
  2724. $c = trim((string)($row['CCYDH'] ?? ''));
  2725. if ($c !== '') {
  2726. $set[$c] = true;
  2727. }
  2728. }
  2729. } catch (\Throwable $e) {
  2730. return [];
  2731. }
  2732. return $set;
  2733. }
  2734. /**
  2735. * 确认供应商列表:按开标状态筛选(已开标 / 已指定供应商 / 待开标)
  2736. *
  2737. * @param array<int, array<string, mixed>> $pool
  2738. * @return array<int, array<string, mixed>>
  2739. */
  2740. protected function filterProcuremenPoolByBidOpenStatus(array $pool, string $status): array
  2741. {
  2742. $status = trim($status);
  2743. if ($status === '' || !in_array($status, ['待开标', '已开标', '已指定供应商'], true)) {
  2744. return $pool;
  2745. }
  2746. $ccydhList = [];
  2747. foreach ($pool as $rw) {
  2748. if (!is_array($rw)) {
  2749. continue;
  2750. }
  2751. $c = trim((string)($rw['CCYDH'] ?? ''));
  2752. if ($c !== '') {
  2753. $ccydhList[] = $c;
  2754. }
  2755. }
  2756. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  2757. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  2758. $out = [];
  2759. foreach ($pool as $rw) {
  2760. if (!is_array($rw)) {
  2761. continue;
  2762. }
  2763. $c = trim((string)($rw['CCYDH'] ?? ''));
  2764. if ($c !== '' && isset($bidOpenSet[$c])) {
  2765. $t = '已开标';
  2766. } elseif ($c !== '' && isset($manualPickSet[$c])) {
  2767. $t = '已指定供应商';
  2768. } else {
  2769. $t = '待开标';
  2770. }
  2771. if ($t === $status) {
  2772. $out[] = $rw;
  2773. }
  2774. }
  2775. return $out;
  2776. }
  2777. /**
  2778. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  2779. *
  2780. * @param array<string, mixed> $group
  2781. */
  2782. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  2783. {
  2784. if ($quoteVisible) {
  2785. $group['remark_quote_pending'] = 0;
  2786. return;
  2787. }
  2788. $group['remark'] = '';
  2789. $group['remark_quote_pending'] = 0;
  2790. }
  2791. /**
  2792. * @param array{ccydh?:string} $bundle
  2793. */
  2794. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  2795. {
  2796. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  2797. }
  2798. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  2799. {
  2800. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  2801. return true;
  2802. }
  2803. return $this->isProcuremenManualPickedForBundle($bundle);
  2804. }
  2805. /**
  2806. * 确保 purchase_order 自选供应商字段
  2807. */
  2808. protected function ensurePurchaseOrderManualPickColumns(): void
  2809. {
  2810. static $done = false;
  2811. if ($done) {
  2812. return;
  2813. }
  2814. $done = true;
  2815. $adds = [
  2816. 'manual_pick' => "ADD COLUMN `manual_pick` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=自选供应商(免开标)' AFTER `pick_company_name`",
  2817. 'manual_pick_reason' => "ADD COLUMN `manual_pick_reason` varchar(500) NOT NULL DEFAULT '' COMMENT '自选供应商选择说明' AFTER `manual_pick`",
  2818. ];
  2819. foreach ($adds as $col => $ddl) {
  2820. try {
  2821. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  2822. if (!is_array($cols) || $cols === []) {
  2823. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  2824. }
  2825. } catch (\Throwable $e) {
  2826. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  2827. }
  2828. }
  2829. }
  2830. /**
  2831. * 是否已自选供应商(免开标查看报价)
  2832. *
  2833. * @param array{pos?:array} $bundle
  2834. */
  2835. protected function isProcuremenManualPickedForBundle(array $bundle): bool
  2836. {
  2837. $this->ensurePurchaseOrderManualPickColumns();
  2838. foreach ($bundle['pos'] ?? [] as $poRow) {
  2839. if (!is_array($poRow)) {
  2840. continue;
  2841. }
  2842. if ((int)($poRow['manual_pick'] ?? 0) === 1) {
  2843. return true;
  2844. }
  2845. }
  2846. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2847. if ($ccydh === '') {
  2848. return false;
  2849. }
  2850. try {
  2851. $v = Db::table('purchase_order')->where('CCYDH', $ccydh)->where('manual_pick', 1)->value('id');
  2852. return $v !== null && $v !== false && (int)$v > 0;
  2853. } catch (\Throwable $e) {
  2854. return false;
  2855. }
  2856. }
  2857. /**
  2858. * @param array{pos?:array} $bundle
  2859. * @return array{company:string,reason:string}
  2860. */
  2861. protected function resolveProcuremenManualPickInfo(array $bundle): array
  2862. {
  2863. $this->ensurePurchaseOrderManualPickColumns();
  2864. foreach ($bundle['pos'] ?? [] as $poRow) {
  2865. if (!is_array($poRow)) {
  2866. continue;
  2867. }
  2868. if ((int)($poRow['manual_pick'] ?? 0) !== 1) {
  2869. continue;
  2870. }
  2871. $cn = trim((string)($poRow['pick_company_name'] ?? ''));
  2872. $reason = trim((string)($poRow['manual_pick_reason'] ?? ''));
  2873. return ['company' => $cn, 'reason' => $reason];
  2874. }
  2875. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2876. if ($ccydh === '') {
  2877. return ['company' => '', 'reason' => ''];
  2878. }
  2879. try {
  2880. $row = Db::table('purchase_order')
  2881. ->where('CCYDH', $ccydh)
  2882. ->where('manual_pick', 1)
  2883. ->field('pick_company_name,manual_pick_reason')
  2884. ->order('id', 'asc')
  2885. ->find();
  2886. } catch (\Throwable $e) {
  2887. $row = null;
  2888. }
  2889. if (!is_array($row)) {
  2890. return ['company' => '', 'reason' => ''];
  2891. }
  2892. return [
  2893. 'company' => trim((string)($row['pick_company_name'] ?? '')),
  2894. 'reason' => trim((string)($row['manual_pick_reason'] ?? '')),
  2895. ];
  2896. }
  2897. protected function loadBidOpenAdminUser(int $adminId): ?array
  2898. {
  2899. if ($adminId <= 0) {
  2900. return null;
  2901. }
  2902. try {
  2903. $row = Db::name('admin')->where('id', $adminId)->find();
  2904. } catch (\Throwable $e) {
  2905. return null;
  2906. }
  2907. if (!is_array($row)) {
  2908. return null;
  2909. }
  2910. $status = strtolower(trim((string)($row['status'] ?? '')));
  2911. if ($status !== '' && $status !== 'normal') {
  2912. return null;
  2913. }
  2914. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  2915. return null;
  2916. }
  2917. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  2918. if (!preg_match('/^1\d{10}$/', $phone)) {
  2919. return null;
  2920. }
  2921. $name = trim((string)($row['nickname'] ?? ''));
  2922. if ($name === '') {
  2923. $name = trim((string)($row['username'] ?? ''));
  2924. }
  2925. return [
  2926. 'id' => (int)$row['id'],
  2927. 'username' => trim((string)($row['username'] ?? '')),
  2928. 'nickname' => $name,
  2929. 'mobile' => $phone,
  2930. ];
  2931. }
  2932. /**
  2933. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  2934. */
  2935. protected function bidOpenVerifierAuthGroupRootId(): int
  2936. {
  2937. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  2938. return $id > 0 ? $id : 10;
  2939. }
  2940. /**
  2941. * @return int[]
  2942. */
  2943. protected function loadBidOpenVerifierAuthGroupIds(): array
  2944. {
  2945. static $memo = [];
  2946. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  2947. if (isset($memo[$rootId])) {
  2948. return $memo[$rootId];
  2949. }
  2950. try {
  2951. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  2952. } catch (\Throwable $e) {
  2953. $memo[$rootId] = [$rootId];
  2954. return $memo[$rootId];
  2955. }
  2956. if (!is_array($groups) || $groups === []) {
  2957. $memo[$rootId] = [$rootId];
  2958. return $memo[$rootId];
  2959. }
  2960. $groupList = [];
  2961. foreach ($groups as $g) {
  2962. if (is_array($g)) {
  2963. $groupList[] = $g;
  2964. }
  2965. }
  2966. if ($groupList === []) {
  2967. $memo[$rootId] = [$rootId];
  2968. return $memo[$rootId];
  2969. }
  2970. $tree = \fast\Tree::instance();
  2971. $tree->init($groupList);
  2972. $ids = $tree->getChildrenIds($rootId, true);
  2973. if (!is_array($ids) || $ids === []) {
  2974. $memo[$rootId] = [$rootId];
  2975. return $memo[$rootId];
  2976. }
  2977. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  2978. return $memo[$rootId];
  2979. }
  2980. protected function isBidOpenVerifierAdmin(int $adminId): bool
  2981. {
  2982. if ($adminId <= 0) {
  2983. return false;
  2984. }
  2985. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2986. if ($groupIds === []) {
  2987. return false;
  2988. }
  2989. try {
  2990. return (bool)Db::name('auth_group_access')
  2991. ->where('uid', $adminId)
  2992. ->where('group_id', 'in', $groupIds)
  2993. ->count();
  2994. } catch (\Throwable $e) {
  2995. return false;
  2996. }
  2997. }
  2998. /**
  2999. * @return array<int, array<string, mixed>>
  3000. */
  3001. protected function listBidOpenVerifierCandidates(): array
  3002. {
  3003. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3004. if ($groupIds === []) {
  3005. return [];
  3006. }
  3007. try {
  3008. $adminIds = Db::name('auth_group_access')
  3009. ->where('group_id', 'in', $groupIds)
  3010. ->column('uid');
  3011. } catch (\Throwable $e) {
  3012. $adminIds = [];
  3013. }
  3014. $adminIds = is_array($adminIds)
  3015. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  3016. : [];
  3017. if ($adminIds === []) {
  3018. return [];
  3019. }
  3020. try {
  3021. $rows = Db::name('admin')
  3022. ->where('status', 'normal')
  3023. ->where('id', 'in', $adminIds)
  3024. ->where('mobile', '<>', '')
  3025. ->order('id', 'asc')
  3026. ->select();
  3027. } catch (\Throwable $e) {
  3028. return [];
  3029. }
  3030. if (!is_array($rows)) {
  3031. return [];
  3032. }
  3033. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  3034. $out = [];
  3035. foreach ($rows as $row) {
  3036. if (!is_array($row)) {
  3037. continue;
  3038. }
  3039. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  3040. if ($one === null) {
  3041. continue;
  3042. }
  3043. $out[] = [
  3044. 'id' => $one['id'],
  3045. 'username' => $one['username'],
  3046. 'nickname' => $one['nickname'],
  3047. 'group_name' => $groupNameMap[$one['id']] ?? '',
  3048. 'mobile' => mask_phone($one['mobile']),
  3049. 'mobile_plain' => (string)$one['mobile'],
  3050. ];
  3051. }
  3052. return $out;
  3053. }
  3054. /**
  3055. * @param int[] $adminIds
  3056. * @return array<int, string>
  3057. */
  3058. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  3059. {
  3060. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  3061. if ($adminIds === []) {
  3062. return [];
  3063. }
  3064. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3065. try {
  3066. $rows = Db::name('auth_group_access')
  3067. ->alias('aga')
  3068. ->join('auth_group ag', 'aga.group_id = ag.id')
  3069. ->where('aga.uid', 'in', $adminIds)
  3070. ->where('aga.group_id', 'in', $groupIds)
  3071. ->field('aga.uid,ag.name')
  3072. ->order('aga.uid', 'asc')
  3073. ->order('aga.group_id', 'asc')
  3074. ->select();
  3075. } catch (\Throwable $e) {
  3076. return [];
  3077. }
  3078. if (!is_array($rows)) {
  3079. return [];
  3080. }
  3081. $out = [];
  3082. foreach ($rows as $row) {
  3083. if (!is_array($row)) {
  3084. continue;
  3085. }
  3086. $uid = (int)($row['uid'] ?? 0);
  3087. $name = trim((string)($row['name'] ?? ''));
  3088. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  3089. continue;
  3090. }
  3091. $out[$uid] = $name;
  3092. }
  3093. return $out;
  3094. }
  3095. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  3096. {
  3097. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  3098. }
  3099. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  3100. {
  3101. return 'procuremen_bidopen_wait_' . $adminId;
  3102. }
  3103. protected function renderBidOpenVerifySms(string $code): string
  3104. {
  3105. $tpl = '';
  3106. try {
  3107. $row = $this->loadNotifyTemplateRow('bid_open');
  3108. if (is_array($row)) {
  3109. $tpl = trim((string)($row['content'] ?? ''));
  3110. }
  3111. } catch (\Throwable $e) {
  3112. $tpl = '';
  3113. }
  3114. if ($tpl === '') {
  3115. $tpl = '【可集达】您的短信验证码是{code}';
  3116. }
  3117. return str_replace('{code}', $code, $tpl);
  3118. }
  3119. protected function sendBidOpenVerifySms(string $phone, string $code): void
  3120. {
  3121. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  3122. }
  3123. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  3124. {
  3125. $code = trim($code);
  3126. if (!preg_match('/^\d{6}$/', $code)) {
  3127. return false;
  3128. }
  3129. $mock = Config::get('mproc.mock_sms_code');
  3130. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3131. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3132. return true;
  3133. }
  3134. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3135. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3136. return false;
  3137. }
  3138. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3139. return true;
  3140. }
  3141. /**
  3142. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3143. */
  3144. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  3145. {
  3146. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3147. if ($ccydh === '') {
  3148. throw new \InvalidArgumentException('订单号无效');
  3149. }
  3150. $this->ensurePurchaseOrderBidOpenTable();
  3151. list($operatorId, $operatorName) = $this->GetUseName();
  3152. $now = date('Y-m-d H:i:s');
  3153. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3154. $payload = [
  3155. 'ccydh' => $ccydh,
  3156. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  3157. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  3158. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  3159. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  3160. 'operator_id' => (int)$operatorId,
  3161. 'operator_name' => trim((string)$operatorName),
  3162. 'createtime' => $now,
  3163. ];
  3164. if (is_array($exists)) {
  3165. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  3166. } else {
  3167. Db::table('purchase_order_bid_open')->insert($payload);
  3168. }
  3169. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  3170. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  3171. $labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
  3172. (int)$payload['verifier1_id'],
  3173. (int)$payload['verifier2_id'],
  3174. ]);
  3175. if (isset($labelMap[(int)$payload['verifier1_id']]) && (int)$payload['verifier1_id'] > 0) {
  3176. $name1 = $labelMap[(int)$payload['verifier1_id']];
  3177. }
  3178. if (isset($labelMap[(int)$payload['verifier2_id']]) && (int)$payload['verifier2_id'] > 0) {
  3179. $name2 = $labelMap[(int)$payload['verifier2_id']];
  3180. }
  3181. $logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
  3182. $seenSid = [];
  3183. foreach ($bundle['pos'] ?? [] as $poRow) {
  3184. if (!is_array($poRow)) {
  3185. continue;
  3186. }
  3187. $sid = (int)($poRow['scydgy_id'] ?? 0);
  3188. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  3189. continue;
  3190. }
  3191. $seenSid[$sid] = true;
  3192. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  3193. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  3194. }
  3195. if ($seenSid === []) {
  3196. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  3197. if ($this->isValidScydgyRowId($anchor)) {
  3198. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  3199. }
  3200. }
  3201. // 开标通过后计算并写入供应商服务评分
  3202. try {
  3203. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  3204. ProcuremenSupplierScore::saveForOrder($ccydh, $quoteGroups, date('Y-m', strtotime($now) ?: time()));
  3205. } catch (\Throwable $e) {
  3206. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  3207. }
  3208. }
  3209. /**
  3210. * 报价行展示字段默认值(模板安全访问)
  3211. *
  3212. * @param array<string, mixed> $line
  3213. * @return array<string, mixed>
  3214. */
  3215. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  3216. {
  3217. if (!array_key_exists('amount_quote_pending', $line)) {
  3218. $line['amount_quote_pending'] = 0;
  3219. }
  3220. if (!array_key_exists('delivery_quote_pending', $line)) {
  3221. $line['delivery_quote_pending'] = 0;
  3222. }
  3223. if (!array_key_exists('quote_before_deadline', $line)) {
  3224. $line['quote_before_deadline'] = 0;
  3225. }
  3226. if (!array_key_exists('amount_filled', $line)) {
  3227. $line['amount_filled'] = 0;
  3228. }
  3229. if (!array_key_exists('delivery_filled', $line)) {
  3230. $line['delivery_filled'] = 0;
  3231. }
  3232. if (!array_key_exists('lead_days_filled', $line)) {
  3233. $line['lead_days_filled'] = 0;
  3234. }
  3235. if (!array_key_exists('lead_days_quote_pending', $line)) {
  3236. $line['lead_days_quote_pending'] = 0;
  3237. }
  3238. if (!array_key_exists('lead_days_show', $line)) {
  3239. $line['lead_days_show'] = '未填写';
  3240. }
  3241. if (!array_key_exists('lead_days_text', $line)) {
  3242. $line['lead_days_text'] = $line['lead_days_show'];
  3243. }
  3244. return $line;
  3245. }
  3246. /**
  3247. * 审核弹窗:按供应商汇总报价明细
  3248. *
  3249. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3250. * @return array<int, array<string, mixed>>
  3251. */
  3252. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  3253. {
  3254. $sids = [];
  3255. foreach ($bundle['pos'] ?? [] as $po) {
  3256. if (!is_array($po)) {
  3257. continue;
  3258. }
  3259. $sid = (int)($po['scydgy_id'] ?? 0);
  3260. if ($this->isValidScydgyRowId($sid)) {
  3261. $sids[$sid] = true;
  3262. }
  3263. }
  3264. if ($sids === []) {
  3265. return [];
  3266. }
  3267. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3268. $gymcMap = [];
  3269. $qtyBySid = [];
  3270. $orderedSids = [];
  3271. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3272. if (!is_array($mr)) {
  3273. continue;
  3274. }
  3275. $gid = $this->extractScydgyRowId($mr);
  3276. if ($this->isValidScydgyRowId($gid)) {
  3277. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3278. $orderedSids[] = $gid;
  3279. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3280. if ($qty === '') {
  3281. $qty = trim((string)($mr['NGZL'] ?? ''));
  3282. }
  3283. $qtyBySid[$gid] = $qty;
  3284. }
  3285. }
  3286. foreach ($bundle['pos'] ?? [] as $po) {
  3287. if (!is_array($po)) {
  3288. continue;
  3289. }
  3290. $gid = (int)($po['scydgy_id'] ?? 0);
  3291. if ($this->isValidScydgyRowId($gid)) {
  3292. $nm = trim((string)($po['CGYMC'] ?? ''));
  3293. if ($nm !== '') {
  3294. $gymcMap[$gid] = $nm;
  3295. }
  3296. if (!in_array($gid, $orderedSids, true)) {
  3297. $orderedSids[] = $gid;
  3298. }
  3299. }
  3300. }
  3301. try {
  3302. $detailsQuery = Db::table('purchase_order_detail')
  3303. ->where('scydgy_id', 'in', array_keys($sids));
  3304. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3305. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  3306. } catch (\Throwable $e) {
  3307. try {
  3308. $detailsQuery = Db::table('purchase_order_detail')
  3309. ->where('scydgy_id', 'in', array_keys($sids));
  3310. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3311. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  3312. } catch (\Throwable $e2) {
  3313. $details = [];
  3314. }
  3315. }
  3316. if (!is_array($details)) {
  3317. $details = [];
  3318. }
  3319. $byCompany = [];
  3320. foreach ($details as $d) {
  3321. if (!is_array($d)) {
  3322. continue;
  3323. }
  3324. $cn = trim((string)($d['company_name'] ?? ''));
  3325. if ($cn === '') {
  3326. continue;
  3327. }
  3328. if (!isset($byCompany[$cn])) {
  3329. $ph = trim((string)($d['phone'] ?? ''));
  3330. $username = trim((string)($d['username'] ?? ''));
  3331. if ($username === '') {
  3332. $username = $this->resolveCustomerContactName($ph, $cn);
  3333. }
  3334. $byCompany[$cn] = [
  3335. 'name' => $cn,
  3336. 'email' => trim((string)($d['email'] ?? '')),
  3337. 'phone' => $ph,
  3338. 'username' => $username,
  3339. 'remark' => '',
  3340. 'has_quote' => false,
  3341. 'lines_map' => [],
  3342. ];
  3343. }
  3344. if ($byCompany[$cn]['remark'] === '') {
  3345. $rm = '';
  3346. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3347. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3348. $rm = trim((string)$d[$rk]);
  3349. break;
  3350. }
  3351. }
  3352. if ($rm !== '') {
  3353. $byCompany[$cn]['remark'] = $rm;
  3354. }
  3355. }
  3356. $sid = (int)($d['scydgy_id'] ?? 0);
  3357. $am = trim((string)($d['amount'] ?? ''));
  3358. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3359. if ($gymc === '') {
  3360. $gymc = '工序';
  3361. }
  3362. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3363. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3364. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3365. $deliveryShow = $deliveryRaw;
  3366. }
  3367. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3368. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3369. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3370. $subtotal = null;
  3371. if ($amountNum !== null) {
  3372. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3373. }
  3374. $unitPriceText = $amountFilled
  3375. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3376. : '未填写';
  3377. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3378. $leadFilled = ($leadDays !== null);
  3379. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3380. $lineRow = [
  3381. 'cgymc' => $gymc,
  3382. 'amount' => $am,
  3383. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  3384. 'amount_filled' => $amountFilled,
  3385. 'unit_price_text' => $unitPriceText,
  3386. 'delivery' => $deliveryRaw,
  3387. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  3388. 'delivery_filled' => $deliveryFilled,
  3389. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  3390. 'lead_days' => $leadFilled ? $leadDays : '',
  3391. 'lead_days_filled'=> $leadFilled,
  3392. 'lead_days_show' => $leadText,
  3393. 'lead_days_text' => $leadText,
  3394. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3395. 'subtotal_num' => $subtotal,
  3396. 'status_name' => trim((string)($d['status_name'] ?? '')),
  3397. 'is_quoted' => $amountFilled,
  3398. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  3399. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3400. ];
  3401. if (!$quoteVisible) {
  3402. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  3403. }
  3404. // 按工序 id 暂存,下面再按上方工序表顺序输出
  3405. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  3406. }
  3407. foreach ($byCompany as $cn => $g) {
  3408. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  3409. $lines = [];
  3410. $usedSids = [];
  3411. foreach ($orderedSids as $sid) {
  3412. if (!isset($linesMap[$sid])) {
  3413. continue;
  3414. }
  3415. $lines[] = $linesMap[$sid];
  3416. $usedSids[$sid] = true;
  3417. }
  3418. foreach ($linesMap as $sid => $ln) {
  3419. if (isset($usedSids[$sid])) {
  3420. continue;
  3421. }
  3422. $lines[] = $ln;
  3423. }
  3424. $total = count($lines);
  3425. $quoted = 0;
  3426. $groupTotal = 0.0;
  3427. $groupHasTotal = false;
  3428. if ($quoteVisible) {
  3429. foreach ($lines as $ln) {
  3430. $am = trim((string)($ln['amount'] ?? ''));
  3431. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  3432. $quoted++;
  3433. }
  3434. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3435. $groupTotal += (float)$ln['subtotal_num'];
  3436. $groupHasTotal = true;
  3437. }
  3438. }
  3439. }
  3440. unset($byCompany[$cn]['lines_map']);
  3441. $byCompany[$cn]['lines'] = $lines;
  3442. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  3443. $byCompany[$cn]['line_count'] = $total;
  3444. $byCompany[$cn]['has_total'] = $total > 0;
  3445. $byCompany[$cn]['has_remark'] = $total > 0;
  3446. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  3447. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3448. // 工序行 + 备注行 + 总计行
  3449. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  3450. }
  3451. $groups = array_values($byCompany);
  3452. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3453. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  3454. }
  3455. /**
  3456. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  3457. *
  3458. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3459. * @return array<int, array<string, mixed>>
  3460. */
  3461. protected function loadConfirmSupplierPickGroups(array $bundle): array
  3462. {
  3463. $sids = [];
  3464. $poIdMap = [];
  3465. foreach ($bundle['pos'] ?? [] as $po) {
  3466. if (!is_array($po)) {
  3467. continue;
  3468. }
  3469. $sid = (int)($po['scydgy_id'] ?? 0);
  3470. if ($this->isValidScydgyRowId($sid)) {
  3471. $sids[$sid] = true;
  3472. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  3473. }
  3474. }
  3475. if ($sids === []) {
  3476. return [];
  3477. }
  3478. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3479. $gymcMap = [];
  3480. $qtyBySid = [];
  3481. $orderedSids = [];
  3482. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3483. if (!is_array($mr)) {
  3484. continue;
  3485. }
  3486. $gid = $this->extractScydgyRowId($mr);
  3487. if ($this->isValidScydgyRowId($gid)) {
  3488. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3489. $orderedSids[] = $gid;
  3490. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3491. if ($qty === '') {
  3492. $qty = trim((string)($mr['NGZL'] ?? ''));
  3493. }
  3494. $qtyBySid[$gid] = $qty;
  3495. }
  3496. }
  3497. foreach ($bundle['pos'] ?? [] as $po) {
  3498. if (!is_array($po)) {
  3499. continue;
  3500. }
  3501. $gid = (int)($po['scydgy_id'] ?? 0);
  3502. if ($this->isValidScydgyRowId($gid)) {
  3503. $nm = trim((string)($po['CGYMC'] ?? ''));
  3504. if ($nm !== '') {
  3505. $gymcMap[$gid] = $nm;
  3506. }
  3507. }
  3508. }
  3509. try {
  3510. $details = Db::table('purchase_order_detail')
  3511. ->where('scydgy_id', 'in', array_keys($sids))
  3512. ->order('company_name', 'asc')
  3513. ->order('id', 'asc')
  3514. ->select();
  3515. } catch (\Throwable $e) {
  3516. try {
  3517. $details = Db::table('purchase_order_detail')
  3518. ->where('scydgy_id', 'in', array_keys($sids))
  3519. ->order('company_name', 'asc')
  3520. ->order('ID', 'asc')
  3521. ->select();
  3522. } catch (\Throwable $e2) {
  3523. $details = [];
  3524. }
  3525. }
  3526. if (!is_array($details)) {
  3527. $details = [];
  3528. }
  3529. $byCompany = [];
  3530. foreach ($details as $d) {
  3531. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3532. continue;
  3533. }
  3534. $cn = trim((string)($d['company_name'] ?? ''));
  3535. if ($cn === '') {
  3536. continue;
  3537. }
  3538. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  3539. $sid = (int)($d['scydgy_id'] ?? 0);
  3540. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  3541. continue;
  3542. }
  3543. if (!isset($byCompany[$cn])) {
  3544. $ph = trim((string)($d['phone'] ?? ''));
  3545. $username = trim((string)($d['username'] ?? ''));
  3546. if ($username === '') {
  3547. $username = $this->resolveCustomerContactName($ph, $cn);
  3548. }
  3549. $byCompany[$cn] = [
  3550. 'name' => $cn,
  3551. 'email' => trim((string)($d['email'] ?? '')),
  3552. 'phone' => $ph,
  3553. 'username' => $username,
  3554. 'remark' => '',
  3555. 'pick_lines' => [],
  3556. 'detail_picks' => [],
  3557. ];
  3558. }
  3559. if ($byCompany[$cn]['remark'] === '') {
  3560. $rm = '';
  3561. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3562. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3563. $rm = trim((string)$d[$rk]);
  3564. break;
  3565. }
  3566. }
  3567. if ($rm !== '') {
  3568. $byCompany[$cn]['remark'] = $rm;
  3569. }
  3570. }
  3571. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3572. if ($gymc === '') {
  3573. $gymc = '工序';
  3574. }
  3575. $am = trim((string)($d['amount'] ?? ''));
  3576. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3577. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3578. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3579. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3580. $deliveryShow = $deliveryRaw;
  3581. }
  3582. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3583. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3584. $subtotal = null;
  3585. if ($amountNum !== null) {
  3586. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3587. }
  3588. $unitPriceText = $amountFilled
  3589. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3590. : '未填写';
  3591. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3592. $leadFilled = ($leadDays !== null);
  3593. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3594. $pickLine = [
  3595. 'cgymc' => $gymc,
  3596. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  3597. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  3598. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  3599. 'amount_filled' => $amountFilled,
  3600. 'delivery_filled' => $deliveryFilled,
  3601. 'unit_price_text' => $unitPriceText,
  3602. 'lead_days' => $leadFilled ? $leadDays : '',
  3603. 'lead_days_filled'=> $leadFilled,
  3604. 'lead_days_show' => $leadText,
  3605. 'lead_days_text' => $leadText,
  3606. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3607. 'subtotal_num' => $subtotal,
  3608. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3609. 'is_quoted' => $amountFilled,
  3610. ];
  3611. if (!$quoteVisible) {
  3612. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  3613. }
  3614. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  3615. $byCompany[$cn]['detail_picks'][$sid] = [
  3616. 'scydgy_id' => $sid,
  3617. 'detail_id' => $detailId,
  3618. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  3619. 'cgymc' => $gymc,
  3620. ];
  3621. }
  3622. $out = [];
  3623. foreach ($byCompany as $g) {
  3624. $pickLinesMap = $g['pick_lines'] ?? [];
  3625. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  3626. continue;
  3627. }
  3628. $pickLines = [];
  3629. $usedLineSids = [];
  3630. foreach ($orderedSids as $sid) {
  3631. if (!isset($pickLinesMap[$sid])) {
  3632. continue;
  3633. }
  3634. $pickLines[] = $pickLinesMap[$sid];
  3635. $usedLineSids[$sid] = true;
  3636. }
  3637. foreach ($pickLinesMap as $sid => $ln) {
  3638. if (isset($usedLineSids[$sid])) {
  3639. continue;
  3640. }
  3641. $pickLines[] = $ln;
  3642. }
  3643. $groupTotal = 0.0;
  3644. $groupHasTotal = false;
  3645. if ($quoteVisible) {
  3646. foreach ($pickLines as $ln) {
  3647. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3648. $groupTotal += (float)$ln['subtotal_num'];
  3649. $groupHasTotal = true;
  3650. }
  3651. }
  3652. }
  3653. $lineCount = count($pickLines);
  3654. $g['pick_lines'] = $pickLines;
  3655. $g['line_count'] = $lineCount;
  3656. $g['has_total'] = $lineCount > 0;
  3657. $g['has_remark'] = $lineCount > 0;
  3658. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  3659. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3660. // 工序行 + 备注行 + 总计行
  3661. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  3662. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  3663. $detailPicks = [];
  3664. $usedPickSids = [];
  3665. foreach ($orderedSids as $sid) {
  3666. if (!isset($detailPicksMap[$sid])) {
  3667. continue;
  3668. }
  3669. $detailPicks[] = $detailPicksMap[$sid];
  3670. $usedPickSids[$sid] = true;
  3671. }
  3672. foreach ($detailPicksMap as $sid => $dp) {
  3673. if (isset($usedPickSids[$sid])) {
  3674. continue;
  3675. }
  3676. $detailPicks[] = $dp;
  3677. }
  3678. $g['detail_picks'] = $detailPicks;
  3679. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  3680. unset($g['detail_picks']);
  3681. $out[] = $g;
  3682. }
  3683. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3684. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  3685. }
  3686. /**
  3687. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  3688. * @return array<int, int[]> scydgy_id => detail_id[]
  3689. */
  3690. protected function mapDetailIdsByScydgyId(array $details): array
  3691. {
  3692. $out = [];
  3693. foreach ($details as $d) {
  3694. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3695. continue;
  3696. }
  3697. $sid = (int)($d['scydgy_id'] ?? 0);
  3698. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  3699. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  3700. continue;
  3701. }
  3702. if (!isset($out[$sid])) {
  3703. $out[$sid] = [];
  3704. }
  3705. $out[$sid][] = $pk;
  3706. }
  3707. foreach ($out as $sid => $ids) {
  3708. $out[$sid] = array_values(array_unique($ids));
  3709. }
  3710. return $out;
  3711. }
  3712. /**
  3713. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  3714. *
  3715. * @param array<string, mixed> $dbRow
  3716. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  3717. */
  3718. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  3719. {
  3720. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  3721. $r = [
  3722. 'ID' => $sid,
  3723. 'scydgy_id' => $sid,
  3724. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  3725. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  3726. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  3727. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  3728. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  3729. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  3730. 'CDW' => $dbRow['CDW'] ?? '',
  3731. 'czlyq' => $dbRow['czlyq'] ?? '',
  3732. 'NGZL' => $dbRow['NGZL'] ?? '',
  3733. 'CDF' => $dbRow['CDF'] ?? '',
  3734. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  3735. 'MBZ' => $dbRow['MBZ'] ?? '',
  3736. 'bwjg' => $dbRow['bwjg'] ?? '',
  3737. 'iStatus' => $dbRow['iStatus'] ?? '',
  3738. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  3739. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  3740. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  3741. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  3742. 'dStamp' => $dbRow['dStamp'] ?? '',
  3743. 'pick_time' => $dbRow['pick_time'] ?? '',
  3744. ];
  3745. $r['This_quantity'] = $this->resolveProcuremenThisQuantity($r);
  3746. $r['ceilingPrice'] = $this->resolveProcuremenCeilingPrice($r);
  3747. if ($sid > 0 && isset($dStampMap[$sid])) {
  3748. $t = trim((string)$dStampMap[$sid]);
  3749. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  3750. $r['dStamp'] = $dStampMap[$sid];
  3751. }
  3752. }
  3753. $dsOut = trim((string)($r['dStamp'] ?? ''));
  3754. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  3755. $ct = $dbRow['createtime'];
  3756. if (is_numeric($ct) && (int)$ct > 946684800) {
  3757. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  3758. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  3759. $r['dStamp'] = trim($ct);
  3760. }
  3761. }
  3762. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  3763. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  3764. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  3765. $fallback = trim((string)($r['dStamp'] ?? ''));
  3766. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  3767. $r['dputrecord'] = $fallback;
  3768. }
  3769. }
  3770. if (array_key_exists('id', $dbRow)) {
  3771. $r['purchase_order_id'] = (int)$dbRow['id'];
  3772. }
  3773. if ($sid < 0) {
  3774. $r['_is_manual'] = 1;
  3775. }
  3776. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  3777. $pickOut = trim((string)($r['pick_time'] ?? ''));
  3778. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  3779. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  3780. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  3781. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  3782. $r['pick_time'] = $pickFallback;
  3783. break;
  3784. }
  3785. }
  3786. }
  3787. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  3788. if ($pickNm !== '') {
  3789. $r['pick_company_name'] = $pickNm;
  3790. $r['picked_supplier_name'] = $pickNm;
  3791. }
  3792. return $r;
  3793. }
  3794. /**
  3795. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  3796. *
  3797. * @return array<int, array<string, mixed>>
  3798. */
  3799. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  3800. {
  3801. $pool = [];
  3802. if (!is_array($dbRows) || $dbRows === []) {
  3803. return $pool;
  3804. }
  3805. $dStampMap = [];
  3806. $sidList = [];
  3807. foreach ($dbRows as $tmpRow) {
  3808. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  3809. $sid = (int)$tmpRow['scydgy_id'];
  3810. if ($sid > 0) {
  3811. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  3812. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3813. $sidList[$sid] = true;
  3814. }
  3815. }
  3816. }
  3817. }
  3818. if ($sidList !== []) {
  3819. try {
  3820. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  3821. } catch (\Throwable $e) {
  3822. $dStampMap = [];
  3823. }
  3824. }
  3825. foreach ($dbRows as $dbRow) {
  3826. if (!is_array($dbRow)) {
  3827. continue;
  3828. }
  3829. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  3830. }
  3831. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  3832. $needCcydh = [];
  3833. foreach ($pool as $row) {
  3834. if (!is_array($row)) {
  3835. continue;
  3836. }
  3837. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3838. continue;
  3839. }
  3840. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3841. if ($ccydh !== '') {
  3842. $needCcydh[$ccydh] = true;
  3843. }
  3844. }
  3845. if ($needCcydh !== []) {
  3846. $czMap = [];
  3847. try {
  3848. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  3849. } catch (\Throwable $e) {
  3850. $czMap = [];
  3851. }
  3852. if (is_array($czMap) && $czMap !== []) {
  3853. foreach ($pool as &$row) {
  3854. if (!is_array($row)) {
  3855. continue;
  3856. }
  3857. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3858. continue;
  3859. }
  3860. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3861. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  3862. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  3863. }
  3864. }
  3865. unset($row);
  3866. }
  3867. }
  3868. return $pool;
  3869. }
  3870. /**
  3871. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  3872. *
  3873. * @param int[] $scydgyIds
  3874. * @return array<int, array<string, mixed>>
  3875. */
  3876. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  3877. {
  3878. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3879. if ($scydgyIds === []) {
  3880. return [];
  3881. }
  3882. try {
  3883. $list = Db::table('purchase_order_detail')
  3884. ->where('scydgy_id', 'in', $scydgyIds)
  3885. ->field('scydgy_id,company_name,amount,delivery')
  3886. ->select();
  3887. } catch (\Throwable $e) {
  3888. $list = [];
  3889. }
  3890. return is_array($list) ? $list : [];
  3891. }
  3892. /**
  3893. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  3894. *
  3895. * @param int[] $scydgyIds
  3896. * @param array<int, array<string, mixed>> $allRows
  3897. * @return array{cnt:int, amt:int, deliv:int}
  3898. */
  3899. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  3900. {
  3901. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3902. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3903. if ($scydgyIds === [] || $allRows === []) {
  3904. return $out;
  3905. }
  3906. $idSet = array_flip($scydgyIds);
  3907. $all = [];
  3908. $withAmt = [];
  3909. $withDeliv = [];
  3910. foreach ($allRows as $r) {
  3911. if (!is_array($r)) {
  3912. continue;
  3913. }
  3914. $sid = (int)($r['scydgy_id'] ?? 0);
  3915. if (!isset($idSet[$sid])) {
  3916. continue;
  3917. }
  3918. $cn = trim((string)($r['company_name'] ?? ''));
  3919. if ($cn === '') {
  3920. continue;
  3921. }
  3922. $all[$cn] = true;
  3923. $am = $r['amount'] ?? null;
  3924. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  3925. $withAmt[$cn] = true;
  3926. }
  3927. $dv = $r['delivery'] ?? null;
  3928. if ($dv !== null && trim((string)$dv) !== '') {
  3929. $withDeliv[$cn] = true;
  3930. }
  3931. }
  3932. return [
  3933. 'cnt' => count($all),
  3934. 'amt' => count($withAmt),
  3935. 'deliv' => count($withDeliv),
  3936. ];
  3937. }
  3938. /**
  3939. * 本次数量:优先 This_quantity,空则回退工作量 NGZL(与下发/确认/审批弹窗一致)
  3940. *
  3941. * @param array<string, mixed> $row
  3942. */
  3943. protected function resolveProcuremenThisQuantity(array $row): string
  3944. {
  3945. $q = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  3946. if ($q !== '') {
  3947. return $q;
  3948. }
  3949. $ngzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  3950. if (!is_scalar($ngzl)) {
  3951. return '';
  3952. }
  3953. $s = trim((string)$ngzl);
  3954. if ($s === '') {
  3955. return '';
  3956. }
  3957. if (is_numeric($s) && (float)$s === 0.0) {
  3958. return '';
  3959. }
  3960. return $s;
  3961. }
  3962. /**
  3963. * @param array<string, mixed> $row
  3964. */
  3965. protected function resolveProcuremenCeilingPrice(array $row): string
  3966. {
  3967. return trim((string)($row['ceilingPrice'] ?? $row['ceiling_price'] ?? ''));
  3968. }
  3969. /**
  3970. * 多工序数量/限价拼接:跳过空值,避免出现「、10」「304、」
  3971. *
  3972. * @param array<int, mixed> $parts
  3973. */
  3974. protected function joinProcuremenNonEmpty(array $parts, string $sep = '、'): string
  3975. {
  3976. $out = [];
  3977. foreach ($parts as $p) {
  3978. $s = trim((string)$p);
  3979. if ($s !== '') {
  3980. $out[] = $s;
  3981. }
  3982. }
  3983. return $out === [] ? '' : implode($sep, $out);
  3984. }
  3985. /**
  3986. * 确认/审批列表:合并行按各工序同步本次数量、最高限价(顿号间隔)
  3987. *
  3988. * @param array<int, array<string, mixed>> $rows
  3989. */
  3990. protected function syncCollapsedOrderQtyPriceForList(array &$rows): void
  3991. {
  3992. if ($rows === []) {
  3993. return;
  3994. }
  3995. $idList = [];
  3996. foreach ($rows as $rw) {
  3997. if (!is_array($rw)) {
  3998. continue;
  3999. }
  4000. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4001. foreach ($rw['_order_merge_rows'] as $mr) {
  4002. if (!is_array($mr)) {
  4003. continue;
  4004. }
  4005. $mid = (int)($mr['ID'] ?? 0);
  4006. if ($this->isValidScydgyRowId($mid)) {
  4007. $idList[$mid] = true;
  4008. }
  4009. }
  4010. }
  4011. $id = (int)($rw['ID'] ?? 0);
  4012. if ($this->isValidScydgyRowId($id)) {
  4013. $idList[$id] = true;
  4014. }
  4015. }
  4016. if ($idList === []) {
  4017. return;
  4018. }
  4019. try {
  4020. $list = Db::table('purchase_order')
  4021. ->where('scydgy_id', 'in', array_keys($idList))
  4022. ->field('scydgy_id,This_quantity,ceilingPrice,NGZL,pick_company_name')
  4023. ->select();
  4024. } catch (\Throwable $e) {
  4025. return;
  4026. }
  4027. if (!is_array($list)) {
  4028. return;
  4029. }
  4030. $byId = [];
  4031. foreach ($list as $dbRow) {
  4032. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4033. continue;
  4034. }
  4035. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4036. }
  4037. foreach ($rows as &$rw) {
  4038. if (!is_array($rw)) {
  4039. continue;
  4040. }
  4041. $mergeRows = [];
  4042. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4043. $mergeRows = $rw['_order_merge_rows'];
  4044. } else {
  4045. $mergeRows = [$rw];
  4046. }
  4047. $qtyList = [];
  4048. $priceList = [];
  4049. $picked = '';
  4050. foreach ($mergeRows as $mr) {
  4051. if (!is_array($mr)) {
  4052. continue;
  4053. }
  4054. $sid = (int)($mr['ID'] ?? 0);
  4055. $db = ($sid !== 0 && isset($byId[$sid])) ? $byId[$sid] : null;
  4056. $src = $mr;
  4057. if (is_array($db)) {
  4058. $qDb = trim((string)($db['This_quantity'] ?? $db['this_quantity'] ?? ''));
  4059. $pDb = trim((string)($db['ceilingPrice'] ?? $db['ceiling_price'] ?? ''));
  4060. $ngzlDb = $db['NGZL'] ?? $db['ngzl'] ?? null;
  4061. if ($qDb !== '') {
  4062. $src['This_quantity'] = $qDb;
  4063. }
  4064. if ($pDb !== '') {
  4065. $src['ceilingPrice'] = $pDb;
  4066. }
  4067. if ($ngzlDb !== null && trim((string)$ngzlDb) !== '') {
  4068. $src['NGZL'] = $ngzlDb;
  4069. }
  4070. if ($picked === '') {
  4071. $picked = trim((string)($db['pick_company_name'] ?? ''));
  4072. }
  4073. }
  4074. if ($picked === '') {
  4075. $picked = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  4076. }
  4077. $qtyList[] = $this->resolveProcuremenThisQuantity($src);
  4078. $priceList[] = $this->resolveProcuremenCeilingPrice($src);
  4079. }
  4080. $rw['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  4081. $rw['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  4082. if ($picked !== '') {
  4083. $rw['pick_company_name'] = $picked;
  4084. $rw['picked_supplier_name'] = $picked;
  4085. }
  4086. }
  4087. unset($rw);
  4088. }
  4089. /**
  4090. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  4091. *
  4092. * @param int[] $scydgyIds
  4093. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  4094. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  4095. */
  4096. protected function OrderDetailSummary(array $scydgyIds)
  4097. {
  4098. $out = [];
  4099. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4100. if ($scydgyIds === []) {
  4101. return $out;
  4102. }
  4103. $list = [];
  4104. try {
  4105. $list = Db::table('purchase_order_detail')
  4106. ->where('scydgy_id', 'in', $scydgyIds)
  4107. ->field('id,scydgy_id,amount,delivery')
  4108. ->select();
  4109. } catch (\Throwable $e) {
  4110. $list = [];
  4111. }
  4112. if (!is_array($list)) {
  4113. return $out;
  4114. }
  4115. foreach ($list as $r) {
  4116. if (!is_array($r)) {
  4117. continue;
  4118. }
  4119. $ids = (int)($r['scydgy_id'] ?? 0);
  4120. if (!$this->isValidScydgyRowId($ids)) {
  4121. continue;
  4122. }
  4123. if (!isset($out[$ids])) {
  4124. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4125. }
  4126. $out[$ids]['cnt']++;
  4127. $am = $r['amount'] ?? null;
  4128. if ($am !== null && $am !== '') {
  4129. if (!(is_string($am) && trim($am) === '')) {
  4130. $out[$ids]['amt']++;
  4131. }
  4132. }
  4133. $dv = $r['delivery'] ?? null;
  4134. if ($dv !== null && trim((string)$dv) !== '') {
  4135. $out[$ids]['deliv']++;
  4136. }
  4137. }
  4138. return $out;
  4139. }
  4140. /**
  4141. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  4142. *
  4143. * @return array
  4144. */
  4145. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  4146. {
  4147. $strContains = function ($haystack, $needle) {
  4148. if ($needle === '') {
  4149. return false;
  4150. }
  4151. $haystack = (string)$haystack;
  4152. if (function_exists('mb_stripos')) {
  4153. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  4154. }
  4155. return stripos($haystack, $needle) !== false;
  4156. };
  4157. $stripAlias = function ($f) {
  4158. return preg_replace('/^[ab]\./i', '', (string)$f);
  4159. };
  4160. $searchColNames = [];
  4161. foreach (explode(',', $this->searchFields) as $colRaw) {
  4162. $c = $stripAlias(trim($colRaw));
  4163. if ($c !== '') {
  4164. $searchColNames[] = $c;
  4165. }
  4166. }
  4167. // 等值条件先行(表头下拉),减少后续日期解析量
  4168. $eqFilters = [];
  4169. $otherFilters = [];
  4170. foreach ($filterArr as $fk => $fv) {
  4171. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  4172. continue;
  4173. }
  4174. if (is_array($fv)) {
  4175. continue;
  4176. }
  4177. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  4178. continue;
  4179. }
  4180. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  4181. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  4182. $field = $stripAlias($fk);
  4183. if ($sym === '=' || $sym === '') {
  4184. $eqFilters[$field] = trim((string)$fv);
  4185. } else {
  4186. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  4187. }
  4188. }
  4189. $ymTarget = '';
  4190. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  4191. $ymTarget = $ymM[1];
  4192. }
  4193. $filtered = [];
  4194. foreach ($pool as $r) {
  4195. if (!is_array($r)) {
  4196. continue;
  4197. }
  4198. foreach ($eqFilters as $field => $fv) {
  4199. if (trim((string)($r[$field] ?? '')) !== $fv) {
  4200. continue 2;
  4201. }
  4202. }
  4203. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  4204. // 初选池不应含手工单;若混入则直接剔除
  4205. if ($isManual) {
  4206. continue;
  4207. }
  4208. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  4209. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  4210. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  4211. continue;
  4212. }
  4213. if ($applyMonthRange) {
  4214. $mo = (int)$m[2];
  4215. if ($mo < 1 || $mo > 12) {
  4216. continue;
  4217. }
  4218. if ($ymTarget !== '') {
  4219. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4220. if ($ymRow !== $ymTarget) {
  4221. continue;
  4222. }
  4223. } else {
  4224. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4225. $rowMonthStart = $ymRow . '-01 00:00:00';
  4226. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  4227. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  4228. continue;
  4229. }
  4230. }
  4231. }
  4232. if ($search !== '') {
  4233. $hitSearch = false;
  4234. foreach ($searchColNames as $c) {
  4235. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  4236. if ($cell !== '' && $strContains($cell, $search)) {
  4237. $hitSearch = true;
  4238. break;
  4239. }
  4240. }
  4241. if (!$hitSearch) {
  4242. continue;
  4243. }
  4244. }
  4245. foreach ($otherFilters as $item) {
  4246. $fv = $item['fv'];
  4247. $sym = $item['sym'];
  4248. $field = $item['field'];
  4249. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  4250. $cellStr = trim((string)$cell);
  4251. switch ($sym) {
  4252. case '<>':
  4253. if ((string)$cell === (string)$fv) {
  4254. continue 3;
  4255. }
  4256. break;
  4257. case 'LIKE':
  4258. case 'NOT LIKE':
  4259. $needle = trim((string)$fv);
  4260. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  4261. if ($sym === 'LIKE' && !$hit) {
  4262. continue 3;
  4263. }
  4264. if ($sym === 'NOT LIKE' && $hit) {
  4265. continue 3;
  4266. }
  4267. break;
  4268. case 'BETWEEN':
  4269. case 'RANGE':
  4270. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  4271. if (count($parts) < 2) {
  4272. $parts = is_string($fv) ? explode(',', $fv) : [];
  4273. }
  4274. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  4275. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  4276. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  4277. continue 3;
  4278. }
  4279. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  4280. continue 3;
  4281. }
  4282. break;
  4283. case '>':
  4284. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  4285. continue 3;
  4286. }
  4287. break;
  4288. case '>=':
  4289. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  4290. continue 3;
  4291. }
  4292. break;
  4293. case '<':
  4294. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  4295. continue 3;
  4296. }
  4297. break;
  4298. case '<=':
  4299. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  4300. continue 3;
  4301. }
  4302. break;
  4303. default:
  4304. if ((string)$cell !== (string)$fv) {
  4305. continue 3;
  4306. }
  4307. break;
  4308. }
  4309. }
  4310. $filtered[] = $r;
  4311. }
  4312. return $filtered;
  4313. }
  4314. /**
  4315. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  4316. */
  4317. public function snapshotToProcure()
  4318. {
  4319. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4320. $this->error(__('Invalid parameters'));
  4321. }
  4322. $row = json_decode($this->request->post('row_json', ''), true);
  4323. if (!is_array($row)) {
  4324. $this->error(__('Invalid parameters'));
  4325. }
  4326. try {
  4327. $ids = $this->extractScydgyRowId($row);
  4328. if (!$this->isValidScydgyRowId($ids)) {
  4329. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4330. }
  4331. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4332. $data = [
  4333. 'scydgy_id' => $ids,
  4334. 'CCYDH' => $row['CCYDH'] ?? null,
  4335. 'CYJMC' => $row['CYJMC'] ?? null,
  4336. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4337. 'CDXMC' => $row['CDXMC'] ?? null,
  4338. 'CGYBH' => $row['CGYBH'] ?? null,
  4339. 'CGYMC' => $row['CGYMC'] ?? null,
  4340. 'CDW' => $row['CDW'] ?? null,
  4341. 'czlyq' => $row['czlyq'] ?? null,
  4342. 'NGZL' => $row['NGZL'] ?? null,
  4343. 'CDF' => $row['CDF'] ?? null,
  4344. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4345. 'MBZ' => $row['MBZ'] ?? null,
  4346. 'bwjg' => $row['bwjg'] ?? null,
  4347. 'iStatus' => $row['iStatus'] ?? null,
  4348. 'dStamp' => $row['dStamp'] ?? null,
  4349. 'dputrecord' => $row['dputrecord'] ?? null,
  4350. 'cywyxm' => $row['cywyxm'] ?? null,
  4351. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4352. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4353. ];
  4354. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  4355. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  4356. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  4357. $this->success('操作成功');
  4358. return;
  4359. }
  4360. if ($exists) {
  4361. $upd = $data;
  4362. unset($upd['scydgy_id'], $upd['status']);
  4363. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4364. } else {
  4365. // 新增:不写 status(空/走库默认);仅写创建时间
  4366. $data['createtime'] = date('Y-m-d H:i:s');
  4367. Db::table('purchase_order')->insert($data);
  4368. }
  4369. } catch (\Throwable $e) {
  4370. $this->error($e->getMessage());
  4371. }
  4372. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  4373. $this->success('操作成功');
  4374. }
  4375. /**
  4376. * 未发列表
  4377. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  4378. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  4379. */
  4380. public function completeDirectly()
  4381. {
  4382. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4383. $this->error(__('参数错误'));
  4384. }
  4385. if (!$this->procuremenCanComplete()) {
  4386. $this->error(__('You have no permission'));
  4387. }
  4388. $row = json_decode($this->request->post('row_json', ''), true);
  4389. if (!is_array($row)) {
  4390. $this->error(__('Invalid parameters'));
  4391. }
  4392. $finishRaw = $this->request->post('finish', '1');
  4393. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  4394. $poIdLog = null;
  4395. try {
  4396. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  4397. $ids = $this->extractScydgyRowId($row);
  4398. if (!$this->isValidScydgyRowId($ids)) {
  4399. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4400. }
  4401. if ($asComplete) {
  4402. $this->assertPickRowCanComplete($ids, $row);
  4403. }
  4404. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4405. $data = [
  4406. 'scydgy_id' => $ids,
  4407. 'CCYDH' => $row['CCYDH'] ?? null,
  4408. 'CYJMC' => $row['CYJMC'] ?? null,
  4409. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4410. 'CDXMC' => $row['CDXMC'] ?? null,
  4411. 'CGYBH' => $row['CGYBH'] ?? null,
  4412. 'CGYMC' => $row['CGYMC'] ?? null,
  4413. 'CDW' => $row['CDW'] ?? null,
  4414. 'czlyq' => $row['czlyq'] ?? null,
  4415. 'NGZL' => $row['NGZL'] ?? null,
  4416. 'CDF' => $row['CDF'] ?? null,
  4417. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4418. 'MBZ' => $row['MBZ'] ?? null,
  4419. 'bwjg' => $row['bwjg'] ?? null,
  4420. 'iStatus' => $row['iStatus'] ?? null,
  4421. 'dStamp' => $row['dStamp'] ?? null,
  4422. 'dputrecord' => $row['dputrecord'] ?? null,
  4423. 'cywyxm' => $row['cywyxm'] ?? null,
  4424. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4425. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4426. ];
  4427. if ($asComplete) {
  4428. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  4429. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  4430. }
  4431. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  4432. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  4433. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  4434. $this->success('操作成功');
  4435. return;
  4436. }
  4437. if ($exists) {
  4438. $upd = $data;
  4439. unset($upd['scydgy_id']);
  4440. if (!$asComplete) {
  4441. unset($upd['status']);
  4442. }
  4443. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4444. } else {
  4445. // 新增:不写 status;完结时 $data 已含 status=1
  4446. $data['createtime'] = date('Y-m-d H:i:s');
  4447. Db::table('purchase_order')->insert($data);
  4448. }
  4449. } catch (\Throwable $e) {
  4450. $this->error($e->getMessage());
  4451. }
  4452. try {
  4453. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4454. if (is_array($rpo)) {
  4455. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4456. $poIdLog = $tid > 0 ? $tid : null;
  4457. }
  4458. } catch (\Throwable $e) {
  4459. $poIdLog = null;
  4460. }
  4461. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  4462. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  4463. if ($asComplete) {
  4464. $this->addOrderLog(
  4465. $ids,
  4466. 'mark_complete',
  4467. '点击「完结」,已标记为已完结',
  4468. $poIdLog
  4469. );
  4470. try {
  4471. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  4472. if ($pdfPublicPath === '') {
  4473. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  4474. }
  4475. } catch (\Throwable $e) {
  4476. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  4477. }
  4478. } else {
  4479. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  4480. $qtyPart = '本次数量「' . ($q !== '' ? $q : '') . '」';
  4481. $pricePart = '最高限价「' . ($p !== '' ? $p : '') . '」';
  4482. $detail = ($gymc !== '' ? ($gymc . $qtyPart) : $qtyPart) . ',' . $pricePart;
  4483. $this->addOrderLog(
  4484. $ids,
  4485. 'save_qty_price',
  4486. '保存本次数量、最高限价:' . $detail,
  4487. $poIdLog
  4488. );
  4489. }
  4490. $this->pickHiddenScydgySetCache = null;
  4491. $this->success("操作成功");
  4492. }
  4493. /**
  4494. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  4495. *
  4496. * @param array<int, array> $rows 引用传递当前页行
  4497. */
  4498. protected function mergePurchaseOrder(array &$rows)
  4499. {
  4500. if ($rows === []) {
  4501. return;
  4502. }
  4503. $ids = [];
  4504. foreach ($rows as $rw) {
  4505. if (!is_array($rw)) {
  4506. continue;
  4507. }
  4508. $id = (int)($rw['ID'] ?? 0);
  4509. // 含手工新增负数 scydgy_id,避免限价/数量不同步
  4510. if ($this->isValidScydgyRowId($id)) {
  4511. $ids[$id] = true;
  4512. }
  4513. }
  4514. $idList = array_keys($ids);
  4515. if ($idList === []) {
  4516. return;
  4517. }
  4518. try {
  4519. $list = Db::table('purchase_order')
  4520. ->where('scydgy_id', 'in', $idList)
  4521. ->field('scydgy_id,This_quantity,ceilingPrice')
  4522. ->select();
  4523. } catch (\Throwable $e) {
  4524. return;
  4525. }
  4526. if (!is_array($list)) {
  4527. return;
  4528. }
  4529. $byId = [];
  4530. foreach ($list as $dbRow) {
  4531. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4532. continue;
  4533. }
  4534. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4535. }
  4536. foreach ($rows as &$rw) {
  4537. if (!is_array($rw)) {
  4538. continue;
  4539. }
  4540. $sid = (int)($rw['ID'] ?? 0);
  4541. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  4542. continue;
  4543. }
  4544. $db = $byId[$sid];
  4545. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  4546. if (array_key_exists('This_quantity', $db)) {
  4547. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  4548. }
  4549. if (array_key_exists('ceilingPrice', $db)) {
  4550. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  4551. } elseif (array_key_exists('ceiling_price', $db)) {
  4552. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  4553. }
  4554. }
  4555. unset($rw);
  4556. }
  4557. /**
  4558. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  4559. */
  4560. public function purchaseConfirmPick()
  4561. {
  4562. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4563. $this->error(__('Invalid parameters'));
  4564. }
  4565. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  4566. $this->error(__('You have no permission'));
  4567. }
  4568. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  4569. if ($batchRaw !== '') {
  4570. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  4571. return;
  4572. }
  4573. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  4574. $sid = (int)$scydgyId;
  4575. if (!$this->isValidScydgyRowId($sid)) {
  4576. $this->error('参数无效');
  4577. }
  4578. $parseIdList = function ($raw) {
  4579. if (is_array($raw)) {
  4580. $arr = $raw;
  4581. } else {
  4582. $decoded = json_decode((string)$raw, true);
  4583. $arr = is_array($decoded) ? $decoded : [];
  4584. }
  4585. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  4586. };
  4587. $selectedRaw = $this->request->post('selected_ids', null);
  4588. if ($selectedRaw === null || $selectedRaw === '') {
  4589. $legacy = (int)$this->request->post('selected_id', 0);
  4590. $selectedIds = $legacy > 0 ? [$legacy] : [];
  4591. } else {
  4592. $selectedIds = $parseIdList($selectedRaw);
  4593. }
  4594. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  4595. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  4596. try {
  4597. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  4598. } catch (\InvalidArgumentException $e) {
  4599. $this->error($e->getMessage());
  4600. } catch (\Throwable $e) {
  4601. $this->error($e->getMessage());
  4602. }
  4603. $this->pickHiddenScydgySetCache = null;
  4604. $this->success('操作成功', '', $result);
  4605. }
  4606. /**
  4607. * 整单采购确认(多道工序一次提交)
  4608. */
  4609. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  4610. {
  4611. $decoded = json_decode($batchRaw, true);
  4612. if (!is_array($decoded) || $decoded === []) {
  4613. $this->error('提交数据无效');
  4614. }
  4615. $picks = [];
  4616. foreach ($decoded as $item) {
  4617. if (!is_array($item)) {
  4618. continue;
  4619. }
  4620. $sid = (int)($item['scydgy_id'] ?? 0);
  4621. if (!$this->isValidScydgyRowId($sid)) {
  4622. continue;
  4623. }
  4624. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  4625. if (!is_array($sel)) {
  4626. $sel = [(int)$sel];
  4627. }
  4628. $unsel = $item['unselected_ids'] ?? [];
  4629. if (!is_array($unsel)) {
  4630. $unsel = json_decode((string)$unsel, true);
  4631. $unsel = is_array($unsel) ? $unsel : [];
  4632. }
  4633. $picks[] = [
  4634. 'scydgy_id' => $sid,
  4635. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  4636. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  4637. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  4638. ];
  4639. }
  4640. if ($picks === []) {
  4641. $this->error('提交数据无效');
  4642. }
  4643. Db::startTrans();
  4644. $results = [];
  4645. try {
  4646. foreach ($picks as $pick) {
  4647. $results[] = $this->runPurchaseConfirmPick(
  4648. (int)$pick['scydgy_id'],
  4649. $pick['selected_ids'],
  4650. $pick['unselected_ids'],
  4651. (int)$pick['purchase_order_id'],
  4652. false,
  4653. false
  4654. );
  4655. }
  4656. Db::commit();
  4657. } catch (\Throwable $e) {
  4658. Db::rollback();
  4659. $msg = $e->getMessage();
  4660. $this->error($msg !== '' ? $msg : '提交失败');
  4661. }
  4662. try {
  4663. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  4664. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  4665. } catch (\Throwable $e) {
  4666. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  4667. }
  4668. $this->pickHiddenScydgySetCache = null;
  4669. $this->success('操作成功', '', ['batch' => $results]);
  4670. }
  4671. /**
  4672. * @return array<string, mixed>
  4673. */
  4674. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  4675. {
  4676. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  4677. ProcuremenGuard::assertWflowPendingApproval($poRow);
  4678. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  4679. $scydgyId = (string)$sid;
  4680. if ($selectedIds === []) {
  4681. throw new \InvalidArgumentException('请至少勾选一条明细');
  4682. }
  4683. $inter = array_intersect($selectedIds, $unselectedIds);
  4684. if ($inter !== []) {
  4685. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  4686. }
  4687. $allIds = $this->purchaseOrderDetail($sid);
  4688. if ($allIds === []) {
  4689. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  4690. }
  4691. foreach ($selectedIds as $id) {
  4692. if (!in_array($id, $allIds, true)) {
  4693. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  4694. }
  4695. }
  4696. foreach ($unselectedIds as $id) {
  4697. if (!in_array($id, $allIds, true)) {
  4698. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  4699. }
  4700. }
  4701. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  4702. sort($union, SORT_NUMERIC);
  4703. $expect = $allIds;
  4704. sort($expect, SORT_NUMERIC);
  4705. if ($union !== $expect) {
  4706. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  4707. }
  4708. if ($manageTransaction) {
  4709. Db::startTrans();
  4710. }
  4711. try {
  4712. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  4713. $aff = 0;
  4714. try {
  4715. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4716. } catch (\Throwable $e) {
  4717. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4718. }
  4719. if ($aff < 1) {
  4720. throw new \Exception('更新选中状态失败');
  4721. }
  4722. $poPayload = [
  4723. // 审核通过后进入「待入库评分」;合格/不合格后才置已完结
  4724. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  4725. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  4726. ];
  4727. if ($purchaseOrderId > 0) {
  4728. $poAff = (int)Db::table('purchase_order')
  4729. ->where('id', $purchaseOrderId)
  4730. ->where('scydgy_id', $sid)
  4731. ->update($poPayload);
  4732. if ($poAff < 1) {
  4733. throw new \Exception('主表订单不存在或与工序行不匹配');
  4734. }
  4735. } else {
  4736. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  4737. if ($poAff < 1) {
  4738. throw new \Exception('未找到');
  4739. }
  4740. }
  4741. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  4742. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  4743. if ($manageTransaction) {
  4744. Db::commit();
  4745. }
  4746. } catch (\Throwable $e) {
  4747. if ($manageTransaction) {
  4748. Db::rollback();
  4749. }
  4750. throw $e;
  4751. }
  4752. $poIdFinal = $purchaseOrderId;
  4753. if ($poIdFinal <= 0) {
  4754. try {
  4755. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4756. if (is_array($rpo)) {
  4757. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4758. }
  4759. } catch (\Throwable $e) {
  4760. $poIdFinal = 0;
  4761. }
  4762. }
  4763. $pickNames = [];
  4764. foreach ($selectedIds as $pid) {
  4765. $dr = $this->purchaseOrderDetai($sid, $pid);
  4766. $nm = trim((string)($dr['company_name'] ?? ''));
  4767. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  4768. }
  4769. $this->addOrderLog(
  4770. $sid,
  4771. 'purchase_confirm',
  4772. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  4773. $poIdFinal > 0 ? $poIdFinal : null
  4774. );
  4775. if ($sendNotifications) {
  4776. try {
  4777. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  4778. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  4779. 'scydgy_id' => $sid,
  4780. 'selected_ids' => $selectedIds,
  4781. 'unselected_ids' => $unselectedIds,
  4782. 'purchase_order_id' => $purchaseOrderId,
  4783. ]]);
  4784. } catch (\Throwable $e) {
  4785. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  4786. }
  4787. }
  4788. Log::write(sprintf(
  4789. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  4790. $scydgyId,
  4791. $purchaseOrderId,
  4792. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  4793. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  4794. ), 'notice');
  4795. $pdfPublicPath = '';
  4796. try {
  4797. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  4798. } catch (\Throwable $e) {
  4799. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  4800. }
  4801. return [
  4802. 'scydgy_id' => $scydgyId,
  4803. 'purchase_order_id' => $purchaseOrderId,
  4804. 'selected_ids' => $selectedIds,
  4805. 'unselected_ids' => $unselectedIds,
  4806. 'purchase_confirm_pdf' => $pdfPublicPath,
  4807. ];
  4808. }
  4809. /**
  4810. * 审批通过短信:按本次涉及的工序汇总 process_lines
  4811. *
  4812. * @param int[]|string[] $scydgyIds
  4813. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4814. */
  4815. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  4816. {
  4817. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4818. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4819. if ($scydgyIds === []) {
  4820. return $empty;
  4821. }
  4822. $pos = [];
  4823. try {
  4824. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  4825. } catch (\Throwable $e) {
  4826. $rows = [];
  4827. }
  4828. if (is_array($rows)) {
  4829. foreach ($rows as $po) {
  4830. if (is_array($po)) {
  4831. $pos[] = $po;
  4832. }
  4833. }
  4834. }
  4835. if ($pos === []) {
  4836. return $empty;
  4837. }
  4838. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  4839. return [
  4840. 'ccydh' => $ccydh,
  4841. 'pos' => $pos,
  4842. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4843. ];
  4844. }
  4845. /**
  4846. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  4847. *
  4848. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  4849. * @param array<int, array<string, mixed>> $picks
  4850. */
  4851. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  4852. {
  4853. if ($picks === []) {
  4854. return;
  4855. }
  4856. $fallbackDetailId = 0;
  4857. $winners = [];
  4858. $losers = [];
  4859. foreach ($picks as $pick) {
  4860. if (!is_array($pick)) {
  4861. continue;
  4862. }
  4863. $sid = (int)($pick['scydgy_id'] ?? 0);
  4864. if (!$this->isValidScydgyRowId($sid)) {
  4865. continue;
  4866. }
  4867. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  4868. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  4869. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  4870. $fallbackDetailId = (int)$selectedIds[0];
  4871. }
  4872. foreach ($selectedIds as $pid) {
  4873. $dr = $this->purchaseOrderDetai($sid, $pid);
  4874. if (!is_array($dr)) {
  4875. continue;
  4876. }
  4877. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  4878. }
  4879. foreach ($unselectedIds as $pid) {
  4880. $dr = $this->purchaseOrderDetai($sid, $pid);
  4881. if (!is_array($dr)) {
  4882. continue;
  4883. }
  4884. $key = $this->notifySupplierDedupeKey($dr);
  4885. if (!isset($winners[$key])) {
  4886. $losers[$key] = $dr;
  4887. }
  4888. }
  4889. }
  4890. if ($winners === [] && $losers === []) {
  4891. return;
  4892. }
  4893. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  4894. $sendSmsSafe = function ($phone, $content) {
  4895. $phone = trim((string)$phone);
  4896. if ($phone === '') {
  4897. return;
  4898. }
  4899. try {
  4900. $this->smsbao($phone, $content);
  4901. } catch (\Throwable $e) {
  4902. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  4903. }
  4904. };
  4905. foreach ($winners as $dr) {
  4906. $cname = trim((string)($dr['company_name'] ?? ''));
  4907. $ph = trim((string)($dr['phone'] ?? ''));
  4908. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  4909. 'company_name' => $cname,
  4910. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4911. 'phone' => $ph,
  4912. ]));
  4913. $sendSmsSafe($ph, $sms);
  4914. }
  4915. foreach ($losers as $dr) {
  4916. $cname = trim((string)($dr['company_name'] ?? ''));
  4917. $ph = trim((string)($dr['phone'] ?? ''));
  4918. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  4919. 'company_name' => $cname,
  4920. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4921. 'phone' => $ph,
  4922. ]));
  4923. $sendSmsSafe($ph, $sms);
  4924. }
  4925. }
  4926. /**
  4927. * 短信去重键:优先手机号,否则公司名
  4928. */
  4929. protected function notifySupplierDedupeKey(array $detailRow): string
  4930. {
  4931. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  4932. if ($ph !== '') {
  4933. return 'p:' . $ph;
  4934. }
  4935. $cn = trim((string)($detailRow['company_name'] ?? ''));
  4936. return 'c:' . $cn;
  4937. }
  4938. /**
  4939. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  4940. *
  4941. * @param int[] $detailIds
  4942. */
  4943. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  4944. {
  4945. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  4946. if ($detailIds === []) {
  4947. return;
  4948. }
  4949. $payload = ['status_name' => $statusName];
  4950. try {
  4951. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  4952. } catch (\Throwable $e) {
  4953. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  4954. }
  4955. }
  4956. /**
  4957. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  4958. */
  4959. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  4960. {
  4961. try {
  4962. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  4963. } catch (\Throwable $e) {
  4964. return;
  4965. }
  4966. if (!is_array($rows)) {
  4967. return;
  4968. }
  4969. foreach ($rows as $dr) {
  4970. if (!is_array($dr)) {
  4971. continue;
  4972. }
  4973. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  4974. if ($id <= 0) {
  4975. continue;
  4976. }
  4977. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  4978. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  4979. try {
  4980. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  4981. } catch (\Throwable $e) {
  4982. }
  4983. }
  4984. }
  4985. /**
  4986. * @param array<string, mixed> $detailRow
  4987. */
  4988. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  4989. {
  4990. $am = $detailRow['amount'] ?? null;
  4991. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  4992. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  4993. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  4994. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  4995. }
  4996. /**
  4997. * @return int[]
  4998. */
  4999. protected function purchaseOrderDetail(int $scydgyId): array
  5000. {
  5001. if (!$this->isValidScydgyRowId($scydgyId)) {
  5002. return [];
  5003. }
  5004. try {
  5005. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  5006. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  5007. $list = $listQuery->select();
  5008. } catch (\Throwable $e) {
  5009. return [];
  5010. }
  5011. if (!is_array($list)) {
  5012. return [];
  5013. }
  5014. $ids = [];
  5015. foreach ($list as $r) {
  5016. if (!is_array($r)) {
  5017. continue;
  5018. }
  5019. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  5020. if ($pk > 0) {
  5021. $ids[] = $pk;
  5022. }
  5023. }
  5024. return array_values(array_unique($ids));
  5025. }
  5026. /**
  5027. * 获取当前登录用户信息 [id, 展示名]
  5028. */
  5029. protected function GetUseName(): array
  5030. {
  5031. $id = 0;
  5032. $name = '';
  5033. try {
  5034. if ($this->auth && $this->auth->isLogin()) {
  5035. $u = $this->auth->getUserInfo();
  5036. if (is_array($u)) {
  5037. $id = (int)($u['id'] ?? 0);
  5038. $name = trim((string)($u['nickname'] ?? ''));
  5039. if ($name === '') {
  5040. $name = trim((string)($u['username'] ?? ''));
  5041. }
  5042. }
  5043. }
  5044. } catch (\Throwable $e) {
  5045. }
  5046. if ($name === '') {
  5047. $name = '未知用户';
  5048. }
  5049. return [$id, $name];
  5050. }
  5051. /**
  5052. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  5053. */
  5054. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  5055. {
  5056. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  5057. }
  5058. /**
  5059. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  5060. *
  5061. * @param array<int, array<string, mixed>> $rows
  5062. */
  5063. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  5064. {
  5065. $sidList = [];
  5066. foreach ($rows as $rw) {
  5067. if (!is_array($rw)) {
  5068. continue;
  5069. }
  5070. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5071. foreach ($rw['_order_merge_rows'] as $mr) {
  5072. $mid = (int)($mr['ID'] ?? 0);
  5073. if ($this->isValidScydgyRowId($mid)) {
  5074. $sidList[$mid] = true;
  5075. }
  5076. }
  5077. }
  5078. $id = (int)($rw['ID'] ?? 0);
  5079. if ($this->isValidScydgyRowId($id)) {
  5080. $sidList[$id] = true;
  5081. }
  5082. }
  5083. $sids = array_keys($sidList);
  5084. $issueBySid = [];
  5085. $confirmBySid = [];
  5086. $approveBySid = [];
  5087. if ($sids !== []) {
  5088. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  5089. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  5090. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  5091. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  5092. try {
  5093. $logs = Db::table('purchase_order_oper_log')
  5094. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  5095. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  5096. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  5097. ->order('id', 'asc')
  5098. ->select();
  5099. } catch (\Throwable $e) {
  5100. $logs = [];
  5101. }
  5102. if (is_array($logs)) {
  5103. $issueSet = array_fill_keys($issueActs, true);
  5104. $confirmSet = array_fill_keys($confirmActs, true);
  5105. $approveSet = array_fill_keys($approveActs, true);
  5106. foreach ($logs as $lg) {
  5107. if (!is_array($lg)) {
  5108. continue;
  5109. }
  5110. $lg = ProcuremenOperLog::normalizeRow($lg);
  5111. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  5112. if ($sid === 0) {
  5113. continue;
  5114. }
  5115. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  5116. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  5117. if ($t === '') {
  5118. continue;
  5119. }
  5120. if (isset($issueSet[$action])) {
  5121. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  5122. $issueBySid[$sid] = $t;
  5123. }
  5124. }
  5125. if (isset($confirmSet[$action])) {
  5126. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  5127. $confirmBySid[$sid] = $t;
  5128. }
  5129. }
  5130. if (isset($approveSet[$action])) {
  5131. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  5132. $approveBySid[$sid] = $t;
  5133. }
  5134. }
  5135. }
  5136. }
  5137. }
  5138. foreach ($rows as &$rw) {
  5139. if (!is_array($rw)) {
  5140. continue;
  5141. }
  5142. $mergeSids = [];
  5143. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5144. foreach ($rw['_order_merge_rows'] as $mr) {
  5145. $mid = (int)($mr['ID'] ?? 0);
  5146. if ($this->isValidScydgyRowId($mid)) {
  5147. $mergeSids[] = $mid;
  5148. }
  5149. }
  5150. }
  5151. $rid = (int)($rw['ID'] ?? 0);
  5152. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  5153. $mergeSids[] = $rid;
  5154. }
  5155. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  5156. $issue = $pick;
  5157. $confirm = '';
  5158. $approve = '';
  5159. foreach ($mergeSids as $sid) {
  5160. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  5161. $issue = $issueBySid[$sid];
  5162. }
  5163. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  5164. $confirm = $confirmBySid[$sid];
  5165. }
  5166. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  5167. $approve = $approveBySid[$sid];
  5168. }
  5169. }
  5170. if ($issue === '' && $pick !== '') {
  5171. $issue = $pick;
  5172. }
  5173. $rw['issue_time'] = $issue;
  5174. $rw['confirm_time'] = $confirm;
  5175. $rw['approve_time'] = $approve;
  5176. }
  5177. unset($rw);
  5178. }
  5179. /**
  5180. * 按主键取一条
  5181. */
  5182. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  5183. {
  5184. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  5185. return [];
  5186. }
  5187. try {
  5188. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  5189. if (is_array($one)) {
  5190. return $one;
  5191. }
  5192. } catch (\Throwable $e) {
  5193. }
  5194. try {
  5195. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  5196. if (is_array($one)) {
  5197. return $one;
  5198. }
  5199. } catch (\Throwable $e) {
  5200. }
  5201. return [];
  5202. }
  5203. /**
  5204. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  5205. */
  5206. protected function formatProcuremenDetailTime($v): string
  5207. {
  5208. if ($v === null || $v === '') {
  5209. return '';
  5210. }
  5211. if (is_numeric($v) && (int)$v > 946684800) {
  5212. return date('Y-m-d H:i:s', (int)$v);
  5213. }
  5214. return ProcuremenTime::formatDisplayDateTime($v);
  5215. }
  5216. /**
  5217. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  5218. */
  5219. protected function formatDeliveryYmd($v): string
  5220. {
  5221. if ($v === null || $v === '') {
  5222. return '';
  5223. }
  5224. $s = trim((string)$v);
  5225. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  5226. return '';
  5227. }
  5228. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5229. return $m[1];
  5230. }
  5231. $ts = strtotime($s);
  5232. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  5233. }
  5234. /**
  5235. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  5236. */
  5237. protected function detailRowSupplierOperated(array $r): bool
  5238. {
  5239. $am = $r['amount'] ?? null;
  5240. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5241. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5242. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5243. return $okAmt || $okDel;
  5244. }
  5245. /**
  5246. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  5247. */
  5248. protected function resolveDetailSupplierOperTime(array $r): string
  5249. {
  5250. if (!$this->detailRowSupplierOperated($r)) {
  5251. return '';
  5252. }
  5253. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  5254. if ($t !== '') {
  5255. return $t;
  5256. }
  5257. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  5258. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  5259. continue;
  5260. }
  5261. $t = $this->formatProcuremenDetailTime($r[$col]);
  5262. if ($t !== '') {
  5263. return $t;
  5264. }
  5265. }
  5266. return '';
  5267. }
  5268. /**
  5269. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  5270. */
  5271. protected function detailRowSupplierAccepted(array $r): bool
  5272. {
  5273. $am = $r['amount'] ?? null;
  5274. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5275. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5276. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5277. return $okAmt && $okDel;
  5278. }
  5279. /**
  5280. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  5281. */
  5282. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  5283. {
  5284. if ($detailCount > 0) {
  5285. return true;
  5286. }
  5287. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  5288. return true;
  5289. }
  5290. $pickTime = trim((string)($main['pick_time'] ?? ''));
  5291. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  5292. return true;
  5293. }
  5294. return false;
  5295. }
  5296. /**
  5297. * 下发时间:优先 pick_time,其次首条下发明细时间
  5298. */
  5299. protected function resolveProcuremenIssueTime(array $main, array $details): string
  5300. {
  5301. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  5302. if ($issueTime !== '') {
  5303. return $issueTime;
  5304. }
  5305. foreach ($details as $dr) {
  5306. if (!is_array($dr)) {
  5307. continue;
  5308. }
  5309. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5310. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  5311. $issueTime = $t;
  5312. }
  5313. }
  5314. if ($issueTime !== '') {
  5315. return $issueTime;
  5316. }
  5317. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5318. }
  5319. /**
  5320. * 直接点「完结」时间:优先操作记录 mark_complete
  5321. */
  5322. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  5323. {
  5324. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  5325. }
  5326. /**
  5327. * 操作记录时间(取指定 action 最近一条)
  5328. *
  5329. * @param string|array<int, string> $actions
  5330. */
  5331. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  5332. {
  5333. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  5334. }
  5335. /**
  5336. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  5337. *
  5338. * @param array $main purchase_order 一行
  5339. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  5340. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  5341. */
  5342. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  5343. {
  5344. $issueCnt = count($details);
  5345. $acceptCnt = 0;
  5346. $pickedName = '';
  5347. $pickedTime = '';
  5348. foreach ($details as $dr) {
  5349. if (!is_array($dr)) {
  5350. continue;
  5351. }
  5352. if ($this->detailRowSupplierAccepted($dr)) {
  5353. $acceptCnt++;
  5354. }
  5355. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5356. if ($pickedName === '') {
  5357. $pickedName = trim((string)($dr['company_name'] ?? ''));
  5358. }
  5359. if ($pickedTime === '') {
  5360. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  5361. if ($pickedTime === '') {
  5362. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5363. }
  5364. }
  5365. }
  5366. }
  5367. $hasMain = $main !== [];
  5368. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  5369. if ($poTime === '') {
  5370. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  5371. }
  5372. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  5373. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  5374. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  5375. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  5376. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  5377. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  5378. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  5379. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  5380. $inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
  5381. $inboundResult = '';
  5382. if ($scydgyId > 0) {
  5383. try {
  5384. $inRow = Db::table('purchase_order_inbound_score')
  5385. ->where('scydgy_id', $scydgyId)
  5386. ->field('result,updatetime,createtime')
  5387. ->find();
  5388. } catch (\Throwable $e) {
  5389. $inRow = null;
  5390. }
  5391. if (is_array($inRow) && $inRow !== []) {
  5392. $inboundResult = trim((string)($inRow['result'] ?? ''));
  5393. if ($inboundScoreTime === '') {
  5394. $inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
  5395. }
  5396. }
  5397. }
  5398. $inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
  5399. $supplierTime = '';
  5400. if ($acceptCnt > 0) {
  5401. foreach ($details as $dr) {
  5402. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  5403. continue;
  5404. }
  5405. $t = $this->resolveDetailSupplierOperTime($dr);
  5406. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  5407. $supplierTime = $t;
  5408. }
  5409. }
  5410. }
  5411. $directComplete = ($mainCompleted && !$issued);
  5412. $doneTime = '';
  5413. if ($mainCompleted) {
  5414. if ($directComplete) {
  5415. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  5416. }
  5417. if ($doneTime === '' && $inboundScoreTime !== '') {
  5418. $doneTime = $inboundScoreTime;
  5419. }
  5420. if ($doneTime === '') {
  5421. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5422. }
  5423. if ($doneTime === '') {
  5424. foreach ($details as $dr) {
  5425. if (!is_array($dr)) {
  5426. continue;
  5427. }
  5428. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  5429. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  5430. $doneTime = $t;
  5431. }
  5432. }
  5433. }
  5434. if ($doneTime === '') {
  5435. $doneTime = $poTime;
  5436. }
  5437. // 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
  5438. if ($doneTime === '' && $confirmApproveTime !== '') {
  5439. $doneTime = $confirmApproveTime;
  5440. }
  5441. }
  5442. if ($directComplete) {
  5443. // 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
  5444. $step1Done = $hasMain;
  5445. $step2Done = false;
  5446. $step3Done = false;
  5447. $step4Done = false;
  5448. $step5Done = false;
  5449. $stepInboundDone = $inboundScored;
  5450. $step6Done = $mainCompleted && $inboundScored;
  5451. } else {
  5452. $step1Done = $issued;
  5453. $step2Done = $issued;
  5454. $step3Done = $acceptCnt > 0;
  5455. $step4Done = $wflowPendingApproval;
  5456. if (!$step4Done) {
  5457. foreach ($details as $dr) {
  5458. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5459. $step4Done = true;
  5460. break;
  5461. }
  5462. }
  5463. }
  5464. $step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
  5465. $stepInboundDone = $inboundScored;
  5466. // 未确认合格/不合格时,「已完结」保持未点亮(灰色)
  5467. $step6Done = $mainCompleted && $inboundScored;
  5468. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  5469. if ($mainCompleted && $issued) {
  5470. $step3Done = true;
  5471. $step4Done = true;
  5472. $step5Done = true;
  5473. // 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
  5474. if ($supplierTime === '') {
  5475. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5476. if ($fillT !== '') {
  5477. $supplierTime = $fillT;
  5478. }
  5479. }
  5480. if ($pickedTime === '') {
  5481. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5482. if ($fillT !== '') {
  5483. $pickedTime = $fillT;
  5484. }
  5485. }
  5486. if ($auditSelectTime === '') {
  5487. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5488. if ($fillT !== '') {
  5489. $auditSelectTime = $fillT;
  5490. }
  5491. }
  5492. if ($confirmApproveTime === '') {
  5493. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5494. if ($fillT !== '') {
  5495. $confirmApproveTime = $fillT;
  5496. }
  5497. }
  5498. }
  5499. }
  5500. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  5501. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  5502. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  5503. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  5504. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  5505. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  5506. $inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
  5507. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  5508. $deadlineLines = [];
  5509. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  5510. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  5511. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  5512. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  5513. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  5514. }
  5515. }
  5516. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  5517. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  5518. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  5519. if ($deliveryDisp === '') {
  5520. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  5521. }
  5522. if ($deliveryDisp !== '') {
  5523. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  5524. }
  5525. }
  5526. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  5527. $deadlineText = implode("\n", $deadlineLines);
  5528. $prefixOperTime = static function (string $t): string {
  5529. $t = trim($t);
  5530. if ($t === '' || $t === '—') {
  5531. return $t;
  5532. }
  5533. if (strpos($t, '操作时间') === 0) {
  5534. return $t;
  5535. }
  5536. return '操作时间:' . $t;
  5537. };
  5538. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  5539. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  5540. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
  5541. $stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5542. $step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5543. $steps = [
  5544. [
  5545. 'title' => '未发',
  5546. 'subtitle' => '',
  5547. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  5548. 'done' => $step1Done,
  5549. ],
  5550. [
  5551. 'title' => '下发',
  5552. 'subtitle' => $deadlineText,
  5553. 'time' => $prefixOperTime($step2Time),
  5554. 'done' => $step2Done,
  5555. ],
  5556. [
  5557. 'title' => '供应商接单',
  5558. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  5559. 'time' => '',
  5560. 'done' => $step3Done,
  5561. ],
  5562. [
  5563. 'title' => '待确认',
  5564. 'subtitle' => $step4Done
  5565. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  5566. : ($issued ? '待选供应商' : ''),
  5567. 'time' => $prefixOperTime($step4Time),
  5568. 'done' => $step4Done,
  5569. ],
  5570. [
  5571. 'title' => '待审批',
  5572. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  5573. 'time' => $prefixOperTime($step5Time),
  5574. 'done' => $step5Done,
  5575. ],
  5576. [
  5577. 'title' => '是否合格',
  5578. 'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
  5579. 'time' => $prefixOperTime($stepInboundTime),
  5580. 'done' => $stepInboundDone,
  5581. ],
  5582. [
  5583. 'title' => '已完结',
  5584. 'subtitle' => '',
  5585. 'time' => $prefixOperTime($step6Time),
  5586. 'done' => $step6Done,
  5587. ],
  5588. ];
  5589. $currentIdx = count($steps) - 1;
  5590. if ($directComplete) {
  5591. // 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
  5592. if (!$step6Done) {
  5593. foreach ($steps as $i => $s) {
  5594. if (($s['title'] ?? '') === '是否合格') {
  5595. $currentIdx = $i;
  5596. break;
  5597. }
  5598. }
  5599. }
  5600. } else {
  5601. foreach ($steps as $i => $s) {
  5602. if (!$s['done']) {
  5603. $currentIdx = $i;
  5604. break;
  5605. }
  5606. }
  5607. }
  5608. $nSteps = count($steps);
  5609. foreach ($steps as $idx => &$s) {
  5610. $s['current'] = ($idx === $currentIdx);
  5611. if ($idx === 0) {
  5612. $s['pdf_left_bg'] = '';
  5613. } else {
  5614. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  5615. }
  5616. if ($idx >= $nSteps - 1) {
  5617. $s['pdf_right_bg'] = '';
  5618. } else {
  5619. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  5620. }
  5621. }
  5622. unset($s);
  5623. $labelMap = [
  5624. 'CCYDH' => '订单号',
  5625. 'CYJMC' => '印件名称',
  5626. 'CCLBMMC' => '承揽部门',
  5627. 'CGYMC' => '工序名称',
  5628. 'CDW' => '单位',
  5629. 'czlyq' => '类型',
  5630. 'NGZL' => '工作量',
  5631. 'CDF' => '单价',
  5632. 'cGzzxMc' => '工作中心',
  5633. 'MBZ' => '备注',
  5634. 'This_quantity' => '本次数量',
  5635. 'ceilingPrice' => '最高限价',
  5636. ];
  5637. $orderSummary = [];
  5638. foreach ($labelMap as $key => $lab) {
  5639. if (!array_key_exists($key, $main)) {
  5640. continue;
  5641. }
  5642. $val = $main[$key];
  5643. if ($val === null) {
  5644. $val = '';
  5645. } elseif (!is_scalar($val)) {
  5646. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  5647. } else {
  5648. $val = (string)$val;
  5649. }
  5650. $orderSummary[] = ['label' => $lab, 'value' => $val];
  5651. }
  5652. $orderSummary[] = [
  5653. 'label' => '是否合格',
  5654. 'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
  5655. ];
  5656. $orderSummaryGrid = [];
  5657. $n = count($orderSummary);
  5658. for ($i = 0; $i < $n; $i += 2) {
  5659. $left = $orderSummary[$i];
  5660. $hasRight = ($i + 1) < $n;
  5661. $orderSummaryGrid[] = [
  5662. 'l1' => $left['label'],
  5663. 'v1' => $left['value'],
  5664. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  5665. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  5666. ];
  5667. }
  5668. return [
  5669. 'steps' => $steps,
  5670. 'orderSummary' => $orderSummary,
  5671. 'orderSummaryGrid' => $orderSummaryGrid,
  5672. 'inbound_result' => $inboundResult,
  5673. 'inbound_score_time'=> $inboundScoreTime,
  5674. 'detailRows' => $details,
  5675. ];
  5676. }
  5677. /**
  5678. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  5679. *
  5680. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  5681. */
  5682. protected function prepareProcuremenDetailsView(string $ids): array
  5683. {
  5684. $main = [];
  5685. try {
  5686. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5687. $main = is_array($one) ? $one : [];
  5688. } catch (\Throwable $e) {
  5689. $main = [];
  5690. }
  5691. $details = [];
  5692. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  5693. if ($mergeRows === []) {
  5694. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  5695. if ($mergeRows === [] && $main !== []) {
  5696. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  5697. }
  5698. }
  5699. $detailSidList = [];
  5700. $anchorSid = (int)$ids;
  5701. if ($anchorSid !== 0) {
  5702. $detailSidList[$anchorSid] = true;
  5703. }
  5704. foreach ($mergeRows as $mr) {
  5705. if (!is_array($mr)) {
  5706. continue;
  5707. }
  5708. $sid = $this->extractScydgyRowId($mr);
  5709. if ($sid !== 0) {
  5710. $detailSidList[$sid] = true;
  5711. }
  5712. }
  5713. try {
  5714. if ($detailSidList !== []) {
  5715. $details = Db::table('purchase_order_detail')
  5716. ->where('scydgy_id', 'in', array_keys($detailSidList))
  5717. ->order('id', 'asc')
  5718. ->select();
  5719. }
  5720. } catch (\Throwable $e) {
  5721. $details = [];
  5722. }
  5723. if (!is_array($details)) {
  5724. $details = [];
  5725. }
  5726. foreach ($details as &$r) {
  5727. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  5728. $r['id'] = $r['ID'];
  5729. }
  5730. if (isset($r['createtime'])) {
  5731. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  5732. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  5733. } else {
  5734. $r['createtime_text'] = (string)$r['createtime'];
  5735. }
  5736. } else {
  5737. $r['createtime_text'] = '';
  5738. }
  5739. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  5740. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  5741. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  5742. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  5743. if (is_array($r)) {
  5744. $r = $this->maskSupplierContactFields($r);
  5745. }
  5746. }
  5747. unset($r);
  5748. $activeDetails = [];
  5749. foreach ($details as $r) {
  5750. if (is_array($r) && empty($r['is_void'])) {
  5751. $activeDetails[] = $r;
  5752. }
  5753. }
  5754. $operLogs = [];
  5755. try {
  5756. $operSidList = array_keys($detailSidList);
  5757. if ($operSidList === [] && (int)$ids !== 0) {
  5758. $operSidList = [(int)$ids];
  5759. }
  5760. if ($operSidList !== []) {
  5761. $operLogs = Db::table('purchase_order_oper_log')
  5762. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  5763. ->order('id', 'asc')
  5764. ->select();
  5765. }
  5766. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  5767. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  5768. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  5769. if ($poId > 0) {
  5770. $operLogs = Db::table('purchase_order_oper_log')
  5771. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  5772. ->order('id', 'asc')
  5773. ->select();
  5774. }
  5775. }
  5776. } catch (\Throwable $e) {
  5777. $operLogs = [];
  5778. }
  5779. if (!is_array($operLogs)) {
  5780. $operLogs = [];
  5781. }
  5782. $operLogsRaw = $operLogs;
  5783. $processNameBySid = [];
  5784. foreach ($mergeRows as $mr) {
  5785. if (!is_array($mr)) {
  5786. continue;
  5787. }
  5788. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  5789. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5790. if ($psid !== 0 && $gymc !== '') {
  5791. $processNameBySid[$psid] = $gymc;
  5792. }
  5793. }
  5794. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  5795. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
  5796. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  5797. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  5798. if ($ccydh === '') {
  5799. foreach ($details as $r) {
  5800. if (!is_array($r)) {
  5801. continue;
  5802. }
  5803. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  5804. if ($ccydh !== '') {
  5805. break;
  5806. }
  5807. }
  5808. }
  5809. $this->view->assign('ccydh', $ccydh);
  5810. $this->view->assign('steps', $bundle['steps']);
  5811. $this->view->assign('orderSummary', $bundle['orderSummary']);
  5812. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  5813. $this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
  5814. $this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
  5815. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  5816. $this->view->assign('processCount', count($mergeRows));
  5817. $this->view->assign('detailRows', $details);
  5818. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  5819. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  5820. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  5821. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  5822. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  5823. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  5824. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  5825. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  5826. $this->view->assign('operLogs', $operLogs);
  5827. $sg = $quoteView['supplier_groups'] ?? [];
  5828. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
  5829. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  5830. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
  5831. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
  5832. return [
  5833. 'ok' => $main !== [] || $details !== [],
  5834. 'ccydh' => $ccydh,
  5835. ];
  5836. }
  5837. /**
  5838. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  5839. */
  5840. public function details()
  5841. {
  5842. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5843. if (is_array($ids)) {
  5844. $ids = isset($ids[0]) ? $ids[0] : '';
  5845. }
  5846. $ids = trim((string)$ids);
  5847. if ($ids === '') {
  5848. $this->error(__('Invalid parameters'));
  5849. }
  5850. $this->assertManualOrderDetailsViewable((int)$ids);
  5851. $this->prepareProcuremenDetailsView($ids);
  5852. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  5853. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  5854. $this->view->engine->layout(false);
  5855. try {
  5856. return $this->view->fetch('procuremen/details_dialog_shell');
  5857. } finally {
  5858. if ($restoreLayout) {
  5859. $this->view->engine->layout($restoreLayout);
  5860. }
  5861. }
  5862. }
  5863. /**
  5864. * 解析合并审核工序行(订单号须一致,且均未协助)
  5865. *
  5866. * @return array<int, array<string, mixed>>
  5867. */
  5868. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  5869. {
  5870. $primary = json_decode($rowJson, true);
  5871. if (!is_array($primary)) {
  5872. $this->error(__('Invalid parameters'));
  5873. }
  5874. $merge = json_decode($mergeRowsJson, true);
  5875. if (!is_array($merge) || $merge === []) {
  5876. $merge = [$primary];
  5877. }
  5878. $seen = [];
  5879. $out = [];
  5880. foreach ($merge as $r) {
  5881. if (!is_array($r)) {
  5882. continue;
  5883. }
  5884. $id = $this->extractScydgyRowId($r);
  5885. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  5886. continue;
  5887. }
  5888. $seen[$id] = true;
  5889. $out[] = $r;
  5890. }
  5891. if ($out === []) {
  5892. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  5893. }
  5894. $ccydh = null;
  5895. foreach ($out as $r) {
  5896. $dh = trim((string)($r['CCYDH'] ?? ''));
  5897. if ($ccydh === null) {
  5898. $ccydh = $dh;
  5899. } elseif ($dh !== $ccydh) {
  5900. $this->error('合并审核要求所选行的订单号一致');
  5901. }
  5902. }
  5903. $ids = [];
  5904. foreach ($out as $r) {
  5905. $id = $this->extractScydgyRowId($r);
  5906. if ($this->isValidScydgyRowId($id)) {
  5907. $ids[$id] = true;
  5908. }
  5909. }
  5910. $poBySid = [];
  5911. $detCntBySid = [];
  5912. if ($ids !== []) {
  5913. $idList = array_keys($ids);
  5914. try {
  5915. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  5916. if (is_array($poList)) {
  5917. foreach ($poList as $po) {
  5918. if (!is_array($po)) {
  5919. continue;
  5920. }
  5921. $sid = (int)($po['scydgy_id'] ?? 0);
  5922. if ($this->isValidScydgyRowId($sid)) {
  5923. $poBySid[$sid] = $po;
  5924. }
  5925. }
  5926. }
  5927. } catch (\Throwable $e) {
  5928. }
  5929. try {
  5930. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  5931. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  5932. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  5933. if (is_array($detRows)) {
  5934. foreach ($detRows as $dr) {
  5935. if (!is_array($dr)) {
  5936. continue;
  5937. }
  5938. $sid = (int)($dr['scydgy_id'] ?? 0);
  5939. if ($this->isValidScydgyRowId($sid)) {
  5940. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  5941. }
  5942. }
  5943. }
  5944. } catch (\Throwable $e) {
  5945. }
  5946. }
  5947. foreach ($out as $r) {
  5948. $id = $this->extractScydgyRowId($r);
  5949. if (!$this->isValidScydgyRowId($id)) {
  5950. continue;
  5951. }
  5952. $po = $poBySid[$id] ?? null;
  5953. if (!is_array($po)) {
  5954. continue;
  5955. }
  5956. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  5957. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5958. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  5959. }
  5960. $detCnt = (int)($detCntBySid[$id] ?? 0);
  5961. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  5962. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5963. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  5964. }
  5965. }
  5966. return $out;
  5967. }
  5968. /**
  5969. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  5970. */
  5971. protected function maskSupplierContactFields(array $item): array
  5972. {
  5973. if (array_key_exists('email', $item)) {
  5974. $item['email'] = mask_email((string)$item['email']);
  5975. }
  5976. if (array_key_exists('phone', $item)) {
  5977. $item['phone'] = mask_phone((string)$item['phone']);
  5978. }
  5979. return $item;
  5980. }
  5981. /**
  5982. * @param array<int, array<string, mixed>> $list
  5983. * @return array<int, array<string, mixed>>
  5984. */
  5985. protected function maskSupplierContactList(array $list): array
  5986. {
  5987. $out = [];
  5988. foreach ($list as $item) {
  5989. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  5990. }
  5991. return $out;
  5992. }
  5993. /**
  5994. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  5995. *
  5996. * @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
  5997. * @return array<string, string>|null
  5998. */
  5999. protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
  6000. {
  6001. if (!is_array($row)) {
  6002. return null;
  6003. }
  6004. $norm = [];
  6005. foreach ($row as $k => $v) {
  6006. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  6007. }
  6008. $row = $norm;
  6009. $st = $row['status'] ?? '';
  6010. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  6011. return null;
  6012. }
  6013. $companyName = '';
  6014. foreach (['company_name', 'name'] as $nk) {
  6015. if (!empty($row[$nk])) {
  6016. $companyName = trim((string)$row[$nk]);
  6017. break;
  6018. }
  6019. }
  6020. if ($companyName === '') {
  6021. return null;
  6022. }
  6023. $username = '';
  6024. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  6025. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  6026. $username = trim((string)$row[$uk]);
  6027. break;
  6028. }
  6029. }
  6030. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  6031. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  6032. if ($phone === '' && isset($row['account'])) {
  6033. $phone = trim((string)$row['account']);
  6034. }
  6035. if ($phone === '' && isset($row['mobile'])) {
  6036. $phone = trim((string)$row['mobile']);
  6037. }
  6038. if ($requireContactChannels && $email === '' && $phone === '') {
  6039. return null;
  6040. }
  6041. $category = '';
  6042. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6043. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6044. $category = trim((string)$row[$ck]);
  6045. break;
  6046. }
  6047. }
  6048. return [
  6049. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  6050. 'name' => $companyName,
  6051. 'company_name' => $companyName,
  6052. 'username' => $username,
  6053. 'email' => $email,
  6054. 'phone' => $phone,
  6055. 'category' => $category,
  6056. 'company_type' => $category,
  6057. ];
  6058. }
  6059. /**
  6060. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  6061. */
  6062. protected function resolveCustomerContactById(string $id): ?array
  6063. {
  6064. $id = trim($id);
  6065. if ($id === '' || !ctype_digit($id)) {
  6066. return null;
  6067. }
  6068. try {
  6069. $row = Db::table('customer')->where('id', (int)$id)->find();
  6070. } catch (\Throwable $e) {
  6071. return null;
  6072. }
  6073. return $this->buildCustomerContactPayloadFromRow($row);
  6074. }
  6075. /**
  6076. * 按供应商名称解析联系信息(兼容旧提交数据)
  6077. *
  6078. * @param bool $requireContactChannels true 时须有邮箱或手机
  6079. */
  6080. protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
  6081. {
  6082. $name = trim($name);
  6083. if ($name === '') {
  6084. return null;
  6085. }
  6086. try {
  6087. // customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
  6088. $row = Db::table('customer')
  6089. ->where('company_name', $name)
  6090. ->order('id', 'desc')
  6091. ->find();
  6092. } catch (\Throwable $e) {
  6093. return null;
  6094. }
  6095. return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
  6096. }
  6097. /**
  6098. * 规范化下发/确认时勾选的供应商
  6099. *
  6100. * @param array<int, mixed> $companies
  6101. * @return array<int, array<string, string>>
  6102. */
  6103. protected function normalizePickCompanies(array $companies): array
  6104. {
  6105. $out = [];
  6106. foreach ($companies as $c) {
  6107. if (!is_array($c)) {
  6108. continue;
  6109. }
  6110. $resolved = null;
  6111. $cid = trim((string)($c['id'] ?? ''));
  6112. if ($cid !== '') {
  6113. $resolved = $this->resolveCustomerContactById($cid);
  6114. }
  6115. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  6116. if ($resolved === null && $name !== '') {
  6117. $resolved = $this->resolveCustomerContactByCompanyName($name);
  6118. }
  6119. if ($resolved === null) {
  6120. continue;
  6121. }
  6122. $out[] = $resolved;
  6123. }
  6124. return $out;
  6125. }
  6126. /**
  6127. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  6128. *
  6129. * @param array<int, array<string, mixed>> $pool
  6130. * @return array<int, array<string, mixed>>
  6131. */
  6132. protected function collapseProcuremenPoolByOrder(array $pool): array
  6133. {
  6134. if ($pool === []) {
  6135. return [];
  6136. }
  6137. $groups = [];
  6138. foreach ($pool as $row) {
  6139. if (!is_array($row)) {
  6140. continue;
  6141. }
  6142. $dh = trim((string)($row['CCYDH'] ?? ''));
  6143. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  6144. if (!isset($groups[$key])) {
  6145. $groups[$key] = [];
  6146. }
  6147. $groups[$key][] = $row;
  6148. }
  6149. $out = [];
  6150. foreach ($groups as $ccydh => $rows) {
  6151. if ($rows === []) {
  6152. continue;
  6153. }
  6154. usort($rows, function ($a, $b) {
  6155. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  6156. });
  6157. $head = $rows[0];
  6158. $gymcList = [];
  6159. foreach ($rows as $r) {
  6160. $g = trim((string)($r['CGYMC'] ?? ''));
  6161. if ($g !== '' && !in_array($g, $gymcList, true)) {
  6162. $gymcList[] = $g;
  6163. }
  6164. }
  6165. $merged = $head;
  6166. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  6167. $merged['process_count'] = count($rows);
  6168. $merged['_order_merge_rows'] = $rows;
  6169. $qtyList = [];
  6170. $priceList = [];
  6171. foreach ($rows as $r) {
  6172. if (!is_array($r)) {
  6173. continue;
  6174. }
  6175. $qtyList[] = $this->resolveProcuremenThisQuantity($r);
  6176. $priceList[] = $this->resolveProcuremenCeilingPrice($r);
  6177. }
  6178. if (count($rows) > 1) {
  6179. $merged['CGYMC'] = implode('、', $gymcList);
  6180. // 多工序:数量/限价按有值项顿号间隔(空值不占位)
  6181. $merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  6182. $merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  6183. } else {
  6184. $merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
  6185. $merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
  6186. }
  6187. // 已选供应商:取合并行中首个非空 pick_company_name
  6188. $pickedName = '';
  6189. foreach ($rows as $r) {
  6190. if (!is_array($r)) {
  6191. continue;
  6192. }
  6193. $pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
  6194. if ($pn !== '') {
  6195. $pickedName = $pn;
  6196. break;
  6197. }
  6198. }
  6199. if ($pickedName !== '') {
  6200. $merged['pick_company_name'] = $pickedName;
  6201. $merged['picked_supplier_name'] = $pickedName;
  6202. }
  6203. $mergedPickTime = '';
  6204. foreach ($rows as $r) {
  6205. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  6206. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  6207. $mergedPickTime = $t;
  6208. }
  6209. }
  6210. if ($mergedPickTime !== '') {
  6211. $merged['pick_time'] = $mergedPickTime;
  6212. }
  6213. $out[] = $merged;
  6214. }
  6215. usort($out, function ($a, $b) {
  6216. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  6217. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  6218. if ($ta === $tb) {
  6219. $ida = (int)($a['purchase_order_id'] ?? 0);
  6220. $idb = (int)($b['purchase_order_id'] ?? 0);
  6221. if ($ida !== $idb) {
  6222. return $idb <=> $ida;
  6223. }
  6224. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  6225. }
  6226. if ($ta === '') {
  6227. return 1;
  6228. }
  6229. if ($tb === '') {
  6230. return -1;
  6231. }
  6232. return strcmp($tb, $ta);
  6233. });
  6234. return $out;
  6235. }
  6236. /**
  6237. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  6238. *
  6239. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6240. */
  6241. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  6242. {
  6243. $scydgyId = trim($scydgyId);
  6244. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6245. if ($scydgyId === '') {
  6246. return $empty;
  6247. }
  6248. try {
  6249. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6250. } catch (\Throwable $e) {
  6251. $anchor = null;
  6252. }
  6253. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  6254. return $empty;
  6255. }
  6256. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6257. if ($ccydh === '') {
  6258. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  6259. }
  6260. try {
  6261. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  6262. } catch (\Throwable $e) {
  6263. $pos = [$anchor];
  6264. }
  6265. if (!is_array($pos) || $pos === []) {
  6266. $pos = [$anchor];
  6267. }
  6268. return [
  6269. 'ccydh' => $ccydh,
  6270. 'pos' => $pos,
  6271. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6272. ];
  6273. }
  6274. /**
  6275. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  6276. */
  6277. protected function purchaseOrderRowInConfirmStage(array $po): bool
  6278. {
  6279. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6280. return false;
  6281. }
  6282. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  6283. return false;
  6284. }
  6285. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  6286. return true;
  6287. }
  6288. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  6289. $sid = (int)($po['scydgy_id'] ?? 0);
  6290. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  6291. }
  6292. return false;
  6293. }
  6294. /**
  6295. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  6296. *
  6297. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6298. */
  6299. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  6300. {
  6301. $scydgyId = trim($scydgyId);
  6302. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6303. if ($scydgyId === '') {
  6304. return $empty;
  6305. }
  6306. try {
  6307. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6308. } catch (\Throwable $e) {
  6309. $anchor = null;
  6310. }
  6311. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  6312. return $empty;
  6313. }
  6314. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6315. if ($ccydh === '') {
  6316. return [
  6317. 'ccydh' => '',
  6318. 'pos' => [$anchor],
  6319. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  6320. ];
  6321. }
  6322. try {
  6323. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  6324. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  6325. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  6326. } catch (\Throwable $e) {
  6327. $pos = [$anchor];
  6328. }
  6329. if (!is_array($pos) || $pos === []) {
  6330. $pos = [$anchor];
  6331. }
  6332. $pos = array_values(array_filter($pos, function ($po) {
  6333. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  6334. }));
  6335. if ($pos === []) {
  6336. $pos = [$anchor];
  6337. }
  6338. return [
  6339. 'ccydh' => $ccydh,
  6340. 'pos' => $pos,
  6341. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6342. ];
  6343. }
  6344. /**
  6345. * @param array<int, array<string, mixed>> $purchaseOrders
  6346. * @return array<int, array<string, mixed>>
  6347. */
  6348. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  6349. {
  6350. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  6351. $byId = [];
  6352. foreach ($pool as $r) {
  6353. if (!is_array($r)) {
  6354. continue;
  6355. }
  6356. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  6357. if ($this->isValidScydgyRowId($sid)) {
  6358. $byId[$sid] = $r;
  6359. }
  6360. }
  6361. $out = [];
  6362. foreach ($purchaseOrders as $po) {
  6363. if (!is_array($po)) {
  6364. continue;
  6365. }
  6366. $sid = (int)($po['scydgy_id'] ?? 0);
  6367. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  6368. $out[] = $byId[$sid];
  6369. }
  6370. }
  6371. return $out;
  6372. }
  6373. /**
  6374. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  6375. *
  6376. * @return array<int, array<string, mixed>>
  6377. */
  6378. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  6379. {
  6380. $scydgyId = trim($scydgyId);
  6381. if ($scydgyId === '') {
  6382. return [];
  6383. }
  6384. try {
  6385. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6386. } catch (\Throwable $e) {
  6387. $anchor = null;
  6388. }
  6389. if (!is_array($anchor)) {
  6390. return [];
  6391. }
  6392. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  6393. return [];
  6394. }
  6395. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6396. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  6397. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  6398. try {
  6399. $q = Db::table('purchase_order');
  6400. if ($ccydh !== '') {
  6401. $q->where('CCYDH', $ccydh);
  6402. } else {
  6403. $q->where('scydgy_id', $scydgyId);
  6404. }
  6405. if ($isValidPick) {
  6406. $q->where('pick_time', $pickTime);
  6407. }
  6408. $pos = $q->order('scydgy_id', 'asc')->select();
  6409. } catch (\Throwable $e) {
  6410. $pos = [$anchor];
  6411. }
  6412. if (!is_array($pos) || $pos === []) {
  6413. $pos = [$anchor];
  6414. }
  6415. $pos = array_values(array_filter($pos, function ($po) {
  6416. if (!is_array($po)) {
  6417. return false;
  6418. }
  6419. $mr = $po['mod_rq'] ?? null;
  6420. if ($mr === null || $mr === '') {
  6421. return true;
  6422. }
  6423. $mrs = trim((string)$mr);
  6424. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  6425. }));
  6426. if ($pos === []) {
  6427. $pos = [$anchor];
  6428. }
  6429. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  6430. if ($rows === []) {
  6431. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  6432. }
  6433. return $rows;
  6434. }
  6435. /**
  6436. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  6437. *
  6438. * @param array<int, array<string, mixed>> $mergeRows
  6439. * @return array<int, array<string, mixed>>
  6440. */
  6441. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  6442. {
  6443. $list = array_values($mergeRows);
  6444. $n = count($list);
  6445. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  6446. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  6447. $mergeSame = $n > 1 && $orderKey0 !== '';
  6448. if ($mergeSame) {
  6449. foreach ($list as $rr) {
  6450. if (!is_array($rr)) {
  6451. $mergeSame = false;
  6452. break;
  6453. }
  6454. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  6455. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  6456. $mergeSame = false;
  6457. break;
  6458. }
  6459. }
  6460. }
  6461. $out = [];
  6462. foreach ($list as $idx => $r) {
  6463. if (!is_array($r)) {
  6464. continue;
  6465. }
  6466. $qty = $this->resolveProcuremenThisQuantity($r);
  6467. $price = $this->resolveProcuremenCeilingPrice($r);
  6468. $sid = $this->extractScydgyRowId($r);
  6469. $out[] = [
  6470. 'seq' => $idx + 1,
  6471. 'scydgy_id' => $sid,
  6472. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6473. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6474. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6475. 'CDW' => trim((string)($r['CDW'] ?? '')),
  6476. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  6477. 'NGZL' => $r['NGZL'] ?? '',
  6478. 'This_quantity' => $qty,
  6479. 'ceilingPrice' => $price,
  6480. 'CDF' => trim((string)($r['CDF'] ?? '')),
  6481. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  6482. 'show_order_cells' => !$mergeSame || $idx === 0,
  6483. 'order_rowspan' => $mergeSame ? $n : 1,
  6484. ];
  6485. }
  6486. return $out;
  6487. }
  6488. /**
  6489. * 解析金额/数量(去千分位等非数字字符)
  6490. */
  6491. protected function parseProcuremenMoneyNumber($value): ?float
  6492. {
  6493. if ($value === null || $value === '') {
  6494. return null;
  6495. }
  6496. if (is_numeric($value)) {
  6497. return (float)$value;
  6498. }
  6499. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  6500. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  6501. }
  6502. protected function formatProcuremenMoneyDisplay(?float $amount): string
  6503. {
  6504. if ($amount === null) {
  6505. return '';
  6506. }
  6507. // 保留小数(最多 5 位),去掉末尾无意义的 0,避免 0.25 被显示成 0
  6508. $s = rtrim(rtrim(sprintf('%.5F', (float)$amount), '0'), '.');
  6509. return $s === '' ? '0' : $s;
  6510. }
  6511. /**
  6512. * 列表/详情展示:工作量为 0 时显示空
  6513. */
  6514. protected function formatProcuremenWorkloadDisplay($value): string
  6515. {
  6516. if ($value === null || $value === '') {
  6517. return '';
  6518. }
  6519. $s = trim((string)$value);
  6520. if ($s === '') {
  6521. return '';
  6522. }
  6523. if (is_numeric($s) && (float)$s == 0) {
  6524. return '';
  6525. }
  6526. return $s;
  6527. }
  6528. /**
  6529. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  6530. */
  6531. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  6532. {
  6533. foreach ($details as $d) {
  6534. if (!is_array($d)) {
  6535. continue;
  6536. }
  6537. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  6538. $cn = trim((string)($d['company_name'] ?? ''));
  6539. if ($cn !== '') {
  6540. return $cn;
  6541. }
  6542. }
  6543. }
  6544. return trim((string)($main['pick_company_name'] ?? ''));
  6545. }
  6546. /**
  6547. * 详情报价小计:单价 × 本工序本次数量
  6548. */
  6549. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  6550. {
  6551. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  6552. if ($unit === null) {
  6553. return null;
  6554. }
  6555. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  6556. if ($qty === null || $qty <= 0) {
  6557. return null;
  6558. }
  6559. return $unit * $qty;
  6560. }
  6561. /**
  6562. * 详情页:工序小计 + 供应商分组报价与总计
  6563. *
  6564. * @param array<int, array<string, mixed>> $mergeRows
  6565. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  6566. * @return array{
  6567. * process_rows: array,
  6568. * supplier_groups: array,
  6569. * order_total_text: string,
  6570. * order_total_has: bool,
  6571. * selected_company: string
  6572. * }
  6573. */
  6574. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  6575. {
  6576. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  6577. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  6578. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
  6579. || ((int)($main['manual_pick'] ?? 0) === 1);
  6580. $qtyBySid = [];
  6581. $gymcBySid = [];
  6582. $orderedSids = [];
  6583. foreach ($mergeRows as $mr) {
  6584. if (!is_array($mr)) {
  6585. continue;
  6586. }
  6587. $sid = $this->extractScydgyRowId($mr);
  6588. if ($this->isValidScydgyRowId($sid)) {
  6589. $orderedSids[] = $sid;
  6590. }
  6591. $qty = trim((string)($mr['This_quantity'] ?? ''));
  6592. if ($qty === '') {
  6593. $qty = trim((string)($mr['NGZL'] ?? ''));
  6594. }
  6595. $qtyBySid[$sid] = $qty;
  6596. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  6597. }
  6598. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  6599. $detailByCompanySid = [];
  6600. foreach ($details as $d) {
  6601. if (!is_array($d)) {
  6602. continue;
  6603. }
  6604. $cn = trim((string)($d['company_name'] ?? ''));
  6605. $sid = (int)($d['scydgy_id'] ?? 0);
  6606. if ($cn === '' || $sid === 0) {
  6607. continue;
  6608. }
  6609. if (!isset($detailByCompanySid[$cn])) {
  6610. $detailByCompanySid[$cn] = [];
  6611. }
  6612. $detailByCompanySid[$cn][$sid] = $d;
  6613. }
  6614. $supplierGroups = [];
  6615. foreach ($detailByCompanySid as $cn => $bySid) {
  6616. $lines = [];
  6617. $groupTotal = 0.0;
  6618. $groupHas = false;
  6619. $groupVoid = true;
  6620. $usedSids = [];
  6621. $appendLine = function (int $sid, array $d) use (
  6622. &$lines,
  6623. &$groupTotal,
  6624. &$groupHas,
  6625. &$groupVoid,
  6626. $qtyBySid,
  6627. $gymcBySid,
  6628. $quoteVisible
  6629. ) {
  6630. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  6631. if (!$isVoid) {
  6632. $groupVoid = false;
  6633. }
  6634. $qtyStr = $qtyBySid[$sid] ?? '';
  6635. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  6636. $am = trim((string)($d['amount'] ?? ''));
  6637. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  6638. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  6639. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  6640. $sub = null;
  6641. if (!$isVoid && $amountNum !== null) {
  6642. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  6643. }
  6644. $ct = $this->resolveDetailSupplierOperTime($d);
  6645. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  6646. $leadFilled = ($leadDays !== null);
  6647. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  6648. $line = [
  6649. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  6650. 'amount' => $am,
  6651. 'unit_price_text' => $amountFilled
  6652. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  6653. : '未填写',
  6654. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  6655. 'delivery_ymd' => $deliveryYmd,
  6656. 'amount_filled' => $amountFilled,
  6657. 'delivery_filled' => $deliveryFilled,
  6658. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  6659. 'lead_days' => $leadFilled ? $leadDays : '',
  6660. 'lead_days_filled'=> $leadFilled,
  6661. 'lead_days_show' => $leadText,
  6662. 'lead_days_text' => $leadText,
  6663. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  6664. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  6665. 'is_void' => $isVoid,
  6666. 'oper_time_text' => $ct,
  6667. ];
  6668. if (!$quoteVisible && !$isVoid) {
  6669. $this->maskSupplierQuoteLineBeforeDeadline($line);
  6670. } elseif ($sub !== null) {
  6671. $groupTotal += $sub;
  6672. $groupHas = true;
  6673. }
  6674. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  6675. };
  6676. foreach ($orderedSids as $sid) {
  6677. if (!isset($bySid[$sid])) {
  6678. continue;
  6679. }
  6680. $usedSids[$sid] = true;
  6681. $appendLine($sid, $bySid[$sid]);
  6682. }
  6683. foreach ($bySid as $sid => $d) {
  6684. if (isset($usedSids[$sid])) {
  6685. continue;
  6686. }
  6687. $appendLine((int)$sid, $d);
  6688. }
  6689. $firstDetail = null;
  6690. foreach ($bySid as $d) {
  6691. if (is_array($d)) {
  6692. $firstDetail = $d;
  6693. break;
  6694. }
  6695. }
  6696. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  6697. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  6698. if ($username === '' && $ph !== '') {
  6699. $username = $this->resolveCustomerContactName($ph, $cn);
  6700. }
  6701. $remark = '';
  6702. foreach ($bySid as $d) {
  6703. if (!is_array($d)) {
  6704. continue;
  6705. }
  6706. $rm = '';
  6707. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  6708. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  6709. $rm = trim((string)$d[$rk]);
  6710. break;
  6711. }
  6712. }
  6713. if ($rm !== '') {
  6714. $remark = $rm;
  6715. break;
  6716. }
  6717. }
  6718. $lineCount = count($lines);
  6719. $hasRemark = $lineCount > 0;
  6720. $supplierGroup = [
  6721. 'company_name' => $cn,
  6722. 'username' => $username,
  6723. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  6724. 'phone' => $ph,
  6725. 'remark' => $remark,
  6726. 'has_remark' => $hasRemark,
  6727. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  6728. 'is_void' => $groupVoid,
  6729. 'lines' => $lines,
  6730. 'line_count' => $lineCount,
  6731. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  6732. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  6733. 'has_total' => $lineCount > 0,
  6734. ];
  6735. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  6736. $supplierGroups[] = $supplierGroup;
  6737. }
  6738. usort($supplierGroups, function ($a, $b) {
  6739. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  6740. return ($a['is_void'] ?? false) ? 1 : -1;
  6741. }
  6742. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  6743. return ($a['is_selected'] ?? false) ? -1 : 1;
  6744. }
  6745. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  6746. });
  6747. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  6748. return [
  6749. 'process_rows' => $processRows,
  6750. 'supplier_groups' => $supplierGroups,
  6751. 'order_total_text' => '',
  6752. 'order_total_has' => false,
  6753. 'selected_company' => $selectedCompany,
  6754. ];
  6755. }
  6756. /**
  6757. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  6758. */
  6759. protected function buildProcessLinesPlain(array $mergeRows): string
  6760. {
  6761. $lines = [];
  6762. $i = 1;
  6763. foreach ($mergeRows as $r) {
  6764. if (!is_array($r)) {
  6765. continue;
  6766. }
  6767. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6768. $dw = trim((string)($r['CDW'] ?? ''));
  6769. $gzl = trim((string)($r['NGZL'] ?? ''));
  6770. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  6771. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  6772. if ($dw !== '') {
  6773. $parts[] = '单位:' . $dw;
  6774. }
  6775. if ($gzl !== '') {
  6776. $parts[] = '工作量:' . $gzl;
  6777. }
  6778. if ($qty !== '') {
  6779. $parts[] = '本次数量:' . $qty;
  6780. }
  6781. $lines[] = implode(' ', $parts);
  6782. $i++;
  6783. }
  6784. return implode("\n", $lines);
  6785. }
  6786. /**
  6787. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  6788. *
  6789. * @return array<string, string>
  6790. */
  6791. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  6792. {
  6793. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  6794. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  6795. }
  6796. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  6797. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  6798. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6799. $cyjmc = '';
  6800. foreach ($mergeRows as $mr) {
  6801. if (!is_array($mr)) {
  6802. continue;
  6803. }
  6804. if ($ccydh === '') {
  6805. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  6806. }
  6807. if ($cyjmc === '') {
  6808. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  6809. }
  6810. }
  6811. if ($pos !== []) {
  6812. $firstPo = $pos[0];
  6813. if (is_array($firstPo)) {
  6814. if ($ccydh === '') {
  6815. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  6816. }
  6817. if ($cyjmc === '') {
  6818. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  6819. }
  6820. }
  6821. }
  6822. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  6823. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  6824. if (is_array($any)) {
  6825. if ($ccydh === '') {
  6826. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  6827. }
  6828. if ($cyjmc === '') {
  6829. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  6830. }
  6831. }
  6832. }
  6833. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  6834. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  6835. $cgymc = '';
  6836. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  6837. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  6838. }
  6839. return [
  6840. 'ccydh' => $ccydh,
  6841. 'cyjmc' => $cyjmc,
  6842. 'cgymc' => $cgymc,
  6843. 'process_lines' => $processLines,
  6844. 'process_lines_html' => '',
  6845. ];
  6846. }
  6847. /**
  6848. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  6849. */
  6850. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  6851. {
  6852. $lines = [];
  6853. if ($ccydh !== '') {
  6854. $lines[] = '订单号:' . $ccydh;
  6855. }
  6856. if ($cyjmc !== '') {
  6857. $lines[] = '印件名称:' . $cyjmc;
  6858. }
  6859. if ($processPlain !== '') {
  6860. $lines[] = $processPlain;
  6861. }
  6862. return implode("\n", $lines);
  6863. }
  6864. /**
  6865. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  6866. *
  6867. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6868. */
  6869. protected function buildPlatformLinksPlain(array $detailLinks): string
  6870. {
  6871. $lines = [];
  6872. $i = 1;
  6873. foreach ($detailLinks as $lk) {
  6874. if (!is_array($lk)) {
  6875. continue;
  6876. }
  6877. $url = trim((string)($lk['url'] ?? ''));
  6878. if ($url === '') {
  6879. continue;
  6880. }
  6881. $label = trim((string)($lk['cgymc'] ?? ''));
  6882. if ($label === '') {
  6883. $label = '工序' . $i;
  6884. }
  6885. $lines[] = $label . ':' . $url;
  6886. $i++;
  6887. }
  6888. return implode("\n", $lines);
  6889. }
  6890. /**
  6891. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  6892. *
  6893. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6894. */
  6895. protected function buildPlatformLinksHtml(array $detailLinks): string
  6896. {
  6897. $parts = [];
  6898. $i = 1;
  6899. foreach ($detailLinks as $lk) {
  6900. if (!is_array($lk)) {
  6901. continue;
  6902. }
  6903. $url = trim((string)($lk['url'] ?? ''));
  6904. if ($url === '') {
  6905. continue;
  6906. }
  6907. $label = trim((string)($lk['cgymc'] ?? ''));
  6908. if ($label === '') {
  6909. $label = '工序' . $i;
  6910. }
  6911. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  6912. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  6913. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  6914. $i++;
  6915. }
  6916. return implode("<br>\n", $parts);
  6917. }
  6918. /**
  6919. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  6920. *
  6921. * @return array<string, mixed>
  6922. */
  6923. protected function loadMailerConfig(): array
  6924. {
  6925. try {
  6926. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  6927. } catch (\Throwable $e) {
  6928. $cfg = [];
  6929. }
  6930. return is_array($cfg) ? $cfg : [];
  6931. }
  6932. protected function loadNotifyTemplateRow(string $scene): ?array
  6933. {
  6934. try {
  6935. $row = Db::table('purchase_sms_template')
  6936. ->where('scene', $scene)
  6937. ->where(function ($q) {
  6938. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  6939. })
  6940. ->order('id', 'asc')
  6941. ->find();
  6942. } catch (\Throwable $e) {
  6943. return null;
  6944. }
  6945. if (!is_array($row) || $row === []) {
  6946. return null;
  6947. }
  6948. return [
  6949. 'title' => trim((string)($row['title'] ?? '')),
  6950. 'content' => trim((string)($row['content'] ?? '')),
  6951. ];
  6952. }
  6953. /**
  6954. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  6955. */
  6956. protected function buildProcessLinesHtml(array $mergeRows): string
  6957. {
  6958. if (count($mergeRows) <= 1) {
  6959. $r = $mergeRows[0] ?? [];
  6960. if (!is_array($r)) {
  6961. return '';
  6962. }
  6963. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6964. $dw = trim((string)($r['CDW'] ?? ''));
  6965. $gzl = trim((string)($r['NGZL'] ?? ''));
  6966. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  6967. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  6968. if ($dw !== '') {
  6969. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  6970. }
  6971. if ($gzl !== '') {
  6972. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  6973. }
  6974. if ($qty !== '') {
  6975. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  6976. }
  6977. return $html;
  6978. }
  6979. $rows = '';
  6980. $i = 1;
  6981. foreach ($mergeRows as $r) {
  6982. if (!is_array($r)) {
  6983. continue;
  6984. }
  6985. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  6986. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  6987. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  6988. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  6989. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  6990. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  6991. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  6992. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  6993. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  6994. $i++;
  6995. }
  6996. if ($rows === '') {
  6997. return '';
  6998. }
  6999. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  7000. . '<thead><tr style="background:#f5f5f5;">'
  7001. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  7002. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  7003. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  7004. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  7005. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  7006. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  7007. }
  7008. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  7009. {
  7010. $sysRq = trim($sysRq);
  7011. if ($sysRq === '') {
  7012. if ($required) {
  7013. $this->error('请选择招标截止日期');
  7014. }
  7015. return '';
  7016. }
  7017. $ts = strtotime($sysRq);
  7018. if ($ts === false || $ts <= 0) {
  7019. $this->error('招标截止日期格式无效');
  7020. }
  7021. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  7022. if (!$allowPast) {
  7023. $ymd = date('Y-m-d', $ts);
  7024. if ($ymd < date('Y-m-d')) {
  7025. $this->error('招标截止日期不能早于今天');
  7026. }
  7027. if ($ts <= time()) {
  7028. $this->error('招标截止时间不能早于当前时间');
  7029. }
  7030. }
  7031. return date('Y-m-d H:i:s', $ts);
  7032. }
  7033. /**
  7034. * 确保 purchase_order.czlyq(类型)存在
  7035. */
  7036. protected function ensurePurchaseOrderCzlyqColumn(): void
  7037. {
  7038. static $done = false;
  7039. if ($done) {
  7040. return;
  7041. }
  7042. $done = true;
  7043. try {
  7044. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  7045. if (empty($cols)) {
  7046. Db::execute(
  7047. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  7048. );
  7049. }
  7050. } catch (\Throwable $e) {
  7051. // ignore
  7052. }
  7053. }
  7054. /**
  7055. * 确保 purchase_order.delivery_deadline 存在
  7056. */
  7057. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  7058. {
  7059. static $done = false;
  7060. if ($done) {
  7061. return;
  7062. }
  7063. $done = true;
  7064. try {
  7065. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  7066. if (empty($cols)) {
  7067. Db::execute(
  7068. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  7069. );
  7070. }
  7071. } catch (\Throwable $e) {
  7072. // ignore
  7073. }
  7074. }
  7075. /**
  7076. * 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
  7077. */
  7078. protected function ensurePurchaseOrderScoreRuleIdColumn(): void
  7079. {
  7080. static $done = false;
  7081. if ($done) {
  7082. return;
  7083. }
  7084. $done = true;
  7085. // 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
  7086. $adds = [
  7087. 'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
  7088. 'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
  7089. 'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
  7090. 'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
  7091. 'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
  7092. ];
  7093. $changed = false;
  7094. foreach ($adds as $col => $ddl) {
  7095. try {
  7096. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  7097. if (!is_array($cols) || $cols === []) {
  7098. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  7099. $changed = true;
  7100. }
  7101. } catch (\Throwable $e) {
  7102. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  7103. }
  7104. }
  7105. if ($changed) {
  7106. $this->clearPurchaseOrderTableFieldsCache();
  7107. }
  7108. }
  7109. /**
  7110. * ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
  7111. */
  7112. protected function clearPurchaseOrderTableFieldsCache(): void
  7113. {
  7114. try {
  7115. $db = (string)Config::get('database.database');
  7116. $key = $db . '.purchase_order';
  7117. $ref = new \ReflectionProperty(\think\db\Query::class, 'info');
  7118. $ref->setAccessible(true);
  7119. $info = $ref->getValue();
  7120. if (is_array($info) && isset($info[$key])) {
  7121. unset($info[$key]);
  7122. $ref->setValue(null, $info);
  7123. }
  7124. } catch (\Throwable $e) {
  7125. }
  7126. try {
  7127. $db = (string)Config::get('database.database');
  7128. $schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
  7129. if (is_file($schemaFile)) {
  7130. @unlink($schemaFile);
  7131. }
  7132. } catch (\Throwable $e) {
  7133. }
  7134. }
  7135. /**
  7136. * @return array<string, bool>
  7137. */
  7138. protected function loadPurchaseOrderColumnSet(): array
  7139. {
  7140. static $set = null;
  7141. if (is_array($set)) {
  7142. return $set;
  7143. }
  7144. $set = [];
  7145. try {
  7146. $cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
  7147. } catch (\Throwable $e) {
  7148. return $set;
  7149. }
  7150. if (!is_array($cols)) {
  7151. return $set;
  7152. }
  7153. foreach ($cols as $c) {
  7154. if (!is_array($c)) {
  7155. continue;
  7156. }
  7157. $f = (string)($c['Field'] ?? $c['field'] ?? '');
  7158. if ($f !== '') {
  7159. $set[$f] = true;
  7160. }
  7161. }
  7162. return $set;
  7163. }
  7164. /**
  7165. * 解析交货截止日期(仅年月日)
  7166. */
  7167. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  7168. {
  7169. $raw = trim($raw);
  7170. if ($raw === '') {
  7171. if ($required) {
  7172. $this->error('请选择交货截止日期');
  7173. }
  7174. return '';
  7175. }
  7176. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  7177. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  7178. } else {
  7179. $ts = strtotime(str_replace('/', '-', $raw));
  7180. if ($ts === false || $ts <= 0) {
  7181. $this->error('交货截止日期格式无效');
  7182. }
  7183. $ymd = date('Y-m-d', $ts);
  7184. }
  7185. if ($ymd < date('Y-m-d')) {
  7186. $this->error('交货截止日期不能早于今天');
  7187. }
  7188. return $ymd;
  7189. }
  7190. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  7191. {
  7192. $s = trim((string)$value);
  7193. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  7194. return '';
  7195. }
  7196. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  7197. return $m[1];
  7198. }
  7199. $ts = strtotime(str_replace('/', '-', $s));
  7200. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  7201. }
  7202. /**
  7203. * @param array{pos?:array} $bundle
  7204. */
  7205. protected function resolveBundleDeliveryDeadline(array $bundle): string
  7206. {
  7207. foreach ($bundle['pos'] ?? [] as $po) {
  7208. if (!is_array($po)) {
  7209. continue;
  7210. }
  7211. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7212. if ($d !== '') {
  7213. return $d;
  7214. }
  7215. }
  7216. return '';
  7217. }
  7218. protected function formatProcuremenSysRqForInput($sysRq): string
  7219. {
  7220. $sr = trim((string)$sysRq);
  7221. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  7222. return '';
  7223. }
  7224. $ts = strtotime($sr);
  7225. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  7226. }
  7227. protected function formatProcuremenSysRqForDisplay($sysRq): string
  7228. {
  7229. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  7230. if ($sr === '') {
  7231. return '—';
  7232. }
  7233. $ts = strtotime($sr);
  7234. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  7235. }
  7236. /**
  7237. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  7238. *
  7239. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  7240. * @return array{ccydh?:string,pos:array,merge_rows:array}
  7241. */
  7242. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  7243. {
  7244. return $bundle;
  7245. }
  7246. /**
  7247. * 写入/更新 purchase_order(单道工序行)
  7248. *
  7249. * @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
  7250. */
  7251. protected function upsertPurchaseOrderFromRow(
  7252. array $row,
  7253. string $sysRqDb,
  7254. $wflowStatus = null,
  7255. ?string $pickTime = null,
  7256. ?array $exists = null,
  7257. ?string $deliveryDeadline = null,
  7258. $scoreRuleId = null
  7259. ): void {
  7260. $ids = $this->extractScydgyRowId($row);
  7261. if (!$this->isValidScydgyRowId($ids)) {
  7262. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  7263. }
  7264. if ($exists === null) {
  7265. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7266. }
  7267. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  7268. $this->ensurePurchaseOrderScoreRuleIdColumn();
  7269. $this->ensurePurchaseOrderCzlyqColumn();
  7270. $data = [
  7271. 'scydgy_id' => $ids,
  7272. 'CCYDH' => $row['CCYDH'] ?? null,
  7273. 'CYJMC' => $row['CYJMC'] ?? null,
  7274. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  7275. 'CDXMC' => $row['CDXMC'] ?? null,
  7276. 'CGYBH' => $row['CGYBH'] ?? null,
  7277. 'CGYMC' => $row['CGYMC'] ?? null,
  7278. 'CDW' => $row['CDW'] ?? null,
  7279. 'czlyq' => $row['czlyq'] ?? null,
  7280. 'NGZL' => $row['NGZL'] ?? null,
  7281. 'CDF' => $row['CDF'] ?? null,
  7282. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  7283. 'MBZ' => $row['MBZ'] ?? null,
  7284. 'bwjg' => $row['bwjg'] ?? null,
  7285. 'iStatus' => $row['iStatus'] ?? null,
  7286. 'dStamp' => $row['dStamp'] ?? null,
  7287. 'dputrecord' => $row['dputrecord'] ?? null,
  7288. 'cywyxm' => $row['cywyxm'] ?? null,
  7289. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  7290. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  7291. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7292. 'sys_rq' => $sysRqDb,
  7293. ];
  7294. // 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
  7295. $qtyUp = trim((string)($data['This_quantity'] ?? ''));
  7296. if ($qtyUp === '') {
  7297. $qtyFallback = $this->resolveProcuremenThisQuantity([
  7298. 'This_quantity' => '',
  7299. 'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
  7300. ]);
  7301. if ($qtyFallback !== '') {
  7302. $data['This_quantity'] = $qtyFallback;
  7303. }
  7304. }
  7305. if ($deliveryDeadline !== null) {
  7306. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  7307. }
  7308. // 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
  7309. $scoreRule = null;
  7310. if (is_array($scoreRuleId)) {
  7311. $scoreRule = $scoreRuleId;
  7312. $scoreRuleId = (int)($scoreRule['id'] ?? 0);
  7313. } else {
  7314. $scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
  7315. }
  7316. if ($scoreRuleId !== null && $scoreRuleId > 0) {
  7317. $poCols = $this->loadPurchaseOrderColumnSet();
  7318. if (!empty($poCols['score_rule_id'])) {
  7319. $data['score_rule_id'] = $scoreRuleId;
  7320. if (is_array($scoreRule)) {
  7321. if (!empty($poCols['score_rule_name'])) {
  7322. $data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
  7323. }
  7324. if (!empty($poCols['score_quality_weight'])) {
  7325. $data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
  7326. }
  7327. if (!empty($poCols['score_price_weight'])) {
  7328. $data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
  7329. }
  7330. if (!empty($poCols['score_lead_weight'])) {
  7331. $data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
  7332. }
  7333. }
  7334. }
  7335. }
  7336. if ($wflowStatus !== null && $wflowStatus !== '') {
  7337. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  7338. }
  7339. if ($pickTime !== null && $pickTime !== '') {
  7340. $data['pick_time'] = $pickTime;
  7341. $data['pick_company_name'] = '';
  7342. }
  7343. if ($exists) {
  7344. $upd = $data;
  7345. unset($upd['scydgy_id']);
  7346. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  7347. } else {
  7348. $data['createtime'] = date('Y-m-d H:i:s');
  7349. Db::table('purchase_order')->insert($data);
  7350. }
  7351. }
  7352. /**
  7353. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  7354. *
  7355. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  7356. */
  7357. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
  7358. {
  7359. $toDb = function ($value) {
  7360. if ($value === null) {
  7361. return null;
  7362. }
  7363. if (is_scalar($value)) {
  7364. return $value;
  7365. }
  7366. return json_encode($value, JSON_UNESCAPED_UNICODE);
  7367. };
  7368. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7369. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7370. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7371. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  7372. if ($username === '') {
  7373. $username = $this->resolveCustomerContactName($phone, $companyName);
  7374. }
  7375. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  7376. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  7377. }
  7378. if ($requirePhone && $phone === '') {
  7379. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  7380. }
  7381. $detailLinks = [];
  7382. foreach ($mergeRows as $row) {
  7383. if (!is_array($row)) {
  7384. continue;
  7385. }
  7386. $sid = $this->extractScydgyRowId($row);
  7387. $detailId = 0;
  7388. if ($skipExisting) {
  7389. try {
  7390. $existsQuery = Db::table('purchase_order_detail')
  7391. ->where('scydgy_id', $sid)
  7392. ->where('company_name', $companyName);
  7393. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  7394. $exists = $existsQuery->find();
  7395. } catch (\Throwable $e) {
  7396. $exists = null;
  7397. }
  7398. if (is_array($exists)) {
  7399. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  7400. }
  7401. }
  7402. if ($detailId <= 0) {
  7403. $one = [
  7404. 'scydgy_id' => $toDb($sid),
  7405. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  7406. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  7407. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  7408. 'username' => $username !== '' ? $username : null,
  7409. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  7410. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  7411. 'createtime' => date('Y-m-d H:i:s'),
  7412. 'status' => ProcuremenStatus::POD_UNPICKED,
  7413. 'status_name' => '未提交',
  7414. ];
  7415. Db::table('purchase_order_detail')->insert($one);
  7416. $detailId = (int)Db::getLastInsID();
  7417. }
  7418. $mprocUrl = '';
  7419. if ($buildMobileLinks && $detailId > 0) {
  7420. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  7421. }
  7422. $detailLinks[] = [
  7423. 'detail_id' => $detailId,
  7424. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  7425. 'url' => $mprocUrl,
  7426. ];
  7427. }
  7428. $this->invalidatePickHiddenScydgyCache();
  7429. return $detailLinks;
  7430. }
  7431. /**
  7432. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  7433. * @return array<string, mixed>
  7434. */
  7435. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks, string $emailTplScene = 'review_email'): array
  7436. {
  7437. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7438. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7439. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7440. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  7441. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  7442. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  7443. $isMerge = !empty($ctx['is_merge']);
  7444. $contactName = trim((string)($c['username'] ?? ''));
  7445. if ($contactName === '') {
  7446. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  7447. }
  7448. $notifyVars = [
  7449. 'company_name' => $companyName,
  7450. 'contact_name' => $contactName,
  7451. 'phone' => $phone,
  7452. 'email' => $toEmail,
  7453. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  7454. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  7455. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  7456. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  7457. 'deadline' => (string)($ctx['deadline'] ?? ''),
  7458. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  7459. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  7460. 'platform_url' => $platformUrl,
  7461. 'platform_links' => $platformLinksPlain,
  7462. 'platform_links_html' => $platformLinksHtml,
  7463. ];
  7464. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  7465. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  7466. $mailPlain = $this->renderNotifyTemplate($emailTplScene, $notifyVars);
  7467. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  7468. return [
  7469. 'company_name' => $companyName,
  7470. 'phone' => $phone,
  7471. 'email' => $toEmail,
  7472. 'sms_content' => $smsContent,
  7473. 'mail_plain' => $mailPlain,
  7474. 'mail_body' => $mailBody,
  7475. 'notify_vars' => $notifyVars,
  7476. 'detail_links' => $detailLinks,
  7477. ];
  7478. }
  7479. /**
  7480. * @param array<string, mixed> $chosen
  7481. * @param array<int, array<string, mixed>> $mergeRows
  7482. * @param array{ccydh:string, pos:array} $bundle
  7483. */
  7484. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue', string $emailTplScene = 'review_email'): void
  7485. {
  7486. if (!$sendSms && !$sendEmail) {
  7487. return;
  7488. }
  7489. $companyName = trim((string)($chosen['name'] ?? ''));
  7490. $phone = trim((string)($chosen['phone'] ?? ''));
  7491. $toEmail = trim((string)($chosen['email'] ?? ''));
  7492. if ($companyName === '') {
  7493. throw new \Exception('供应商名称无效');
  7494. }
  7495. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  7496. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  7497. }
  7498. if ($sendSms && $phone === '') {
  7499. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  7500. }
  7501. $sids = [];
  7502. foreach ($mergeRows as $mr) {
  7503. if (!is_array($mr)) {
  7504. continue;
  7505. }
  7506. $sid = $this->extractScydgyRowId($mr);
  7507. if ($this->isValidScydgyRowId($sid)) {
  7508. $sids[$sid] = true;
  7509. }
  7510. }
  7511. if ($sids === []) {
  7512. throw new \Exception('未找到工序行,无法发送通知');
  7513. }
  7514. $sysRqNotify = '';
  7515. $pos = $bundle['pos'] ?? [];
  7516. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7517. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  7518. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  7519. $ts = strtotime($sr);
  7520. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  7521. }
  7522. }
  7523. try {
  7524. $detailsQuery = Db::table('purchase_order_detail')
  7525. ->where('scydgy_id', 'in', array_keys($sids))
  7526. ->where('company_name', $companyName);
  7527. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7528. $details = $detailsQuery->order('id', 'asc')->select();
  7529. } catch (\Throwable $e) {
  7530. $details = [];
  7531. }
  7532. if (!is_array($details) || $details === []) {
  7533. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  7534. try {
  7535. $detailsQuery = Db::table('purchase_order_detail')
  7536. ->where('scydgy_id', 'in', array_keys($sids))
  7537. ->where('company_name', $companyName);
  7538. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7539. $details = $detailsQuery->order('id', 'asc')->select();
  7540. } catch (\Throwable $e) {
  7541. $details = [];
  7542. }
  7543. }
  7544. if (!is_array($details) || $details === []) {
  7545. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  7546. }
  7547. $detailLinks = [];
  7548. foreach ($details as $d) {
  7549. if (!is_array($d)) {
  7550. continue;
  7551. }
  7552. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  7553. if ($detailId <= 0) {
  7554. continue;
  7555. }
  7556. $sid = (int)($d['scydgy_id'] ?? 0);
  7557. $gymc = '';
  7558. foreach ($mergeRows as $mr) {
  7559. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  7560. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  7561. break;
  7562. }
  7563. }
  7564. $detailLinks[] = [
  7565. 'detail_id' => $detailId,
  7566. 'cgymc' => $gymc,
  7567. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  7568. ];
  7569. }
  7570. if ($detailLinks === []) {
  7571. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  7572. }
  7573. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  7574. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  7575. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks, $emailTplScene);
  7576. $notifyBundle['email_log_scene'] = $emailLogScene;
  7577. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  7578. $poIdLog = 0;
  7579. $pos = $bundle['pos'] ?? [];
  7580. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7581. $poIdLog = (int)($pos[0]['id'] ?? 0);
  7582. }
  7583. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  7584. if ($sendEmail) {
  7585. $mailTplRow = $this->loadNotifyTemplateRow($emailTplScene);
  7586. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  7587. throw new \Exception($this->notifyTemplateMissingMessage($emailTplScene));
  7588. }
  7589. $mailSubject = $this->resolveProcuremenEmailSubject($emailTplScene);
  7590. $mailConfig = $this->loadMailerConfig();
  7591. if (!$this->isProcuremenNotifyDryRun()) {
  7592. if (empty($mailConfig['host'])) {
  7593. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  7594. }
  7595. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  7596. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  7597. }
  7598. }
  7599. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  7600. }
  7601. if ($sendSms) {
  7602. $this->issueSendSupplierSms($notifyBundle);
  7603. }
  7604. }
  7605. /**
  7606. * @param array<int, array<string, mixed>> $quoteGroups
  7607. * @return array<int, array<string, mixed>>
  7608. */
  7609. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  7610. {
  7611. $names = [];
  7612. if (is_string($companiesJson) && $companiesJson !== '') {
  7613. $decoded = json_decode($companiesJson, true);
  7614. if (is_array($decoded)) {
  7615. foreach ($decoded as $nm) {
  7616. $nm = trim((string)$nm);
  7617. if ($nm !== '') {
  7618. $names[] = $nm;
  7619. }
  7620. }
  7621. }
  7622. }
  7623. $names = array_values(array_unique($names));
  7624. if ($names === [] && $selectedCompany !== '') {
  7625. $names = [$selectedCompany];
  7626. }
  7627. if ($names === []) {
  7628. return $quoteGroups;
  7629. }
  7630. $targets = [];
  7631. foreach ($quoteGroups as $g) {
  7632. if (!is_array($g)) {
  7633. continue;
  7634. }
  7635. $cn = trim((string)($g['name'] ?? ''));
  7636. if ($cn !== '' && in_array($cn, $names, true)) {
  7637. $targets[] = $g;
  7638. }
  7639. }
  7640. return $targets;
  7641. }
  7642. /**
  7643. * @return array{pos:array, merge_rows:array, bundle:array}
  7644. */
  7645. protected function loadAuditResendBundle(string $scydgyId): array
  7646. {
  7647. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7648. $pos = $bundle['pos'];
  7649. $mergeRows = $bundle['merge_rows'];
  7650. if ($pos === [] || $mergeRows === []) {
  7651. $this->error('该订单不在待确认供应商状态');
  7652. }
  7653. $sysRqDb = '';
  7654. if (isset($pos[0]) && is_array($pos[0])) {
  7655. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  7656. }
  7657. foreach ($pos as $i => $poRow) {
  7658. if (is_array($pos[$i]) && $sysRqDb !== '') {
  7659. $pos[$i]['sys_rq'] = $sysRqDb;
  7660. }
  7661. }
  7662. $bundle['pos'] = $pos;
  7663. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  7664. }
  7665. /**
  7666. * @param array<int, array<string, mixed>> $targets
  7667. */
  7668. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  7669. {
  7670. if ($targets === []) {
  7671. $this->error('未找到可通知的供应商');
  7672. }
  7673. $notifyErrors = [];
  7674. try {
  7675. $this->notifyDryRunPreview = [];
  7676. foreach ($targets as $g) {
  7677. if (!is_array($g)) {
  7678. continue;
  7679. }
  7680. $cname = trim((string)($g['name'] ?? ''));
  7681. if ($cname === '') {
  7682. continue;
  7683. }
  7684. $chosen = [
  7685. 'name' => $cname,
  7686. 'company_name' => $cname,
  7687. 'email' => trim((string)($g['email'] ?? '')),
  7688. 'phone' => trim((string)($g['phone'] ?? '')),
  7689. 'username' => trim((string)($g['username'] ?? '')),
  7690. ];
  7691. try {
  7692. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  7693. } catch (\Throwable $e) {
  7694. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7695. }
  7696. }
  7697. } catch (\Throwable $e) {
  7698. $this->error('通知发送失败:' . $e->getMessage());
  7699. }
  7700. if ($notifyErrors !== []) {
  7701. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  7702. }
  7703. if ($this->isProcuremenNotifyDryRun()) {
  7704. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  7705. 'notify_dry_run' => true,
  7706. 'notify_preview' => $this->notifyDryRunPreview,
  7707. ]);
  7708. }
  7709. $nameLabels = [];
  7710. foreach ($targets as $g) {
  7711. if (!is_array($g)) {
  7712. continue;
  7713. }
  7714. $n = trim((string)($g['name'] ?? ''));
  7715. if ($n !== '') {
  7716. $nameLabels[] = $n;
  7717. }
  7718. }
  7719. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  7720. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  7721. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  7722. $seenLogSid = [];
  7723. foreach ($bundle['pos'] ?? [] as $poRow) {
  7724. if (!is_array($poRow)) {
  7725. continue;
  7726. }
  7727. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7728. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  7729. continue;
  7730. }
  7731. $seenLogSid[$sid] = true;
  7732. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7733. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7734. }
  7735. if ($seenLogSid === []) {
  7736. foreach ($mergeRows as $mr) {
  7737. if (!is_array($mr)) {
  7738. continue;
  7739. }
  7740. $sid = $this->extractScydgyRowId($mr);
  7741. if ($this->isValidScydgyRowId($sid)) {
  7742. $this->addOrderLog($sid, $logAction, $logMsg, null);
  7743. break;
  7744. }
  7745. }
  7746. }
  7747. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  7748. }
  7749. /**
  7750. * 协助下发 — 发送短信(一家供应商)
  7751. *
  7752. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  7753. */
  7754. protected function issueSendSupplierSms(array $bundle): void
  7755. {
  7756. $companyName = (string)($bundle['company_name'] ?? '');
  7757. $phone = (string)($bundle['phone'] ?? '');
  7758. $smsContent = (string)($bundle['sms_content'] ?? '');
  7759. $this->logIssueNotifyDebug('短信', [
  7760. 'company' => $companyName,
  7761. 'phone' => $phone,
  7762. 'sms_content' => $smsContent,
  7763. ]);
  7764. if ($this->isProcuremenNotifyDryRun()) {
  7765. $this->recordNotifyDryRunPreview([
  7766. 'scene' => 'issue_sms',
  7767. 'company_name' => $companyName,
  7768. 'phone' => $phone,
  7769. 'sms_content' => $smsContent,
  7770. ]);
  7771. return;
  7772. }
  7773. $this->smsbao($phone, $smsContent);
  7774. }
  7775. /**
  7776. * 协助下发 — 发送邮件(一家供应商)
  7777. *
  7778. * @param array<string, mixed> $bundle
  7779. * @param array<string, mixed> $mailConfig
  7780. */
  7781. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  7782. {
  7783. $companyName = (string)($bundle['company_name'] ?? '');
  7784. $toEmail = (string)($bundle['email'] ?? '');
  7785. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  7786. $mailBody = (string)($bundle['mail_body'] ?? '');
  7787. $this->logIssueNotifyDebug('邮件', [
  7788. 'company' => $companyName,
  7789. 'email' => $toEmail,
  7790. 'mail_subject' => $mailSubject,
  7791. 'mail_body' => $mailPlain,
  7792. ]);
  7793. if ($this->isProcuremenNotifyDryRun()) {
  7794. $this->recordNotifyDryRunPreview([
  7795. 'scene' => 'issue_email',
  7796. 'company_name' => $companyName,
  7797. 'email' => $toEmail,
  7798. 'mail_subject' => $mailSubject,
  7799. 'mail_body' => $mailPlain,
  7800. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  7801. 'notify_vars' => $bundle['notify_vars'] ?? [],
  7802. 'detail_links' => $bundle['detail_links'] ?? [],
  7803. ]);
  7804. return;
  7805. }
  7806. $mail = new PHPMailer(true);
  7807. $mail->isSMTP();
  7808. $mail->Host = $mailConfig['host'];
  7809. $mail->SMTPAuth = true;
  7810. $mail->Username = $mailConfig['addr'];
  7811. $mail->Password = $mailConfig['pass'];
  7812. $mail->SMTPSecure = $mailConfig['security'];
  7813. $mail->Port = $mailConfig['port'];
  7814. $mail->CharSet = $mailConfig['charset'];
  7815. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  7816. $mail->addAddress($toEmail, $companyName);
  7817. $mail->isHTML(true);
  7818. $mail->Subject = $mailSubject;
  7819. $mail->Body = $mailBody;
  7820. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  7821. $sendOk = true;
  7822. $failReason = '';
  7823. try {
  7824. $mail->send();
  7825. } catch (\Throwable $e) {
  7826. $sendOk = false;
  7827. $failReason = $e->getMessage();
  7828. $this->persistEmailSendLog([
  7829. 'from_email' => $fromEmail,
  7830. 'to_email' => $toEmail,
  7831. 'send_time' => date('Y-m-d H:i:s'),
  7832. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7833. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7834. 'company_name' => $companyName,
  7835. 'mail_subject' => $mailSubject,
  7836. 'status' => 0,
  7837. 'fail_reason' => $failReason,
  7838. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7839. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7840. ]);
  7841. throw $e;
  7842. }
  7843. $this->persistEmailSendLog([
  7844. 'from_email' => $fromEmail,
  7845. 'to_email' => $toEmail,
  7846. 'send_time' => date('Y-m-d H:i:s'),
  7847. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7848. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7849. 'company_name' => $companyName,
  7850. 'mail_subject' => $mailSubject,
  7851. 'status' => 1,
  7852. 'fail_reason' => '',
  7853. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7854. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7855. ]);
  7856. }
  7857. /**
  7858. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  7859. *
  7860. * @param array<int, array<string, mixed>> $mergeRows
  7861. * @return array<string, mixed>
  7862. */
  7863. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  7864. {
  7865. $head = $mergeRows[0] ?? [];
  7866. $isMerge = count($mergeRows) > 1;
  7867. return [
  7868. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  7869. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  7870. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  7871. 'is_merge' => $isMerge,
  7872. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  7873. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  7874. 'deadline' => $sysRqNotify,
  7875. ];
  7876. }
  7877. /**
  7878. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  7879. *
  7880. * @param array<string, mixed> $data
  7881. */
  7882. protected function logIssueNotifyDebug(string $type, array $data): void
  7883. {
  7884. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  7885. return;
  7886. }
  7887. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  7888. }
  7889. protected function ensurePurchaseEmailSendLogTableOnce(): void
  7890. {
  7891. try {
  7892. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  7893. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  7894. return;
  7895. } catch (\Throwable $e) {
  7896. }
  7897. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  7898. if (is_file($sqlFile)) {
  7899. $sql = file_get_contents($sqlFile);
  7900. if (is_string($sql) && $sql !== '') {
  7901. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  7902. $stmt = trim($stmt);
  7903. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  7904. continue;
  7905. }
  7906. try {
  7907. Db::execute($stmt);
  7908. } catch (\Throwable $ignore) {
  7909. }
  7910. }
  7911. }
  7912. }
  7913. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  7914. }
  7915. /**
  7916. * @param array<string, mixed> $row
  7917. */
  7918. protected function persistEmailSendLog(array $row): void
  7919. {
  7920. try {
  7921. $this->ensurePurchaseEmailSendLogTableOnce();
  7922. } catch (\Throwable $e) {
  7923. return;
  7924. }
  7925. list($adminId, $adminName) = $this->GetUseName();
  7926. $cut = function ($s, $max) {
  7927. $s = (string)$s;
  7928. if (function_exists('mb_substr')) {
  7929. return mb_substr($s, 0, $max, 'UTF-8');
  7930. }
  7931. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  7932. };
  7933. $data = [
  7934. 'from_email' => $cut($row['from_email'] ?? '', 128),
  7935. 'to_email' => $cut($row['to_email'] ?? '', 128),
  7936. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  7937. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  7938. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  7939. 'company_name' => $cut($row['company_name'] ?? '', 128),
  7940. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  7941. 'status' => !empty($row['status']) ? 1 : 0,
  7942. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  7943. 'admin_id' => (int)$adminId,
  7944. 'admin_name' => $cut($adminName, 64),
  7945. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  7946. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  7947. 'createtime' => date('Y-m-d H:i:s'),
  7948. ];
  7949. try {
  7950. Db::table('purchase_email_send_log')->insert($data);
  7951. } catch (\Throwable $e) {
  7952. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  7953. }
  7954. }
  7955. protected function formatEmailLogSceneText(string $scene): string
  7956. {
  7957. $map = [
  7958. 'pick_issue' => '初选下发',
  7959. 'audit_resend' => '确认页重发',
  7960. 'rfq_salesman' => '询价通知业务员',
  7961. 'rfq_supplier' => '供应商询价通知',
  7962. ];
  7963. return $map[$scene] ?? $scene;
  7964. }
  7965. /**
  7966. * 邮件发送日志列表
  7967. */
  7968. public function emailLog()
  7969. {
  7970. $this->relationSearch = false;
  7971. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  7972. $this->request->filter(['strip_tags', 'trim']);
  7973. $bakModel = $this->model;
  7974. $this->model = new \app\admin\model\Purchaseemailsendlog;
  7975. if ($this->request->isAjax()) {
  7976. $this->ensurePurchaseEmailSendLogTableOnce();
  7977. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  7978. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  7979. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  7980. $list = $this->model
  7981. ->where($where)
  7982. ->order($sortField, $orderDir)
  7983. ->paginate($limit);
  7984. $rows = [];
  7985. foreach ($list->items() as $item) {
  7986. $row = is_array($item) ? $item : $item->toArray();
  7987. $scene = trim((string)($row['scene'] ?? ''));
  7988. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  7989. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  7990. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  7991. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  7992. $rows[] = $row;
  7993. }
  7994. $this->model = $bakModel;
  7995. return json(['total' => $list->total(), 'rows' => $rows]);
  7996. }
  7997. $this->model = $bakModel;
  7998. return $this->view->fetch('procuremen/emaillog');
  7999. }
  8000. /**
  8001. * 协助下发弹窗(选多家供应商并通知)
  8002. */
  8003. public function pickReview()
  8004. {
  8005. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  8006. $this->error(__('You have no permission'));
  8007. }
  8008. if ($this->request->isPost()) {
  8009. $this->error('请使用弹窗内「确认下发」提交');
  8010. }
  8011. $this->view->assign('pickMode', 1);
  8012. $this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
  8013. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  8014. }
  8015. /**
  8016. * 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
  8017. */
  8018. protected function ensurePurchaseOrderNotifySalesmanColumn(): void
  8019. {
  8020. static $done = false;
  8021. if ($done) {
  8022. return;
  8023. }
  8024. $done = true;
  8025. try {
  8026. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'notify_salesman'");
  8027. if (empty($cols)) {
  8028. Db::execute(
  8029. "ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
  8030. );
  8031. } else {
  8032. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  8033. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
  8034. Db::execute(
  8035. "ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
  8036. );
  8037. }
  8038. }
  8039. } catch (\Throwable $e) {
  8040. // ignore
  8041. }
  8042. }
  8043. /**
  8044. * 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
  8045. */
  8046. protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
  8047. {
  8048. static $done = false;
  8049. if ($done) {
  8050. return;
  8051. }
  8052. $done = true;
  8053. try {
  8054. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
  8055. if (empty($cols)) {
  8056. Db::execute(
  8057. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
  8058. );
  8059. }
  8060. } catch (\Throwable $e) {
  8061. // ignore
  8062. }
  8063. try {
  8064. $cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
  8065. if (empty($cols2)) {
  8066. Db::execute(
  8067. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
  8068. );
  8069. }
  8070. } catch (\Throwable $e) {
  8071. // ignore
  8072. }
  8073. }
  8074. /**
  8075. * 确保「供应商询价通知」邮箱模版存在(查询询价-询价/发邮件;可在短信模版配置中修改)
  8076. */
  8077. protected function ensureRfqSupplierEmailTemplate(): void
  8078. {
  8079. static $done = false;
  8080. if ($done) {
  8081. return;
  8082. }
  8083. $done = true;
  8084. $content = "您好,{company_name}:\n\n"
  8085. . "您有新的协助采购询价需求,请登录平台查看并处理。\n\n"
  8086. . "需求编号:{ccydh}\n"
  8087. . "印件名称:{cyjmc}\n"
  8088. . "{process_lines}\n\n"
  8089. . "请在 {deadline} 前完成回复。\n\n"
  8090. . "平台链接:{platform_url}\n";
  8091. try {
  8092. $row = Db::table('purchase_sms_template')
  8093. ->where('scene', 'rfq_supplier_email')
  8094. ->find();
  8095. } catch (\Throwable $e) {
  8096. return;
  8097. }
  8098. $now = date('Y-m-d H:i:s');
  8099. if (is_array($row) && $row !== []) {
  8100. return;
  8101. }
  8102. try {
  8103. $data = [
  8104. 'scene' => 'rfq_supplier_email',
  8105. 'title' => '供应商询价通知',
  8106. 'content' => $content,
  8107. 'remark' => '查询询价-询价/发邮件通知供应商;模版名称作邮件主题',
  8108. 'status' => 1,
  8109. ];
  8110. try {
  8111. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8112. } catch (\Throwable $e) {
  8113. $cols = [];
  8114. }
  8115. $colNames = [];
  8116. foreach ($cols as $c) {
  8117. if (!is_array($c)) {
  8118. continue;
  8119. }
  8120. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8121. if ($n !== '') {
  8122. $colNames[$n] = true;
  8123. }
  8124. }
  8125. if (isset($colNames['updatetime'])) {
  8126. $data['updatetime'] = $now;
  8127. }
  8128. if (isset($colNames['createtime'])) {
  8129. $data['createtime'] = $now;
  8130. }
  8131. Db::table('purchase_sms_template')->insert($data);
  8132. } catch (\Throwable $e) {
  8133. // ignore
  8134. }
  8135. }
  8136. /**
  8137. * 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
  8138. */
  8139. protected function ensureRfqSalesmanEmailTemplate(): void
  8140. {
  8141. static $done = false;
  8142. if ($done) {
  8143. return;
  8144. }
  8145. $done = true;
  8146. $content = "您好,{contact_name}:\n\n"
  8147. . "有新的协助采购询价需求,请知悉。\n"
  8148. . "印件名称:{cyjmc}\n"
  8149. . "工序名称:{cgymc}\n"
  8150. . "本次数量:{this_quantity}\n"
  8151. . "供应商报价:\n{supplier_quotes}\n"
  8152. . "需求发起人:{cywyxm}\n";
  8153. try {
  8154. $row = Db::table('purchase_sms_template')
  8155. ->where('scene', 'rfq_salesman_email')
  8156. ->find();
  8157. } catch (\Throwable $e) {
  8158. return;
  8159. }
  8160. $now = date('Y-m-d H:i:s');
  8161. if (is_array($row) && $row !== []) {
  8162. $old = (string)($row['content'] ?? '');
  8163. // 仍用旧的「供应商:{supplier_name}」或没有报价占位符时,补上单价表格
  8164. $needMigrate = (strpos($old, '{supplier_quotes}') === false)
  8165. || (strpos($old, '供应商:{supplier_name}') !== false);
  8166. if ($needMigrate) {
  8167. $data = ['content' => $content];
  8168. if (trim((string)($row['title'] ?? '')) === '' || trim((string)($row['title'] ?? '')) === '询价通知') {
  8169. $data['title'] = '业务员询价通知';
  8170. }
  8171. try {
  8172. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
  8173. if (!empty($cols)) {
  8174. $data['updatetime'] = $now;
  8175. }
  8176. } catch (\Throwable $e) {
  8177. }
  8178. try {
  8179. Db::table('purchase_sms_template')
  8180. ->where('id', (int)($row['id'] ?? 0))
  8181. ->update($data);
  8182. } catch (\Throwable $e) {
  8183. }
  8184. }
  8185. return;
  8186. }
  8187. try {
  8188. $data = [
  8189. 'scene' => 'rfq_salesman_email',
  8190. 'title' => '业务员询价通知',
  8191. 'content' => $content,
  8192. 'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
  8193. 'status' => 1,
  8194. ];
  8195. try {
  8196. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8197. } catch (\Throwable $e) {
  8198. $cols = [];
  8199. }
  8200. $colNames = [];
  8201. foreach ($cols as $c) {
  8202. if (!is_array($c)) {
  8203. continue;
  8204. }
  8205. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8206. if ($n !== '') {
  8207. $colNames[$n] = true;
  8208. }
  8209. }
  8210. if (isset($colNames['updatetime'])) {
  8211. $data['updatetime'] = $now;
  8212. }
  8213. if (isset($colNames['createtime'])) {
  8214. $data['createtime'] = $now;
  8215. }
  8216. Db::table('purchase_sms_template')->insert($data);
  8217. } catch (\Throwable $e) {
  8218. // ignore
  8219. }
  8220. }
  8221. /**
  8222. * 通知业务员邮件:供应商报价明细行(仅名称+单价)
  8223. *
  8224. * @return array<int, array{name:string,amount:string}>
  8225. */
  8226. protected function loadRfqSalesmanSupplierQuoteRows(int $sid, string $supplierRaw = ''): array
  8227. {
  8228. $list = [];
  8229. $seen = [];
  8230. try {
  8231. $rows = Db::table('purchase_order_detail')
  8232. ->where('scydgy_id', $sid)
  8233. ->field('company_name,amount')
  8234. ->order('id', 'asc')
  8235. ->select();
  8236. if (is_array($rows)) {
  8237. foreach ($rows as $r) {
  8238. if (!is_array($r)) {
  8239. continue;
  8240. }
  8241. $cn = trim((string)($r['company_name'] ?? ''));
  8242. if ($cn === '' || isset($seen[$cn])) {
  8243. continue;
  8244. }
  8245. $seen[$cn] = true;
  8246. $amount = trim((string)($r['amount'] ?? ''));
  8247. $list[] = [
  8248. 'name' => $cn,
  8249. 'amount' => $amount !== '' ? $amount : '未报价',
  8250. ];
  8251. }
  8252. }
  8253. } catch (\Throwable $e) {
  8254. }
  8255. if ($list === [] && $supplierRaw !== '') {
  8256. foreach ($this->splitRfqSalesmanNames($supplierRaw) as $cn) {
  8257. if ($cn === '' || isset($seen[$cn])) {
  8258. continue;
  8259. }
  8260. $seen[$cn] = true;
  8261. $list[] = [
  8262. 'name' => $cn,
  8263. 'amount' => '未报价',
  8264. ];
  8265. }
  8266. }
  8267. return $list;
  8268. }
  8269. /**
  8270. * 通知业务员邮件:供应商报价 HTML 表格(名称+单价,不含时间)
  8271. */
  8272. protected function buildRfqSalesmanSupplierQuotesHtml(int $sid, string $supplierRaw = ''): string
  8273. {
  8274. $rows = $this->loadRfqSalesmanSupplierQuoteRows($sid, $supplierRaw);
  8275. if ($rows === []) {
  8276. return '<p style="margin:8px 0;color:#888;">暂无报价</p>';
  8277. }
  8278. $html = '<table cellpadding="0" cellspacing="0" border="1" '
  8279. . 'style="border-collapse:collapse;border-color:#ddd;width:100%;max-width:560px;font-size:14px;margin:8px 0;">'
  8280. . '<thead><tr style="background:#f5f5f5;">'
  8281. . '<th style="padding:8px 10px;text-align:center;width:56px;">序号</th>'
  8282. . '<th style="padding:8px 10px;text-align:left;">供应商名称</th>'
  8283. . '<th style="padding:8px 10px;text-align:center;width:100px;">单价</th>'
  8284. . '</tr></thead><tbody>';
  8285. foreach ($rows as $i => $row) {
  8286. $html .= '<tr>'
  8287. . '<td style="padding:8px 10px;text-align:center;">' . ($i + 1) . '</td>'
  8288. . '<td style="padding:8px 10px;">' . htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8') . '</td>'
  8289. . '<td style="padding:8px 10px;text-align:center;">' . htmlspecialchars($row['amount'], ENT_QUOTES, 'UTF-8') . '</td>'
  8290. . '</tr>';
  8291. }
  8292. $html .= '</tbody></table>';
  8293. return $html;
  8294. }
  8295. /**
  8296. * 询价多选字段:数组或字符串统一为顿号拼接
  8297. *
  8298. * @param mixed $raw
  8299. */
  8300. protected function joinRfqMultiSelectValues($raw): string
  8301. {
  8302. $parts = [];
  8303. if (is_array($raw)) {
  8304. foreach ($raw as $item) {
  8305. if (is_array($item)) {
  8306. continue;
  8307. }
  8308. $v = trim((string)$item);
  8309. if ($v !== '') {
  8310. $parts[] = $v;
  8311. }
  8312. }
  8313. } else {
  8314. $s = trim((string)$raw);
  8315. if ($s !== '') {
  8316. foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
  8317. $v = trim((string)$piece);
  8318. if ($v !== '') {
  8319. $parts[] = $v;
  8320. }
  8321. }
  8322. }
  8323. }
  8324. $parts = array_values(array_unique($parts));
  8325. return implode('、', $parts);
  8326. }
  8327. /**
  8328. * 新增询价:可选供应商名称(仅落库记录,不发通知)
  8329. *
  8330. * @return string[]
  8331. */
  8332. protected function loadRfqSupplierNameOptions(): array
  8333. {
  8334. $out = [];
  8335. try {
  8336. $rows = Db::table('customer')
  8337. ->where(function ($q) {
  8338. $q->where('status', 1)
  8339. ->whereOr('status', '1')
  8340. ->whereOr('status', '')
  8341. ->whereNull('status');
  8342. })
  8343. ->order('id', 'desc')
  8344. ->column('company_name');
  8345. } catch (\Throwable $e) {
  8346. return [];
  8347. }
  8348. if (!is_array($rows)) {
  8349. return [];
  8350. }
  8351. foreach ($rows as $name) {
  8352. $name = trim((string)$name);
  8353. if ($name === '' || isset($out[$name])) {
  8354. continue;
  8355. }
  8356. $out[$name] = $name;
  8357. }
  8358. return array_values($out);
  8359. }
  8360. /**
  8361. * 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
  8362. */
  8363. protected function rfqNotifySalesmanAuthGroupId(): int
  8364. {
  8365. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  8366. if ($id > 0) {
  8367. return $id;
  8368. }
  8369. try {
  8370. $found = Db::name('auth_group')
  8371. ->where('name', '业务员')
  8372. ->where('status', 'normal')
  8373. ->order('id', 'asc')
  8374. ->value('id');
  8375. $id = (int)$found;
  8376. } catch (\Throwable $e) {
  8377. $id = 0;
  8378. }
  8379. return $id > 0 ? $id : 12;
  8380. }
  8381. /**
  8382. * 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
  8383. *
  8384. * @return string[]
  8385. */
  8386. protected function loadRfqSalesmanNameOptions(): array
  8387. {
  8388. $out = [];
  8389. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8390. $name = trim((string)($row['name'] ?? ''));
  8391. if ($name !== '') {
  8392. $out[] = $name;
  8393. }
  8394. }
  8395. return $out;
  8396. }
  8397. /**
  8398. * 业务员角色组下管理员:姓名、邮箱、手机
  8399. *
  8400. * @return array<int, array{name:string,email:string,mobile:string}>
  8401. */
  8402. protected function loadRfqSalesmanContactOptions(): array
  8403. {
  8404. $out = [];
  8405. $seen = [];
  8406. $groupId = $this->rfqNotifySalesmanAuthGroupId();
  8407. if ($groupId <= 0) {
  8408. return [];
  8409. }
  8410. try {
  8411. $adminIds = Db::name('auth_group_access')
  8412. ->where('group_id', $groupId)
  8413. ->column('uid');
  8414. } catch (\Throwable $e) {
  8415. return [];
  8416. }
  8417. $adminIds = is_array($adminIds)
  8418. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  8419. : [];
  8420. if ($adminIds === []) {
  8421. return [];
  8422. }
  8423. try {
  8424. $rows = Db::name('admin')
  8425. ->where('status', 'normal')
  8426. ->where('id', 'in', $adminIds)
  8427. ->order('id', 'asc')
  8428. ->field('id,nickname,username,email,mobile')
  8429. ->select();
  8430. } catch (\Throwable $e) {
  8431. return [];
  8432. }
  8433. if (!is_array($rows)) {
  8434. return [];
  8435. }
  8436. foreach ($rows as $row) {
  8437. if (!is_array($row)) {
  8438. continue;
  8439. }
  8440. $name = trim((string)($row['nickname'] ?? ''));
  8441. if ($name === '') {
  8442. $name = trim((string)($row['username'] ?? ''));
  8443. }
  8444. if ($name === '' || isset($seen[$name])) {
  8445. continue;
  8446. }
  8447. $seen[$name] = true;
  8448. $out[] = [
  8449. 'name' => $name,
  8450. 'email' => trim((string)($row['email'] ?? '')),
  8451. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  8452. ];
  8453. }
  8454. return $out;
  8455. }
  8456. /**
  8457. * 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
  8458. *
  8459. * @return string[]
  8460. */
  8461. protected function loadRfqDeptNameOptions(): array
  8462. {
  8463. $out = [];
  8464. // ERP 承揽部门(主来源)
  8465. try {
  8466. $vals = Db::table('mcyd')
  8467. ->where('CCLBMMC', '<>', '')
  8468. ->whereNotNull('CCLBMMC')
  8469. ->distinct(true)
  8470. ->limit(300)
  8471. ->column('CCLBMMC');
  8472. } catch (\Throwable $e) {
  8473. $vals = [];
  8474. }
  8475. if (is_array($vals)) {
  8476. foreach ($vals as $v) {
  8477. $v = trim((string)$v);
  8478. if ($v === '' || isset($out[$v])) {
  8479. continue;
  8480. }
  8481. $out[$v] = $v;
  8482. }
  8483. }
  8484. // 手工询价历史部门补全
  8485. try {
  8486. $poVals = Db::table('purchase_order')
  8487. ->where('CCLBMMC', '<>', '')
  8488. ->whereNotNull('CCLBMMC')
  8489. ->distinct(true)
  8490. ->limit(200)
  8491. ->column('CCLBMMC');
  8492. } catch (\Throwable $e) {
  8493. $poVals = [];
  8494. }
  8495. if (is_array($poVals)) {
  8496. foreach ($poVals as $v) {
  8497. $v = trim((string)$v);
  8498. if ($v === '' || isset($out[$v])) {
  8499. continue;
  8500. }
  8501. $out[$v] = $v;
  8502. }
  8503. }
  8504. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  8505. if (!isset($out[$preset])) {
  8506. $out[$preset] = $preset;
  8507. }
  8508. }
  8509. $list = array_values($out);
  8510. // 常用部门靠前
  8511. usort($list, static function ($a, $b) {
  8512. $weight = [
  8513. '营销中心' => 1,
  8514. '业务部' => 2,
  8515. '市场部' => 3,
  8516. '外贸部' => 4,
  8517. '新华技术业务部' => 5,
  8518. ];
  8519. $wa = $weight[$a] ?? 100;
  8520. $wb = $weight[$b] ?? 100;
  8521. if ($wa !== $wb) {
  8522. return $wa <=> $wb;
  8523. }
  8524. return strcmp((string)$a, (string)$b);
  8525. });
  8526. return $list;
  8527. }
  8528. /**
  8529. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  8530. */
  8531. public function add()
  8532. {
  8533. if ($this->request->isPost()) {
  8534. $params = $this->request->post('row/a');
  8535. if (!is_array($params)) {
  8536. $this->error(__('Parameter %s can not be empty', ''));
  8537. }
  8538. [, $adminName] = $this->GetUseName();
  8539. $params['cywyxm'] = $adminName;
  8540. try {
  8541. $sid = $this->saveManualPickOrder($params);
  8542. } catch (\InvalidArgumentException $e) {
  8543. $this->error($e->getMessage());
  8544. } catch (\Throwable $e) {
  8545. $this->error($e->getMessage());
  8546. }
  8547. $this->success('新增成功', '', [
  8548. 'scydgy_id' => $sid,
  8549. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  8550. ]);
  8551. }
  8552. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8553. [, $adminName] = $this->GetUseName();
  8554. $this->view->assign('adminNickname', $adminName);
  8555. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  8556. $this->view->assign('defaultCclbmmc', '营销中心');
  8557. $this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
  8558. $this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
  8559. $this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
  8560. return $this->view->fetch();
  8561. }
  8562. /**
  8563. * 业务员新增进度查询(手工询价;有查询权限看全部,含手机端新增且未通知业务员的)
  8564. */
  8565. public function rfqlist()
  8566. {
  8567. $this->relationSearch = false;
  8568. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ';
  8569. $this->request->filter(['strip_tags', 'trim']);
  8570. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8571. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8572. $this->ensureRfqSalesmanEmailTemplate();
  8573. $this->ensureRfqSupplierEmailTemplate();
  8574. if ($this->request->isAjax()) {
  8575. try {
  8576. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  8577. $limit = max(10, min(500, (int)$limit));
  8578. $filterYm = trim((string)$this->request->param('filter_ym', ''));
  8579. if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
  8580. $filterYm = date('Y-m');
  8581. }
  8582. $applyFilters = function ($query) use ($where, $filterYm) {
  8583. $query->where('scydgy_id', '<', 0);
  8584. $this->applyPurchaseOrderNotDeletedWhere($query);
  8585. // 查询询价:有菜单权限即可看全部手工单(含手机端新增、尚未通知业务员的)
  8586. $this->applyRfqListMonthFilter($query, $filterYm);
  8587. if (!empty($where)) {
  8588. // 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
  8589. $safeWhere = [];
  8590. $skipFields = [
  8591. 'supplier_name' => true,
  8592. 'progress_text' => true,
  8593. 'createtime_text' => true,
  8594. 'notify_time_text' => true,
  8595. 'can_notify_salesman' => true,
  8596. 'has_issued' => true,
  8597. 'has_quoted' => true,
  8598. ];
  8599. foreach ((array)$where as $cond) {
  8600. if (!is_array($cond) || !isset($cond[0])) {
  8601. continue;
  8602. }
  8603. $field = (string)$cond[0];
  8604. $fieldBase = (string)preg_replace('/\|.*$/', '', $field);
  8605. $fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
  8606. if (isset($skipFields[$fieldBase])) {
  8607. continue;
  8608. }
  8609. if ($fieldBase === 'supplier_name') {
  8610. continue;
  8611. }
  8612. $safeWhere[] = $cond;
  8613. }
  8614. if ($safeWhere !== []) {
  8615. $query->where($safeWhere);
  8616. }
  8617. }
  8618. };
  8619. $countQuery = Db::table('purchase_order');
  8620. $applyFilters($countQuery);
  8621. $total = (int)$countQuery->count();
  8622. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  8623. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  8624. $listQuery = Db::table('purchase_order');
  8625. $applyFilters($listQuery);
  8626. $rows = $listQuery
  8627. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,CDW,CDF,This_quantity,ceilingPrice,cGzzxMc,pick_company_name,cywyxm,notify_salesman,rfq_salesman_notified,rfq_salesman_notify_time,MBZ,createtime,dStamp,status,wflow_status')
  8628. ->order($sortField, $orderDir)
  8629. ->limit($offset, $limit)
  8630. ->select();
  8631. if (!is_array($rows)) {
  8632. $rows = [];
  8633. }
  8634. $sidList = [];
  8635. foreach ($rows as $r) {
  8636. if (!is_array($r)) {
  8637. continue;
  8638. }
  8639. $sid = (int)($r['scydgy_id'] ?? 0);
  8640. if ($sid < 0) {
  8641. $sidList[$sid] = true;
  8642. }
  8643. }
  8644. $issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
  8645. $quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
  8646. $out = [];
  8647. foreach ($rows as $r) {
  8648. if (!is_array($r)) {
  8649. continue;
  8650. }
  8651. $sid = (int)($r['scydgy_id'] ?? 0);
  8652. if ($sid >= 0) {
  8653. continue;
  8654. }
  8655. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  8656. if ($createdText === '') {
  8657. $createdText = trim((string)($r['dStamp'] ?? ''));
  8658. }
  8659. $notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
  8660. $supplier = trim((string)($r['cGzzxMc'] ?? ''));
  8661. if ($supplier === '') {
  8662. $supplier = trim((string)($r['pick_company_name'] ?? ''));
  8663. }
  8664. $hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
  8665. || isset($issuedSidSet[$sid]);
  8666. $hasQuoted = isset($quotedSidSet[$sid]);
  8667. $salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
  8668. $canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
  8669. $out[] = [
  8670. 'id' => (int)($r['id'] ?? 0),
  8671. 'scydgy_id' => $sid,
  8672. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  8673. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  8674. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  8675. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  8676. 'CDW' => trim((string)($r['CDW'] ?? '')),
  8677. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  8678. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  8679. 'CDF' => trim((string)($r['CDF'] ?? '')),
  8680. 'supplier_name' => $supplier,
  8681. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  8682. 'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
  8683. 'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
  8684. 'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
  8685. 'notify_time_text' => $notifyTimeText,
  8686. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  8687. 'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
  8688. 'has_issued' => $hasIssued ? 1 : 0,
  8689. 'has_quoted' => $hasQuoted ? 1 : 0,
  8690. 'can_notify_salesman' => $canNotifySalesman,
  8691. 'createtime' => $r['createtime'] ?? null,
  8692. 'createtime_text' => $createdText,
  8693. ];
  8694. }
  8695. return json(['total' => $total, 'rows' => $out]);
  8696. } catch (\Throwable $e) {
  8697. Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
  8698. return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
  8699. }
  8700. }
  8701. $sidebar = $this->loadRfqSidebarYearMonths();
  8702. $defaultYm = $this->resolveRfqListDefaultYm($sidebar);
  8703. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  8704. [, $adminName] = $this->GetUseName();
  8705. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  8706. $this->view->assign('adminNickname', $adminName);
  8707. $this->view->assign('defaultYm', $defaultYm);
  8708. $this->view->assign('sidebarYearMonths', $sidebar);
  8709. return $this->view->fetch('procuremen/rfqlist');
  8710. }
  8711. /**
  8712. * 列表默认月份:当月有数据用当月,否则取最近有数据的月份
  8713. *
  8714. * @param array<int, array{year:string, months:array}> $sidebar
  8715. */
  8716. protected function resolveRfqListDefaultYm(array $sidebar): string
  8717. {
  8718. $current = date('Y-m');
  8719. $yms = $this->flattenProcuremenSidebarYms($sidebar);
  8720. if (in_array($current, $yms, true)) {
  8721. return $current;
  8722. }
  8723. if ($yms !== []) {
  8724. rsort($yms, SORT_STRING);
  8725. return (string)$yms[0];
  8726. }
  8727. return $current;
  8728. }
  8729. /**
  8730. * 手工询价列表左侧月份(按 createtime / dStamp)
  8731. *
  8732. * @return array<int, array{year:string, months:array}>
  8733. */
  8734. protected function loadRfqSidebarYearMonths(): array
  8735. {
  8736. $ymSet = [];
  8737. try {
  8738. $q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
  8739. $this->applyPurchaseOrderNotDeletedWhere($q);
  8740. $rows = $q->field('createtime,dStamp')->limit(5000)->select();
  8741. } catch (\Throwable $e) {
  8742. $rows = [];
  8743. }
  8744. if (!is_array($rows)) {
  8745. $rows = [];
  8746. }
  8747. foreach ($rows as $r) {
  8748. if (!is_array($r)) {
  8749. continue;
  8750. }
  8751. $t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  8752. if ($t === '') {
  8753. $t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
  8754. }
  8755. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  8756. $ymSet[$m[1] . '-' . $m[2]] = true;
  8757. }
  8758. }
  8759. return $this->buildYearMonthSidebar(array_keys($ymSet));
  8760. }
  8761. /**
  8762. * 手工询价可见范围(用于详情/操作校验):
  8763. * 超管、具备「查询询价」权限、需求发起人、通知业务员 → 可见
  8764. * 列表页本身不再按发起人/通知过滤,避免手机端新增后后台看不到。
  8765. */
  8766. protected function applyManualRfqViewerWhere($query): void
  8767. {
  8768. if ($this->auth->isSuperAdmin() || $this->hasProcuremenPerm(['rfqlist'])) {
  8769. return;
  8770. }
  8771. [, $adminName] = $this->GetUseName();
  8772. $adminName = trim((string)$adminName);
  8773. if ($adminName === '') {
  8774. $query->whereRaw('1 = 0');
  8775. return;
  8776. }
  8777. // 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
  8778. $query->where(function ($q) use ($adminName) {
  8779. $q->where('cywyxm', $adminName)
  8780. ->whereOr('notify_salesman', $adminName)
  8781. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  8782. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  8783. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  8784. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  8785. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  8786. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  8787. });
  8788. }
  8789. /**
  8790. * 当前用户是否可查看/操作该手工询价单
  8791. */
  8792. protected function canViewManualRfqOrder(array $po): bool
  8793. {
  8794. if ($this->auth->isSuperAdmin()) {
  8795. return true;
  8796. }
  8797. // 有查询询价权限则可操作全部手工询价(询价/查看报价/通知业务员等)
  8798. if ($this->hasProcuremenPerm(['rfqlist'])) {
  8799. return true;
  8800. }
  8801. [, $adminName] = $this->GetUseName();
  8802. $adminName = trim((string)$adminName);
  8803. if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
  8804. return true;
  8805. }
  8806. if ($adminName !== '') {
  8807. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  8808. if ($n === $adminName) {
  8809. return true;
  8810. }
  8811. }
  8812. }
  8813. return false;
  8814. }
  8815. /**
  8816. * 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
  8817. */
  8818. protected function applyRfqListMonthFilter($query, string $ym): void
  8819. {
  8820. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  8821. $ym = date('Y-m');
  8822. }
  8823. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  8824. // 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
  8825. $query->whereRaw(
  8826. "("
  8827. . "CASE "
  8828. . "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  8829. . "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
  8830. . "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
  8831. . "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  8832. . "THEN TRIM(CAST(createtime AS CHAR(32))) "
  8833. . "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
  8834. . "END"
  8835. . ") LIKE '{$ymEsc}-%'"
  8836. );
  8837. }
  8838. /**
  8839. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  8840. */
  8841. public function rfqlistDetails()
  8842. {
  8843. return $this->details();
  8844. }
  8845. /**
  8846. * 查询询价 — 弹窗:可选通知业务员名单(勾选后确认通知)
  8847. */
  8848. public function rfqnotifysalesmen()
  8849. {
  8850. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman'])) {
  8851. $this->error(__('You have no permission'));
  8852. }
  8853. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8854. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8855. $sid = (int)$this->request->param('scydgy_id', 0);
  8856. if ($sid >= 0) {
  8857. $this->error('仅支持手工新增询价单');
  8858. }
  8859. $po = $this->loadManualRfqOrderForNotify($sid);
  8860. $selectedMap = [];
  8861. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  8862. $selectedMap[$n] = true;
  8863. }
  8864. $list = [];
  8865. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8866. $name = trim((string)($row['name'] ?? ''));
  8867. if ($name === '') {
  8868. continue;
  8869. }
  8870. $email = trim((string)($row['email'] ?? ''));
  8871. $mobile = trim((string)($row['mobile'] ?? ''));
  8872. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  8873. $list[] = [
  8874. 'name' => $name,
  8875. 'email' => $email,
  8876. 'mobile' => $mobile,
  8877. 'can_select' => $hasEmail ? 1 : 0,
  8878. 'checked' => (!empty($selectedMap[$name]) && $hasEmail) ? 1 : 0,
  8879. ];
  8880. }
  8881. $canNotify = $this->canRfqNotifySalesman($po);
  8882. $this->success('', null, [
  8883. 'scydgy_id' => $sid,
  8884. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  8885. 'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
  8886. 'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
  8887. 'can_notify_salesman' => $canNotify ? 1 : 0,
  8888. 'list' => $list,
  8889. ]);
  8890. }
  8891. /**
  8892. * 查询询价 — 补加通知业务员可选名单
  8893. */
  8894. public function rfqsalesmanoptions()
  8895. {
  8896. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen'])) {
  8897. $this->error(__('You have no permission'));
  8898. }
  8899. $out = [];
  8900. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8901. $email = trim((string)($row['email'] ?? ''));
  8902. $mobile = trim((string)($row['mobile'] ?? ''));
  8903. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  8904. $out[] = [
  8905. 'name' => (string)($row['name'] ?? ''),
  8906. 'email' => $email,
  8907. 'mobile' => $mobile,
  8908. 'can_select' => $hasEmail ? 1 : 0,
  8909. ];
  8910. }
  8911. $this->success('', null, ['list' => $out]);
  8912. }
  8913. /**
  8914. * 查询询价 — 补加通知业务员(合并更新 notify_salesman)
  8915. */
  8916. public function rfqappendsalesmen()
  8917. {
  8918. if (!$this->request->isPost()) {
  8919. $this->error(__('Invalid parameters'));
  8920. }
  8921. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen'])) {
  8922. $this->error(__('You have no permission'));
  8923. }
  8924. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8925. $sid = (int)$this->request->post('scydgy_id', 0);
  8926. if ($sid >= 0) {
  8927. $this->error('仅支持手工新增询价单');
  8928. }
  8929. $po = $this->loadManualRfqOrderForNotify($sid);
  8930. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  8931. $this->error('订单已完结,无法添加业务员');
  8932. }
  8933. $raw = $this->request->post('salesmen/a', []);
  8934. if (!is_array($raw) || $raw === []) {
  8935. $salesmenJson = $this->request->post('salesmen_json', '');
  8936. if (is_string($salesmenJson) && $salesmenJson !== '') {
  8937. $decoded = json_decode($salesmenJson, true);
  8938. $raw = is_array($decoded) ? $decoded : [];
  8939. }
  8940. }
  8941. $addNames = [];
  8942. foreach ((array)$raw as $item) {
  8943. if (is_array($item)) {
  8944. $n = trim((string)($item['name'] ?? ''));
  8945. } else {
  8946. $n = trim((string)$item);
  8947. }
  8948. if ($n !== '') {
  8949. $addNames[] = $n;
  8950. }
  8951. }
  8952. $addNames = array_values(array_unique($addNames));
  8953. if ($addNames === []) {
  8954. $this->error('请选择要添加的业务员');
  8955. }
  8956. $allowedOptions = $this->loadRfqSalesmanContactOptions();
  8957. $allowedMap = [];
  8958. foreach ($allowedOptions as $opt) {
  8959. $n = trim((string)($opt['name'] ?? ''));
  8960. if ($n === '') {
  8961. continue;
  8962. }
  8963. $email = trim((string)($opt['email'] ?? ''));
  8964. $allowedMap[$n] = ($email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL));
  8965. }
  8966. foreach ($addNames as $n) {
  8967. if (!array_key_exists($n, $allowedMap)) {
  8968. $this->error('业务员不在可选名单中:' . $n);
  8969. }
  8970. if (!$allowedMap[$n]) {
  8971. $this->error('业务员未填写有效邮箱,无法添加:' . $n);
  8972. }
  8973. }
  8974. $existingRaw = trim((string)($po['notify_salesman'] ?? ''));
  8975. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  8976. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  8977. try {
  8978. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['notify_salesman' => $mergedStr]);
  8979. } catch (\Throwable $e) {
  8980. $this->error('保存失败:' . $e->getMessage());
  8981. }
  8982. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  8983. $this->addOrderLog($sid, 'rfq_append_salesman', '添加通知业务员:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  8984. $this->success('已添加业务员', null, [
  8985. 'scydgy_id' => $sid,
  8986. 'notify_salesman' => $mergedStr,
  8987. 'added_count' => count($addNames),
  8988. ]);
  8989. }
  8990. /**
  8991. * 查询询价 — 勾选业务员后邮箱通知(salesmen_json)
  8992. */
  8993. public function rfqnotifysalesman()
  8994. {
  8995. if (!$this->request->isPost()) {
  8996. $this->error(__('Invalid parameters'));
  8997. }
  8998. if (!$this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen'])) {
  8999. $this->error(__('You have no permission'));
  9000. }
  9001. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9002. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  9003. $sid = (int)$this->request->post('scydgy_id', 0);
  9004. if ($sid >= 0) {
  9005. $this->error('仅支持手工新增询价单');
  9006. }
  9007. $po = $this->loadManualRfqOrderForNotify($sid);
  9008. $this->assertRfqCanNotifySalesman($po);
  9009. $raw = $this->request->post('salesmen/a', []);
  9010. if (!is_array($raw) || $raw === []) {
  9011. $salesmenJson = $this->request->post('salesmen_json', '');
  9012. if (is_string($salesmenJson) && $salesmenJson !== '') {
  9013. $decoded = json_decode($salesmenJson, true);
  9014. $raw = is_array($decoded) ? $decoded : [];
  9015. }
  9016. }
  9017. // 兼容旧参数:notify_all / 单人 name
  9018. if ((!is_array($raw) || $raw === []) && (int)$this->request->post('notify_all', 0) === 1) {
  9019. $raw = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  9020. }
  9021. if ((!is_array($raw) || $raw === [])) {
  9022. $oneName = trim((string)$this->request->post('name', ''));
  9023. if ($oneName !== '') {
  9024. $raw = [$oneName];
  9025. }
  9026. }
  9027. $selectedNames = [];
  9028. foreach ((array)$raw as $item) {
  9029. if (is_array($item)) {
  9030. $n = trim((string)($item['name'] ?? ''));
  9031. } else {
  9032. $n = trim((string)$item);
  9033. }
  9034. if ($n !== '') {
  9035. $selectedNames[] = $n;
  9036. }
  9037. }
  9038. $selectedNames = array_values(array_unique($selectedNames));
  9039. if ($selectedNames === []) {
  9040. $this->error('请选择要通知的业务员');
  9041. }
  9042. $optionMap = [];
  9043. foreach ($this->loadRfqSalesmanContactOptions() as $opt) {
  9044. $n = trim((string)($opt['name'] ?? ''));
  9045. if ($n === '') {
  9046. continue;
  9047. }
  9048. $optionMap[$n] = $opt;
  9049. }
  9050. $targets = [];
  9051. foreach ($selectedNames as $n) {
  9052. if (!isset($optionMap[$n])) {
  9053. $this->error('业务员不在可选名单中:' . $n);
  9054. }
  9055. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  9056. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9057. $this->error('业务员未填写有效邮箱,无法通知:' . $n);
  9058. }
  9059. $resolved = $this->resolveRfqSalesmanContactRows([$n]);
  9060. $targets[] = $resolved[0] ?? [
  9061. 'admin_id' => 0,
  9062. 'name' => $n,
  9063. 'email' => $email,
  9064. ];
  9065. }
  9066. $mergedStr = $this->joinRfqMultiSelectValues($selectedNames);
  9067. try {
  9068. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  9069. 'notify_salesman' => $mergedStr,
  9070. ]);
  9071. } catch (\Throwable $e) {
  9072. $this->error('保存通知业务员失败:' . $e->getMessage());
  9073. }
  9074. $po['notify_salesman'] = $mergedStr;
  9075. $mailConfig = $this->loadMailerConfig();
  9076. if (empty($mailConfig['host'])) {
  9077. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9078. }
  9079. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9080. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9081. }
  9082. $this->ensureRfqSalesmanEmailTemplate();
  9083. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  9084. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  9085. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  9086. $cdw = trim((string)($po['CDW'] ?? ''));
  9087. $qty = trim((string)$this->resolveProcuremenThisQuantity($po));
  9088. $ceiling = trim((string)$this->resolveProcuremenCeilingPrice($po));
  9089. $mbz = trim((string)($po['MBZ'] ?? ''));
  9090. $cywyxm = trim((string)($po['cywyxm'] ?? ''));
  9091. $supplier = trim((string)($po['cGzzxMc'] ?? ''));
  9092. if ($supplier === '') {
  9093. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  9094. }
  9095. $supplierQuotesHtml = $this->buildRfqSalesmanSupplierQuotesHtml($sid, $supplier);
  9096. try {
  9097. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
  9098. } catch (\Throwable $e) {
  9099. $this->error($e->getMessage());
  9100. }
  9101. $okNames = [];
  9102. $failMsgs = [];
  9103. foreach ($targets as $contact) {
  9104. $toEmail = trim((string)($contact['email'] ?? ''));
  9105. $toName = trim((string)($contact['name'] ?? ''));
  9106. $notifyVars = [
  9107. 'contact_name' => $toName,
  9108. 'salesman_name' => $toName,
  9109. 'company_name' => $toName,
  9110. 'email' => $toEmail,
  9111. 'ccydh' => $ccydh,
  9112. 'cyjmc' => $cyjmc,
  9113. 'cgymc' => $cgymc,
  9114. 'cdw' => $cdw,
  9115. 'this_quantity' => $qty,
  9116. 'ceilingPrice' => $ceiling,
  9117. 'MBZ' => $mbz,
  9118. 'supplier_name' => $supplier,
  9119. // 占位符,转 HTML 后再替换成表格,避免被 htmlspecialchars 转义
  9120. 'supplier_quotes' => '__RFQ_SUPPLIER_QUOTES_TABLE__',
  9121. 'cywyxm' => $cywyxm,
  9122. ];
  9123. try {
  9124. $mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
  9125. $mailSubject = $mailSubjectTpl;
  9126. foreach ($notifyVars as $k => $v) {
  9127. if ($k === 'supplier_quotes') {
  9128. continue;
  9129. }
  9130. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  9131. }
  9132. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  9133. $mailSubject = trim((string)$mailSubject);
  9134. if ($mailSubject === '') {
  9135. $mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  9136. }
  9137. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  9138. $mailBody = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', $supplierQuotesHtml, $mailBody);
  9139. $mailPlainForLog = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', strip_tags(str_replace(['</tr>', '</p>'], "\n", $supplierQuotesHtml)), $mailPlain);
  9140. $bundle = [
  9141. 'company_name' => $toName,
  9142. 'email' => $toEmail,
  9143. 'mail_plain' => $mailPlainForLog,
  9144. 'mail_body' => $mailBody,
  9145. 'ccydh' => $ccydh,
  9146. 'email_log_scene' => 'rfq_salesman',
  9147. 'email_log_scydgy_id' => $sid,
  9148. 'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
  9149. 'notify_vars' => $notifyVars,
  9150. ];
  9151. $this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
  9152. $okNames[] = $toName . '(' . $toEmail . ')';
  9153. } catch (\Throwable $e) {
  9154. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  9155. }
  9156. }
  9157. if ($okNames === []) {
  9158. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  9159. }
  9160. $now = date('Y-m-d H:i:s');
  9161. try {
  9162. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  9163. 'rfq_salesman_notified' => 1,
  9164. 'rfq_salesman_notify_time' => $now,
  9165. ]);
  9166. } catch (\Throwable $e) {
  9167. // ignore
  9168. }
  9169. $this->addOrderLog(
  9170. $sid,
  9171. 'rfq_notify_salesman',
  9172. '邮箱通知业务员:' . implode('、', $okNames),
  9173. (int)($po['id'] ?? 0)
  9174. );
  9175. $msg = '已通知 ' . count($okNames) . ' 人';
  9176. if ($failMsgs !== []) {
  9177. $msg .= ';部分失败:' . implode(';', $failMsgs);
  9178. }
  9179. $this->success($msg, null, [
  9180. 'scydgy_id' => $sid,
  9181. 'notify_salesman' => $mergedStr,
  9182. 'rfq_salesman_notified' => 1,
  9183. 'rfq_salesman_notify_time' => $now,
  9184. 'notify_time_text' => $now,
  9185. 'ok_count' => count($okNames),
  9186. 'fail_count' => count($failMsgs),
  9187. ]);
  9188. }
  9189. /**
  9190. * 查询询价 — 下发前:返回将通知的供应商表格数据
  9191. */
  9192. public function rfqissuesuppliers()
  9193. {
  9194. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers'])) {
  9195. $this->error(__('You have no permission'));
  9196. }
  9197. $sid = (int)$this->request->param('scydgy_id', 0);
  9198. if ($sid >= 0) {
  9199. $this->error('仅支持手工新增询价单');
  9200. }
  9201. $po = $this->loadManualRfqOrderForNotify($sid);
  9202. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9203. if ($supplierRaw === '') {
  9204. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9205. }
  9206. $names = $this->splitRfqSalesmanNames($supplierRaw);
  9207. // 已成功发过询价邮件的供应商(含历史 pick_issue 场景)
  9208. $notifiedMap = [];
  9209. try {
  9210. $this->ensurePurchaseEmailSendLogTableOnce();
  9211. $logRows = Db::table('purchase_email_send_log')
  9212. ->where('scydgy_id', $sid)
  9213. ->where('status', 1)
  9214. ->where('scene', 'in', ['rfq_supplier', 'pick_issue'])
  9215. ->field('company_name')
  9216. ->select();
  9217. if (is_array($logRows)) {
  9218. foreach ($logRows as $lr) {
  9219. if (!is_array($lr)) {
  9220. continue;
  9221. }
  9222. $cn = trim((string)($lr['company_name'] ?? ''));
  9223. if ($cn !== '') {
  9224. $notifiedMap[$cn] = true;
  9225. }
  9226. }
  9227. }
  9228. } catch (\Throwable $e) {
  9229. }
  9230. // 兼容:明细已生成(曾下发)也视为已通知
  9231. try {
  9232. $detRows = Db::table('purchase_order_detail')
  9233. ->where('scydgy_id', $sid)
  9234. ->field('company_name')
  9235. ->select();
  9236. if (is_array($detRows)) {
  9237. foreach ($detRows as $dr) {
  9238. if (!is_array($dr)) {
  9239. continue;
  9240. }
  9241. $cn = trim((string)($dr['company_name'] ?? ''));
  9242. if ($cn !== '') {
  9243. $notifiedMap[$cn] = true;
  9244. }
  9245. }
  9246. }
  9247. } catch (\Throwable $e) {
  9248. }
  9249. $list = [];
  9250. foreach ($names as $name) {
  9251. // 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
  9252. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9253. $email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
  9254. $phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
  9255. $username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
  9256. $okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
  9257. $notified = !empty($notifiedMap[$name]) ? 1 : 0;
  9258. $list[] = [
  9259. 'name' => $name,
  9260. 'username' => $username,
  9261. 'email' => $email,
  9262. 'phone' => $phone,
  9263. 'can_notify' => $okEmail ? 1 : 0,
  9264. 'found' => is_array($contact) ? 1 : 0,
  9265. 'notified' => $notified,
  9266. 'notify_status_text' => $notified ? '已通知' : '未通知',
  9267. ];
  9268. }
  9269. $this->success('', null, [
  9270. 'scydgy_id' => $sid,
  9271. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9272. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9273. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9274. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9275. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9276. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9277. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9278. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9279. 'list' => $list,
  9280. ]);
  9281. }
  9282. /**
  9283. * 查询询价 — 补加供应商可选名单
  9284. */
  9285. public function rfqsupplieroptions()
  9286. {
  9287. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
  9288. $this->error(__('You have no permission'));
  9289. }
  9290. $names = array_values($this->loadRfqSupplierNameOptions());
  9291. $out = [];
  9292. foreach ($names as $name) {
  9293. $out[] = ['name' => $name];
  9294. }
  9295. $this->success('', null, ['list' => $out]);
  9296. }
  9297. /**
  9298. * 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
  9299. */
  9300. public function rfqappendsuppliers()
  9301. {
  9302. if (!$this->request->isPost()) {
  9303. $this->error(__('Invalid parameters'));
  9304. }
  9305. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers'])) {
  9306. $this->error(__('You have no permission'));
  9307. }
  9308. $sid = (int)$this->request->post('scydgy_id', 0);
  9309. if ($sid >= 0) {
  9310. $this->error('仅支持手工新增询价单');
  9311. }
  9312. $po = $this->loadManualRfqOrderForNotify($sid);
  9313. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9314. $this->error('订单已完结,无法补加供应商');
  9315. }
  9316. $raw = $this->request->post('suppliers/a', []);
  9317. if (!is_array($raw) || $raw === []) {
  9318. $suppliersJson = $this->request->post('suppliers_json', '');
  9319. if (is_string($suppliersJson) && $suppliersJson !== '') {
  9320. $decoded = json_decode($suppliersJson, true);
  9321. $raw = is_array($decoded) ? $decoded : [];
  9322. }
  9323. }
  9324. $addNames = [];
  9325. foreach ((array)$raw as $item) {
  9326. if (is_array($item)) {
  9327. $n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
  9328. } else {
  9329. $n = trim((string)$item);
  9330. }
  9331. if ($n !== '') {
  9332. $addNames[] = $n;
  9333. }
  9334. }
  9335. $addNames = array_values(array_unique($addNames));
  9336. if ($addNames === []) {
  9337. $this->error('请选择要补加的供应商');
  9338. }
  9339. $existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9340. if ($existingRaw === '') {
  9341. $existingRaw = trim((string)($po['pick_company_name'] ?? ''));
  9342. }
  9343. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9344. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9345. try {
  9346. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
  9347. } catch (\Throwable $e) {
  9348. $this->error('保存失败:' . $e->getMessage());
  9349. }
  9350. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9351. $this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9352. $this->success('已补加供应商', null, [
  9353. 'scydgy_id' => $sid,
  9354. 'cGzzxMc' => $mergedStr,
  9355. 'added_count' => count($addNames),
  9356. ]);
  9357. }
  9358. /**
  9359. * 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
  9360. */
  9361. public function rfqissue()
  9362. {
  9363. if (!$this->request->isPost()) {
  9364. $this->error(__('Invalid parameters'));
  9365. }
  9366. if (!$this->hasProcuremenPerm(['rfqissue'])) {
  9367. $this->error(__('You have no permission'));
  9368. }
  9369. $this->ensureRfqSupplierEmailTemplate();
  9370. $sid = (int)$this->request->post('scydgy_id', 0);
  9371. if ($sid >= 0) {
  9372. $this->error('仅支持手工新增询价单');
  9373. }
  9374. $po = $this->loadManualRfqOrderForNotify($sid);
  9375. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9376. $this->error('订单已完结,无法下发');
  9377. }
  9378. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9379. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9380. $this->error('订单已进入后续流程,无法再下发');
  9381. }
  9382. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9383. if ($supplierRaw === '') {
  9384. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9385. }
  9386. $supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
  9387. if ($supplierNames === []) {
  9388. $this->error('请先在新增询价时选择供应商');
  9389. }
  9390. $companies = [];
  9391. $missing = [];
  9392. $noEmail = [];
  9393. foreach ($supplierNames as $name) {
  9394. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9395. if ($contact === null) {
  9396. $missing[] = $name;
  9397. continue;
  9398. }
  9399. $em = trim((string)($contact['email'] ?? ''));
  9400. if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
  9401. $noEmail[] = $name;
  9402. continue;
  9403. }
  9404. $companies[] = $contact;
  9405. }
  9406. if ($missing !== []) {
  9407. $this->error('未找到供应商档案:' . implode('、', $missing));
  9408. }
  9409. if ($noEmail !== []) {
  9410. $this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
  9411. }
  9412. if ($companies === []) {
  9413. $this->error('没有可通知的供应商');
  9414. }
  9415. $mailConfig = $this->loadMailerConfig();
  9416. if (empty($mailConfig['host'])) {
  9417. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9418. }
  9419. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9420. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9421. }
  9422. $mergeRow = $po;
  9423. $mergeRow['ID'] = $sid;
  9424. $mergeRow['id'] = $sid;
  9425. $mergeRows = [$mergeRow];
  9426. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9427. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9428. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9429. }
  9430. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9431. $issueTime = date('Y-m-d H:i:s');
  9432. $nameLabels = [];
  9433. foreach ($companies as $c) {
  9434. $nameLabels[] = trim((string)($c['name'] ?? ''));
  9435. }
  9436. $logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
  9437. Db::startTrans();
  9438. try {
  9439. $this->upsertPurchaseOrderFromRow(
  9440. $mergeRow,
  9441. $sysRqDb,
  9442. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9443. $issueTime,
  9444. $po,
  9445. null,
  9446. $scoreRule
  9447. );
  9448. foreach ($companies as $c) {
  9449. $this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
  9450. }
  9451. Db::commit();
  9452. } catch (\Throwable $e) {
  9453. Db::rollback();
  9454. $this->error($e->getMessage());
  9455. }
  9456. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9457. if ($poId <= 0) {
  9458. try {
  9459. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9460. } catch (\Throwable $e) {
  9461. $poId = 0;
  9462. }
  9463. }
  9464. $this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
  9465. $posNotify = [];
  9466. try {
  9467. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9468. if (is_array($fresh)) {
  9469. $fresh['sys_rq'] = $sysRqDb;
  9470. $posNotify = [$fresh];
  9471. }
  9472. } catch (\Throwable $e) {
  9473. $posNotify = [$po];
  9474. $posNotify[0]['sys_rq'] = $sysRqDb;
  9475. }
  9476. $notifyBundle = [
  9477. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9478. 'pos' => $posNotify,
  9479. 'merge_rows' => $mergeRows,
  9480. ];
  9481. $notifyErrors = [];
  9482. foreach ($companies as $c) {
  9483. $cname = trim((string)($c['name'] ?? ''));
  9484. try {
  9485. // 询价下发:仅邮箱通知供应商
  9486. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  9487. } catch (\Throwable $e) {
  9488. $notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
  9489. }
  9490. }
  9491. if ($notifyErrors !== []) {
  9492. $this->error('下发已保存,但邮件通知失败:' . implode(';', $notifyErrors));
  9493. }
  9494. $this->success('已询价并邮件通知供应商', null, [
  9495. 'scydgy_id' => $sid,
  9496. 'progress_text' => '待报价',
  9497. 'supplier_count' => count($companies),
  9498. ]);
  9499. }
  9500. /**
  9501. * 查询询价 — 弹窗内向单个供应商发送询价邮件
  9502. */
  9503. public function rfqissuesendmail()
  9504. {
  9505. if (!$this->request->isPost()) {
  9506. $this->error(__('Invalid parameters'));
  9507. }
  9508. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail'])) {
  9509. $this->error(__('You have no permission'));
  9510. }
  9511. $this->ensureRfqSupplierEmailTemplate();
  9512. $sid = (int)$this->request->post('scydgy_id', 0);
  9513. $companyName = trim((string)$this->request->post('company_name', ''));
  9514. if ($sid >= 0) {
  9515. $this->error('仅支持手工新增询价单');
  9516. }
  9517. if ($companyName === '') {
  9518. $this->error('请选择供应商');
  9519. }
  9520. $po = $this->loadManualRfqOrderForNotify($sid);
  9521. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9522. $this->error('订单已完结,无法发送');
  9523. }
  9524. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9525. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9526. $this->error('订单已进入后续流程,无法再发送');
  9527. }
  9528. $contact = $this->resolveCustomerContactByCompanyName($companyName, false);
  9529. if ($contact === null) {
  9530. $this->error('未找到供应商档案:' . $companyName);
  9531. }
  9532. $email = trim((string)($contact['email'] ?? ''));
  9533. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9534. $this->error('该供应商未填写有效邮箱');
  9535. }
  9536. $mailConfig = $this->loadMailerConfig();
  9537. if (empty($mailConfig['host'])) {
  9538. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9539. }
  9540. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9541. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9542. }
  9543. $mergeRow = $po;
  9544. $mergeRow['ID'] = $sid;
  9545. $mergeRow['id'] = $sid;
  9546. $mergeRows = [$mergeRow];
  9547. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9548. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9549. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9550. }
  9551. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9552. $issueTime = date('Y-m-d H:i:s');
  9553. Db::startTrans();
  9554. try {
  9555. $this->upsertPurchaseOrderFromRow(
  9556. $mergeRow,
  9557. $sysRqDb,
  9558. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9559. $issueTime,
  9560. $po,
  9561. null,
  9562. $scoreRule
  9563. );
  9564. $this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
  9565. Db::commit();
  9566. } catch (\Throwable $e) {
  9567. Db::rollback();
  9568. $this->error($e->getMessage());
  9569. }
  9570. $posNotify = [];
  9571. try {
  9572. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9573. if (is_array($fresh)) {
  9574. $fresh['sys_rq'] = $sysRqDb;
  9575. $posNotify = [$fresh];
  9576. }
  9577. } catch (\Throwable $e) {
  9578. $posNotify = [$po];
  9579. $posNotify[0]['sys_rq'] = $sysRqDb;
  9580. }
  9581. $notifyBundle = [
  9582. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9583. 'pos' => $posNotify,
  9584. 'merge_rows' => $mergeRows,
  9585. ];
  9586. try {
  9587. $this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  9588. } catch (\Throwable $e) {
  9589. $this->error('明细已保存,但邮件发送失败:' . $e->getMessage());
  9590. }
  9591. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9592. if ($poId <= 0) {
  9593. try {
  9594. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9595. } catch (\Throwable $e) {
  9596. $poId = 0;
  9597. }
  9598. }
  9599. $this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
  9600. $this->success('已向「' . $companyName . '」发送询价邮件', null, [
  9601. 'scydgy_id' => $sid,
  9602. 'company_name' => $companyName,
  9603. ]);
  9604. }
  9605. /**
  9606. * 查询询价 — 查看各供应商报价(单价)
  9607. */
  9608. public function rfqquotes()
  9609. {
  9610. if (!$this->hasProcuremenPerm(['rfqquotes', 'rfqissue'])) {
  9611. $this->error(__('You have no permission'));
  9612. }
  9613. $sid = (int)$this->request->param('scydgy_id', 0);
  9614. if ($sid >= 0) {
  9615. $this->error('仅支持手工新增询价单');
  9616. }
  9617. $po = $this->loadManualRfqOrderForNotify($sid);
  9618. $rows = [];
  9619. try {
  9620. // 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
  9621. $q = Db::table('purchase_order_detail')
  9622. ->where('scydgy_id', $sid)
  9623. ->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
  9624. ->order('id', 'asc');
  9625. $this->applyActivePurchaseOrderDetailWhere($q);
  9626. $rows = $q->select();
  9627. } catch (\Throwable $e) {
  9628. try {
  9629. $q = Db::table('purchase_order_detail')
  9630. ->where('scydgy_id', $sid)
  9631. ->order('id', 'asc');
  9632. $this->applyActivePurchaseOrderDetailWhere($q);
  9633. $rows = $q->select();
  9634. } catch (\Throwable $e2) {
  9635. $rows = [];
  9636. }
  9637. }
  9638. if (!is_array($rows)) {
  9639. $rows = [];
  9640. }
  9641. $list = [];
  9642. foreach ($rows as $row) {
  9643. if (!is_array($row)) {
  9644. continue;
  9645. }
  9646. $amount = trim((string)($row['amount'] ?? ''));
  9647. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  9648. // 未报价不显示时间(createtime 是下发时间,不是报价时间)
  9649. $oper = '';
  9650. if ($isQuoted) {
  9651. $oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
  9652. if ($oper === '') {
  9653. $oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  9654. }
  9655. }
  9656. $list[] = [
  9657. 'id' => (int)($row['id'] ?? 0),
  9658. 'company_name' => trim((string)($row['company_name'] ?? '')),
  9659. 'amount' => $amount,
  9660. 'amount_text' => $isQuoted ? $amount : '',
  9661. 'is_quoted' => $isQuoted,
  9662. 'quote_label' => $isQuoted ? '已报价' : '未报价',
  9663. 'status_name' => trim((string)($row['status_name'] ?? '')),
  9664. 'oper_time' => $oper,
  9665. ];
  9666. }
  9667. $this->success('', null, [
  9668. 'scydgy_id' => $sid,
  9669. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9670. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9671. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9672. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9673. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9674. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9675. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9676. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9677. 'list' => $list,
  9678. ]);
  9679. }
  9680. /**
  9681. * 手工询价是否已下发(有下发明细或已进入待确认及之后)
  9682. */
  9683. protected function isRfqOrderIssued(array $po): bool
  9684. {
  9685. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  9686. return true;
  9687. }
  9688. $sid = (int)($po['scydgy_id'] ?? 0);
  9689. if ($sid >= 0) {
  9690. return false;
  9691. }
  9692. try {
  9693. $q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  9694. $this->applyActivePurchaseOrderDetailWhere($q);
  9695. return (int)$q->count() > 0;
  9696. } catch (\Throwable $e) {
  9697. return false;
  9698. }
  9699. }
  9700. /**
  9701. * 批量:已有下发明细的手工询价 scydgy_id
  9702. *
  9703. * @param int[] $scydgyIds
  9704. * @return array<int, bool>
  9705. */
  9706. protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
  9707. {
  9708. $set = [];
  9709. $ids = [];
  9710. foreach ($scydgyIds as $sid) {
  9711. $sid = (int)$sid;
  9712. if ($sid < 0) {
  9713. $ids[$sid] = true;
  9714. }
  9715. }
  9716. if ($ids === []) {
  9717. return $set;
  9718. }
  9719. try {
  9720. $q = Db::table('purchase_order_detail')
  9721. ->where('scydgy_id', 'in', array_keys($ids))
  9722. ->field('scydgy_id');
  9723. $this->applyActivePurchaseOrderDetailWhere($q);
  9724. $rows = $q->select();
  9725. } catch (\Throwable $e) {
  9726. return $set;
  9727. }
  9728. if (!is_array($rows)) {
  9729. return $set;
  9730. }
  9731. foreach ($rows as $row) {
  9732. if (!is_array($row)) {
  9733. continue;
  9734. }
  9735. $sid = (int)($row['scydgy_id'] ?? 0);
  9736. if ($sid < 0) {
  9737. $set[$sid] = true;
  9738. }
  9739. }
  9740. return $set;
  9741. }
  9742. /**
  9743. * 批量:已填单价(已报价)的手工询价 scydgy_id
  9744. *
  9745. * @param int[] $scydgyIds
  9746. * @return array<int, bool>
  9747. */
  9748. protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
  9749. {
  9750. $set = [];
  9751. $ids = [];
  9752. foreach ($scydgyIds as $sid) {
  9753. $sid = (int)$sid;
  9754. if ($sid < 0) {
  9755. $ids[$sid] = true;
  9756. }
  9757. }
  9758. if ($ids === []) {
  9759. return $set;
  9760. }
  9761. try {
  9762. $q = Db::table('purchase_order_detail')
  9763. ->where('scydgy_id', 'in', array_keys($ids))
  9764. ->field('scydgy_id,amount');
  9765. $this->applyActivePurchaseOrderDetailWhere($q);
  9766. $rows = $q->select();
  9767. } catch (\Throwable $e) {
  9768. return $set;
  9769. }
  9770. if (!is_array($rows)) {
  9771. return $set;
  9772. }
  9773. foreach ($rows as $row) {
  9774. if (!is_array($row)) {
  9775. continue;
  9776. }
  9777. $amount = trim((string)($row['amount'] ?? ''));
  9778. if ($amount === '' || $amount === '0' || $amount === '0.00') {
  9779. continue;
  9780. }
  9781. $sid = (int)($row['scydgy_id'] ?? 0);
  9782. if ($sid < 0) {
  9783. $set[$sid] = true;
  9784. }
  9785. }
  9786. return $set;
  9787. }
  9788. /**
  9789. * 已下发且至少一家供应商已报价,才允许通知业务员
  9790. */
  9791. protected function canRfqNotifySalesman(array $po): bool
  9792. {
  9793. if (!$this->isRfqOrderIssued($po)) {
  9794. return false;
  9795. }
  9796. $sid = (int)($po['scydgy_id'] ?? 0);
  9797. if ($sid >= 0) {
  9798. return false;
  9799. }
  9800. $quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
  9801. return isset($quoted[$sid]);
  9802. }
  9803. protected function assertRfqCanNotifySalesman(array $po): void
  9804. {
  9805. if (!$this->isRfqOrderIssued($po)) {
  9806. $this->error('请先询价并等待供应商报价后再通知业务员');
  9807. }
  9808. if (!$this->canRfqNotifySalesman($po)) {
  9809. $this->error('供应商尚未报价,暂不能通知业务员');
  9810. }
  9811. }
  9812. /**
  9813. * 加载手工询价单(含可见性校验)
  9814. *
  9815. * @return array<string, mixed>
  9816. */
  9817. protected function loadManualRfqOrderForNotify(int $scydgyId): array
  9818. {
  9819. try {
  9820. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  9821. } catch (\Throwable $e) {
  9822. $po = null;
  9823. }
  9824. if (!is_array($po)) {
  9825. $this->error('订单不存在');
  9826. }
  9827. $modRq = trim((string)($po['mod_rq'] ?? ''));
  9828. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  9829. $this->error('订单不存在');
  9830. }
  9831. if ($this->auth->isSuperAdmin()) {
  9832. return $po;
  9833. }
  9834. if ($this->canViewManualRfqOrder($po)) {
  9835. return $po;
  9836. }
  9837. $this->error('无权操作该订单');
  9838. }
  9839. /**
  9840. * @return string[]
  9841. */
  9842. protected function splitRfqSalesmanNames(string $raw): array
  9843. {
  9844. $parts = [];
  9845. $raw = trim($raw);
  9846. if ($raw === '') {
  9847. return [];
  9848. }
  9849. foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
  9850. $v = trim((string)$piece);
  9851. if ($v !== '' && !in_array($v, $parts, true)) {
  9852. $parts[] = $v;
  9853. }
  9854. }
  9855. return $parts;
  9856. }
  9857. /**
  9858. * 按姓名匹配 fa_admin 邮箱
  9859. *
  9860. * @param string[] $names
  9861. * @return array<int, array{admin_id:int,name:string,email:string}>
  9862. */
  9863. protected function resolveRfqSalesmanContactRows(array $names): array
  9864. {
  9865. $out = [];
  9866. foreach ($names as $name) {
  9867. $name = trim((string)$name);
  9868. if ($name === '') {
  9869. continue;
  9870. }
  9871. $adminId = 0;
  9872. $email = '';
  9873. try {
  9874. $row = Db::name('admin')
  9875. ->where(function ($q) use ($name) {
  9876. $q->where('nickname', $name)->whereOr('username', $name);
  9877. })
  9878. ->where('status', 'normal')
  9879. ->order('id', 'asc')
  9880. ->field('id,nickname,username,email')
  9881. ->find();
  9882. } catch (\Throwable $e) {
  9883. $row = null;
  9884. }
  9885. if (is_array($row)) {
  9886. $adminId = (int)($row['id'] ?? 0);
  9887. $email = trim((string)($row['email'] ?? ''));
  9888. $disp = trim((string)($row['nickname'] ?? ''));
  9889. if ($disp === '') {
  9890. $disp = trim((string)($row['username'] ?? ''));
  9891. }
  9892. if ($disp !== '') {
  9893. $name = $disp;
  9894. }
  9895. }
  9896. $out[] = [
  9897. 'admin_id' => $adminId,
  9898. 'name' => $name,
  9899. 'email' => $email,
  9900. ];
  9901. }
  9902. return $out;
  9903. }
  9904. /**
  9905. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  9906. */
  9907. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  9908. {
  9909. if ($scydgyId >= 0) {
  9910. return;
  9911. }
  9912. try {
  9913. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  9914. } catch (\Throwable $e) {
  9915. $po = null;
  9916. }
  9917. if (!is_array($po)) {
  9918. $this->error('订单不存在');
  9919. }
  9920. $modRq = trim((string)($po['mod_rq'] ?? ''));
  9921. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  9922. $this->error('订单不存在');
  9923. }
  9924. if ($this->auth->isSuperAdmin()) {
  9925. return;
  9926. }
  9927. [, $adminName] = $this->GetUseName();
  9928. $cywy = trim((string)($po['cywyxm'] ?? ''));
  9929. if ($cywy !== '' && $cywy === $adminName) {
  9930. return;
  9931. }
  9932. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  9933. try {
  9934. if ($this->auth->check($rule)) {
  9935. return;
  9936. }
  9937. } catch (\Throwable $e) {
  9938. }
  9939. }
  9940. $this->error('无权查看该订单');
  9941. }
  9942. /**
  9943. * 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
  9944. */
  9945. protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
  9946. {
  9947. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  9948. return ProcuremenStatus::PO_COMPLETED;
  9949. }
  9950. $sid = (int)($row['scydgy_id'] ?? 0);
  9951. if ($sid < 0) {
  9952. if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
  9953. return '已通知业务员';
  9954. }
  9955. if ($hasQuoted) {
  9956. return '供应商已报价';
  9957. }
  9958. if ($hasIssued
  9959. || ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
  9960. || ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
  9961. return '待报价';
  9962. }
  9963. try {
  9964. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  9965. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  9966. if ((int)$detCntQuery->count() > 0) {
  9967. return '待报价';
  9968. }
  9969. } catch (\Throwable $e) {
  9970. }
  9971. return '待询价';
  9972. }
  9973. if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
  9974. return '待入库评分';
  9975. }
  9976. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  9977. return '待采购确认';
  9978. }
  9979. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  9980. return '待确认供应商';
  9981. }
  9982. return '待协助下发';
  9983. }
  9984. /**
  9985. * 协助初选列表 — 批量软删除
  9986. */
  9987. public function pickDelete()
  9988. {
  9989. if (!$this->request->isPost() || !$this->request->isAjax()) {
  9990. $this->error(__('Invalid parameters'));
  9991. }
  9992. if (!$this->procuremenCanPickDelete()) {
  9993. $this->error(__('You have no permission'));
  9994. }
  9995. $rowsRaw = $this->request->post('rows_json', '[]');
  9996. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  9997. if (!is_array($rows) || $rows === []) {
  9998. $this->error('请至少勾选一条工序');
  9999. }
  10000. $done = 0;
  10001. Db::startTrans();
  10002. try {
  10003. foreach ($rows as $row) {
  10004. if (!is_array($row)) {
  10005. continue;
  10006. }
  10007. $this->softDeleteProcuremenPickRow($row);
  10008. $done++;
  10009. }
  10010. if ($done < 1) {
  10011. throw new \Exception('没有可删除的工序');
  10012. }
  10013. Db::commit();
  10014. } catch (\InvalidArgumentException $e) {
  10015. Db::rollback();
  10016. $this->error($e->getMessage());
  10017. } catch (\Throwable $e) {
  10018. Db::rollback();
  10019. $this->error($e->getMessage());
  10020. }
  10021. $this->pickHiddenScydgySetCache = null;
  10022. $this->success('已删除 ' . $done . ' 条工序');
  10023. }
  10024. /**
  10025. * 下发 — 手工新增工序(弹窗)
  10026. */
  10027. public function pickAdd()
  10028. {
  10029. if ($this->request->isPost()) {
  10030. $params = $this->request->post('row/a');
  10031. if (!is_array($params)) {
  10032. $this->error(__('Parameter %s can not be empty', ''));
  10033. }
  10034. try {
  10035. $sid = $this->saveManualPickOrder($params);
  10036. } catch (\InvalidArgumentException $e) {
  10037. $this->error($e->getMessage());
  10038. } catch (\Throwable $e) {
  10039. $this->error($e->getMessage());
  10040. }
  10041. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  10042. }
  10043. return $this->view->fetch('procuremen/pick_add');
  10044. }
  10045. /**
  10046. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  10047. */
  10048. public function pickSubmit()
  10049. {
  10050. if (!$this->request->isPost()) {
  10051. $this->error(__('Invalid parameters'));
  10052. }
  10053. // ---------- 接口订单数据 ----------
  10054. $rowJson = $this->request->post('row_json', '');
  10055. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  10056. $companiesJson = $this->request->post('companies_json', '[]');
  10057. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  10058. $companies = json_decode($companiesJson, true);
  10059. if (!is_array($companies)) {
  10060. $this->error('供应商数据无效');
  10061. }
  10062. $issueCompanies = $this->normalizePickCompanies($companies);
  10063. if ($issueCompanies === []) {
  10064. $this->error('请至少选择一家合作供应商');
  10065. }
  10066. $issueNameLabels = [];
  10067. foreach ($issueCompanies as $pc) {
  10068. $issueNameLabels[] = $pc['name'];
  10069. }
  10070. $issueNamesSummary = implode('、', $issueNameLabels);
  10071. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  10072. if ($sysRq === '') {
  10073. $this->error('请选择招标截止日期');
  10074. }
  10075. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  10076. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  10077. (string)$this->request->post('delivery_deadline', ''),
  10078. true
  10079. );
  10080. $scoreRuleId = (int)$this->request->post('score_rule_id', 0);
  10081. if ($scoreRuleId <= 0) {
  10082. $this->error('请选择订单类型');
  10083. }
  10084. $scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
  10085. if ((int)($scoreRule['id'] ?? 0) <= 0) {
  10086. $this->error('订单类型无效,请刷新后重选');
  10087. }
  10088. $scoreRuleId = (int)$scoreRule['id'];
  10089. $this->ensurePurchaseOrderScoreRuleIdColumn();
  10090. $isMerge = count($mergeRows) > 1;
  10091. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  10092. $logMsg = '下发' . $procPart
  10093. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  10094. $issueTime = date('Y-m-d H:i:s');
  10095. $logSidList = [];
  10096. foreach ($mergeRows as $row) {
  10097. if (!is_array($row)) {
  10098. continue;
  10099. }
  10100. $sid = $this->extractScydgyRowId($row);
  10101. if ($this->isValidScydgyRowId($sid)) {
  10102. $logSidList[$sid] = true;
  10103. }
  10104. }
  10105. $existingBySid = [];
  10106. if ($logSidList !== []) {
  10107. try {
  10108. $existingRows = Db::table('purchase_order')
  10109. ->where('scydgy_id', 'in', array_keys($logSidList))
  10110. ->select();
  10111. if (is_array($existingRows)) {
  10112. foreach ($existingRows as $poRow) {
  10113. if (!is_array($poRow)) {
  10114. continue;
  10115. }
  10116. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10117. if ($this->isValidScydgyRowId($sid)) {
  10118. $existingBySid[$sid] = $poRow;
  10119. }
  10120. }
  10121. }
  10122. } catch (\Throwable $e) {
  10123. $existingBySid = [];
  10124. }
  10125. }
  10126. Db::startTrans();
  10127. try {
  10128. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  10129. foreach ($mergeRows as $row) {
  10130. if (!is_array($row)) {
  10131. continue;
  10132. }
  10133. $sid = $this->extractScydgyRowId($row);
  10134. $this->upsertPurchaseOrderFromRow(
  10135. $row,
  10136. $sysRqDb,
  10137. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  10138. $issueTime,
  10139. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  10140. $deliveryDeadlineDb,
  10141. $scoreRule
  10142. );
  10143. }
  10144. foreach ($issueCompanies as $c) {
  10145. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10146. }
  10147. Db::commit();
  10148. } catch (\Throwable $e) {
  10149. Db::rollback();
  10150. $this->error($e->getMessage());
  10151. }
  10152. $poIdBySid = [];
  10153. if ($logSidList !== []) {
  10154. try {
  10155. $poIdBySid = Db::table('purchase_order')
  10156. ->where('scydgy_id', 'in', array_keys($logSidList))
  10157. ->column('id', 'scydgy_id');
  10158. } catch (\Throwable $e) {
  10159. $poIdBySid = [];
  10160. }
  10161. }
  10162. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  10163. if ($logSidList !== []) {
  10164. list($adminId, $adminName) = $this->GetUseName();
  10165. $logRows = [];
  10166. $seenLogSid = [];
  10167. foreach ($mergeRows as $row) {
  10168. if (!is_array($row)) {
  10169. continue;
  10170. }
  10171. $ids = $this->extractScydgyRowId($row);
  10172. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  10173. continue;
  10174. }
  10175. $seenLogSid[$ids] = true;
  10176. $poIdLog = null;
  10177. if (isset($poIdBySid[$ids])) {
  10178. $tid = (int)$poIdBySid[$ids];
  10179. $poIdLog = $tid > 0 ? $tid : null;
  10180. }
  10181. $logRows[] = ProcuremenOperLog::buildInsertRow(
  10182. $ids,
  10183. 'issue_submit',
  10184. $logMsg,
  10185. $poIdLog,
  10186. (int)$adminId,
  10187. (string)$adminName
  10188. );
  10189. }
  10190. if ($logRows !== []) {
  10191. try {
  10192. Db::table('purchase_order_oper_log')->insertAll($logRows);
  10193. } catch (\Throwable $e) {
  10194. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  10195. }
  10196. }
  10197. }
  10198. $notifyErrors = [];
  10199. $posNotify = [];
  10200. if ($logSidList !== []) {
  10201. try {
  10202. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  10203. } catch (\Throwable $e) {
  10204. $posNotify = [];
  10205. }
  10206. }
  10207. if (!is_array($posNotify)) {
  10208. $posNotify = [];
  10209. }
  10210. foreach ($posNotify as $i => $prow) {
  10211. if (is_array($posNotify[$i])) {
  10212. $posNotify[$i]['sys_rq'] = $sysRqDb;
  10213. }
  10214. }
  10215. $ccydhPick = '';
  10216. foreach ($mergeRows as $row) {
  10217. if (!is_array($row)) {
  10218. continue;
  10219. }
  10220. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  10221. if ($ccydhPick !== '') {
  10222. break;
  10223. }
  10224. }
  10225. $notifyBundleBase = [
  10226. 'ccydh' => $ccydhPick,
  10227. 'pos' => $posNotify,
  10228. 'merge_rows' => $mergeRows,
  10229. ];
  10230. try {
  10231. $this->notifyDryRunPreview = [];
  10232. foreach ($issueCompanies as $c) {
  10233. if (!is_array($c)) {
  10234. continue;
  10235. }
  10236. $cname = trim((string)($c['name'] ?? ''));
  10237. if ($cname === '') {
  10238. continue;
  10239. }
  10240. try {
  10241. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  10242. } catch (\Throwable $e) {
  10243. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10244. }
  10245. }
  10246. } catch (\Throwable $e) {
  10247. $this->error('通知发送失败:' . $e->getMessage());
  10248. }
  10249. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10250. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  10251. }
  10252. if ($this->isProcuremenNotifyDryRun()) {
  10253. $this->success('【演练模式】已保存并生成通知预览', '', [
  10254. 'notify_dry_run' => true,
  10255. 'notify_preview' => $this->notifyDryRunPreview,
  10256. ]);
  10257. }
  10258. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  10259. }
  10260. /**
  10261. * 确认供应商弹窗
  10262. */
  10263. public function auditIssue()
  10264. {
  10265. $ids = $this->request->param('ids', $this->request->param('id', ''));
  10266. if (is_array($ids)) {
  10267. $ids = isset($ids[0]) ? $ids[0] : '';
  10268. }
  10269. $ids = trim((string)$ids);
  10270. if ($ids === '') {
  10271. $this->error(__('Invalid parameters'));
  10272. }
  10273. if ($this->request->isPost()) {
  10274. $this->error('请使用弹窗内「确认」提交');
  10275. }
  10276. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10277. $pos = $bundle['pos'];
  10278. if ($pos === []) {
  10279. $this->error('该订单不在待确认供应商状态');
  10280. }
  10281. $po = $pos[0];
  10282. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10283. if ($quoteGroups === []) {
  10284. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  10285. }
  10286. $pickedName = '';
  10287. foreach ($pos as $poRow) {
  10288. if (!is_array($poRow)) {
  10289. continue;
  10290. }
  10291. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  10292. if ($pn !== '') {
  10293. $pickedName = $pn;
  10294. break;
  10295. }
  10296. }
  10297. $this->view->assign('po', $po);
  10298. $this->view->assign('scydgyId', $ids);
  10299. $this->view->assign('orderCcydh', $bundle['ccydh']);
  10300. $mergeRows = $bundle['merge_rows'];
  10301. $this->view->assign('processRows', $mergeRows);
  10302. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  10303. $this->view->assign('processCount', count($mergeRows));
  10304. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  10305. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  10306. $this->view->assign('pickedCompanyName', $pickedName);
  10307. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10308. if ($sysRqForView === '') {
  10309. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10310. }
  10311. $this->view->assign('sysRq', $sysRqForView);
  10312. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  10313. if ($deliveryDeadlineForView === '') {
  10314. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10315. }
  10316. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10317. $this->ensurePurchaseOrderManualPickColumns();
  10318. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
  10319. $manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
  10320. $manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
  10321. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  10322. if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
  10323. $pickedName = $manualPickInfo['company'];
  10324. $this->view->assign('pickedCompanyName', $pickedName);
  10325. }
  10326. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  10327. $this->view->assign('manualPicked', $manualPicked);
  10328. $this->view->assign('manualPickReason', $manualPickInfo['reason']);
  10329. $this->view->assign('quoteVisible', $quoteVisible);
  10330. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
  10331. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  10332. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
  10333. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
  10334. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  10335. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  10336. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  10337. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  10338. return $this->view->fetch('procuremen/audit_issue');
  10339. }
  10340. /**
  10341. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  10342. *
  10343. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10344. */
  10345. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  10346. {
  10347. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10348. return false;
  10349. }
  10350. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10351. return false;
  10352. }
  10353. return true;
  10354. }
  10355. /**
  10356. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  10357. *
  10358. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10359. */
  10360. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  10361. {
  10362. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10363. return false;
  10364. }
  10365. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10366. return false;
  10367. }
  10368. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  10369. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  10370. return true;
  10371. }
  10372. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  10373. }
  10374. /**
  10375. * 确认页 — 补加供应商弹窗
  10376. */
  10377. public function auditAppend()
  10378. {
  10379. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  10380. $this->error(__('You have no permission'));
  10381. }
  10382. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  10383. if (is_array($ids)) {
  10384. $ids = isset($ids[0]) ? $ids[0] : '';
  10385. }
  10386. $ids = trim((string)$ids);
  10387. if ($ids === '') {
  10388. $this->error(__('Invalid parameters'));
  10389. }
  10390. if ($this->request->isPost()) {
  10391. $this->error('请使用弹窗内「确认」提交');
  10392. }
  10393. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10394. if (($bundle['pos'] ?? []) === []) {
  10395. $this->error('该订单不在待确认供应商状态');
  10396. }
  10397. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10398. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10399. $this->error('已开标验证,不能再补加供应商');
  10400. }
  10401. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10402. $this->error('已指定供应商,不能再补加供应商');
  10403. }
  10404. $this->error('已经超过了招标截止日期,不可操作');
  10405. }
  10406. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10407. $existingNames = [];
  10408. foreach ($quoteGroups as $g) {
  10409. if (!is_array($g)) {
  10410. continue;
  10411. }
  10412. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  10413. if ($n !== '') {
  10414. $existingNames[$n] = true;
  10415. }
  10416. }
  10417. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  10418. $mergeRows = $bundle['merge_rows'] ?? [];
  10419. $this->view->assign('scydgyId', $ids);
  10420. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  10421. $this->view->assign('po', $po);
  10422. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  10423. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  10424. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  10425. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10426. if ($sysRqForView === '') {
  10427. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10428. }
  10429. $this->view->assign('sysRq', $sysRqForView);
  10430. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  10431. if ($deliveryDeadlineForView === '') {
  10432. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10433. }
  10434. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10435. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  10436. }
  10437. /**
  10438. * 确认页 — 补加供应商提交
  10439. */
  10440. public function auditAppendSubmit()
  10441. {
  10442. if (!$this->request->isPost()) {
  10443. $this->error(__('Invalid parameters'));
  10444. }
  10445. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  10446. $this->error(__('You have no permission'));
  10447. }
  10448. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  10449. if ($ids === '') {
  10450. $this->error(__('Invalid parameters'));
  10451. }
  10452. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10453. if (($bundle['pos'] ?? []) === []) {
  10454. $this->error('该订单不在待确认供应商状态');
  10455. }
  10456. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10457. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10458. $this->error('已开标验证,不能再补加供应商');
  10459. }
  10460. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10461. $this->error('已指定供应商,不能再补加供应商');
  10462. }
  10463. $this->error('已经超过了招标截止日期,不可操作');
  10464. }
  10465. $companiesJson = $this->request->post('companies_json', '[]');
  10466. $companies = json_decode((string)$companiesJson, true);
  10467. if (!is_array($companies)) {
  10468. $this->error('供应商数据无效');
  10469. }
  10470. $issueCompanies = $this->normalizePickCompanies($companies);
  10471. if ($issueCompanies === []) {
  10472. $this->error('请至少选择一家合作供应商');
  10473. }
  10474. $mergeRows = $bundle['merge_rows'] ?? [];
  10475. if (!is_array($mergeRows) || $mergeRows === []) {
  10476. $this->error('未找到工序行,无法补加');
  10477. }
  10478. $existingNames = [];
  10479. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  10480. if (!is_array($g)) {
  10481. continue;
  10482. }
  10483. $n = trim((string)($g['company_name'] ?? ''));
  10484. if ($n !== '') {
  10485. $existingNames[$n] = true;
  10486. }
  10487. }
  10488. $toAdd = [];
  10489. foreach ($issueCompanies as $c) {
  10490. if (!is_array($c)) {
  10491. continue;
  10492. }
  10493. $n = trim((string)($c['name'] ?? ''));
  10494. if ($n === '' || isset($existingNames[$n])) {
  10495. continue;
  10496. }
  10497. $toAdd[] = $c;
  10498. }
  10499. if ($toAdd === []) {
  10500. $this->error('所选供应商均已在本单中,请选择新的供应商');
  10501. }
  10502. $addedNames = [];
  10503. Db::startTrans();
  10504. try {
  10505. foreach ($toAdd as $c) {
  10506. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10507. $addedNames[] = trim((string)($c['name'] ?? ''));
  10508. }
  10509. Db::commit();
  10510. } catch (\Throwable $e) {
  10511. Db::rollback();
  10512. $this->error($e->getMessage());
  10513. }
  10514. $notifyErrors = [];
  10515. $notifyBundleBase = [
  10516. 'ccydh' => $bundle['ccydh'] ?? '',
  10517. 'pos' => $bundle['pos'] ?? [],
  10518. 'merge_rows' => $mergeRows,
  10519. ];
  10520. foreach ($toAdd as $c) {
  10521. if (!is_array($c)) {
  10522. continue;
  10523. }
  10524. $cname = trim((string)($c['name'] ?? ''));
  10525. if ($cname === '') {
  10526. continue;
  10527. }
  10528. try {
  10529. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  10530. } catch (\Throwable $e) {
  10531. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10532. }
  10533. }
  10534. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  10535. $seenLogSid = [];
  10536. foreach ($bundle['pos'] ?? [] as $poRow) {
  10537. if (!is_array($poRow)) {
  10538. continue;
  10539. }
  10540. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10541. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  10542. continue;
  10543. }
  10544. $seenLogSid[$sid] = true;
  10545. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10546. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10547. }
  10548. if ($seenLogSid === []) {
  10549. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  10550. if ($this->isValidScydgyRowId($logSid)) {
  10551. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  10552. }
  10553. }
  10554. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10555. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  10556. }
  10557. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  10558. }
  10559. /**
  10560. * 开标双重验证 — 可选验证人列表
  10561. */
  10562. public function bidOpenUsers()
  10563. {
  10564. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10565. $this->error('无权限');
  10566. }
  10567. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  10568. if ($scydgyId !== '') {
  10569. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10570. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10571. $this->success('已完成开标验证', null, [
  10572. 'verified' => 1,
  10573. 'users' => [],
  10574. ]);
  10575. }
  10576. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10577. $this->error('本单已指定供应商,无需再开标');
  10578. }
  10579. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10580. }
  10581. $this->success('', null, [
  10582. 'verified' => 0,
  10583. 'users' => $this->listBidOpenVerifierCandidates(),
  10584. ]);
  10585. }
  10586. /**
  10587. * 开标双重验证 — 向指定管理员发送短信验证码
  10588. */
  10589. public function bidOpenSendCode()
  10590. {
  10591. if (!$this->request->isPost()) {
  10592. $this->error(__('Invalid parameters'));
  10593. }
  10594. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10595. $this->error('无权限');
  10596. }
  10597. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10598. $adminId = (int)$this->request->post('admin_id', 0);
  10599. if ($scydgyId === '' || $adminId <= 0) {
  10600. $this->error('参数无效');
  10601. }
  10602. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10603. if ($bundle['pos'] === []) {
  10604. $this->error('该订单不在待确认供应商状态');
  10605. }
  10606. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10607. $this->success('已完成开标验证,无需重复发送');
  10608. }
  10609. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10610. $this->error('本单已指定供应商,无需再开标');
  10611. }
  10612. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10613. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10614. if ($ccydh === '') {
  10615. $this->error('订单号无效');
  10616. }
  10617. $admin = $this->loadBidOpenAdminUser($adminId);
  10618. if ($admin === null) {
  10619. $this->error('验证人无效或未绑定手机号');
  10620. }
  10621. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  10622. $cd = max(30, min(120, $cd));
  10623. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  10624. $this->error('发送过于频繁,请稍后再试');
  10625. }
  10626. $code = (string)random_int(100000, 999999);
  10627. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  10628. $ttl = max(60, min(600, $ttl));
  10629. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  10630. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  10631. try {
  10632. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  10633. } catch (\Throwable $e) {
  10634. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  10635. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  10636. $this->error($e->getMessage());
  10637. }
  10638. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  10639. }
  10640. /**
  10641. * 开标双重验证 — 两人验证码校验并记录
  10642. */
  10643. public function bidOpenVerify()
  10644. {
  10645. if (!$this->request->isPost()) {
  10646. $this->error(__('Invalid parameters'));
  10647. }
  10648. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10649. $this->error('无权限');
  10650. }
  10651. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10652. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  10653. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  10654. $code1 = trim((string)$this->request->post('code1', ''));
  10655. $code2 = trim((string)$this->request->post('code2', ''));
  10656. if ($scydgyId === '') {
  10657. $this->error('参数无效');
  10658. }
  10659. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  10660. $this->error('请选择两位验证人');
  10661. }
  10662. if ($verifier1Id === $verifier2Id) {
  10663. $this->error('两位验证人不能相同');
  10664. }
  10665. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  10666. $this->error('请输入6位短信验证码');
  10667. }
  10668. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10669. if ($bundle['pos'] === []) {
  10670. $this->error('该订单不在待确认供应商状态');
  10671. }
  10672. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10673. if ($ccydh === '') {
  10674. $this->error('订单号无效');
  10675. }
  10676. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10677. $this->success('已完成开标验证');
  10678. }
  10679. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10680. $this->error('本单已指定供应商,无需再开标');
  10681. }
  10682. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10683. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  10684. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  10685. if ($verifier1 === null || $verifier2 === null) {
  10686. $this->error('验证人无效或未绑定手机号');
  10687. }
  10688. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  10689. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  10690. }
  10691. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  10692. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  10693. }
  10694. try {
  10695. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  10696. } catch (\Throwable $e) {
  10697. $this->error($e->getMessage());
  10698. }
  10699. $this->success('开标验证成功,可查看供应商报价与交货日期');
  10700. }
  10701. /**
  10702. * 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
  10703. */
  10704. public function auditManualPick()
  10705. {
  10706. if (!$this->request->isPost()) {
  10707. $this->error(__('Invalid parameters'));
  10708. }
  10709. if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
  10710. $this->error('无权限');
  10711. }
  10712. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10713. if ($scydgyId === '') {
  10714. $this->error('参数无效');
  10715. }
  10716. $companyName = trim((string)$this->request->post('selected_company', ''));
  10717. $reason = trim((string)$this->request->post('pick_reason', ''));
  10718. if ($companyName === '') {
  10719. $this->error('请选择一家供应商');
  10720. }
  10721. if ($reason === '') {
  10722. $this->error('请填写选择说明');
  10723. }
  10724. if (mb_strlen($reason) > 500) {
  10725. $this->error('选择说明不能超过500字');
  10726. }
  10727. $this->ensurePurchaseOrderManualPickColumns();
  10728. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10729. $pos = $bundle['pos'];
  10730. if ($pos === []) {
  10731. $this->error('该订单不在待确认供应商状态');
  10732. }
  10733. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10734. $this->error('本单已开标验证,请直接在列表中选定供应商后确认');
  10735. }
  10736. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10737. if ($quoteGroups === []) {
  10738. $this->error('暂无供应商,请确认已完成协助初选通知');
  10739. }
  10740. $matched = null;
  10741. foreach ($quoteGroups as $g) {
  10742. if (!is_array($g)) {
  10743. continue;
  10744. }
  10745. if (trim((string)($g['name'] ?? '')) === $companyName) {
  10746. $matched = $g;
  10747. break;
  10748. }
  10749. }
  10750. if ($matched === null) {
  10751. $this->error('所选供应商不在本单报价列表中');
  10752. }
  10753. $logMsg = '指定供应商:已选定「' . $companyName . '」;说明:' . $reason;
  10754. Db::startTrans();
  10755. try {
  10756. foreach ($pos as $poRow) {
  10757. if (!is_array($poRow)) {
  10758. continue;
  10759. }
  10760. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10761. if (!$this->isValidScydgyRowId($sid)) {
  10762. continue;
  10763. }
  10764. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10765. 'pick_company_name' => $companyName,
  10766. 'manual_pick' => 1,
  10767. 'manual_pick_reason' => $reason,
  10768. ]);
  10769. }
  10770. Db::commit();
  10771. } catch (\Throwable $e) {
  10772. Db::rollback();
  10773. $this->error($e->getMessage());
  10774. }
  10775. foreach ($pos as $poRow) {
  10776. if (!is_array($poRow)) {
  10777. continue;
  10778. }
  10779. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10780. if (!$this->isValidScydgyRowId($sid)) {
  10781. continue;
  10782. }
  10783. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10784. $this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10785. }
  10786. // 自选后可见报价:按本单规则计算评分(与开标后一致)
  10787. try {
  10788. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10789. if ($ccydh !== '') {
  10790. // 重新加载以拿到未掩码报价参与计分
  10791. $bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10792. $groupsFresh = $this->loadAuditSupplierQuoteGroups($bundleFresh);
  10793. ProcuremenSupplierScore::saveForOrder($ccydh, $groupsFresh, date('Y-m'));
  10794. }
  10795. } catch (\Throwable $e) {
  10796. Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
  10797. }
  10798. $this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
  10799. }
  10800. /**
  10801. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  10802. */
  10803. public function auditSubmit()
  10804. {
  10805. if (!$this->request->isPost()) {
  10806. $this->error(__('Invalid parameters'));
  10807. }
  10808. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10809. if ($scydgyId === '') {
  10810. $this->error('参数无效');
  10811. }
  10812. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10813. $pos = $bundle['pos'];
  10814. $mergeRows = $bundle['merge_rows'];
  10815. if ($pos === [] || $mergeRows === []) {
  10816. $this->error('该订单不在待确认供应商状态');
  10817. }
  10818. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10819. if ($quoteGroups === []) {
  10820. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  10821. }
  10822. $companyName = trim((string)$this->request->post('selected_company', ''));
  10823. if ($companyName === '') {
  10824. $this->error('请选择一家供应商');
  10825. }
  10826. $matched = null;
  10827. foreach ($quoteGroups as $g) {
  10828. if (!is_array($g)) {
  10829. continue;
  10830. }
  10831. if (trim((string)($g['name'] ?? '')) === $companyName) {
  10832. $matched = $g;
  10833. break;
  10834. }
  10835. }
  10836. if ($matched === null) {
  10837. $this->error('所选供应商不在本单报价列表中');
  10838. }
  10839. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10840. if ($sysRqDb === '') {
  10841. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  10842. } else {
  10843. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  10844. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  10845. }
  10846. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  10847. $this->error('未到招标截止日期,暂不可确认');
  10848. }
  10849. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
  10850. && !$this->isProcuremenManualPickedForBundle($bundle)
  10851. ) {
  10852. $this->error('请先完成开标双重验证或指定供应商后再确认');
  10853. }
  10854. $procCnt = count($mergeRows);
  10855. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  10856. $logMsg = '确认供应商' . $procPart . ':已选定「' . $companyName . '」';
  10857. Db::startTrans();
  10858. try {
  10859. foreach ($pos as $poRow) {
  10860. if (!is_array($poRow)) {
  10861. continue;
  10862. }
  10863. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10864. if (!$this->isValidScydgyRowId($sid)) {
  10865. continue;
  10866. }
  10867. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10868. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  10869. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  10870. 'pick_company_name' => $companyName,
  10871. 'sys_rq' => $sysRqDb,
  10872. ]);
  10873. }
  10874. Db::commit();
  10875. } catch (\Throwable $e) {
  10876. Db::rollback();
  10877. $this->error($e->getMessage());
  10878. }
  10879. foreach ($pos as $poRow) {
  10880. if (!is_array($poRow)) {
  10881. continue;
  10882. }
  10883. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10884. if (!$this->isValidScydgyRowId($sid)) {
  10885. continue;
  10886. }
  10887. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10888. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10889. }
  10890. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  10891. }
  10892. /**
  10893. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  10894. */
  10895. public function auditResendSms()
  10896. {
  10897. if (!$this->request->isPost()) {
  10898. $this->error(__('Invalid parameters'));
  10899. }
  10900. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10901. if ($scydgyId === '') {
  10902. $this->error('参数无效');
  10903. }
  10904. $loaded = $this->loadAuditResendBundle($scydgyId);
  10905. $mergeRows = $loaded['merge_rows'];
  10906. $bundle = $loaded['bundle'];
  10907. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  10908. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10909. if ($quoteGroups === []) {
  10910. $this->error('暂无可通知的供应商');
  10911. }
  10912. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  10913. $companiesJson = (string)$this->request->post('companies_json', '');
  10914. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  10915. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  10916. }
  10917. /**
  10918. * 确认供应商 — 二次发送邮件(可选单家/批量)
  10919. */
  10920. public function auditResendEmail()
  10921. {
  10922. if (!$this->request->isPost()) {
  10923. $this->error(__('Invalid parameters'));
  10924. }
  10925. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10926. if ($scydgyId === '') {
  10927. $this->error('参数无效');
  10928. }
  10929. $loaded = $this->loadAuditResendBundle($scydgyId);
  10930. $mergeRows = $loaded['merge_rows'];
  10931. $bundle = $loaded['bundle'];
  10932. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  10933. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10934. if ($quoteGroups === []) {
  10935. $this->error('暂无可通知的供应商');
  10936. }
  10937. $companiesJson = (string)$this->request->post('companies_json', '');
  10938. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  10939. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  10940. if ($companiesJson === '' && $selectedCompany === '') {
  10941. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  10942. }
  10943. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  10944. }
  10945. /**
  10946. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  10947. *
  10948. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  10949. * @return array<int, true> 已处理的 scydgy_id 集合
  10950. */
  10951. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  10952. {
  10953. $pos = $bundle['pos'] ?? [];
  10954. if (!is_array($pos) || $pos === []) {
  10955. return [];
  10956. }
  10957. $sids = [];
  10958. $poIdBySid = [];
  10959. foreach ($pos as $poRow) {
  10960. if (!is_array($poRow)) {
  10961. continue;
  10962. }
  10963. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10964. if ($this->isValidScydgyRowId($sid)) {
  10965. $sids[$sid] = true;
  10966. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10967. if ($poId > 0) {
  10968. $poIdBySid[$sid] = $poId;
  10969. }
  10970. }
  10971. }
  10972. if ($sids === []) {
  10973. return [];
  10974. }
  10975. $logMsg = '重新下发';
  10976. $suffix = trim((string)$logSuffix, ',, ');
  10977. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  10978. $logMsg .= ':从历史存证退回协助初选';
  10979. } else {
  10980. $logMsg .= ':退回协助初选';
  10981. }
  10982. Db::table('purchase_order')
  10983. ->where('scydgy_id', 'in', array_keys($sids))
  10984. ->update([
  10985. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  10986. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  10987. 'pick_company_name' => '',
  10988. 'pick_time' => null,
  10989. 'sys_rq' => null,
  10990. 'mod_rq' => null,
  10991. ]);
  10992. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  10993. foreach (array_keys($sids) as $sid) {
  10994. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  10995. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10996. }
  10997. return $sids;
  10998. }
  10999. /**
  11000. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  11001. *
  11002. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  11003. */
  11004. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  11005. {
  11006. $scydgyId = trim($scydgyId);
  11007. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11008. if ($scydgyId === '') {
  11009. return $empty;
  11010. }
  11011. try {
  11012. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  11013. } catch (\Throwable $e) {
  11014. $anchor = null;
  11015. }
  11016. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  11017. return $empty;
  11018. }
  11019. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  11020. if ($ccydh === '') {
  11021. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  11022. }
  11023. try {
  11024. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  11025. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  11026. $pos = $query->order('scydgy_id', 'asc')->select();
  11027. } catch (\Throwable $e) {
  11028. $pos = [$anchor];
  11029. }
  11030. if (!is_array($pos) || $pos === []) {
  11031. $pos = [$anchor];
  11032. }
  11033. return [
  11034. 'ccydh' => $ccydh,
  11035. 'pos' => $pos,
  11036. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  11037. ];
  11038. }
  11039. protected function purchaseOrderRowIsCompleted(array $po): bool
  11040. {
  11041. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11042. }
  11043. /**
  11044. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  11045. *
  11046. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  11047. */
  11048. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  11049. {
  11050. $scydgyId = trim($scydgyId);
  11051. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11052. if ($scydgyId === '') {
  11053. return $empty;
  11054. }
  11055. try {
  11056. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  11057. } catch (\Throwable $e) {
  11058. $anchor = null;
  11059. }
  11060. if (!is_array($anchor)) {
  11061. return $empty;
  11062. }
  11063. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  11064. if ($ccydh === '') {
  11065. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  11066. }
  11067. try {
  11068. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  11069. } catch (\Throwable $e) {
  11070. $pos = [$anchor];
  11071. }
  11072. if (!is_array($pos) || $pos === []) {
  11073. $pos = [$anchor];
  11074. }
  11075. return [
  11076. 'ccydh' => $ccydh,
  11077. 'pos' => $pos,
  11078. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  11079. ];
  11080. }
  11081. /**
  11082. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  11083. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  11084. */
  11085. public function auditAbandon()
  11086. {
  11087. if (!$this->request->isPost()) {
  11088. $this->error(__('Invalid parameters'));
  11089. }
  11090. $anchorIds = [];
  11091. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  11092. if ($batchRaw !== '') {
  11093. $decoded = json_decode($batchRaw, true);
  11094. if (is_array($decoded)) {
  11095. foreach ($decoded as $id) {
  11096. $s = trim((string)$id);
  11097. if ($s !== '') {
  11098. $anchorIds[] = $s;
  11099. }
  11100. }
  11101. }
  11102. }
  11103. if ($anchorIds === []) {
  11104. $single = trim((string)$this->request->post('scydgy_id', ''));
  11105. if ($single !== '') {
  11106. $anchorIds[] = $single;
  11107. }
  11108. }
  11109. if ($anchorIds === []) {
  11110. $this->error('请至少选择一条订单');
  11111. }
  11112. $processedCcydh = [];
  11113. $doneOrders = 0;
  11114. $allSids = [];
  11115. Db::startTrans();
  11116. try {
  11117. foreach ($anchorIds as $anchorId) {
  11118. $fromArchive = false;
  11119. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  11120. if (($bundle['pos'] ?? []) === []) {
  11121. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  11122. $fromArchive = ($bundle['pos'] ?? []) !== [];
  11123. }
  11124. if (($bundle['pos'] ?? []) === []) {
  11125. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  11126. $fromArchive = ($bundle['pos'] ?? []) !== [];
  11127. }
  11128. if (($bundle['pos'] ?? []) === []) {
  11129. continue;
  11130. }
  11131. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11132. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  11133. if (isset($processedCcydh[$dedupeKey])) {
  11134. continue;
  11135. }
  11136. $processedCcydh[$dedupeKey] = true;
  11137. $sids = $fromArchive
  11138. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回协助初选')
  11139. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  11140. if ($sids === []) {
  11141. continue;
  11142. }
  11143. $doneOrders++;
  11144. foreach (array_keys($sids) as $sid) {
  11145. $allSids[(int)$sid] = true;
  11146. }
  11147. }
  11148. if ($doneOrders < 1) {
  11149. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  11150. }
  11151. Db::commit();
  11152. } catch (\Throwable $e) {
  11153. Db::rollback();
  11154. $this->error($e->getMessage());
  11155. }
  11156. $this->pickHiddenScydgySetCache = null;
  11157. $msg = $doneOrders > 1
  11158. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  11159. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  11160. $this->success($msg);
  11161. }
  11162. /**
  11163. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  11164. */
  11165. public function archiveAbandon()
  11166. {
  11167. return $this->auditAbandon();
  11168. }
  11169. /**
  11170. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  11171. */
  11172. public function purchaseApprovalReject()
  11173. {
  11174. if (!$this->request->isPost() || !$this->request->isAjax()) {
  11175. $this->error(__('Invalid parameters'));
  11176. }
  11177. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  11178. $this->error(__('You have no permission'));
  11179. }
  11180. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  11181. $decoded = json_decode($batchRaw, true);
  11182. if (!is_array($decoded) || $decoded === []) {
  11183. $this->error('提交数据无效');
  11184. }
  11185. $done = 0;
  11186. Db::startTrans();
  11187. try {
  11188. foreach ($decoded as $item) {
  11189. if (!is_array($item)) {
  11190. continue;
  11191. }
  11192. $sid = (int)($item['scydgy_id'] ?? 0);
  11193. if (!$this->isValidScydgyRowId($sid)) {
  11194. continue;
  11195. }
  11196. $this->runPurchaseApprovalRejectForSid($sid);
  11197. $done++;
  11198. }
  11199. if ($done < 1) {
  11200. throw new \Exception('所选订单均不在待审批状态');
  11201. }
  11202. Db::commit();
  11203. } catch (\Throwable $e) {
  11204. Db::rollback();
  11205. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  11206. }
  11207. $this->pickHiddenScydgySetCache = null;
  11208. $this->success('已驳回并退回「协助审批下发」');
  11209. }
  11210. /**
  11211. * @throws \Exception
  11212. */
  11213. protected function runPurchaseApprovalRejectForSid(int $sid): void
  11214. {
  11215. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  11216. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  11217. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  11218. $allIds = $this->purchaseOrderDetail($sid);
  11219. if ($allIds === []) {
  11220. throw new \Exception('未找到下发明细');
  11221. }
  11222. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11223. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  11224. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11225. 'pick_company_name' => '',
  11226. ]);
  11227. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  11228. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  11229. $poId = 0;
  11230. try {
  11231. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  11232. if (is_array($po)) {
  11233. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11234. }
  11235. } catch (\Throwable $e) {
  11236. }
  11237. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  11238. }
  11239. /**
  11240. * 审核弹窗(旧入口,POST 已关闭)
  11241. */
  11242. public function review()
  11243. {
  11244. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  11245. $this->error(__('You have no permission'));
  11246. }
  11247. if ($this->request->isPost()) {
  11248. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  11249. }
  11250. $this->view->assign('pickMode', 0);
  11251. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  11252. }
  11253. /**
  11254. * 审核弹窗获取公司列表
  11255. */
  11256. public function reviewCompanies()
  11257. {
  11258. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  11259. $this->error(__('You have no permission'));
  11260. }
  11261. if (!$this->request->isAjax()) {
  11262. $this->error(__('Invalid parameters'));
  11263. }
  11264. $list = [];
  11265. try {
  11266. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  11267. $rows = Db::table('customer')
  11268. ->where(function ($q) {
  11269. $q->where('status', 1)
  11270. ->whereOr('status', '1')
  11271. ->whereOr('status', '')
  11272. ->whereNull('status');
  11273. })
  11274. ->order('id', 'desc')
  11275. ->select();
  11276. } catch (\Throwable $e) {
  11277. $this->success('', '', []);
  11278. return;
  11279. }
  11280. if (!is_array($rows)) {
  11281. $this->success('', '', []);
  11282. return;
  11283. }
  11284. $detailColCandidates = [
  11285. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  11286. 'company_detail', 'company_desc', 'address',
  11287. ];
  11288. foreach ($rows as $row) {
  11289. if (!is_array($row)) {
  11290. continue;
  11291. }
  11292. $norm = [];
  11293. foreach ($row as $k => $v) {
  11294. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  11295. }
  11296. $row = $norm;
  11297. $st = $row['status'] ?? '';
  11298. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  11299. continue;
  11300. }
  11301. $payload = $this->buildCustomerContactPayloadFromRow($row);
  11302. if ($payload === null) {
  11303. continue;
  11304. }
  11305. $detail = '';
  11306. foreach ($detailColCandidates as $dk) {
  11307. if (!isset($row[$dk])) {
  11308. continue;
  11309. }
  11310. $dv = trim((string)$row[$dk]);
  11311. if ($dv !== '') {
  11312. $detail = $dv;
  11313. break;
  11314. }
  11315. }
  11316. $payload['detail'] = $detail;
  11317. $list[] = $this->maskSupplierContactFields($payload);
  11318. }
  11319. $this->success('', '', $list);
  11320. }
  11321. /**
  11322. * 采购确认-下发明细弹窗:
  11323. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  11324. */
  11325. public function outward_detail()
  11326. {
  11327. $ids = $this->request->param('ids', $this->request->param('id', ''));
  11328. if (is_array($ids)) {
  11329. $ids = isset($ids[0]) ? $ids[0] : '';
  11330. }
  11331. $ids = trim((string)$ids);
  11332. if ($ids === '') {
  11333. $this->error(__('Invalid parameters'));
  11334. }
  11335. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  11336. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  11337. $wffTab = 'all';
  11338. }
  11339. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  11340. $purchaseOrderId = 0;
  11341. $po = null;
  11342. try {
  11343. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  11344. if (is_array($po)) {
  11345. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11346. }
  11347. } catch (\Throwable $e) {
  11348. $purchaseOrderId = 0;
  11349. $po = null;
  11350. }
  11351. if (!$isPurchaseConfirm && is_array($po)) {
  11352. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11353. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  11354. $isPurchaseConfirm = true;
  11355. }
  11356. }
  11357. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  11358. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11359. $confirmProcessCount = 1;
  11360. $confirmPickGroups = [];
  11361. $processDisplayRows = [];
  11362. $allDetailsBySid = [];
  11363. $requiredSidList = [];
  11364. $sidList = [$ids];
  11365. if ($isPurchaseConfirm) {
  11366. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  11367. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  11368. if ($mergeRows !== []) {
  11369. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  11370. }
  11371. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  11372. if ($confirmBundle['pos'] !== []) {
  11373. $sidList = [];
  11374. foreach ($confirmBundle['pos'] as $poRow) {
  11375. if (!is_array($poRow)) {
  11376. continue;
  11377. }
  11378. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11379. if (!$this->isValidScydgyRowId($sid)) {
  11380. continue;
  11381. }
  11382. $sidList[] = (string)$sid;
  11383. $requiredSidList[] = $sid;
  11384. }
  11385. }
  11386. if ($sidList === []) {
  11387. $sidList = [$ids];
  11388. $requiredSidList = [(int)$ids];
  11389. }
  11390. $confirmProcessCount = max(1, count($requiredSidList));
  11391. if (is_array($po) && $purchaseOrderId <= 0) {
  11392. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11393. }
  11394. }
  11395. $rows = [];
  11396. try {
  11397. if (count($sidList) === 1) {
  11398. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  11399. } else {
  11400. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  11401. }
  11402. } catch (\Throwable $e) {
  11403. $rows = [];
  11404. }
  11405. if ($isPurchaseConfirm) {
  11406. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  11407. }
  11408. foreach ($rows as &$r) {
  11409. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  11410. $r['id'] = $r['ID'];
  11411. }
  11412. if (isset($r['createtime'])) {
  11413. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  11414. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  11415. } else {
  11416. $r['createtime_text'] = (string)$r['createtime'];
  11417. }
  11418. } else {
  11419. $r['createtime_text'] = '';
  11420. }
  11421. if (is_array($r)) {
  11422. $r = $this->maskSupplierContactFields($r);
  11423. }
  11424. }
  11425. unset($r);
  11426. $pickedCompanyName = '';
  11427. $manualPicked = 0;
  11428. $manualPickReason = '';
  11429. $quoteVisible = 0;
  11430. $bidOpenVerified = 0;
  11431. if ($isPurchaseConfirm) {
  11432. // 确认包为空时,用当前主单兜底,避免指定说明读不到
  11433. if (($confirmBundle['ccydh'] ?? '') === '' && is_array($po)) {
  11434. $confirmBundle['ccydh'] = trim((string)($po['CCYDH'] ?? ''));
  11435. }
  11436. if (($confirmBundle['pos'] ?? []) === [] && is_array($po)) {
  11437. $confirmBundle['pos'] = [$po];
  11438. }
  11439. $manualPickInfo = $this->resolveProcuremenManualPickInfo($confirmBundle);
  11440. $manualPicked = $this->isProcuremenManualPickedForBundle($confirmBundle) ? 1 : 0;
  11441. $manualPickReason = (string)($manualPickInfo['reason'] ?? '');
  11442. if ($manualPickInfo['company'] !== '') {
  11443. $pickedCompanyName = $manualPickInfo['company'];
  11444. }
  11445. if ($pickedCompanyName === '') {
  11446. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  11447. if (!is_array($poRow)) {
  11448. continue;
  11449. }
  11450. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  11451. if ($pn !== '') {
  11452. $pickedCompanyName = $pn;
  11453. break;
  11454. }
  11455. }
  11456. }
  11457. // 再兜底:直接读当前主单字段
  11458. if (is_array($po) && (int)($po['manual_pick'] ?? 0) === 1) {
  11459. $manualPicked = 1;
  11460. if ($manualPickReason === '') {
  11461. $manualPickReason = trim((string)($po['manual_pick_reason'] ?? ''));
  11462. }
  11463. if ($pickedCompanyName === '') {
  11464. $pickedCompanyName = trim((string)($po['pick_company_name'] ?? ''));
  11465. }
  11466. }
  11467. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle) ? 1 : 0;
  11468. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  11469. }
  11470. $this->view->assign('rows', $rows ?: []);
  11471. $this->view->assign('rowCount', count($rows ?: []));
  11472. $this->view->assign('scydgyId', $ids);
  11473. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  11474. $this->view->assign('headTitle', $headTitle);
  11475. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  11476. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  11477. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  11478. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  11479. $this->view->assign('processDisplayRows', $processDisplayRows);
  11480. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  11481. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  11482. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  11483. $this->view->assign('manualPicked', $manualPicked);
  11484. $this->view->assign('manualPickReason', $manualPickReason);
  11485. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  11486. $this->view->assign('quoteVisible', $quoteVisible);
  11487. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
  11488. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  11489. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
  11490. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
  11491. $sysRqDisplay = '—';
  11492. if ($isPurchaseConfirm) {
  11493. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  11494. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  11495. );
  11496. }
  11497. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  11498. $this->view->assign('sysRq', $isPurchaseConfirm
  11499. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  11500. : '');
  11501. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  11502. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  11503. : '');
  11504. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  11505. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  11506. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  11507. if ($isPurchaseConfirm) {
  11508. return $this->view->fetch();
  11509. }
  11510. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  11511. $this->view->engine->layout(false);
  11512. try {
  11513. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  11514. $this->view->assign('dialogBody', $bodyHtml);
  11515. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  11516. } finally {
  11517. if ($restoreLayout) {
  11518. $this->view->engine->layout($restoreLayout);
  11519. }
  11520. }
  11521. }
  11522. /**
  11523. * 月度导出记录表(不存在时自动创建)
  11524. */
  11525. protected function ensurePurchaseMonthExportLogTable(): void
  11526. {
  11527. try {
  11528. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  11529. } catch (\Throwable $e) {
  11530. Db::execute(
  11531. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  11532. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  11533. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  11534. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  11535. `admin_name` varchar(64) NOT NULL DEFAULT '',
  11536. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  11537. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  11538. `createtime` int(10) unsigned DEFAULT NULL,
  11539. PRIMARY KEY (`id`),
  11540. KEY `idx_ym` (`ym`),
  11541. KEY `idx_ct` (`createtime`)
  11542. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  11543. );
  11544. }
  11545. }
  11546. /**
  11547. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  11548. *
  11549. * @param array<int, mixed> $dbRows
  11550. * @return array<int, array<string, mixed>>
  11551. */
  11552. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  11553. {
  11554. $keyword = trim((string)$this->request->get('search', ''));
  11555. if ($keyword === '') {
  11556. $keyword = trim((string)$this->request->request('search', ''));
  11557. }
  11558. $filter = $this->request->get('filter', '');
  11559. $op = $this->request->get('op', '');
  11560. if (is_string($filter) && $filter !== '') {
  11561. $filterArr = (array)json_decode($filter, true);
  11562. } else {
  11563. $filterArr = is_array($filter) ? $filter : [];
  11564. }
  11565. if (is_string($op) && $op !== '') {
  11566. $opArr = (array)json_decode($op, true);
  11567. } else {
  11568. $opArr = is_array($op) ? $op : [];
  11569. }
  11570. if ($keyword === '' && $filterArr === []) {
  11571. return array_values(array_filter($dbRows, 'is_array'));
  11572. }
  11573. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  11574. $out = [];
  11575. foreach ($dbRows as $row) {
  11576. if (!is_array($row)) {
  11577. continue;
  11578. }
  11579. if ($keyword !== '') {
  11580. $hit = false;
  11581. foreach ($searchFields as $f) {
  11582. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  11583. $hit = true;
  11584. break;
  11585. }
  11586. }
  11587. if (!$hit) {
  11588. continue;
  11589. }
  11590. }
  11591. $passFilter = true;
  11592. foreach ($filterArr as $field => $val) {
  11593. $field = (string)$field;
  11594. $val = trim((string)$val);
  11595. if ($field === '' || $val === '') {
  11596. continue;
  11597. }
  11598. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  11599. continue;
  11600. }
  11601. $cell = (string)($row[$field] ?? '');
  11602. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  11603. if ($mode === '=' || $mode === 'EQUAL') {
  11604. if (strcasecmp($cell, $val) !== 0) {
  11605. $passFilter = false;
  11606. break;
  11607. }
  11608. } elseif (mb_stripos($cell, $val) === false) {
  11609. $passFilter = false;
  11610. break;
  11611. }
  11612. }
  11613. if (!$passFilter) {
  11614. continue;
  11615. }
  11616. $out[] = $row;
  11617. }
  11618. return $out;
  11619. }
  11620. /**
  11621. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  11622. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  11623. */
  11624. public function export_month_outward()
  11625. {
  11626. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  11627. $this->error(__('You have no permission'));
  11628. }
  11629. $bundle = $this->prepareMonthOutwardExportBundle();
  11630. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  11631. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  11632. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  11633. $spreadsheet = new Spreadsheet();
  11634. $sheet = $spreadsheet->getActiveSheet();
  11635. $sheet->setTitle('外协加工明细');
  11636. $mon = (int)substr($ym, 5, 2);
  11637. $sheet->mergeCells('A1:H1');
  11638. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  11639. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  11640. $sheet->getStyle('A1')->getAlignment()
  11641. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11642. ->setVertical(Alignment::VERTICAL_CENTER);
  11643. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  11644. $col = 'A';
  11645. foreach ($headers as $h) {
  11646. $sheet->setCellValue($col . '2', $h);
  11647. $col++;
  11648. }
  11649. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  11650. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11651. $rowNum = 3;
  11652. $sumSubtotalCounts = 0;
  11653. $grandAmount = 0.0;
  11654. $globalSeq = 0;
  11655. if ($groups === []) {
  11656. $sheet->mergeCells('A3:H3');
  11657. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  11658. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11659. $rowNum = 4;
  11660. } else {
  11661. foreach ($groups as $items) {
  11662. if ($items === []) {
  11663. continue;
  11664. }
  11665. $groupLineCount = count($items);
  11666. $subAmount = 0.0;
  11667. foreach ($items as $line) {
  11668. $globalSeq++;
  11669. $dr = $line['detail'];
  11670. $amt = $this->procuremenExportAmount($dr);
  11671. $subAmount += $amt;
  11672. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  11673. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  11674. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  11675. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  11676. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  11677. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  11678. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  11679. $sheet->setCellValue('H' . $rowNum, $amt);
  11680. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  11681. $rowNum++;
  11682. }
  11683. $sumSubtotalCounts += $groupLineCount;
  11684. $grandAmount += $subAmount;
  11685. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11686. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  11687. $sheet->getStyle('G' . $rowNum)->getAlignment()
  11688. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  11689. ->setVertical(Alignment::VERTICAL_CENTER);
  11690. $rowNum++;
  11691. }
  11692. }
  11693. $sheet->setCellValue('A' . $rowNum, '总计');
  11694. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  11695. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11696. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  11697. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  11698. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  11699. $lastRow = $rowNum;
  11700. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  11701. 'borders' => [
  11702. 'allBorders' => [
  11703. 'borderStyle' => Border::BORDER_THIN,
  11704. 'color' => ['rgb' => '000000'],
  11705. ],
  11706. ],
  11707. ]);
  11708. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  11709. if ($lastRow >= 3) {
  11710. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11711. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11712. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11713. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11714. }
  11715. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  11716. $sheet->getColumnDimension('A')->setWidth(7);
  11717. $sheet->getColumnDimension('B')->setWidth(16);
  11718. $sheet->getColumnDimension('C')->setWidth(52);
  11719. $sheet->getColumnDimension('D')->setWidth(32);
  11720. $sheet->getColumnDimension('E')->setWidth(12);
  11721. $sheet->getColumnDimension('F')->setWidth(44);
  11722. $sheet->getColumnDimension('G')->setWidth(26);
  11723. $sheet->getColumnDimension('H')->setWidth(13);
  11724. $sheet->getRowDimension(1)->setRowHeight(28);
  11725. $ymCompact = str_replace('-', '', $ym);
  11726. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  11727. $filename = $fileBase . '.xlsx';
  11728. try {
  11729. $this->ensurePurchaseMonthExportLogTable();
  11730. list($adminId, $adminName) = $this->GetUseName();
  11731. Db::table('purchase_month_export_log')->insert([
  11732. 'ym' => $ym,
  11733. 'admin_id' => (int)$adminId,
  11734. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  11735. 'row_count' => count($exportLines),
  11736. 'total_amount' => round($grandAmount, 2),
  11737. 'createtime' => time(),
  11738. ]);
  11739. } catch (\Throwable $e) {
  11740. Log::write('month export log: ' . $e->getMessage(), 'error');
  11741. }
  11742. if (ob_get_length()) {
  11743. ob_end_clean();
  11744. }
  11745. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  11746. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  11747. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  11748. header('Cache-Control: max-age=0');
  11749. $writer = new Xlsx($spreadsheet);
  11750. $writer->save('php://output');
  11751. $spreadsheet->disconnectWorksheets();
  11752. unset($spreadsheet);
  11753. exit;
  11754. }
  11755. /**
  11756. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  11757. */
  11758. public function export_month_quote()
  11759. {
  11760. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  11761. $this->error(__('You have no permission'));
  11762. }
  11763. $bundle = $this->prepareMonthOutwardExportBundle();
  11764. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  11765. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  11766. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  11767. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  11768. $spreadsheet = new Spreadsheet();
  11769. $sheet = $spreadsheet->getActiveSheet();
  11770. $sheet->setTitle('供应商报价明细');
  11771. $mon = (int)substr($ym, 5, 2);
  11772. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  11773. $sheet->getColumnDimension('A')->setWidth(7);
  11774. $sheet->getColumnDimension('B')->setWidth(16);
  11775. $sheet->getColumnDimension('C')->setWidth(52);
  11776. $sheet->getColumnDimension('D')->setWidth(26);
  11777. $sheet->getColumnDimension('E')->setWidth(32);
  11778. $sheet->getColumnDimension('F')->setWidth(12);
  11779. $sheet->getColumnDimension('G')->setWidth(14);
  11780. $sheet->getColumnDimension('H')->setWidth(12);
  11781. if ($quoteLastRow < 1) {
  11782. $quoteLastRow = 3;
  11783. }
  11784. $ymCompact = str_replace('-', '', $ym);
  11785. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  11786. if (ob_get_length()) {
  11787. ob_end_clean();
  11788. }
  11789. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  11790. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  11791. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  11792. header('Cache-Control: max-age=0');
  11793. $writer = new Xlsx($spreadsheet);
  11794. $writer->save('php://output');
  11795. $spreadsheet->disconnectWorksheets();
  11796. unset($spreadsheet);
  11797. exit;
  11798. }
  11799. /**
  11800. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  11801. *
  11802. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  11803. */
  11804. protected function prepareMonthOutwardExportBundle(): array
  11805. {
  11806. $this->request->filter(['strip_tags', 'trim']);
  11807. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  11808. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  11809. $ym = date('Y-m');
  11810. }
  11811. $dbRows = [];
  11812. try {
  11813. $query = Db::table('purchase_order');
  11814. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  11815. $dbRows = $query->select();
  11816. } catch (\Throwable $e) {
  11817. $dbRows = [];
  11818. }
  11819. if (!is_array($dbRows)) {
  11820. $dbRows = [];
  11821. }
  11822. $completeTsMap = [];
  11823. $sidList = [];
  11824. foreach ($dbRows as $dbRow) {
  11825. if (!is_array($dbRow)) {
  11826. continue;
  11827. }
  11828. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  11829. if ($sid > 0) {
  11830. $sidList[$sid] = true;
  11831. }
  11832. }
  11833. if ($sidList !== []) {
  11834. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  11835. }
  11836. $searchKw = trim((string)$this->request->get('search', ''));
  11837. if ($searchKw === '') {
  11838. $searchKw = trim((string)$this->request->request('search', ''));
  11839. }
  11840. $filterRaw = $this->request->get('filter', '');
  11841. $filterArrTmp = [];
  11842. if (is_string($filterRaw) && $filterRaw !== '') {
  11843. $filterArrTmp = (array)json_decode($filterRaw, true);
  11844. } elseif (is_array($filterRaw)) {
  11845. $filterArrTmp = $filterRaw;
  11846. }
  11847. $hasSearch = ($searchKw !== '');
  11848. if (!$hasSearch) {
  11849. foreach ($filterArrTmp as $fv) {
  11850. if (trim((string)$fv) !== '') {
  11851. $hasSearch = true;
  11852. break;
  11853. }
  11854. }
  11855. }
  11856. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap, $hasSearch) {
  11857. if (!is_array($dbRow)) {
  11858. return false;
  11859. }
  11860. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  11861. if ($done['ts'] <= 0) {
  11862. return false;
  11863. }
  11864. if ($hasSearch) {
  11865. return true;
  11866. }
  11867. return date('Y-m', $done['ts']) === $ym;
  11868. }));
  11869. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  11870. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  11871. $mainBySid = [];
  11872. foreach ($pool as $rw) {
  11873. if (!is_array($rw)) {
  11874. continue;
  11875. }
  11876. $rid = (int)($rw['ID'] ?? 0);
  11877. if ($rid > 0) {
  11878. $mainBySid[$rid] = $rw;
  11879. }
  11880. }
  11881. if ($mainBySid === []) {
  11882. $detailRows = [];
  11883. } else {
  11884. try {
  11885. $detailRows = Db::table('purchase_order_detail')
  11886. ->where('scydgy_id', 'in', array_keys($mainBySid))
  11887. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  11888. ->order('status', 'desc')
  11889. ->order('CCYDH', 'asc')
  11890. ->order('company_name', 'asc')
  11891. ->order('id', 'asc')
  11892. ->select();
  11893. } catch (\Throwable $e) {
  11894. try {
  11895. $detailRows = Db::table('purchase_order_detail')
  11896. ->where('scydgy_id', 'in', array_keys($mainBySid))
  11897. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  11898. ->order('status', 'desc')
  11899. ->order('CCYDH', 'asc')
  11900. ->order('company_name', 'asc')
  11901. ->order('ID', 'asc')
  11902. ->select();
  11903. } catch (\Throwable $e2) {
  11904. $detailRows = [];
  11905. }
  11906. }
  11907. }
  11908. if (!is_array($detailRows)) {
  11909. $detailRows = [];
  11910. }
  11911. $exportLines = [];
  11912. $detailSidSeen = [];
  11913. foreach ($detailRows as $dr) {
  11914. if (!is_array($dr)) {
  11915. continue;
  11916. }
  11917. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11918. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  11919. continue;
  11920. }
  11921. if (isset($detailSidSeen[$sid])) {
  11922. continue;
  11923. }
  11924. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  11925. continue;
  11926. }
  11927. $detailSidSeen[$sid] = true;
  11928. $m = $mainBySid[$sid];
  11929. $exportLines[] = [
  11930. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11931. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11932. 'company_name' => (string)($dr['company_name'] ?? ''),
  11933. 'CDF' => (string)($m['CDF'] ?? ''),
  11934. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11935. 'gx' => $this->procuremenExportGxText($m),
  11936. 'detail' => $dr,
  11937. ];
  11938. }
  11939. foreach ($detailRows as $dr) {
  11940. if (!is_array($dr)) {
  11941. continue;
  11942. }
  11943. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11944. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  11945. continue;
  11946. }
  11947. $detailSidSeen[$sid] = true;
  11948. $m = $mainBySid[$sid];
  11949. $exportLines[] = [
  11950. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11951. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11952. 'company_name' => (string)($dr['company_name'] ?? ''),
  11953. 'CDF' => (string)($m['CDF'] ?? ''),
  11954. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11955. 'gx' => $this->procuremenExportGxText($m),
  11956. 'detail' => $dr,
  11957. ];
  11958. }
  11959. foreach ($mainBySid as $sid => $m) {
  11960. if (isset($detailSidSeen[$sid])) {
  11961. continue;
  11962. }
  11963. $company = trim((string)($m['pick_company_name'] ?? ''));
  11964. $exportLines[] = [
  11965. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  11966. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  11967. 'company_name' => $company,
  11968. 'CDF' => (string)($m['CDF'] ?? ''),
  11969. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11970. 'gx' => $this->procuremenExportGxText($m),
  11971. 'detail' => [],
  11972. ];
  11973. }
  11974. $groups = [];
  11975. foreach ($exportLines as $line) {
  11976. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  11977. if (!isset($groups[$k])) {
  11978. $groups[$k] = [];
  11979. }
  11980. $groups[$k][] = $line;
  11981. }
  11982. ksort($groups, SORT_STRING);
  11983. return [
  11984. 'ym' => $ym,
  11985. 'mainBySid' => $mainBySid,
  11986. 'detailRows' => $detailRows,
  11987. 'exportLines' => $exportLines,
  11988. 'groups' => $groups,
  11989. ];
  11990. }
  11991. /**
  11992. * 导出用:工序列文案
  11993. */
  11994. protected function procuremenExportGxText(array $r)
  11995. {
  11996. $a = trim((string)($r['CDXMC'] ?? ''));
  11997. $b = trim((string)($r['CGYMC'] ?? ''));
  11998. if ($a !== '' && $b !== '') {
  11999. return $a . ':' . $b;
  12000. }
  12001. return $a !== '' ? $a : $b;
  12002. }
  12003. /**
  12004. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  12005. */
  12006. protected function procuremenExportAmount(array $r)
  12007. {
  12008. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  12009. if (!array_key_exists($k, $r)) {
  12010. continue;
  12011. }
  12012. $v = $r[$k];
  12013. if ($v === null || $v === '') {
  12014. continue;
  12015. }
  12016. if (is_numeric($v)) {
  12017. return (float)$v;
  12018. }
  12019. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  12020. if ($v !== '' && is_numeric($v)) {
  12021. return (float)$v;
  12022. }
  12023. }
  12024. return 0.0;
  12025. }
  12026. /**
  12027. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  12028. *
  12029. * @param array<int, array<string, mixed>> $detailRows
  12030. * @param array<int, array<string, mixed>> $mainBySid
  12031. * @return array<int, array<string, mixed>>
  12032. */
  12033. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  12034. {
  12035. $lines = [];
  12036. foreach ($detailRows as $dr) {
  12037. if (!is_array($dr)) {
  12038. continue;
  12039. }
  12040. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12041. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  12042. continue;
  12043. }
  12044. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  12045. continue;
  12046. }
  12047. $cn = trim((string)($dr['company_name'] ?? ''));
  12048. if ($cn === '') {
  12049. continue;
  12050. }
  12051. $m = $mainBySid[$sid];
  12052. $am = trim((string)($dr['amount'] ?? ''));
  12053. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  12054. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  12055. $amountText = $amountFilled
  12056. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  12057. : '未填写';
  12058. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  12059. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  12060. if ($deliveryShow === '' && $deliveryRaw !== '') {
  12061. $deliveryShow = $deliveryRaw;
  12062. }
  12063. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  12064. ? $deliveryShow
  12065. : '未填写';
  12066. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  12067. $lines[] = [
  12068. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12069. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12070. 'gx' => $this->procuremenExportGxText($m),
  12071. 'company_name' => $cn,
  12072. 'amount_text' => $amountText,
  12073. 'amount_num' => $amountFilled ? $amountNum : null,
  12074. 'delivery_text' => $deliveryText,
  12075. 'picked_text' => $picked ? '中标' : '未中标',
  12076. 'picked' => $picked,
  12077. ];
  12078. }
  12079. $winnerSupplierByOrder = [];
  12080. foreach ($lines as $line) {
  12081. $dh = trim((string)($line['CCYDH'] ?? ''));
  12082. $cn = trim((string)($line['company_name'] ?? ''));
  12083. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  12084. $winnerSupplierByOrder[$dh][$cn] = true;
  12085. }
  12086. }
  12087. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  12088. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  12089. if ($c !== 0) {
  12090. return $c;
  12091. }
  12092. $dh = trim((string)($a['CCYDH'] ?? ''));
  12093. $aCn = trim((string)($a['company_name'] ?? ''));
  12094. $bCn = trim((string)($b['company_name'] ?? ''));
  12095. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  12096. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  12097. if ($aSupplierWin !== $bSupplierWin) {
  12098. return $aSupplierWin ? -1 : 1;
  12099. }
  12100. $c = strcmp($aCn, $bCn);
  12101. if ($c !== 0) {
  12102. return $c;
  12103. }
  12104. if (!empty($a['picked']) !== !empty($b['picked'])) {
  12105. return !empty($a['picked']) ? -1 : 1;
  12106. }
  12107. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  12108. if ($c !== 0) {
  12109. return $c;
  12110. }
  12111. return 0;
  12112. });
  12113. return $lines;
  12114. }
  12115. /**
  12116. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  12117. *
  12118. * @param array<int, array<string, mixed>> $quoteLines
  12119. */
  12120. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  12121. {
  12122. $mon = (int)substr($ym, 5, 2);
  12123. $titleRow = $startRow;
  12124. $headerRow = $startRow + 1;
  12125. $dataStartRow = $startRow + 2;
  12126. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  12127. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  12128. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  12129. $sheet->getStyle('A' . $titleRow)->getAlignment()
  12130. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12131. ->setVertical(Alignment::VERTICAL_CENTER);
  12132. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  12133. $col = 'A';
  12134. foreach ($headers as $h) {
  12135. $sheet->setCellValue($col . $headerRow, $h);
  12136. $col++;
  12137. }
  12138. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  12139. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12140. $rowNum = $dataStartRow;
  12141. if ($quoteLines === []) {
  12142. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  12143. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  12144. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12145. $rowNum = $dataStartRow + 1;
  12146. } else {
  12147. $i = 0;
  12148. foreach ($quoteLines as $line) {
  12149. $i++;
  12150. $sheet->setCellValue('A' . $rowNum, $i);
  12151. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  12152. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  12153. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  12154. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  12155. if ($line['amount_num'] !== null) {
  12156. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  12157. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  12158. } else {
  12159. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  12160. }
  12161. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  12162. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  12163. if (!empty($line['picked'])) {
  12164. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  12165. }
  12166. $rowNum++;
  12167. }
  12168. }
  12169. $lastRow = $rowNum - 1;
  12170. if ($lastRow >= $headerRow) {
  12171. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  12172. 'borders' => [
  12173. 'allBorders' => [
  12174. 'borderStyle' => Border::BORDER_THIN,
  12175. 'color' => ['rgb' => '000000'],
  12176. ],
  12177. ],
  12178. ]);
  12179. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  12180. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12181. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12182. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12183. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  12184. if ($lastRow >= $dataStartRow) {
  12185. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  12186. }
  12187. }
  12188. return $lastRow;
  12189. }
  12190. /**
  12191. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  12192. */
  12193. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  12194. {
  12195. if ($lastRow < $dataStartRow || $headerRow < 1) {
  12196. return;
  12197. }
  12198. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  12199. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12200. ->setVertical(Alignment::VERTICAL_CENTER);
  12201. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  12202. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12203. ->setVertical(Alignment::VERTICAL_CENTER);
  12204. if ($lastCol > 'B') {
  12205. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  12206. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  12207. ->setVertical(Alignment::VERTICAL_CENTER);
  12208. }
  12209. }
  12210. /**
  12211. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  12212. */
  12213. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  12214. {
  12215. $s = trim($ccydh);
  12216. if ($s === '') {
  12217. return 'ORDER';
  12218. }
  12219. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  12220. $s = trim($s, '._-');
  12221. if ($s === '') {
  12222. return 'ORDER';
  12223. }
  12224. if (function_exists('mb_substr')) {
  12225. return mb_substr($s, 0, 80, 'UTF-8');
  12226. }
  12227. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  12228. }
  12229. /**
  12230. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  12231. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  12232. *
  12233. * @return array{objectKey: string, webPath: string}
  12234. */
  12235. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  12236. {
  12237. $sid = (int)$scydgyId;
  12238. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  12239. $y = date('Y');
  12240. $m = date('m');
  12241. $d = date('d');
  12242. $basename = $safeOrder . '_' . $sid . '.pdf';
  12243. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  12244. return [
  12245. 'objectKey' => $objectKey,
  12246. 'webPath' => '/' . $objectKey,
  12247. ];
  12248. }
  12249. /**
  12250. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  12251. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  12252. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  12253. *
  12254. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  12255. */
  12256. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  12257. {
  12258. if (!$this->isValidScydgyRowId($scydgyId)) {
  12259. return '';
  12260. }
  12261. $ids = trim((string)$scydgyId);
  12262. $prep = $this->prepareProcuremenDetailsView($ids);
  12263. if (!$prep['ok']) {
  12264. return '';
  12265. }
  12266. $ccydh = $prep['ccydh'];
  12267. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  12268. $objectKey = $paths['objectKey'];
  12269. $webPath = $paths['webPath'];
  12270. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  12271. $this->view->assign([
  12272. 'pdf_export' => 1,
  12273. 'pdfMetaLine' => $meta,
  12274. ]);
  12275. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  12276. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  12277. $this->view->engine->layout(false);
  12278. try {
  12279. $html = $this->view->fetch('procuremen/details_pdf_shell');
  12280. } catch (\Throwable $e) {
  12281. if ($restoreLayout) {
  12282. $this->view->engine->layout($restoreLayout);
  12283. }
  12284. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  12285. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12286. return '';
  12287. }
  12288. if ($restoreLayout) {
  12289. $this->view->engine->layout($restoreLayout);
  12290. }
  12291. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12292. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  12293. if (!is_dir($tempDir)) {
  12294. @mkdir($tempDir, 0755, true);
  12295. }
  12296. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  12297. try {
  12298. $mpdf = new \Mpdf\Mpdf([
  12299. 'mode' => 'utf-8',
  12300. 'format' => 'A4',
  12301. 'margin_left' => 12,
  12302. 'margin_right' => 12,
  12303. 'margin_top' => 14,
  12304. 'margin_bottom' => 14,
  12305. 'tempDir' => $tempDir,
  12306. 'autoScriptToLang' => true,
  12307. 'autoLangToFont' => true,
  12308. ]);
  12309. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  12310. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  12311. $mpdf->SetBasePath('http://127.0.0.1/');
  12312. $mpdf->WriteHTML($html);
  12313. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  12314. } catch (\Throwable $e) {
  12315. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  12316. if (is_file($tempPdf)) {
  12317. @unlink($tempPdf);
  12318. }
  12319. return '';
  12320. }
  12321. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  12322. if ($ossUrl !== '') {
  12323. @unlink($tempPdf);
  12324. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12325. return $ossUrl;
  12326. }
  12327. $pi = pathinfo($objectKey);
  12328. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  12329. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  12330. if ($baseFile === '') {
  12331. @unlink($tempPdf);
  12332. return '';
  12333. }
  12334. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  12335. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  12336. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  12337. @unlink($tempPdf);
  12338. return '';
  12339. }
  12340. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  12341. if (!@copy($tempPdf, $fullPath)) {
  12342. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  12343. @unlink($tempPdf);
  12344. return '';
  12345. }
  12346. @unlink($tempPdf);
  12347. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12348. return $webPath;
  12349. }
  12350. /**
  12351. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  12352. */
  12353. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  12354. {
  12355. if ($scydgyId <= 0 || $webPath === '') {
  12356. return;
  12357. }
  12358. try {
  12359. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  12360. } catch (\Throwable $e) {
  12361. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  12362. }
  12363. }
  12364. /**
  12365. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  12366. *
  12367. * @param array<string, string> $vars
  12368. * @return array<string, string>
  12369. */
  12370. protected function normalizeSmsTemplateVars(array $vars): array
  12371. {
  12372. $out = [];
  12373. foreach ($vars as $k => $v) {
  12374. $out[(string)$k] = trim((string)$v);
  12375. }
  12376. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  12377. $out['contact_name'] = $out['company_name'];
  12378. }
  12379. return $out;
  12380. }
  12381. /**
  12382. * 按手机号或公司名称查 customer 表联系人姓名
  12383. */
  12384. protected function resolveCustomerContactName(string $phone, string $companyName): string
  12385. {
  12386. $phone = trim($phone);
  12387. $companyName = trim($companyName);
  12388. try {
  12389. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  12390. $row = Db::table('customer')
  12391. ->where(function ($q) use ($phone) {
  12392. $q->where('phone', $phone)->whereOr('account', $phone);
  12393. })
  12394. ->order('id', 'asc')
  12395. ->find();
  12396. if (is_array($row)) {
  12397. $nm = trim((string)($row['username'] ?? ''));
  12398. if ($nm !== '') {
  12399. return $nm;
  12400. }
  12401. }
  12402. }
  12403. if ($companyName !== '') {
  12404. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  12405. if (is_array($row)) {
  12406. return trim((string)($row['username'] ?? ''));
  12407. }
  12408. }
  12409. } catch (\Throwable $e) {
  12410. }
  12411. return '';
  12412. }
  12413. /**
  12414. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  12415. */
  12416. protected function plainTextToHtmlEmailBody(string $text): string
  12417. {
  12418. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  12419. $parts = explode("\n", $text);
  12420. $out = [];
  12421. foreach ($parts as $line) {
  12422. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  12423. $out[] = $line;
  12424. } else {
  12425. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  12426. }
  12427. }
  12428. return implode("<br>\n", $out);
  12429. }
  12430. /**
  12431. * 短信场景:去掉链接类变量,避免误填 URL
  12432. *
  12433. * @param array<string, string> $vars
  12434. * @return array<string, string>
  12435. */
  12436. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  12437. {
  12438. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  12439. return $vars;
  12440. }
  12441. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  12442. $vars[$k] = '';
  12443. }
  12444. return $vars;
  12445. }
  12446. /**
  12447. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  12448. *
  12449. * @param array<string, string> $vars
  12450. */
  12451. protected function renderNotifyTemplate(string $scene, array $vars): string
  12452. {
  12453. $vars = $this->normalizeSmsTemplateVars($vars);
  12454. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  12455. $row = $this->loadNotifyTemplateRow($scene);
  12456. if ($row === null) {
  12457. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12458. }
  12459. $tpl = trim((string)($row['content'] ?? ''));
  12460. if ($tpl === '') {
  12461. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12462. }
  12463. foreach ($vars as $k => $v) {
  12464. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  12465. }
  12466. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  12467. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  12468. return $tpl;
  12469. }
  12470. protected function resolveProcuremenEmailSubject(string $scene): string
  12471. {
  12472. // 询价通知业务员 / 供应商询价:模版名称即邮件主题
  12473. if ($scene === 'rfq_salesman_email' || $scene === 'rfq_supplier_email') {
  12474. $row = $this->loadNotifyTemplateRow($scene);
  12475. $title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
  12476. if ($title !== '') {
  12477. return $title;
  12478. }
  12479. return $scene === 'rfq_supplier_email' ? '供应商询价通知' : '协助采购询价通知';
  12480. }
  12481. $map = [
  12482. 'review_email' => '您有新的协助加工订单',
  12483. ];
  12484. $subject = trim((string)($map[$scene] ?? ''));
  12485. if ($subject === '') {
  12486. $this->error('未配置邮件主题:' . $scene);
  12487. }
  12488. return $subject;
  12489. }
  12490. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  12491. {
  12492. $map = [
  12493. 'review_email' => '协助下发-邮箱',
  12494. 'review_sms' => '协助下发-短信',
  12495. 'confirm_ok' => '采购确认-通过',
  12496. 'confirm_fail' => '采购确认-未通过',
  12497. 'bid_open' => '开标双重验证',
  12498. 'rfq_salesman_email' => '询价通知业务员-邮箱',
  12499. 'rfq_supplier_email' => '供应商询价通知',
  12500. ];
  12501. $label = $map[$scene] ?? $scene;
  12502. if ($titleRequired) {
  12503. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  12504. }
  12505. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  12506. }
  12507. /**
  12508. * 是否开启协助通知演练(不发真实短信/邮件)
  12509. */
  12510. protected function isProcuremenNotifyDryRun(): bool
  12511. {
  12512. return (bool)Config::get('procuremen_notify_dry_run');
  12513. }
  12514. /**
  12515. * @param array<string, mixed> $payload
  12516. */
  12517. protected function recordNotifyDryRunPreview(array $payload): void
  12518. {
  12519. $this->notifyDryRunPreview[] = $payload;
  12520. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  12521. }
  12522. /**
  12523. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  12524. * @throws \Exception
  12525. */
  12526. protected function smsbao($phone, $content)
  12527. {
  12528. if ($this->isProcuremenNotifyDryRun()) {
  12529. $this->recordNotifyDryRunPreview([
  12530. 'scene' => 'sms_only',
  12531. 'phone' => $phone,
  12532. 'sms_content' => $content,
  12533. ]);
  12534. return;
  12535. }
  12536. $statusStr = [
  12537. '0' => '短信发送成功',
  12538. '-1' => '参数不全',
  12539. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  12540. '30' => '密码错误',
  12541. '40' => '账号不存在',
  12542. '41' => '余额不足',
  12543. '42' => '帐户已过期',
  12544. '43' => 'IP地址限制',
  12545. '50' => '内容含有敏感词',
  12546. ];
  12547. $smsapi = 'http://api.smsbao.com/';
  12548. $user = 'zhuwei123';
  12549. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  12550. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  12551. $result = @file_get_contents($sendurl);
  12552. if ($result === false) {
  12553. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  12554. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  12555. }
  12556. $result = trim((string)$result);
  12557. if ($result !== '0') {
  12558. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  12559. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  12560. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  12561. }
  12562. }
  12563. }