Procuremen.php 495 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenGuard;
  6. use app\common\library\ProcuremenOperLog;
  7. use app\common\library\ProcuremenStatus;
  8. use app\common\library\ProcuremenSupplierScore;
  9. use app\common\library\ProcuremenTime;
  10. use PHPMailer\PHPMailer\PHPMailer;
  11. use think\Config;
  12. use think\Cache;
  13. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  14. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  15. use PhpOffice\PhpSpreadsheet\Style\Border;
  16. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  17. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  18. use think\Db;
  19. use think\Log;
  20. class Procuremen extends Backend
  21. {
  22. /**
  23. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  24. */
  25. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,b.czlyq,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  26. /**
  27. * Procuremen模型对象
  28. * @var \app\admin\model\Procuremen
  29. */
  30. protected $model = null;
  31. /**
  32. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  33. */
  34. protected $notifyDryRunPreview = [];
  35. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  36. protected $procuremenRedisCache = null;
  37. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  38. protected $pickHiddenScydgySetCache = null;
  39. /** 邮件发送日志表结构已就绪缓存键 */
  40. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  41. /**
  42. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  43. * @var array
  44. */
  45. protected $noNeedRight = [
  46. 'pickreview', 'review', 'reviewcompanies',
  47. // 方法内用 hasProcuremenPerm 校验(兼容 auditsubmit / auditissue)
  48. 'auditmanualpick',
  49. // 与 rfqlist 同权,方法内校验
  50. 'rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqissuesuppliers', 'rfqissue', 'rfqissuesendmail', 'rfqquotes',
  51. 'rfqappendsuppliers', 'rfqsupplieroptions', 'rfqsalesmanoptions', 'rfqappendsalesmen',
  52. ];
  53. public function _initialize()
  54. {
  55. parent::_initialize();
  56. $this->model = new \app\admin\model\Procuremen;
  57. $this->maybeMigrateLegacyWflowStatusText();
  58. $this->assignProcuremenAuthConfig();
  59. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  60. $this->ensurePurchaseEmailSendLogTableOnce();
  61. }
  62. }
  63. /**
  64. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  65. */
  66. protected function maybeMigrateLegacyWflowStatusText(): void
  67. {
  68. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  69. if (is_file($flagFile)) {
  70. return;
  71. }
  72. $map = [
  73. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  74. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  75. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  76. '3' => ProcuremenStatus::WFLOW_APPROVED,
  77. ];
  78. try {
  79. foreach ($map as $num => $text) {
  80. Db::table('purchase_order')
  81. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  82. ->update(['wflow_status' => $text]);
  83. }
  84. @file_put_contents($flagFile, date('c'));
  85. } catch (\Throwable $e) {
  86. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  87. }
  88. }
  89. /**
  90. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  91. *
  92. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  93. */
  94. protected function hasProcuremenPerm(array $actions): bool
  95. {
  96. foreach ($actions as $action) {
  97. $action = strtolower(trim((string)$action));
  98. if ($action === '') {
  99. continue;
  100. }
  101. if (strpos($action, 'procuremen/') !== 0) {
  102. $action = 'procuremen/' . $action;
  103. }
  104. if ($this->auth->check($action)) {
  105. return true;
  106. }
  107. }
  108. $suffixes = [];
  109. foreach ($actions as $action) {
  110. $action = strtolower(trim((string)$action));
  111. $action = preg_replace('#^procuremen/#', '', $action);
  112. if ($action !== '') {
  113. $suffixes[$action] = true;
  114. }
  115. }
  116. if ($suffixes === []) {
  117. return false;
  118. }
  119. try {
  120. foreach ($this->auth->getRuleList() as $rule) {
  121. $rule = strtolower((string)$rule);
  122. if (strpos($rule, 'procuremen/') !== 0) {
  123. continue;
  124. }
  125. foreach (array_keys($suffixes) as $suffix) {
  126. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  127. return true;
  128. }
  129. }
  130. }
  131. } catch (\Throwable $e) {
  132. }
  133. return false;
  134. }
  135. /**
  136. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  137. *
  138. * @param string[] $actions
  139. */
  140. protected function hasProcuremenPermStrict(array $actions): bool
  141. {
  142. foreach ($actions as $action) {
  143. $action = strtolower(trim((string)$action));
  144. if ($action === '') {
  145. continue;
  146. }
  147. if (strpos($action, 'procuremen/') !== 0) {
  148. $action = 'procuremen/' . $action;
  149. }
  150. if ($this->auth->check($action)) {
  151. return true;
  152. }
  153. }
  154. return false;
  155. }
  156. /**
  157. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  158. *
  159. * @param string[] $titles
  160. */
  161. protected function authHasAssignedRuleTitle(array $titles): bool
  162. {
  163. $titles = array_values(array_filter(array_map('trim', $titles)));
  164. if ($titles === []) {
  165. return false;
  166. }
  167. try {
  168. $ids = $this->auth->getRuleIds();
  169. if (in_array('*', $ids, true)) {
  170. return true;
  171. }
  172. if ($ids === []) {
  173. return false;
  174. }
  175. $rows = Db::name('auth_rule')
  176. ->where('status', 'normal')
  177. ->whereIn('id', $ids)
  178. ->column('title');
  179. foreach ($rows as $title) {
  180. $t = trim((string)$title);
  181. if ($t !== '' && in_array($t, $titles, true)) {
  182. return true;
  183. }
  184. }
  185. } catch (\Throwable $e) {
  186. }
  187. return false;
  188. }
  189. protected function procuremenCanPickDelete(): bool
  190. {
  191. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  192. return true;
  193. }
  194. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  195. }
  196. protected function procuremenCanComplete(): bool
  197. {
  198. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  199. return true;
  200. }
  201. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  202. }
  203. protected function procuremenCanDispatch(): bool
  204. {
  205. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  206. }
  207. /**
  208. * 前端按钮显隐(Config.procuremenAuth)
  209. */
  210. protected function assignProcuremenAuthConfig(): void
  211. {
  212. $authMap = [
  213. 'pickreview' => $this->procuremenCanDispatch(),
  214. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  215. 'pickdelete' => $this->procuremenCanPickDelete(),
  216. 'completedirectly' => $this->procuremenCanComplete(),
  217. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  218. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  219. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  220. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  221. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  222. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  223. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  224. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  225. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  226. 'details' => $this->hasProcuremenPerm(['details']),
  227. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  228. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  229. 'export_month_quote' => $this->hasProcuremenPerm(['export_month_quote', 'exportMonthQuote', 'export_month_outward', 'exportMonthOutward']),
  230. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  231. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  232. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  233. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  234. 'auditmanualpick' => $this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue']),
  235. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  236. 'add' => $this->hasProcuremenPerm(['add']),
  237. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  238. 'rfqnotifysalesmen' => $this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen']),
  239. 'rfqnotifysalesman' => $this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesman']),
  240. 'rfqsalesmanoptions' => $this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen', 'rfqsalesmanoptions', 'rfqappendsalesmen']),
  241. 'rfqappendsalesmen' => $this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen', 'rfqappendsalesmen']),
  242. 'rfqissuesuppliers' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqissuesuppliers']),
  243. 'rfqissue' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue']),
  244. 'rfqissuesendmail' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqissuesendmail']),
  245. 'rfqquotes' => $this->hasProcuremenPerm(['rfqlist', 'rfqquotes', 'rfqissue']),
  246. 'rfqappendsuppliers' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqappendsuppliers']),
  247. 'rfqsupplieroptions' => $this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions']),
  248. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  249. ];
  250. $this->assignconfig('procuremenAuth', $authMap);
  251. }
  252. /**
  253. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  254. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  255. *
  256. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  257. */
  258. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  259. {
  260. static $mprocCfgLoaded = false;
  261. if (!$mprocCfgLoaded) {
  262. $mprocCfgLoaded = true;
  263. if (is_file(APP_PATH . 'extra/mproc.php')) {
  264. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  265. }
  266. }
  267. $eid = (int)$purchaseOrderDetailId;
  268. $base = $this->resolveMprocMobilePublicBaseUrl();
  269. if ($base === '') {
  270. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  271. }
  272. $path = trim((string)Config::get('mproc.mobile_index_path'));
  273. if ($path === '') {
  274. $path = '/index.php/index/index/index';
  275. } else {
  276. $path = '/' . ltrim($path, '/');
  277. }
  278. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  279. if ($eid > 0) {
  280. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  281. }
  282. return $base . $path . '?main_tab=orders';
  283. }
  284. /**
  285. * 邮件/短信外链:须为带点的公网域名
  286. */
  287. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  288. {
  289. $u = trim((string)$baseUrl);
  290. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  291. return false;
  292. }
  293. $host = parse_url($u, PHP_URL_HOST);
  294. if (!is_string($host) || $host === '') {
  295. return false;
  296. }
  297. if (strcasecmp($host, 'localhost') === 0) {
  298. return false;
  299. }
  300. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  301. return false;
  302. }
  303. if (strpos($host, '.') === false) {
  304. return false;
  305. }
  306. return true;
  307. }
  308. /**
  309. * 解析用于协助邮件/短信的手机端站点根
  310. */
  311. protected function resolveMprocMobilePublicBaseUrl()
  312. {
  313. $candidates = [];
  314. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  315. $candidates[] = trim((string)Config::get('site.indexurl'));
  316. $cdn = trim((string)Config::get('site.cdnurl'));
  317. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  318. $candidates[] = rtrim($cdn, '/');
  319. }
  320. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  321. $candidates[] = $reqBase;
  322. foreach ($candidates as $c) {
  323. if ($c === '') {
  324. continue;
  325. }
  326. $c = rtrim($c, '/');
  327. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  328. return $c;
  329. }
  330. }
  331. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  332. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  333. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  334. return $reqBase;
  335. }
  336. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  337. return '';
  338. }
  339. /**
  340. * 获取 Redis 中 procuremen_redis
  341. */
  342. protected function ProcuremenRedis(): array
  343. {
  344. if ($this->procuremenRedisCache !== null) {
  345. return $this->procuremenRedisCache;
  346. }
  347. try {
  348. $redis = redis();
  349. $raw = $redis->get('procuremen_redis');
  350. if ($raw === false || $raw === '') {
  351. $this->procuremenRedisCache = [];
  352. return $this->procuremenRedisCache;
  353. }
  354. $decoded = json_decode($raw, true);
  355. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  356. $this->procuremenRedisCache = [];
  357. return $this->procuremenRedisCache;
  358. }
  359. $this->procuremenRedisCache = $decoded['data'];
  360. // 整包已解码时顺带补齐侧栏小键,避免下次首屏再扫库
  361. if ($this->loadProcuremenSidebarYmList() === []) {
  362. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($this->procuremenRedisCache));
  363. }
  364. return $this->procuremenRedisCache;
  365. } catch (\Throwable $e) {
  366. $this->procuremenRedisCache = [];
  367. return $this->procuremenRedisCache;
  368. }
  369. }
  370. /**
  371. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  372. *
  373. * @return array<int, array<string, mixed>>
  374. */
  375. protected function procuremenFetchErpPoolFromDb(): array
  376. {
  377. try {
  378. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  379. $endTime = date('Y-m-d 23:59:59');
  380. $list = Db::table('scydgy')
  381. ->alias('a')
  382. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  383. ->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')
  384. ->where([
  385. 'a.bwjg' => 1,
  386. 'a.iEndBz' => 0,
  387. 'a.iType' => 0,
  388. 'a.iStatus' => 10,
  389. ])
  390. ->where('a.dStamp', '>=', $startTime)
  391. ->where('a.dStamp', '<=', $endTime)
  392. ->order('a.dStamp', 'desc')
  393. ->select();
  394. if (!is_array($list)) {
  395. return [];
  396. }
  397. try {
  398. $redis = redis();
  399. $payload = [
  400. 'code' => 200,
  401. 'msg' => 'success',
  402. 'data' => $list,
  403. ];
  404. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  405. $this->procuremenRedisCache = $list;
  406. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($list));
  407. $this->clearPickMonthPoolCaches();
  408. $this->warmPickMonthPoolCachesFromPool($list);
  409. } catch (\Throwable $e) {
  410. }
  411. return $list;
  412. } catch (\Throwable $e) {
  413. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  414. return [];
  415. }
  416. }
  417. /**
  418. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  419. *
  420. * @return array<int, array<string, mixed>>
  421. */
  422. protected function procuremenEnsureRedisPool(): array
  423. {
  424. $pool = $this->ProcuremenRedis();
  425. if (is_array($pool) && $pool !== []) {
  426. return $pool;
  427. }
  428. static $warmed = false;
  429. if ($warmed) {
  430. return is_array($pool) ? $pool : [];
  431. }
  432. $warmed = true;
  433. return $this->procuremenFetchErpPoolFromDb();
  434. }
  435. /**
  436. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  437. *
  438. * @param array<string, mixed> $row
  439. */
  440. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  441. {
  442. $t = $this->procuremenRowListSortTime($row, $primary);
  443. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  444. return null;
  445. }
  446. $mo = (int)$m[2];
  447. if ($mo < 1 || $mo > 12) {
  448. return null;
  449. }
  450. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  451. }
  452. /**
  453. * @param array<int, array{year:string, months:array}> $sidebar
  454. * @return array<int, array{year:string, months:array}>
  455. */
  456. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  457. {
  458. $ym = trim($ym);
  459. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  460. return $sidebar;
  461. }
  462. foreach ($sidebar as $block) {
  463. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  464. continue;
  465. }
  466. foreach ($block['months'] as $item) {
  467. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  468. return $sidebar;
  469. }
  470. }
  471. }
  472. $y = substr($ym, 0, 4);
  473. $mo = (int)substr($ym, 5, 2);
  474. $sidebar[] = [
  475. 'year' => $y,
  476. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  477. ];
  478. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  479. }
  480. /**
  481. * @param array<int, array{year:string, months:array}> $sidebar
  482. * @return string[]
  483. */
  484. protected function flattenProcuremenSidebarYms(array $sidebar): array
  485. {
  486. $yms = [];
  487. foreach ($sidebar as $block) {
  488. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  489. continue;
  490. }
  491. foreach ($block['months'] as $item) {
  492. if (!is_array($item)) {
  493. continue;
  494. }
  495. $ym = trim((string)($item['ym'] ?? ''));
  496. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  497. $yms[$ym] = true;
  498. }
  499. }
  500. }
  501. return array_keys($yms);
  502. }
  503. /**
  504. * 左侧菜单(协助初选)
  505. * 禁止扫整包/重 SQL。有月份小键则用;否则只展示当月,等列表第一次暖缓存后再补全。
  506. */
  507. protected function GetIndexYearMonths()
  508. {
  509. $ymList = $this->loadProcuremenSidebarYmList();
  510. if ($ymList === []) {
  511. $def = $this->resolveProcuremenDefaultYm('pick');
  512. $ymList = [preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m')];
  513. }
  514. $def = $this->resolveProcuremenDefaultYm('pick');
  515. if (preg_match('/^\d{4}-\d{2}$/', $def) && !in_array($def, $ymList, true)) {
  516. $ymList[] = $def;
  517. }
  518. return $this->buildYearMonthSidebar($ymList);
  519. }
  520. /**
  521. * @return string[] 形如 2026-07
  522. */
  523. protected function loadProcuremenSidebarYmList(): array
  524. {
  525. try {
  526. $raw = redis()->get('procuremen_redis_yms');
  527. if ($raw === false || $raw === null || $raw === '') {
  528. return [];
  529. }
  530. $decoded = json_decode((string)$raw, true);
  531. if (!is_array($decoded)) {
  532. return [];
  533. }
  534. $out = [];
  535. foreach ($decoded as $ym) {
  536. $ym = trim((string)$ym);
  537. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  538. $out[$ym] = true;
  539. }
  540. }
  541. return array_keys($out);
  542. } catch (\Throwable $e) {
  543. return [];
  544. }
  545. }
  546. /**
  547. * @param string[] $ymList
  548. */
  549. protected function saveProcuremenSidebarYmList(array $ymList): void
  550. {
  551. $out = [];
  552. foreach ($ymList as $ym) {
  553. $ym = trim((string)$ym);
  554. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  555. $out[$ym] = true;
  556. }
  557. }
  558. if ($out === []) {
  559. return;
  560. }
  561. try {
  562. redis()->set('procuremen_redis_yms', json_encode(array_keys($out), JSON_UNESCAPED_UNICODE));
  563. } catch (\Throwable $e) {
  564. }
  565. }
  566. /**
  567. * @param array<int, array<string, mixed>> $pool
  568. * @return string[]
  569. */
  570. protected function extractYearMonthsFromPoolRows(array $pool): array
  571. {
  572. $ymSet = [];
  573. foreach ($pool as $r) {
  574. if (!is_array($r)) {
  575. continue;
  576. }
  577. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  578. continue;
  579. }
  580. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  581. if ($ym !== null) {
  582. $ymSet[$ym] = true;
  583. }
  584. }
  585. return array_keys($ymSet);
  586. }
  587. /**
  588. * 轻量查询初选侧栏月份(只取 DISTINCT 年月,不拉整包工序)
  589. *
  590. * @return string[]
  591. */
  592. protected function queryProcuremenPickSidebarYmListLight(): array
  593. {
  594. try {
  595. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  596. $endTime = date('Y-m-d 23:59:59');
  597. $sql = 'SELECT DISTINCT DATE_FORMAT('
  598. . 'IF(b.dputrecord IS NOT NULL AND TRIM(CAST(b.dputrecord AS CHAR(32))) <> \'\''
  599. . ' AND TRIM(CAST(b.dputrecord AS CHAR(32))) NOT LIKE \'0000-00-00%\','
  600. . ' b.dputrecord, a.dStamp), \'%Y-%m\') AS ym'
  601. . ' FROM scydgy a'
  602. . ' INNER JOIN mcyd b ON b.ICYDID = a.ICYDID AND b.iStatus >= 10'
  603. . ' WHERE a.bwjg = 1 AND a.iEndBz = 0 AND a.iType = 0 AND a.iStatus = 10'
  604. . ' AND a.dStamp >= ? AND a.dStamp <= ?';
  605. $rows = Db::query($sql, [$startTime, $endTime]);
  606. if (!is_array($rows)) {
  607. return [];
  608. }
  609. $out = [];
  610. foreach ($rows as $r) {
  611. $ym = trim((string)($r['ym'] ?? ''));
  612. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  613. $out[$ym] = true;
  614. }
  615. }
  616. return array_keys($out);
  617. } catch (\Throwable $e) {
  618. Log::write('初选侧栏月份轻量查询失败:' . $e->getMessage(), 'warning');
  619. return [];
  620. }
  621. }
  622. /**
  623. * @return string[] 含当月在内的近 N 个自然月
  624. */
  625. protected function buildRecentCalendarYmList(int $months = 12): array
  626. {
  627. $months = max(1, min(24, $months));
  628. $out = [];
  629. $base = strtotime(date('Y-m-01'));
  630. for ($i = 0; $i < $months; $i++) {
  631. $out[] = date('Y-m', strtotime('-' . $i . ' month', $base));
  632. }
  633. return $out;
  634. }
  635. /**
  636. * 初选按月工序池:优先月缓存;未命中则直接按月查 ERP。
  637. * 禁止为列表去解近一年整包 Redis(解包/连接异常会造成长时间转圈)。
  638. *
  639. * @return array<int, array<string, mixed>>
  640. */
  641. protected function loadPickPoolForYm(string $ym): array
  642. {
  643. $ym = trim($ym);
  644. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  645. return [];
  646. }
  647. $hit = $this->readPickMonthPoolCache($ym);
  648. if ($hit !== null) {
  649. return $hit;
  650. }
  651. return $this->queryPickPoolForYmFromDb($ym);
  652. }
  653. /**
  654. * @return array<int, array<string, mixed>>|null null=无有效缓存(含旧版空数组误缓存)
  655. */
  656. protected function readPickMonthPoolCache(string $ym): ?array
  657. {
  658. try {
  659. $raw = redis()->get('procuremen_pick_pool:' . $ym);
  660. if ($raw === false || $raw === null || $raw === '') {
  661. return null;
  662. }
  663. $decoded = json_decode((string)$raw, true);
  664. if (!is_array($decoded)) {
  665. return null;
  666. }
  667. // 新格式:{ok:1, rows:[...]},空月也算有效(已从整包确认)
  668. if (isset($decoded['ok']) && (int)$decoded['ok'] === 1 && isset($decoded['rows']) && is_array($decoded['rows'])) {
  669. return $decoded['rows'];
  670. }
  671. // 旧格式:仅非空行列表可命中;[] 多半是错误 SQL 写入,视为未命中
  672. if ($decoded === []) {
  673. try {
  674. redis()->del('procuremen_pick_pool:' . $ym);
  675. } catch (\Throwable $e) {
  676. }
  677. return null;
  678. }
  679. if (isset($decoded[0]) && is_array($decoded[0])) {
  680. return $decoded;
  681. }
  682. return null;
  683. } catch (\Throwable $e) {
  684. return null;
  685. }
  686. }
  687. /**
  688. * @param array<int, array<string, mixed>> $rows
  689. */
  690. protected function writePickMonthPoolCache(string $ym, array $rows): void
  691. {
  692. try {
  693. redis()->setex(
  694. 'procuremen_pick_pool:' . $ym,
  695. 600,
  696. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  697. );
  698. } catch (\Throwable $e) {
  699. }
  700. }
  701. /**
  702. * @param array<int, array<string, mixed>> $pool
  703. * @return array<int, array<string, mixed>>
  704. */
  705. protected function filterPoolRowsByYm(array $pool, string $ym): array
  706. {
  707. $out = [];
  708. foreach ($pool as $r) {
  709. if (!is_array($r)) {
  710. continue;
  711. }
  712. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  713. continue;
  714. }
  715. if ($this->procuremenRowYearMonth($r, 'dputrecord') === $ym) {
  716. $out[] = $r;
  717. }
  718. }
  719. return $out;
  720. }
  721. /**
  722. * 按 dStamp 取当月附近数据,再用列表规则(dputrecord 优先)精确到 ym
  723. *
  724. * @return array<int, array<string, mixed>>
  725. */
  726. protected function queryPickPoolForYmFromDb(string $ym): array
  727. {
  728. $monthStart = $ym . '-01 00:00:00';
  729. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  730. // 略放大窗口,避免 dStamp 与 dputrecord 跨月导致漏数;最终仍按 ym 精确过滤
  731. $queryStart = date('Y-m-d 00:00:00', strtotime($monthStart . ' -7 days'));
  732. $queryEnd = date('Y-m-d 23:59:59', strtotime($monthEnd . ' +7 days'));
  733. try {
  734. $list = Db::table('scydgy')
  735. ->alias('a')
  736. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  737. ->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')
  738. ->where([
  739. 'a.bwjg' => 1,
  740. 'a.iEndBz' => 0,
  741. 'a.iType' => 0,
  742. 'a.iStatus' => 10,
  743. ])
  744. ->where('a.dStamp', '>=', $queryStart)
  745. ->where('a.dStamp', '<=', $queryEnd)
  746. ->order('a.dStamp', 'desc')
  747. ->select();
  748. } catch (\Throwable $e) {
  749. Log::write('初选按月取数失败 ym=' . $ym . ':' . $e->getMessage(), 'error');
  750. return [];
  751. }
  752. if (!is_array($list)) {
  753. $list = [];
  754. }
  755. $out = $this->filterPoolRowsByYm($list, $ym);
  756. // 新格式缓存(含空月),避免重复打库;读侧只认 ok=1
  757. $this->writePickMonthPoolCache($ym, $out);
  758. try {
  759. $yms = $this->loadProcuremenSidebarYmList();
  760. if ($out !== [] && ($yms === [] || !in_array($ym, $yms, true))) {
  761. $yms[] = $ym;
  762. $this->saveProcuremenSidebarYmList($yms);
  763. }
  764. } catch (\Throwable $e) {
  765. }
  766. return $out;
  767. }
  768. /**
  769. * 整包写入后拆成按月小缓存,供初选列表秒开
  770. *
  771. * @param array<int, array<string, mixed>> $pool
  772. */
  773. protected function warmPickMonthPoolCachesFromPool(array $pool): void
  774. {
  775. if ($pool === []) {
  776. return;
  777. }
  778. $byYm = [];
  779. foreach ($pool as $r) {
  780. if (!is_array($r)) {
  781. continue;
  782. }
  783. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  784. continue;
  785. }
  786. $rowYm = $this->procuremenRowYearMonth($r, 'dputrecord');
  787. if ($rowYm === null) {
  788. continue;
  789. }
  790. $byYm[$rowYm][] = $r;
  791. }
  792. if ($byYm === []) {
  793. return;
  794. }
  795. try {
  796. $redis = redis();
  797. foreach ($byYm as $rowYm => $rows) {
  798. $redis->setex(
  799. 'procuremen_pick_pool:' . $rowYm,
  800. 600,
  801. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  802. );
  803. }
  804. try {
  805. $redis->del('procuremen_pick_hidden_scydgy_v1');
  806. } catch (\Throwable $e) {
  807. }
  808. } catch (\Throwable $e) {
  809. }
  810. }
  811. /**
  812. * 刷新整包后清理近月缓存,避免脏读
  813. */
  814. protected function clearPickMonthPoolCaches(int $months = 24): void
  815. {
  816. try {
  817. $redis = redis();
  818. foreach ($this->buildRecentCalendarYmList($months) as $ym) {
  819. try {
  820. $redis->del('procuremen_pick_pool:' . $ym);
  821. } catch (\Throwable $e) {
  822. }
  823. }
  824. } catch (\Throwable $e) {
  825. }
  826. $this->invalidatePickHiddenScydgyCache();
  827. }
  828. /**
  829. * 下发/完结后清隐藏集缓存,避免初选列表最多 90 秒仍显示已下发行
  830. */
  831. protected function invalidatePickHiddenScydgyCache(): void
  832. {
  833. $this->pickHiddenScydgySetCache = null;
  834. try {
  835. redis()->del('procuremen_pick_hidden_scydgy_v1');
  836. } catch (\Throwable $e) {
  837. }
  838. }
  839. /** 列表/首屏读完鉴权后尽早释放 session,避免多 iframe 串行卡死 */
  840. protected function procuremenReleaseSessionLock(): void
  841. {
  842. if (session_status() === PHP_SESSION_ACTIVE) {
  843. @session_write_close();
  844. }
  845. }
  846. /**
  847. * @param string[] $ymList 形如 2026-06
  848. * @return array<int, array{year:string, months:array}>
  849. */
  850. protected function buildYearMonthSidebar(array $ymList): array
  851. {
  852. rsort($ymList, SORT_STRING);
  853. $byYear = [];
  854. foreach ($ymList as $ym) {
  855. $y = substr($ym, 0, 4);
  856. $mo = (int)substr($ym, 5, 2);
  857. if (!isset($byYear[$y])) {
  858. $byYear[$y] = [];
  859. }
  860. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  861. }
  862. krsort($byYear, SORT_NUMERIC);
  863. foreach ($byYear as $y => $items) {
  864. usort($byYear[$y], function ($a, $b) {
  865. return strcmp($b['ym'], $a['ym']);
  866. });
  867. }
  868. $sidebar = [];
  869. foreach ($byYear as $y => $months) {
  870. $sidebar[] = ['year' => $y, 'months' => $months];
  871. }
  872. return $sidebar;
  873. }
  874. /**
  875. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  876. */
  877. protected function GetIssuedOrderYearMonths(string $stage): array
  878. {
  879. $ymSet = [];
  880. try {
  881. $query = Db::table('purchase_order');
  882. $this->applyPurchaseOrderNotDeletedWhere($query);
  883. if ($stage === 'audit') {
  884. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  885. } elseif ($stage === 'confirm') {
  886. $this->applyPurchaseOrderConfirmStageWhere($query);
  887. } else {
  888. return $this->GetIndexYearMonths();
  889. }
  890. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  891. if (is_array($rows)) {
  892. foreach ($rows as $r) {
  893. if (!is_array($r)) {
  894. continue;
  895. }
  896. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  897. if ($ym !== null) {
  898. $ymSet[$ym] = true;
  899. }
  900. }
  901. }
  902. } catch (\Throwable $e) {
  903. $ymSet = [];
  904. }
  905. $ymList = array_keys($ymSet);
  906. if ($ymList === []) {
  907. $def = $this->resolveProcuremenDefaultYm($stage);
  908. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  909. }
  910. return $this->buildYearMonthSidebar($ymList);
  911. }
  912. /**
  913. * 列表默认月份:已下发类取最近有数据的月份,初选仍用当月
  914. */
  915. protected function resolveProcuremenDefaultYm(string $stage): string
  916. {
  917. if ($stage === 'pick') {
  918. return date('Y-m');
  919. }
  920. try {
  921. $query = Db::table('purchase_order');
  922. $this->applyPurchaseOrderNotDeletedWhere($query);
  923. if ($stage === 'audit') {
  924. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  925. } elseif ($stage === 'confirm') {
  926. $this->applyPurchaseOrderConfirmStageWhere($query);
  927. } else {
  928. return date('Y-m');
  929. }
  930. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  931. if ($latest === null || $latest === '') {
  932. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  933. }
  934. $t = $this->formatProcuremenDetailTime($latest);
  935. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  936. return $m[1] . '-' . $m[2];
  937. }
  938. } catch (\Throwable $e) {
  939. }
  940. return date('Y-m');
  941. }
  942. protected function applyPurchaseOrderNotDeletedWhere($query): void
  943. {
  944. $query->whereRaw(
  945. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  946. );
  947. }
  948. /**
  949. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  950. */
  951. protected function applyPurchaseOrderConfirmStageWhere($query): void
  952. {
  953. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  954. $quoted = [];
  955. foreach ($vals as $v) {
  956. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  957. }
  958. if ($quoted === []) {
  959. $query->whereRaw('1 = 0');
  960. return;
  961. }
  962. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  963. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  964. }
  965. /**
  966. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  967. *
  968. * @param array<string, mixed> $row
  969. * @return array<string, mixed>
  970. */
  971. protected function normalizePurchaseOrderListTimeRow(array $row): array
  972. {
  973. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  974. $pick = trim((string)($row['pick_time'] ?? ''));
  975. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  976. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  977. $t = trim((string)($row[$key] ?? ''));
  978. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  979. $row['pick_time'] = $t;
  980. break;
  981. }
  982. }
  983. }
  984. return $row;
  985. }
  986. /**
  987. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  988. */
  989. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  990. {
  991. if (!in_array($stage, ['audit', 'confirm'], true)) {
  992. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  993. }
  994. if ($pool === []) {
  995. $def = $this->resolveProcuremenDefaultYm($stage);
  996. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  997. }
  998. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  999. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1000. return false;
  1001. }
  1002. $monthStart = $ym . '-01 00:00:00';
  1003. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1004. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  1005. return $probe !== [];
  1006. };
  1007. if ($tryYm($requestedYm)) {
  1008. return $requestedYm;
  1009. }
  1010. $fallback = $this->resolveProcuremenDefaultYm($stage);
  1011. if ($tryYm($fallback)) {
  1012. return $fallback;
  1013. }
  1014. $bestYm = '';
  1015. $bestTime = '';
  1016. foreach ($pool as $row) {
  1017. if (!is_array($row)) {
  1018. continue;
  1019. }
  1020. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  1021. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  1022. continue;
  1023. }
  1024. $ymRow = $m[1];
  1025. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  1026. $bestTime = $t;
  1027. $bestYm = $ymRow;
  1028. }
  1029. }
  1030. if ($bestYm !== '') {
  1031. return $bestYm;
  1032. }
  1033. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1034. }
  1035. protected function isPurchaseOrderDetailVoid(array $row): bool
  1036. {
  1037. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  1038. return true;
  1039. }
  1040. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  1041. }
  1042. /**
  1043. * 仅当前有效下发明细(排除废弃归档)
  1044. */
  1045. protected function applyActivePurchaseOrderDetailWhere($query): void
  1046. {
  1047. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1048. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  1049. }
  1050. /**
  1051. * @param array<string, mixed> $detailRow
  1052. */
  1053. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  1054. {
  1055. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  1056. return false;
  1057. }
  1058. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  1059. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  1060. }
  1061. /**
  1062. * 废弃退回初选:下发明细标记归档,不物理删除
  1063. *
  1064. * @param array<int, int|string> $scydgyIds
  1065. */
  1066. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  1067. {
  1068. $ids = [];
  1069. foreach ($scydgyIds as $sid) {
  1070. $n = (int)$sid;
  1071. if ($this->isValidScydgyRowId($n) || $n < 0) {
  1072. $ids[$n] = true;
  1073. }
  1074. }
  1075. if ($ids === []) {
  1076. return;
  1077. }
  1078. $void = ProcuremenStatus::POD_VOID;
  1079. Db::table('purchase_order_detail')
  1080. ->where('scydgy_id', 'in', array_keys($ids))
  1081. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1082. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  1083. ->update([
  1084. 'status' => $void,
  1085. 'status_name' => $void,
  1086. ]);
  1087. }
  1088. /**
  1089. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  1090. */
  1091. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  1092. {
  1093. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  1094. $norm = function (string $col) use ($p): string {
  1095. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  1096. };
  1097. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  1098. $parts = [];
  1099. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  1100. if ($key === 'createtime') {
  1101. $parts[] = $createtime;
  1102. } else {
  1103. $parts[] = $norm($key);
  1104. }
  1105. }
  1106. return 'COALESCE(' . implode(', ', $parts) . ')';
  1107. }
  1108. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  1109. {
  1110. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  1111. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  1112. }
  1113. /**
  1114. * @return array<int, array<string, mixed>>
  1115. */
  1116. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  1117. {
  1118. $this->ensurePurchaseOrderCzlyqColumn();
  1119. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1120. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  1121. try {
  1122. $query = Db::table('purchase_order')->field($fields);
  1123. $this->applyPurchaseOrderNotDeletedWhere($query);
  1124. if ($stage === 'audit') {
  1125. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1126. } elseif ($stage === 'confirm') {
  1127. $this->applyPurchaseOrderConfirmStageWhere($query);
  1128. } else {
  1129. return [];
  1130. }
  1131. $query->order('pick_time', 'desc')->order('id', 'desc');
  1132. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  1133. $monthStart = $ym . '-01 00:00:00';
  1134. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1135. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  1136. }
  1137. $rows = $query->select();
  1138. } catch (\Throwable $e) {
  1139. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  1140. $rows = [];
  1141. }
  1142. return is_array($rows) ? $rows : [];
  1143. }
  1144. /**
  1145. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  1146. */
  1147. protected function resolveProcuremenListStage(): string
  1148. {
  1149. $tab = trim((string)$this->request->request('wff_tab', ''));
  1150. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  1151. return $tab;
  1152. }
  1153. $action = strtolower((string)$this->request->action());
  1154. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  1155. return $action;
  1156. }
  1157. return 'pick';
  1158. }
  1159. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  1160. {
  1161. $this->procuremenReleaseSessionLock();
  1162. $rootTrue = rtrim((string)$this->request->root(true), '/');
  1163. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  1164. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  1165. $indexPhpRoot = $rootTrue . '/index.php';
  1166. }
  1167. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  1168. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  1169. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  1170. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  1171. $this->view->assign('defaultYm', $defaultYm);
  1172. $this->view->assign('sidebarYearMonths', $sidebar);
  1173. $this->view->assign('procuremenStage', $stage);
  1174. $this->view->assign('procuremenPageTitle', $pageTitle);
  1175. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  1176. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  1177. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  1178. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  1179. $this->assignconfig('procuremenFilterOptions', $this->buildProcuremenFilterOptions($stage));
  1180. }
  1181. /**
  1182. * 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
  1183. *
  1184. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1185. */
  1186. protected function buildProcuremenFilterOptions(string $stage): array
  1187. {
  1188. $buckets = [
  1189. 'czlyq' => [],
  1190. 'CCLBMMC' => [],
  1191. 'cywyxm' => [],
  1192. 'CGYMC' => [],
  1193. ];
  1194. $maxPerField = 300;
  1195. try {
  1196. if ($stage === 'pick') {
  1197. // 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
  1198. return $buckets;
  1199. }
  1200. if (in_array($stage, ['audit', 'confirm'], true)) {
  1201. $this->ensurePurchaseOrderCzlyqColumn();
  1202. foreach (array_keys($buckets) as $field) {
  1203. try {
  1204. $query = Db::table('purchase_order')->field($field);
  1205. $this->applyPurchaseOrderNotDeletedWhere($query);
  1206. if ($stage === 'audit') {
  1207. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1208. } else {
  1209. $this->applyPurchaseOrderConfirmStageWhere($query);
  1210. }
  1211. $query->where($field, '<>', '')->whereNotNull($field);
  1212. $vals = $query->distinct(true)->limit($maxPerField)->column($field);
  1213. if (!is_array($vals)) {
  1214. continue;
  1215. }
  1216. foreach ($vals as $v) {
  1217. $v = trim((string)$v);
  1218. if ($v !== '') {
  1219. $buckets[$field][$v] = $v;
  1220. }
  1221. }
  1222. } catch (\Throwable $e) {
  1223. // 单字段失败不影响其它
  1224. }
  1225. }
  1226. }
  1227. } catch (\Throwable $e) {
  1228. Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
  1229. }
  1230. foreach ($buckets as &$set) {
  1231. if ($set !== []) {
  1232. ksort($set, SORT_STRING);
  1233. }
  1234. }
  1235. unset($set);
  1236. return $buckets;
  1237. }
  1238. /**
  1239. * filter JSON 是否含有效条件
  1240. *
  1241. * @param array<string, mixed> $filterArr
  1242. */
  1243. protected function procuremenFilterArrHasValue(array $filterArr): bool
  1244. {
  1245. foreach ($filterArr as $v) {
  1246. if (is_array($v)) {
  1247. if (array_filter($v, function ($x) {
  1248. return $x !== '' && $x !== null;
  1249. })) {
  1250. return true;
  1251. }
  1252. } elseif ($v !== '' && $v !== null) {
  1253. return true;
  1254. }
  1255. }
  1256. return false;
  1257. }
  1258. /**
  1259. * 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
  1260. *
  1261. * @param array<string, mixed> $filterArr
  1262. * @param array<string, mixed> $opArr
  1263. */
  1264. protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
  1265. {
  1266. if ($search !== '') {
  1267. return false;
  1268. }
  1269. foreach ($filterArr as $fk => $fv) {
  1270. if (is_array($fv)) {
  1271. continue;
  1272. }
  1273. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  1274. continue;
  1275. }
  1276. if ($fv === null) {
  1277. continue;
  1278. }
  1279. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  1280. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  1281. if ($sym === '' || $sym === '=') {
  1282. continue;
  1283. }
  1284. return false;
  1285. }
  1286. return true;
  1287. }
  1288. /**
  1289. * 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
  1290. *
  1291. * @param array<int, mixed> $rows
  1292. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1293. */
  1294. protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
  1295. {
  1296. $buckets = [
  1297. 'czlyq' => [],
  1298. 'CCLBMMC' => [],
  1299. 'cywyxm' => [],
  1300. 'CGYMC' => [],
  1301. ];
  1302. foreach ($rows as $r) {
  1303. if (!is_array($r)) {
  1304. continue;
  1305. }
  1306. foreach ($buckets as $field => &$set) {
  1307. if (count($set) >= $maxPerField) {
  1308. continue;
  1309. }
  1310. $v = trim((string)($r[$field] ?? ''));
  1311. if ($v !== '') {
  1312. $set[$v] = $v;
  1313. }
  1314. }
  1315. unset($set);
  1316. $full = true;
  1317. foreach ($buckets as $set) {
  1318. if (count($set) < $maxPerField) {
  1319. $full = false;
  1320. break;
  1321. }
  1322. }
  1323. if ($full) {
  1324. break;
  1325. }
  1326. }
  1327. foreach ($buckets as &$set) {
  1328. if ($set !== []) {
  1329. // 保证 json 编码为对象(避免 list 下标 0,1,2… 被前端当选项)
  1330. $normalized = [];
  1331. foreach ($set as $k => $v) {
  1332. $s = trim((string)(is_scalar($v) ? $v : $k));
  1333. if ($s === '') {
  1334. continue;
  1335. }
  1336. $normalized[$s] = $s;
  1337. }
  1338. ksort($normalized, SORT_STRING);
  1339. $set = $normalized;
  1340. }
  1341. }
  1342. unset($set);
  1343. return $buckets;
  1344. }
  1345. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  1346. public function pick()
  1347. {
  1348. $this->request->filter(['strip_tags', 'trim']);
  1349. if (!$this->request->isAjax()) {
  1350. $this->assignProcuremenListPage('pick', '协助下发');
  1351. return $this->view->fetch('procuremen/index');
  1352. }
  1353. return $this->index();
  1354. }
  1355. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  1356. public function audit()
  1357. {
  1358. $this->request->filter(['strip_tags', 'trim']);
  1359. if (!$this->request->isAjax()) {
  1360. $this->assignProcuremenListPage('audit', '确认供应商');
  1361. return $this->view->fetch('procuremen/index');
  1362. }
  1363. return $this->index();
  1364. }
  1365. /** 采购确认(定标) */
  1366. public function confirm()
  1367. {
  1368. $this->request->filter(['strip_tags', 'trim']);
  1369. if (!$this->request->isAjax()) {
  1370. $this->assignProcuremenListPage('confirm', '采购确认');
  1371. return $this->view->fetch('procuremen/index');
  1372. }
  1373. return $this->index();
  1374. }
  1375. /**
  1376. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  1377. */
  1378. public function index()
  1379. {
  1380. $this->request->filter(['strip_tags', 'trim']);
  1381. if (!$this->request->isAjax()) {
  1382. $this->assignProcuremenListPage('pick', '协助下发');
  1383. return $this->view->fetch('procuremen/index');
  1384. }
  1385. if ($this->request->request('keyField')) {
  1386. return $this->selectpage();
  1387. }
  1388. $this->procuremenReleaseSessionLock();
  1389. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  1390. $limit = max(10, min(500, (int)$limit));
  1391. $ym = $this->request->request('ym', '');
  1392. $ym = is_string($ym) ? trim($ym) : '';
  1393. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  1394. $wffTab = $this->resolveProcuremenListStage();
  1395. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1396. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  1397. ? $this->resolveProcuremenDefaultYm($wffTab)
  1398. : date('Y-m');
  1399. }
  1400. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1401. $ym = date('Y-m');
  1402. }
  1403. $monthStart = $ym . '-01 00:00:00';
  1404. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1405. $search = trim((string)$this->request->get('search', ''));
  1406. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  1407. $opArr = (array)json_decode($this->request->get('op', ''), true);
  1408. if (!is_array($filterArr)) {
  1409. $filterArr = [];
  1410. }
  1411. if (!is_array($opArr)) {
  1412. $opArr = [];
  1413. }
  1414. // 开标状态为计算字段,不能进池内等值筛选;单独抽出后在合并后再滤
  1415. $bidOpenStatusFilter = '';
  1416. foreach (['bid_open_status_text', 'a.bid_open_status_text'] as $bidFk) {
  1417. if (!array_key_exists($bidFk, $filterArr)) {
  1418. continue;
  1419. }
  1420. $bidOpenStatusFilter = trim((string)$filterArr[$bidFk]);
  1421. unset($filterArr[$bidFk], $opArr[$bidFk]);
  1422. }
  1423. // 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
  1424. $applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
  1425. $hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
  1426. try {
  1427. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  1428. if ($wffTab === 'audit') {
  1429. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  1430. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  1431. );
  1432. } elseif ($wffTab === 'confirm') {
  1433. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  1434. if ($dbRows === []) {
  1435. try {
  1436. $dbRows = Db::table('purchase_order')
  1437. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1438. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  1439. ->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%\')')
  1440. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  1441. ->order('pick_time', 'desc')->order('id', 'desc')
  1442. ->select();
  1443. } catch (\Throwable $e) {
  1444. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  1445. $dbRows = [];
  1446. }
  1447. }
  1448. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  1449. if ($pool === []) {
  1450. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1451. }
  1452. } else {
  1453. // 初选:按月直查 ERP(不解整包 Redis,避免长时间转圈)
  1454. if ($applyMonthRange) {
  1455. $pool = $this->loadPickPoolForYm($ym);
  1456. } else {
  1457. $pool = $this->procuremenEnsureRedisPool();
  1458. }
  1459. if (!is_array($pool)) {
  1460. $pool = [];
  1461. }
  1462. // 只针对本页候选 ID 查隐藏集,避免全表扫 purchase_order_detail
  1463. $hideSet = $this->loadPickHiddenScydgySetForIds($this->extractScydgyIdsFromPool($pool));
  1464. if ($pool !== [] && $hideSet !== []) {
  1465. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1466. if (!is_array($r)) {
  1467. return false;
  1468. }
  1469. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1470. return $id <= 0 || !isset($hideSet[$id]);
  1471. }));
  1472. }
  1473. // 手工新增(YW / scydgy_id<0)只走「新增询价/查询询价」,不进初选表格
  1474. if ($pool === []) {
  1475. return json([
  1476. 'total' => 0,
  1477. 'rows' => [],
  1478. 'activeYm' => $ym,
  1479. 'filterOptions' => (
  1480. (int)$offset === 0
  1481. && !$hasActiveSearch
  1482. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1483. )
  1484. ? $this->extractProcuremenFilterOptionsFromRows([])
  1485. : new \stdClass(),
  1486. ]);
  1487. }
  1488. }
  1489. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  1490. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  1491. $monthStart = $ym . '-01 00:00:00';
  1492. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1493. }
  1494. $filtered = $this->filterProcuremenIndexPool(
  1495. $pool,
  1496. $monthStart,
  1497. $monthEnd,
  1498. $applyMonthRange,
  1499. $search,
  1500. $filterArr,
  1501. $opArr,
  1502. $listTimePrimary
  1503. );
  1504. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1505. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1506. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1507. }
  1508. if ($wffTab === 'audit' && $bidOpenStatusFilter !== '') {
  1509. $filtered = $this->filterProcuremenPoolByBidOpenStatus($filtered, $bidOpenStatusFilter);
  1510. }
  1511. $sortField = 'ID';
  1512. if (is_string($sort) && $sort !== '') {
  1513. $parts = explode(',', $sort);
  1514. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1515. if ($sortField === '') {
  1516. $sortField = 'ID';
  1517. }
  1518. }
  1519. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1520. $nFiltered = count($filtered);
  1521. if ($nFiltered > 1) {
  1522. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1523. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1524. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1525. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1526. if ($ta === $tb) {
  1527. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1528. }
  1529. if ($ta === '') {
  1530. return 1;
  1531. }
  1532. if ($tb === '') {
  1533. return -1;
  1534. }
  1535. return strcmp($ta, $tb) * $ord;
  1536. });
  1537. } elseif ($sortField === 'ID') {
  1538. $sortKeys = [];
  1539. foreach ($filtered as $i => $row) {
  1540. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1541. }
  1542. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1543. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1544. } elseif ($sortField === 'CCYDH') {
  1545. usort($filtered, function ($a, $b) use ($ord) {
  1546. $sa = trim((string)($a['CCYDH'] ?? ''));
  1547. $sb = trim((string)($b['CCYDH'] ?? ''));
  1548. if ($sa === $sb) {
  1549. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1550. }
  1551. if ($sa === '') {
  1552. return 1;
  1553. }
  1554. if ($sb === '') {
  1555. return -1;
  1556. }
  1557. return strcmp($sa, $sb) * $ord;
  1558. });
  1559. } else {
  1560. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1561. $va = $a[$sortField] ?? null;
  1562. $vb = $b[$sortField] ?? null;
  1563. $sa = (string)$va;
  1564. $sb = (string)$vb;
  1565. if ($sa === $sb) {
  1566. return 0;
  1567. }
  1568. return strcmp($sa, $sb) * $ord;
  1569. });
  1570. }
  1571. }
  1572. $offset = max(0, (int)$offset);
  1573. $limit = max(1, (int)$limit);
  1574. $rows = array_slice($filtered, $offset, $limit);
  1575. foreach ($rows as &$rw) {
  1576. if (!is_array($rw)) {
  1577. continue;
  1578. }
  1579. $rid = (int)($rw['ID'] ?? 0);
  1580. $rw['_iss_out'] = ($wffTab !== 'pick');
  1581. }
  1582. unset($rw);
  1583. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1584. $idList = [];
  1585. foreach ($rows as $rw) {
  1586. if (!is_array($rw)) {
  1587. continue;
  1588. }
  1589. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1590. foreach ($rw['_order_merge_rows'] as $mr) {
  1591. $mid = (int)($mr['ID'] ?? 0);
  1592. if ($this->isValidScydgyRowId($mid)) {
  1593. $idList[$mid] = true;
  1594. }
  1595. }
  1596. }
  1597. $id = (int)($rw['ID'] ?? 0);
  1598. if ($this->isValidScydgyRowId($id)) {
  1599. $idList[$id] = true;
  1600. }
  1601. }
  1602. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1603. foreach ($rows as &$rw) {
  1604. if (!is_array($rw)) {
  1605. continue;
  1606. }
  1607. $mergeIds = [];
  1608. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1609. foreach ($rw['_order_merge_rows'] as $mr) {
  1610. $mid = (int)($mr['ID'] ?? 0);
  1611. if ($this->isValidScydgyRowId($mid)) {
  1612. $mergeIds[$mid] = true;
  1613. }
  1614. }
  1615. }
  1616. $rid = (int)($rw['ID'] ?? 0);
  1617. if ($this->isValidScydgyRowId($rid)) {
  1618. $mergeIds[$rid] = true;
  1619. }
  1620. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1621. $rw['po_detail_count'] = $s['cnt'];
  1622. $rw['po_amount_fill_cnt'] = $s['amt'];
  1623. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1624. }
  1625. unset($rw);
  1626. }
  1627. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1628. $idList = [];
  1629. foreach ($rows as $rw) {
  1630. if (!is_array($rw)) {
  1631. continue;
  1632. }
  1633. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1634. foreach ($rw['_order_merge_rows'] as $mr) {
  1635. $mid = (int)($mr['ID'] ?? 0);
  1636. if ($this->isValidScydgyRowId($mid)) {
  1637. $idList[$mid] = true;
  1638. }
  1639. }
  1640. }
  1641. $id = (int)($rw['ID'] ?? 0);
  1642. if ($this->isValidScydgyRowId($id)) {
  1643. $idList[$id] = true;
  1644. }
  1645. }
  1646. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1647. $bidOpenSet = [];
  1648. $manualPickSet = [];
  1649. if ($wffTab === 'audit') {
  1650. $ccydhList = [];
  1651. foreach ($rows as $rw0) {
  1652. if (!is_array($rw0)) {
  1653. continue;
  1654. }
  1655. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1656. if ($c0 !== '') {
  1657. $ccydhList[] = $c0;
  1658. }
  1659. }
  1660. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1661. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  1662. }
  1663. foreach ($rows as &$rw) {
  1664. if (!is_array($rw)) {
  1665. continue;
  1666. }
  1667. $mergeIds = [];
  1668. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1669. foreach ($rw['_order_merge_rows'] as $mr) {
  1670. $mid = (int)($mr['ID'] ?? 0);
  1671. if ($this->isValidScydgyRowId($mid)) {
  1672. $mergeIds[$mid] = true;
  1673. }
  1674. }
  1675. }
  1676. $rid = (int)($rw['ID'] ?? 0);
  1677. if ($this->isValidScydgyRowId($rid)) {
  1678. $mergeIds[$rid] = true;
  1679. }
  1680. $buckets = [];
  1681. foreach (array_keys($mergeIds) as $mid) {
  1682. if (isset($quoteBucket[$mid])) {
  1683. $buckets[] = $quoteBucket[$mid];
  1684. }
  1685. }
  1686. $supplierText = $buckets !== []
  1687. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1688. : '';
  1689. if ($wffTab === 'confirm') {
  1690. $picked = trim((string)($rw['pick_company_name'] ?? $rw['picked_supplier_name'] ?? ''));
  1691. if ($picked === '') {
  1692. // 兜底:从合并工序行取
  1693. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1694. foreach ($rw['_order_merge_rows'] as $mr) {
  1695. if (!is_array($mr)) {
  1696. continue;
  1697. }
  1698. $pn = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  1699. if ($pn !== '') {
  1700. $picked = $pn;
  1701. break;
  1702. }
  1703. }
  1704. }
  1705. }
  1706. $rw['picked_supplier_name'] = $picked;
  1707. } else {
  1708. $rw['notify_supplier_text'] = $supplierText;
  1709. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1710. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1711. $manualPicked = ($ccydh !== '' && isset($manualPickSet[$ccydh]));
  1712. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1713. $rw['manual_picked'] = $manualPicked ? 1 : 0;
  1714. if ($verified) {
  1715. $rw['bid_open_status_text'] = '已开标';
  1716. } elseif ($manualPicked) {
  1717. $rw['bid_open_status_text'] = '已指定供应商';
  1718. } else {
  1719. $rw['bid_open_status_text'] = '待开标';
  1720. }
  1721. }
  1722. }
  1723. unset($rw);
  1724. }
  1725. if (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
  1726. $this->enrichProcuremenListMilestoneTimes($rows);
  1727. $this->syncCollapsedOrderQtyPriceForList($rows);
  1728. }
  1729. if ($wffTab === 'all' && count($rows) > 0) {
  1730. $this->mergePurchaseOrder($rows);
  1731. }
  1732. if ($wffTab === 'pick' && count($rows) > 0) {
  1733. $this->mergePurchaseOrder($rows);
  1734. }
  1735. foreach ($rows as &$rwClean) {
  1736. if (is_array($rwClean)) {
  1737. unset($rwClean['_order_merge_rows']);
  1738. if (array_key_exists('NGZL', $rwClean)) {
  1739. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1740. }
  1741. }
  1742. }
  1743. unset($rwClean);
  1744. return json([
  1745. 'total' => count($filtered),
  1746. 'rows' => $rows,
  1747. 'activeYm' => $ym,
  1748. // 初选:把有数据的月份带回,替换「空月份日历」侧栏
  1749. 'sidebarYms' => ($wffTab === 'pick' && (int)$offset === 0)
  1750. ? $this->loadProcuremenSidebarYmList()
  1751. : [],
  1752. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1753. 'filterOptions' => (
  1754. (int)$offset === 0
  1755. && !$hasActiveSearch
  1756. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1757. )
  1758. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1759. : new \stdClass(),
  1760. ]);
  1761. } catch (\Throwable $e) {
  1762. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1763. return json([
  1764. 'total' => 0,
  1765. 'rows' => [],
  1766. ]);
  1767. }
  1768. }
  1769. /**
  1770. * @param array<int, array<string, mixed>> $pool
  1771. * @return int[]
  1772. */
  1773. protected function extractScydgyIdsFromPool(array $pool): array
  1774. {
  1775. $ids = [];
  1776. foreach ($pool as $r) {
  1777. if (!is_array($r)) {
  1778. continue;
  1779. }
  1780. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1781. if ($id > 0) {
  1782. $ids[$id] = $id;
  1783. }
  1784. }
  1785. return array_values($ids);
  1786. }
  1787. /**
  1788. * 仅查询指定工序 ID 是否已下发/进入后续流程(初选列表加速)
  1789. *
  1790. * @param int[] $scydgyIds
  1791. * @return array<int, true>
  1792. */
  1793. protected function loadPickHiddenScydgySetForIds(array $scydgyIds): array
  1794. {
  1795. $hideSet = [];
  1796. $scydgyIds = array_values(array_filter(array_map('intval', $scydgyIds), function ($id) {
  1797. return $id > 0;
  1798. }));
  1799. if ($scydgyIds === []) {
  1800. return $hideSet;
  1801. }
  1802. // 分批,避免 whereIn 过长
  1803. foreach (array_chunk($scydgyIds, 500) as $chunk) {
  1804. try {
  1805. $poIds = Db::table('purchase_order')
  1806. ->where('scydgy_id', 'in', $chunk)
  1807. ->where(function ($q) {
  1808. $q->whereIn('wflow_status', array_merge(
  1809. ProcuremenStatus::wflowPendingConfirmValues(),
  1810. ProcuremenStatus::wflowPendingApprovalValues()
  1811. ))
  1812. ->whereOr(function ($q1) {
  1813. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1814. })
  1815. ->whereOr(function ($q2) {
  1816. $q2->whereNotNull('pick_time')
  1817. ->where('pick_time', '<>', '')
  1818. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1819. })
  1820. ->whereOr(function ($q3) {
  1821. $q3->whereNotNull('mod_rq')
  1822. ->where('mod_rq', '<>', '')
  1823. ->where('mod_rq', 'not like', '0000-00-00%');
  1824. });
  1825. })
  1826. ->column('scydgy_id');
  1827. if (is_array($poIds)) {
  1828. foreach ($poIds as $pid) {
  1829. $k = (int)$pid;
  1830. if ($k !== 0) {
  1831. $hideSet[$k] = true;
  1832. }
  1833. }
  1834. }
  1835. } catch (\Throwable $e) {
  1836. }
  1837. try {
  1838. $detIdsQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $chunk);
  1839. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1840. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1841. if (is_array($detIds)) {
  1842. foreach ($detIds as $pid) {
  1843. $k = (int)$pid;
  1844. if ($this->isValidScydgyRowId($k)) {
  1845. $hideSet[$k] = true;
  1846. }
  1847. }
  1848. }
  1849. } catch (\Throwable $e) {
  1850. }
  1851. }
  1852. return $hideSet;
  1853. }
  1854. /**
  1855. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1856. *
  1857. * @return array<int, true>
  1858. */
  1859. protected function loadPickHiddenScydgySet(): array
  1860. {
  1861. if ($this->pickHiddenScydgySetCache !== null) {
  1862. return $this->pickHiddenScydgySetCache;
  1863. }
  1864. $cacheKey = 'procuremen_pick_hidden_scydgy_v1';
  1865. try {
  1866. $raw = redis()->get($cacheKey);
  1867. if ($raw !== false && $raw !== null && $raw !== '') {
  1868. $ids = json_decode((string)$raw, true);
  1869. if (is_array($ids)) {
  1870. $hideSet = [];
  1871. foreach ($ids as $pid) {
  1872. $k = (int)$pid;
  1873. if ($k !== 0) {
  1874. $hideSet[$k] = true;
  1875. }
  1876. }
  1877. $this->pickHiddenScydgySetCache = $hideSet;
  1878. return $hideSet;
  1879. }
  1880. }
  1881. } catch (\Throwable $e) {
  1882. }
  1883. $hideSet = [];
  1884. try {
  1885. $poIds = Db::table('purchase_order')
  1886. ->where(function ($q) {
  1887. $q->whereIn('wflow_status', array_merge(
  1888. ProcuremenStatus::wflowPendingConfirmValues(),
  1889. ProcuremenStatus::wflowPendingApprovalValues()
  1890. ))
  1891. ->whereOr(function ($q1) {
  1892. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1893. })
  1894. ->whereOr(function ($q2) {
  1895. $q2->whereNotNull('pick_time')
  1896. ->where('pick_time', '<>', '')
  1897. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1898. })
  1899. ->whereOr(function ($q3) {
  1900. $q3->whereNotNull('mod_rq')
  1901. ->where('mod_rq', '<>', '')
  1902. ->where('mod_rq', 'not like', '0000-00-00%');
  1903. });
  1904. })
  1905. ->column('scydgy_id');
  1906. if (is_array($poIds)) {
  1907. foreach ($poIds as $pid) {
  1908. $k = (int)$pid;
  1909. if ($k !== 0) {
  1910. $hideSet[$k] = true;
  1911. }
  1912. }
  1913. }
  1914. } catch (\Throwable $e) {
  1915. }
  1916. try {
  1917. $detIdsQuery = Db::table('purchase_order_detail');
  1918. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1919. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1920. if (is_array($detIds)) {
  1921. foreach ($detIds as $pid) {
  1922. $k = (int)$pid;
  1923. if ($this->isValidScydgyRowId($k)) {
  1924. $hideSet[$k] = true;
  1925. }
  1926. }
  1927. }
  1928. } catch (\Throwable $e) {
  1929. }
  1930. $this->pickHiddenScydgySetCache = $hideSet;
  1931. try {
  1932. redis()->setex($cacheKey, 90, json_encode(array_map('intval', array_keys($hideSet))));
  1933. } catch (\Throwable $e) {
  1934. }
  1935. return $hideSet;
  1936. }
  1937. /**
  1938. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1939. *
  1940. * @return array<int, array<string, mixed>>
  1941. */
  1942. protected function loadPickManualOrderRows(): array
  1943. {
  1944. try {
  1945. $dbRows = Db::table('purchase_order')
  1946. ->where('scydgy_id', '<', 0)
  1947. ->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%\')')
  1948. ->order('scydgy_id', 'asc')
  1949. ->select();
  1950. } catch (\Throwable $e) {
  1951. try {
  1952. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1953. } catch (\Throwable $e2) {
  1954. return [];
  1955. }
  1956. }
  1957. if (!is_array($dbRows) || $dbRows === []) {
  1958. return [];
  1959. }
  1960. $detailSidSet = [];
  1961. try {
  1962. $negIds = [];
  1963. foreach ($dbRows as $dbRow) {
  1964. if (!is_array($dbRow)) {
  1965. continue;
  1966. }
  1967. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1968. if ($sid < 0) {
  1969. $negIds[$sid] = true;
  1970. }
  1971. }
  1972. if ($negIds !== []) {
  1973. $detQuery = Db::table('purchase_order_detail')
  1974. ->where('scydgy_id', 'in', array_keys($negIds));
  1975. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  1976. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  1977. if (is_array($detRows)) {
  1978. foreach ($detRows as $did) {
  1979. $detailSidSet[(int)$did] = true;
  1980. }
  1981. }
  1982. }
  1983. } catch (\Throwable $e) {
  1984. }
  1985. $pool = [];
  1986. foreach ($dbRows as $dbRow) {
  1987. if (!is_array($dbRow)) {
  1988. continue;
  1989. }
  1990. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1991. if ($sid >= 0) {
  1992. continue;
  1993. }
  1994. // 已进入确认/审批的不进初选;仅废弃明细残留的仍算可下发
  1995. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  1996. continue;
  1997. }
  1998. // 仅排除已完结;空 status / 「进行中」/ 0 均保留(新建手工单)
  1999. if (ProcuremenStatus::isPoCompleted($dbRow['status'] ?? '')) {
  2000. continue;
  2001. }
  2002. if (isset($detailSidSet[$sid])) {
  2003. continue;
  2004. }
  2005. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  2006. $r['_is_manual'] = 1;
  2007. $pool[] = $r;
  2008. }
  2009. return $pool;
  2010. }
  2011. /**
  2012. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  2013. */
  2014. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  2015. {
  2016. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  2017. foreach ($keys as $k) {
  2018. $t = trim((string)($row[$k] ?? ''));
  2019. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2020. return $t;
  2021. }
  2022. }
  2023. return '';
  2024. }
  2025. /**
  2026. * 分配手工新增工序行 ID(负数递减)
  2027. */
  2028. protected function allocateManualScydgyId(): int
  2029. {
  2030. try {
  2031. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  2032. $min = (int)$min;
  2033. return $min < 0 ? $min - 1 : -1;
  2034. } catch (\Throwable $e) {
  2035. return -1;
  2036. }
  2037. }
  2038. /**
  2039. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  2040. */
  2041. protected function allocateManualOrderCcydh(): string
  2042. {
  2043. $prefix = 'YW' . date('Ymd');
  2044. $maxSeq = 0;
  2045. try {
  2046. $rows = Db::table('purchase_order')
  2047. ->where('CCYDH', 'like', $prefix . '%')
  2048. ->column('CCYDH');
  2049. if (is_array($rows)) {
  2050. foreach ($rows as $ccydh) {
  2051. $ccydh = trim((string)$ccydh);
  2052. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  2053. $maxSeq = max($maxSeq, (int)$m[1]);
  2054. }
  2055. }
  2056. }
  2057. } catch (\Throwable $e) {
  2058. }
  2059. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  2060. }
  2061. /**
  2062. * purchase_order.mod_rq 是否有有效软删除时间
  2063. */
  2064. protected function isPurchaseOrderSoftDeleted($modRq): bool
  2065. {
  2066. $t = trim((string)$modRq);
  2067. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  2068. }
  2069. /**
  2070. * 列表行 → purchase_order 写入字段
  2071. *
  2072. * @return array<string, mixed>
  2073. */
  2074. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  2075. {
  2076. return [
  2077. 'scydgy_id' => $scydgyId,
  2078. 'CCYDH' => $row['CCYDH'] ?? null,
  2079. 'CYJMC' => $row['CYJMC'] ?? null,
  2080. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2081. 'CDXMC' => $row['CDXMC'] ?? null,
  2082. 'CGYBH' => $row['CGYBH'] ?? null,
  2083. 'CGYMC' => $row['CGYMC'] ?? null,
  2084. 'CDW' => $row['CDW'] ?? null,
  2085. 'czlyq' => $row['czlyq'] ?? null,
  2086. 'NGZL' => $row['NGZL'] ?? null,
  2087. 'CDF' => $row['CDF'] ?? null,
  2088. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2089. 'MBZ' => $row['MBZ'] ?? null,
  2090. 'bwjg' => $row['bwjg'] ?? null,
  2091. 'iStatus' => $row['iStatus'] ?? null,
  2092. 'dStamp' => $row['dStamp'] ?? null,
  2093. 'dputrecord' => $row['dputrecord'] ?? null,
  2094. 'cywyxm' => $row['cywyxm'] ?? null,
  2095. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2096. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2097. ];
  2098. }
  2099. /**
  2100. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  2101. *
  2102. * @return array{po:?array<string,mixed>, hidden:bool}
  2103. */
  2104. protected function resolvePickRowPoContext(int $sid): array
  2105. {
  2106. $po = null;
  2107. try {
  2108. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2109. if (is_array($found)) {
  2110. $po = $found;
  2111. }
  2112. } catch (\Throwable $e) {
  2113. }
  2114. $hideSet = $this->loadPickHiddenScydgySet();
  2115. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  2116. }
  2117. /**
  2118. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  2119. */
  2120. protected function assertPickRowCanDelete(int $sid, array $row): void
  2121. {
  2122. $ctx = $this->resolvePickRowPoContext($sid);
  2123. $po = $ctx['po'];
  2124. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2125. return;
  2126. }
  2127. if (is_array($po)) {
  2128. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2129. throw new \InvalidArgumentException('该工序已完结,无法删除');
  2130. }
  2131. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2132. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  2133. }
  2134. }
  2135. if ($ctx['hidden']) {
  2136. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2137. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  2138. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  2139. }
  2140. }
  2141. /**
  2142. * 初选直接完结前校验
  2143. */
  2144. protected function assertPickRowCanComplete(int $sid, array $row): void
  2145. {
  2146. $ctx = $this->resolvePickRowPoContext($sid);
  2147. $po = $ctx['po'];
  2148. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2149. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  2150. }
  2151. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2152. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  2153. }
  2154. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  2155. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  2156. }
  2157. }
  2158. /**
  2159. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  2160. */
  2161. protected function softDeleteProcuremenPickRow(array $row): void
  2162. {
  2163. $sid = $this->extractScydgyRowId($row);
  2164. if (!$this->isValidScydgyRowId($sid)) {
  2165. throw new \InvalidArgumentException('无效的行主键');
  2166. }
  2167. $this->assertPickRowCanDelete($sid, $row);
  2168. $po = $this->resolvePickRowPoContext($sid)['po'];
  2169. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2170. return;
  2171. }
  2172. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2173. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  2174. }
  2175. $now = date('Y-m-d H:i:s');
  2176. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2177. if (is_array($exists)) {
  2178. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  2179. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  2180. } else {
  2181. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  2182. $data['mod_rq'] = $now;
  2183. $data['createtime'] = $now;
  2184. Db::table('purchase_order')->insert($data);
  2185. $poIdLog = (int)Db::getLastInsID();
  2186. }
  2187. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  2188. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  2189. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  2190. if ($gymcLog !== '') {
  2191. $logTail .= ' / ' . $gymcLog;
  2192. }
  2193. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  2194. }
  2195. /**
  2196. * 手工新增协助工序(写入 purchase_order)
  2197. *
  2198. * @param array<string, mixed> $params
  2199. * @return int scydgy_id
  2200. */
  2201. protected function saveManualPickOrder(array $params): int
  2202. {
  2203. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  2204. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  2205. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  2206. if ($ccydh === '') {
  2207. $ccydh = $this->allocateManualOrderCcydh();
  2208. }
  2209. $now = date('Y-m-d H:i:s');
  2210. $sid = $this->allocateManualScydgyId();
  2211. $this->ensurePurchaseOrderNotifySalesmanColumn();
  2212. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  2213. // 选择供应商 / 通知业务员:支持多选,落库用顿号拼接
  2214. $supplierName = $this->joinRfqMultiSelectValues($params['cGzzxMc'] ?? ($params['pick_company_name'] ?? ''));
  2215. $notifySalesman = $this->joinRfqMultiSelectValues($params['notify_salesman'] ?? '');
  2216. $data = [
  2217. 'scydgy_id' => $sid,
  2218. 'CCYDH' => $ccydh,
  2219. 'CYJMC' => $cyjmc,
  2220. 'CGYMC' => $cgymc,
  2221. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  2222. 'CDW' => trim((string)($params['CDW'] ?? '')),
  2223. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  2224. 'CDF' => trim((string)($params['CDF'] ?? '')),
  2225. 'cGzzxMc' => $supplierName,
  2226. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  2227. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  2228. 'notify_salesman' => $notifySalesman,
  2229. 'rfq_salesman_notified' => 0,
  2230. 'rfq_salesman_notify_time' => null,
  2231. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  2232. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  2233. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  2234. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  2235. 'createtime' => $now,
  2236. 'dStamp' => $now,
  2237. 'dputrecord' => $now,
  2238. ];
  2239. Db::table('purchase_order')->insert($data);
  2240. $poId = (int)Db::getLastInsID();
  2241. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  2242. return $sid;
  2243. }
  2244. protected function formatProcuremenRowLabel(array $row): string
  2245. {
  2246. $dh = trim((string)($row['CCYDH'] ?? ''));
  2247. $gymc = trim((string)($row['CGYMC'] ?? ''));
  2248. if ($dh !== '' && $gymc !== '') {
  2249. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  2250. }
  2251. if ($dh !== '') {
  2252. return '订单「' . $dh . '」';
  2253. }
  2254. if ($gymc !== '') {
  2255. return '工序「' . $gymc . '」';
  2256. }
  2257. $id = $this->extractScydgyRowId($row);
  2258. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  2259. }
  2260. /**
  2261. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  2262. */
  2263. protected function extractScydgyRowId(array $row): int
  2264. {
  2265. // 优先 scydgy_id,避免明细行 ID(自增主键)被误当成工序主键;手工单为负数
  2266. if (array_key_exists('scydgy_id', $row) && $row['scydgy_id'] !== null && $row['scydgy_id'] !== '') {
  2267. return (int)$row['scydgy_id'];
  2268. }
  2269. if (array_key_exists('SCYDGY_ID', $row) && $row['SCYDGY_ID'] !== null && $row['SCYDGY_ID'] !== '') {
  2270. return (int)$row['SCYDGY_ID'];
  2271. }
  2272. return (int)($row['ID'] ?? $row['id'] ?? 0);
  2273. }
  2274. protected function isValidScydgyRowId(int $id): bool
  2275. {
  2276. return ProcuremenGuard::isValidScydgyId($id);
  2277. }
  2278. protected function isManualScydgyRowId(int $id): bool
  2279. {
  2280. return $id < 0;
  2281. }
  2282. /**
  2283. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  2284. *
  2285. * @param int[] $scydgyIds
  2286. * @return array<int, string[]>
  2287. */
  2288. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  2289. {
  2290. $out = [];
  2291. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2292. if ($scydgyIds === []) {
  2293. return $out;
  2294. }
  2295. try {
  2296. $rows = Db::table('purchase_order_detail')
  2297. ->where('scydgy_id', 'in', $scydgyIds)
  2298. ->field('scydgy_id,company_name')
  2299. ->order('company_name', 'asc')
  2300. ->select();
  2301. } catch (\Throwable $e) {
  2302. $rows = [];
  2303. }
  2304. if (!is_array($rows)) {
  2305. return $out;
  2306. }
  2307. foreach ($rows as $r) {
  2308. if (!is_array($r)) {
  2309. continue;
  2310. }
  2311. $sid = (int)($r['scydgy_id'] ?? 0);
  2312. $cn = trim((string)($r['company_name'] ?? ''));
  2313. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2314. continue;
  2315. }
  2316. if (!isset($out[$sid])) {
  2317. $out[$sid] = [];
  2318. }
  2319. if (!in_array($cn, $out[$sid], true)) {
  2320. $out[$sid][] = $cn;
  2321. }
  2322. }
  2323. return $out;
  2324. }
  2325. /**
  2326. * 列表展示通知供应商(完整列表,前端单行省略展开)
  2327. *
  2328. * @param string[] $names
  2329. */
  2330. protected function formatNotifySupplierDisplay(array $names): string
  2331. {
  2332. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  2333. return trim((string)$n);
  2334. }, $names))));
  2335. if ($names === []) {
  2336. return '';
  2337. }
  2338. sort($names, SORT_STRING);
  2339. return implode("\n", $names);
  2340. }
  2341. /**
  2342. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  2343. *
  2344. * @param int[] $scydgyIds
  2345. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  2346. */
  2347. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  2348. {
  2349. $out = [];
  2350. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2351. if ($scydgyIds === []) {
  2352. return $out;
  2353. }
  2354. try {
  2355. $rows = Db::table('purchase_order_detail')
  2356. ->where('scydgy_id', 'in', $scydgyIds)
  2357. ->field('scydgy_id,company_name,amount')
  2358. ->select();
  2359. } catch (\Throwable $e) {
  2360. $rows = [];
  2361. }
  2362. if (!is_array($rows)) {
  2363. return $out;
  2364. }
  2365. foreach ($rows as $r) {
  2366. if (!is_array($r)) {
  2367. continue;
  2368. }
  2369. $sid = (int)($r['scydgy_id'] ?? 0);
  2370. $cn = trim((string)($r['company_name'] ?? ''));
  2371. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2372. continue;
  2373. }
  2374. if (!isset($out[$sid])) {
  2375. $out[$sid] = ['all' => [], 'quoted' => []];
  2376. }
  2377. $out[$sid]['all'][$cn] = true;
  2378. $am = trim((string)($r['amount'] ?? ''));
  2379. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2380. $out[$sid]['quoted'][$cn] = true;
  2381. }
  2382. }
  2383. return $out;
  2384. }
  2385. /**
  2386. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  2387. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  2388. */
  2389. protected function mergeQuotedSupplierBuckets(array $buckets): array
  2390. {
  2391. $merged = ['all' => [], 'quoted' => []];
  2392. foreach ($buckets as $b) {
  2393. if (!is_array($b)) {
  2394. continue;
  2395. }
  2396. foreach ($b['all'] ?? [] as $cn => $_) {
  2397. $merged['all'][$cn] = true;
  2398. }
  2399. foreach ($b['quoted'] ?? [] as $cn => $_) {
  2400. $merged['quoted'][$cn] = true;
  2401. }
  2402. }
  2403. return $merged;
  2404. }
  2405. /**
  2406. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  2407. */
  2408. protected function formatQuotedSupplierLines(array $bucket): string
  2409. {
  2410. $all = array_keys($bucket['all'] ?? []);
  2411. if ($all === []) {
  2412. return '';
  2413. }
  2414. sort($all, SORT_STRING);
  2415. $lines = [];
  2416. foreach ($all as $cn) {
  2417. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  2418. $lines[] = $cn . '(' . $status . ')';
  2419. }
  2420. return implode("\n", $lines);
  2421. }
  2422. /**
  2423. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  2424. */
  2425. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  2426. {
  2427. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2428. $this->view->engine->layout(false);
  2429. try {
  2430. $bodyHtml = $this->view->fetch($view);
  2431. $this->view->assign('dialogBody', $bodyHtml);
  2432. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  2433. return $this->view->fetch('procuremen/dialog_lite_shell');
  2434. } finally {
  2435. if ($restoreLayout) {
  2436. $this->view->engine->layout($restoreLayout);
  2437. }
  2438. }
  2439. }
  2440. /**
  2441. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  2442. */
  2443. protected function resolveBundleSysRq(array $bundle): string
  2444. {
  2445. foreach ($bundle['pos'] ?? [] as $po) {
  2446. if (!is_array($po)) {
  2447. continue;
  2448. }
  2449. $sr = trim((string)($po['sys_rq'] ?? ''));
  2450. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  2451. return $sr;
  2452. }
  2453. }
  2454. return '';
  2455. }
  2456. /**
  2457. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  2458. */
  2459. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  2460. {
  2461. $raw = trim((string)$sysRq);
  2462. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  2463. return true;
  2464. }
  2465. $ts = strtotime(str_replace('T', ' ', $raw));
  2466. if ($ts === false || $ts <= 0) {
  2467. return true;
  2468. }
  2469. return time() >= $ts;
  2470. }
  2471. /**
  2472. * 开标前校验:必须已过报价截止时间
  2473. *
  2474. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2475. */
  2476. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  2477. {
  2478. $sysRq = $this->resolveBundleSysRq($bundle);
  2479. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  2480. $this->error('未到招标截止日期');
  2481. }
  2482. }
  2483. /**
  2484. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  2485. *
  2486. * @param array<string, mixed> $d
  2487. * @param string $deliveryYmd
  2488. */
  2489. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  2490. {
  2491. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  2492. return max(0, (int)$d['lead_days']);
  2493. }
  2494. if ($deliveryYmd === '') {
  2495. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  2496. }
  2497. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  2498. return null;
  2499. }
  2500. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2501. $t2 = strtotime($m[1] . ' 00:00:00');
  2502. if ($t1 === false || $t2 === false) {
  2503. return null;
  2504. }
  2505. return max(0, (int)round(($t2 - $t1) / 86400));
  2506. }
  2507. /**
  2508. * @param int|null $days
  2509. */
  2510. protected function formatProcuremenLeadDaysText($days): string
  2511. {
  2512. if ($days === null || $days === '') {
  2513. return '未填写';
  2514. }
  2515. if (!is_numeric($days)) {
  2516. return '未填写';
  2517. }
  2518. return ((int)$days) . '天';
  2519. }
  2520. /**
  2521. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2522. *
  2523. * @param array<string, mixed> $line
  2524. */
  2525. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2526. {
  2527. $amountFilled = !empty($line['amount_filled']);
  2528. $deliveryFilled = !empty($line['delivery_filled']);
  2529. $leadFilled = !empty($line['lead_days_filled']);
  2530. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2531. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2532. $line['amount_show'] = '';
  2533. if (array_key_exists('amount_text', $line)) {
  2534. $line['amount_text'] = $line['unit_price_text'];
  2535. }
  2536. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2537. $line['delivery_show'] = $deliveryText;
  2538. if (array_key_exists('delivery_text', $line)) {
  2539. $line['delivery_text'] = $deliveryText;
  2540. }
  2541. $line['delivery_ymd'] = '';
  2542. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2543. $line['lead_days_show'] = $leadText;
  2544. $line['lead_days_text'] = $leadText;
  2545. $line['lead_days'] = '';
  2546. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2547. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2548. $line['subtotal_num'] = null;
  2549. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2550. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2551. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2552. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2553. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2554. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2555. $line['amount_filled'] = false;
  2556. $line['delivery_filled'] = false;
  2557. $line['lead_days_filled'] = false;
  2558. $line['is_quoted'] = false;
  2559. if (array_key_exists('quote_label', $line)) {
  2560. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2561. }
  2562. }
  2563. protected function ensurePurchaseOrderBidOpenTable(): void
  2564. {
  2565. static $ready = false;
  2566. if ($ready) {
  2567. return;
  2568. }
  2569. $cacheKey = 'procuremen_bid_open_table_ok_v1';
  2570. try {
  2571. if (Cache::get($cacheKey)) {
  2572. $ready = true;
  2573. return;
  2574. }
  2575. } catch (\Throwable $e) {
  2576. }
  2577. try {
  2578. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2579. $ready = true;
  2580. try {
  2581. Cache::set($cacheKey, 1, 86400);
  2582. } catch (\Throwable $e) {
  2583. }
  2584. } catch (\Throwable $e) {
  2585. Db::execute(
  2586. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2587. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2588. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2589. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2590. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2591. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2592. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2593. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2594. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2595. `createtime` datetime DEFAULT NULL,
  2596. PRIMARY KEY (`id`),
  2597. UNIQUE KEY `uk_ccydh` (`ccydh`)
  2598. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2599. );
  2600. $ready = true;
  2601. try {
  2602. Cache::set($cacheKey, 1, 86400);
  2603. } catch (\Throwable $e2) {
  2604. }
  2605. }
  2606. }
  2607. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  2608. {
  2609. $ccydh = trim($ccydh);
  2610. if ($ccydh === '') {
  2611. return false;
  2612. }
  2613. $this->ensurePurchaseOrderBidOpenTable();
  2614. try {
  2615. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2616. return is_array($row);
  2617. } catch (\Throwable $e) {
  2618. return false;
  2619. }
  2620. }
  2621. /**
  2622. * 批量查询订单是否已开标验证
  2623. *
  2624. * @param array<int, string> $ccydhs
  2625. * @return array<string, bool> ccydh => true
  2626. */
  2627. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  2628. {
  2629. $set = [];
  2630. $list = [];
  2631. foreach ($ccydhs as $c) {
  2632. $c = trim((string)$c);
  2633. if ($c !== '') {
  2634. $list[$c] = true;
  2635. }
  2636. }
  2637. if ($list === []) {
  2638. return $set;
  2639. }
  2640. $this->ensurePurchaseOrderBidOpenTable();
  2641. try {
  2642. $rows = Db::table('purchase_order_bid_open')
  2643. ->where('ccydh', 'in', array_keys($list))
  2644. ->field('ccydh')
  2645. ->select();
  2646. foreach ($rows as $row) {
  2647. if (!is_array($row)) {
  2648. continue;
  2649. }
  2650. $c = trim((string)($row['ccydh'] ?? ''));
  2651. if ($c !== '') {
  2652. $set[$c] = true;
  2653. }
  2654. }
  2655. } catch (\Throwable $e) {
  2656. return [];
  2657. }
  2658. return $set;
  2659. }
  2660. /**
  2661. * 批量查询订单是否已指定供应商(免开标)
  2662. *
  2663. * @param array<int, string> $ccydhs
  2664. * @return array<string, bool> ccydh => true
  2665. */
  2666. protected function loadProcuremenManualPickedCcydhSet(array $ccydhs): array
  2667. {
  2668. $set = [];
  2669. $list = [];
  2670. foreach ($ccydhs as $c) {
  2671. $c = trim((string)$c);
  2672. if ($c !== '') {
  2673. $list[$c] = true;
  2674. }
  2675. }
  2676. if ($list === []) {
  2677. return $set;
  2678. }
  2679. $this->ensurePurchaseOrderManualPickColumns();
  2680. try {
  2681. $rows = Db::table('purchase_order')
  2682. ->where('CCYDH', 'in', array_keys($list))
  2683. ->where('manual_pick', 1)
  2684. ->field('CCYDH')
  2685. ->select();
  2686. foreach ($rows as $row) {
  2687. if (!is_array($row)) {
  2688. continue;
  2689. }
  2690. $c = trim((string)($row['CCYDH'] ?? ''));
  2691. if ($c !== '') {
  2692. $set[$c] = true;
  2693. }
  2694. }
  2695. } catch (\Throwable $e) {
  2696. return [];
  2697. }
  2698. return $set;
  2699. }
  2700. /**
  2701. * 确认供应商列表:按开标状态筛选(已开标 / 已指定供应商 / 待开标)
  2702. *
  2703. * @param array<int, array<string, mixed>> $pool
  2704. * @return array<int, array<string, mixed>>
  2705. */
  2706. protected function filterProcuremenPoolByBidOpenStatus(array $pool, string $status): array
  2707. {
  2708. $status = trim($status);
  2709. if ($status === '' || !in_array($status, ['待开标', '已开标', '已指定供应商'], true)) {
  2710. return $pool;
  2711. }
  2712. $ccydhList = [];
  2713. foreach ($pool as $rw) {
  2714. if (!is_array($rw)) {
  2715. continue;
  2716. }
  2717. $c = trim((string)($rw['CCYDH'] ?? ''));
  2718. if ($c !== '') {
  2719. $ccydhList[] = $c;
  2720. }
  2721. }
  2722. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  2723. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  2724. $out = [];
  2725. foreach ($pool as $rw) {
  2726. if (!is_array($rw)) {
  2727. continue;
  2728. }
  2729. $c = trim((string)($rw['CCYDH'] ?? ''));
  2730. if ($c !== '' && isset($bidOpenSet[$c])) {
  2731. $t = '已开标';
  2732. } elseif ($c !== '' && isset($manualPickSet[$c])) {
  2733. $t = '已指定供应商';
  2734. } else {
  2735. $t = '待开标';
  2736. }
  2737. if ($t === $status) {
  2738. $out[] = $rw;
  2739. }
  2740. }
  2741. return $out;
  2742. }
  2743. /**
  2744. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  2745. *
  2746. * @param array<string, mixed> $group
  2747. */
  2748. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  2749. {
  2750. if ($quoteVisible) {
  2751. $group['remark_quote_pending'] = 0;
  2752. return;
  2753. }
  2754. $group['remark'] = '';
  2755. $group['remark_quote_pending'] = 0;
  2756. }
  2757. /**
  2758. * @param array{ccydh?:string} $bundle
  2759. */
  2760. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  2761. {
  2762. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  2763. }
  2764. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  2765. {
  2766. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  2767. return true;
  2768. }
  2769. return $this->isProcuremenManualPickedForBundle($bundle);
  2770. }
  2771. /**
  2772. * 确保 purchase_order 自选供应商字段
  2773. */
  2774. protected function ensurePurchaseOrderManualPickColumns(): void
  2775. {
  2776. static $done = false;
  2777. if ($done) {
  2778. return;
  2779. }
  2780. $done = true;
  2781. $adds = [
  2782. 'manual_pick' => "ADD COLUMN `manual_pick` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=自选供应商(免开标)' AFTER `pick_company_name`",
  2783. 'manual_pick_reason' => "ADD COLUMN `manual_pick_reason` varchar(500) NOT NULL DEFAULT '' COMMENT '自选供应商选择说明' AFTER `manual_pick`",
  2784. ];
  2785. foreach ($adds as $col => $ddl) {
  2786. try {
  2787. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  2788. if (!is_array($cols) || $cols === []) {
  2789. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  2790. }
  2791. } catch (\Throwable $e) {
  2792. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  2793. }
  2794. }
  2795. }
  2796. /**
  2797. * 是否已自选供应商(免开标查看报价)
  2798. *
  2799. * @param array{pos?:array} $bundle
  2800. */
  2801. protected function isProcuremenManualPickedForBundle(array $bundle): bool
  2802. {
  2803. $this->ensurePurchaseOrderManualPickColumns();
  2804. foreach ($bundle['pos'] ?? [] as $poRow) {
  2805. if (!is_array($poRow)) {
  2806. continue;
  2807. }
  2808. if ((int)($poRow['manual_pick'] ?? 0) === 1) {
  2809. return true;
  2810. }
  2811. }
  2812. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2813. if ($ccydh === '') {
  2814. return false;
  2815. }
  2816. try {
  2817. $v = Db::table('purchase_order')->where('CCYDH', $ccydh)->where('manual_pick', 1)->value('id');
  2818. return $v !== null && $v !== false && (int)$v > 0;
  2819. } catch (\Throwable $e) {
  2820. return false;
  2821. }
  2822. }
  2823. /**
  2824. * @param array{pos?:array} $bundle
  2825. * @return array{company:string,reason:string}
  2826. */
  2827. protected function resolveProcuremenManualPickInfo(array $bundle): array
  2828. {
  2829. $this->ensurePurchaseOrderManualPickColumns();
  2830. foreach ($bundle['pos'] ?? [] as $poRow) {
  2831. if (!is_array($poRow)) {
  2832. continue;
  2833. }
  2834. if ((int)($poRow['manual_pick'] ?? 0) !== 1) {
  2835. continue;
  2836. }
  2837. $cn = trim((string)($poRow['pick_company_name'] ?? ''));
  2838. $reason = trim((string)($poRow['manual_pick_reason'] ?? ''));
  2839. return ['company' => $cn, 'reason' => $reason];
  2840. }
  2841. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2842. if ($ccydh === '') {
  2843. return ['company' => '', 'reason' => ''];
  2844. }
  2845. try {
  2846. $row = Db::table('purchase_order')
  2847. ->where('CCYDH', $ccydh)
  2848. ->where('manual_pick', 1)
  2849. ->field('pick_company_name,manual_pick_reason')
  2850. ->order('id', 'asc')
  2851. ->find();
  2852. } catch (\Throwable $e) {
  2853. $row = null;
  2854. }
  2855. if (!is_array($row)) {
  2856. return ['company' => '', 'reason' => ''];
  2857. }
  2858. return [
  2859. 'company' => trim((string)($row['pick_company_name'] ?? '')),
  2860. 'reason' => trim((string)($row['manual_pick_reason'] ?? '')),
  2861. ];
  2862. }
  2863. protected function loadBidOpenAdminUser(int $adminId): ?array
  2864. {
  2865. if ($adminId <= 0) {
  2866. return null;
  2867. }
  2868. try {
  2869. $row = Db::name('admin')->where('id', $adminId)->find();
  2870. } catch (\Throwable $e) {
  2871. return null;
  2872. }
  2873. if (!is_array($row)) {
  2874. return null;
  2875. }
  2876. $status = strtolower(trim((string)($row['status'] ?? '')));
  2877. if ($status !== '' && $status !== 'normal') {
  2878. return null;
  2879. }
  2880. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  2881. return null;
  2882. }
  2883. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  2884. if (!preg_match('/^1\d{10}$/', $phone)) {
  2885. return null;
  2886. }
  2887. $name = trim((string)($row['nickname'] ?? ''));
  2888. if ($name === '') {
  2889. $name = trim((string)($row['username'] ?? ''));
  2890. }
  2891. return [
  2892. 'id' => (int)$row['id'],
  2893. 'username' => trim((string)($row['username'] ?? '')),
  2894. 'nickname' => $name,
  2895. 'mobile' => $phone,
  2896. ];
  2897. }
  2898. /**
  2899. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  2900. */
  2901. protected function bidOpenVerifierAuthGroupRootId(): int
  2902. {
  2903. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  2904. return $id > 0 ? $id : 10;
  2905. }
  2906. /**
  2907. * @return int[]
  2908. */
  2909. protected function loadBidOpenVerifierAuthGroupIds(): array
  2910. {
  2911. static $memo = [];
  2912. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  2913. if (isset($memo[$rootId])) {
  2914. return $memo[$rootId];
  2915. }
  2916. try {
  2917. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  2918. } catch (\Throwable $e) {
  2919. $memo[$rootId] = [$rootId];
  2920. return $memo[$rootId];
  2921. }
  2922. if (!is_array($groups) || $groups === []) {
  2923. $memo[$rootId] = [$rootId];
  2924. return $memo[$rootId];
  2925. }
  2926. $groupList = [];
  2927. foreach ($groups as $g) {
  2928. if (is_array($g)) {
  2929. $groupList[] = $g;
  2930. }
  2931. }
  2932. if ($groupList === []) {
  2933. $memo[$rootId] = [$rootId];
  2934. return $memo[$rootId];
  2935. }
  2936. $tree = \fast\Tree::instance();
  2937. $tree->init($groupList);
  2938. $ids = $tree->getChildrenIds($rootId, true);
  2939. if (!is_array($ids) || $ids === []) {
  2940. $memo[$rootId] = [$rootId];
  2941. return $memo[$rootId];
  2942. }
  2943. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  2944. return $memo[$rootId];
  2945. }
  2946. protected function isBidOpenVerifierAdmin(int $adminId): bool
  2947. {
  2948. if ($adminId <= 0) {
  2949. return false;
  2950. }
  2951. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2952. if ($groupIds === []) {
  2953. return false;
  2954. }
  2955. try {
  2956. return (bool)Db::name('auth_group_access')
  2957. ->where('uid', $adminId)
  2958. ->where('group_id', 'in', $groupIds)
  2959. ->count();
  2960. } catch (\Throwable $e) {
  2961. return false;
  2962. }
  2963. }
  2964. /**
  2965. * @return array<int, array<string, mixed>>
  2966. */
  2967. protected function listBidOpenVerifierCandidates(): array
  2968. {
  2969. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2970. if ($groupIds === []) {
  2971. return [];
  2972. }
  2973. try {
  2974. $adminIds = Db::name('auth_group_access')
  2975. ->where('group_id', 'in', $groupIds)
  2976. ->column('uid');
  2977. } catch (\Throwable $e) {
  2978. $adminIds = [];
  2979. }
  2980. $adminIds = is_array($adminIds)
  2981. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  2982. : [];
  2983. if ($adminIds === []) {
  2984. return [];
  2985. }
  2986. try {
  2987. $rows = Db::name('admin')
  2988. ->where('status', 'normal')
  2989. ->where('id', 'in', $adminIds)
  2990. ->where('mobile', '<>', '')
  2991. ->order('id', 'asc')
  2992. ->select();
  2993. } catch (\Throwable $e) {
  2994. return [];
  2995. }
  2996. if (!is_array($rows)) {
  2997. return [];
  2998. }
  2999. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  3000. $out = [];
  3001. foreach ($rows as $row) {
  3002. if (!is_array($row)) {
  3003. continue;
  3004. }
  3005. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  3006. if ($one === null) {
  3007. continue;
  3008. }
  3009. $out[] = [
  3010. 'id' => $one['id'],
  3011. 'username' => $one['username'],
  3012. 'nickname' => $one['nickname'],
  3013. 'group_name' => $groupNameMap[$one['id']] ?? '',
  3014. 'mobile' => mask_phone($one['mobile']),
  3015. ];
  3016. }
  3017. return $out;
  3018. }
  3019. /**
  3020. * @param int[] $adminIds
  3021. * @return array<int, string>
  3022. */
  3023. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  3024. {
  3025. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  3026. if ($adminIds === []) {
  3027. return [];
  3028. }
  3029. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3030. try {
  3031. $rows = Db::name('auth_group_access')
  3032. ->alias('aga')
  3033. ->join('auth_group ag', 'aga.group_id = ag.id')
  3034. ->where('aga.uid', 'in', $adminIds)
  3035. ->where('aga.group_id', 'in', $groupIds)
  3036. ->field('aga.uid,ag.name')
  3037. ->order('aga.uid', 'asc')
  3038. ->order('aga.group_id', 'asc')
  3039. ->select();
  3040. } catch (\Throwable $e) {
  3041. return [];
  3042. }
  3043. if (!is_array($rows)) {
  3044. return [];
  3045. }
  3046. $out = [];
  3047. foreach ($rows as $row) {
  3048. if (!is_array($row)) {
  3049. continue;
  3050. }
  3051. $uid = (int)($row['uid'] ?? 0);
  3052. $name = trim((string)($row['name'] ?? ''));
  3053. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  3054. continue;
  3055. }
  3056. $out[$uid] = $name;
  3057. }
  3058. return $out;
  3059. }
  3060. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  3061. {
  3062. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  3063. }
  3064. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  3065. {
  3066. return 'procuremen_bidopen_wait_' . $adminId;
  3067. }
  3068. protected function renderBidOpenVerifySms(string $code): string
  3069. {
  3070. $tpl = '';
  3071. try {
  3072. $row = $this->loadNotifyTemplateRow('bid_open');
  3073. if (is_array($row)) {
  3074. $tpl = trim((string)($row['content'] ?? ''));
  3075. }
  3076. } catch (\Throwable $e) {
  3077. $tpl = '';
  3078. }
  3079. if ($tpl === '') {
  3080. $tpl = '【可集达】您的短信验证码是{code}';
  3081. }
  3082. return str_replace('{code}', $code, $tpl);
  3083. }
  3084. protected function sendBidOpenVerifySms(string $phone, string $code): void
  3085. {
  3086. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  3087. }
  3088. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  3089. {
  3090. $code = trim($code);
  3091. if (!preg_match('/^\d{6}$/', $code)) {
  3092. return false;
  3093. }
  3094. $mock = Config::get('mproc.mock_sms_code');
  3095. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3096. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3097. return true;
  3098. }
  3099. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3100. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3101. return false;
  3102. }
  3103. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3104. return true;
  3105. }
  3106. /**
  3107. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3108. */
  3109. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  3110. {
  3111. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3112. if ($ccydh === '') {
  3113. throw new \InvalidArgumentException('订单号无效');
  3114. }
  3115. $this->ensurePurchaseOrderBidOpenTable();
  3116. list($operatorId, $operatorName) = $this->GetUseName();
  3117. $now = date('Y-m-d H:i:s');
  3118. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3119. $payload = [
  3120. 'ccydh' => $ccydh,
  3121. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  3122. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  3123. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  3124. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  3125. 'operator_id' => (int)$operatorId,
  3126. 'operator_name' => trim((string)$operatorName),
  3127. 'createtime' => $now,
  3128. ];
  3129. if (is_array($exists)) {
  3130. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  3131. } else {
  3132. Db::table('purchase_order_bid_open')->insert($payload);
  3133. }
  3134. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  3135. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  3136. $labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
  3137. (int)$payload['verifier1_id'],
  3138. (int)$payload['verifier2_id'],
  3139. ]);
  3140. if (isset($labelMap[(int)$payload['verifier1_id']]) && (int)$payload['verifier1_id'] > 0) {
  3141. $name1 = $labelMap[(int)$payload['verifier1_id']];
  3142. }
  3143. if (isset($labelMap[(int)$payload['verifier2_id']]) && (int)$payload['verifier2_id'] > 0) {
  3144. $name2 = $labelMap[(int)$payload['verifier2_id']];
  3145. }
  3146. $logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
  3147. $seenSid = [];
  3148. foreach ($bundle['pos'] ?? [] as $poRow) {
  3149. if (!is_array($poRow)) {
  3150. continue;
  3151. }
  3152. $sid = (int)($poRow['scydgy_id'] ?? 0);
  3153. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  3154. continue;
  3155. }
  3156. $seenSid[$sid] = true;
  3157. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  3158. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  3159. }
  3160. if ($seenSid === []) {
  3161. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  3162. if ($this->isValidScydgyRowId($anchor)) {
  3163. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  3164. }
  3165. }
  3166. // 开标通过后计算并写入供应商服务评分
  3167. try {
  3168. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  3169. ProcuremenSupplierScore::saveForOrder($ccydh, $quoteGroups, date('Y-m', strtotime($now) ?: time()));
  3170. } catch (\Throwable $e) {
  3171. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  3172. }
  3173. }
  3174. /**
  3175. * 报价行展示字段默认值(模板安全访问)
  3176. *
  3177. * @param array<string, mixed> $line
  3178. * @return array<string, mixed>
  3179. */
  3180. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  3181. {
  3182. if (!array_key_exists('amount_quote_pending', $line)) {
  3183. $line['amount_quote_pending'] = 0;
  3184. }
  3185. if (!array_key_exists('delivery_quote_pending', $line)) {
  3186. $line['delivery_quote_pending'] = 0;
  3187. }
  3188. if (!array_key_exists('quote_before_deadline', $line)) {
  3189. $line['quote_before_deadline'] = 0;
  3190. }
  3191. if (!array_key_exists('amount_filled', $line)) {
  3192. $line['amount_filled'] = 0;
  3193. }
  3194. if (!array_key_exists('delivery_filled', $line)) {
  3195. $line['delivery_filled'] = 0;
  3196. }
  3197. if (!array_key_exists('lead_days_filled', $line)) {
  3198. $line['lead_days_filled'] = 0;
  3199. }
  3200. if (!array_key_exists('lead_days_quote_pending', $line)) {
  3201. $line['lead_days_quote_pending'] = 0;
  3202. }
  3203. if (!array_key_exists('lead_days_show', $line)) {
  3204. $line['lead_days_show'] = '未填写';
  3205. }
  3206. if (!array_key_exists('lead_days_text', $line)) {
  3207. $line['lead_days_text'] = $line['lead_days_show'];
  3208. }
  3209. return $line;
  3210. }
  3211. /**
  3212. * 审核弹窗:按供应商汇总报价明细
  3213. *
  3214. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3215. * @return array<int, array<string, mixed>>
  3216. */
  3217. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  3218. {
  3219. $sids = [];
  3220. foreach ($bundle['pos'] ?? [] as $po) {
  3221. if (!is_array($po)) {
  3222. continue;
  3223. }
  3224. $sid = (int)($po['scydgy_id'] ?? 0);
  3225. if ($this->isValidScydgyRowId($sid)) {
  3226. $sids[$sid] = true;
  3227. }
  3228. }
  3229. if ($sids === []) {
  3230. return [];
  3231. }
  3232. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3233. $gymcMap = [];
  3234. $qtyBySid = [];
  3235. $orderedSids = [];
  3236. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3237. if (!is_array($mr)) {
  3238. continue;
  3239. }
  3240. $gid = $this->extractScydgyRowId($mr);
  3241. if ($this->isValidScydgyRowId($gid)) {
  3242. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3243. $orderedSids[] = $gid;
  3244. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3245. if ($qty === '') {
  3246. $qty = trim((string)($mr['NGZL'] ?? ''));
  3247. }
  3248. $qtyBySid[$gid] = $qty;
  3249. }
  3250. }
  3251. foreach ($bundle['pos'] ?? [] as $po) {
  3252. if (!is_array($po)) {
  3253. continue;
  3254. }
  3255. $gid = (int)($po['scydgy_id'] ?? 0);
  3256. if ($this->isValidScydgyRowId($gid)) {
  3257. $nm = trim((string)($po['CGYMC'] ?? ''));
  3258. if ($nm !== '') {
  3259. $gymcMap[$gid] = $nm;
  3260. }
  3261. if (!in_array($gid, $orderedSids, true)) {
  3262. $orderedSids[] = $gid;
  3263. }
  3264. }
  3265. }
  3266. try {
  3267. $detailsQuery = Db::table('purchase_order_detail')
  3268. ->where('scydgy_id', 'in', array_keys($sids));
  3269. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3270. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  3271. } catch (\Throwable $e) {
  3272. try {
  3273. $detailsQuery = Db::table('purchase_order_detail')
  3274. ->where('scydgy_id', 'in', array_keys($sids));
  3275. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3276. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  3277. } catch (\Throwable $e2) {
  3278. $details = [];
  3279. }
  3280. }
  3281. if (!is_array($details)) {
  3282. $details = [];
  3283. }
  3284. $byCompany = [];
  3285. foreach ($details as $d) {
  3286. if (!is_array($d)) {
  3287. continue;
  3288. }
  3289. $cn = trim((string)($d['company_name'] ?? ''));
  3290. if ($cn === '') {
  3291. continue;
  3292. }
  3293. if (!isset($byCompany[$cn])) {
  3294. $ph = trim((string)($d['phone'] ?? ''));
  3295. $username = trim((string)($d['username'] ?? ''));
  3296. if ($username === '') {
  3297. $username = $this->resolveCustomerContactName($ph, $cn);
  3298. }
  3299. $byCompany[$cn] = [
  3300. 'name' => $cn,
  3301. 'email' => trim((string)($d['email'] ?? '')),
  3302. 'phone' => $ph,
  3303. 'username' => $username,
  3304. 'remark' => '',
  3305. 'has_quote' => false,
  3306. 'lines_map' => [],
  3307. ];
  3308. }
  3309. if ($byCompany[$cn]['remark'] === '') {
  3310. $rm = '';
  3311. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3312. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3313. $rm = trim((string)$d[$rk]);
  3314. break;
  3315. }
  3316. }
  3317. if ($rm !== '') {
  3318. $byCompany[$cn]['remark'] = $rm;
  3319. }
  3320. }
  3321. $sid = (int)($d['scydgy_id'] ?? 0);
  3322. $am = trim((string)($d['amount'] ?? ''));
  3323. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3324. if ($gymc === '') {
  3325. $gymc = '工序';
  3326. }
  3327. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3328. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3329. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3330. $deliveryShow = $deliveryRaw;
  3331. }
  3332. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3333. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3334. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3335. $subtotal = null;
  3336. if ($amountNum !== null) {
  3337. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3338. }
  3339. $unitPriceText = $amountFilled
  3340. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3341. : '未填写';
  3342. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3343. $leadFilled = ($leadDays !== null);
  3344. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3345. $lineRow = [
  3346. 'cgymc' => $gymc,
  3347. 'amount' => $am,
  3348. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  3349. 'amount_filled' => $amountFilled,
  3350. 'unit_price_text' => $unitPriceText,
  3351. 'delivery' => $deliveryRaw,
  3352. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  3353. 'delivery_filled' => $deliveryFilled,
  3354. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  3355. 'lead_days' => $leadFilled ? $leadDays : '',
  3356. 'lead_days_filled'=> $leadFilled,
  3357. 'lead_days_show' => $leadText,
  3358. 'lead_days_text' => $leadText,
  3359. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3360. 'subtotal_num' => $subtotal,
  3361. 'status_name' => trim((string)($d['status_name'] ?? '')),
  3362. 'is_quoted' => $amountFilled,
  3363. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  3364. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3365. ];
  3366. if (!$quoteVisible) {
  3367. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  3368. }
  3369. // 按工序 id 暂存,下面再按上方工序表顺序输出
  3370. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  3371. }
  3372. foreach ($byCompany as $cn => $g) {
  3373. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  3374. $lines = [];
  3375. $usedSids = [];
  3376. foreach ($orderedSids as $sid) {
  3377. if (!isset($linesMap[$sid])) {
  3378. continue;
  3379. }
  3380. $lines[] = $linesMap[$sid];
  3381. $usedSids[$sid] = true;
  3382. }
  3383. foreach ($linesMap as $sid => $ln) {
  3384. if (isset($usedSids[$sid])) {
  3385. continue;
  3386. }
  3387. $lines[] = $ln;
  3388. }
  3389. $total = count($lines);
  3390. $quoted = 0;
  3391. $groupTotal = 0.0;
  3392. $groupHasTotal = false;
  3393. if ($quoteVisible) {
  3394. foreach ($lines as $ln) {
  3395. $am = trim((string)($ln['amount'] ?? ''));
  3396. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  3397. $quoted++;
  3398. }
  3399. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3400. $groupTotal += (float)$ln['subtotal_num'];
  3401. $groupHasTotal = true;
  3402. }
  3403. }
  3404. }
  3405. unset($byCompany[$cn]['lines_map']);
  3406. $byCompany[$cn]['lines'] = $lines;
  3407. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  3408. $byCompany[$cn]['line_count'] = $total;
  3409. $byCompany[$cn]['has_total'] = $total > 0;
  3410. $byCompany[$cn]['has_remark'] = $total > 0;
  3411. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  3412. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3413. // 工序行 + 备注行 + 总计行
  3414. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  3415. }
  3416. $groups = array_values($byCompany);
  3417. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3418. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  3419. }
  3420. /**
  3421. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  3422. *
  3423. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3424. * @return array<int, array<string, mixed>>
  3425. */
  3426. protected function loadConfirmSupplierPickGroups(array $bundle): array
  3427. {
  3428. $sids = [];
  3429. $poIdMap = [];
  3430. foreach ($bundle['pos'] ?? [] as $po) {
  3431. if (!is_array($po)) {
  3432. continue;
  3433. }
  3434. $sid = (int)($po['scydgy_id'] ?? 0);
  3435. if ($this->isValidScydgyRowId($sid)) {
  3436. $sids[$sid] = true;
  3437. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  3438. }
  3439. }
  3440. if ($sids === []) {
  3441. return [];
  3442. }
  3443. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3444. $gymcMap = [];
  3445. $qtyBySid = [];
  3446. $orderedSids = [];
  3447. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3448. if (!is_array($mr)) {
  3449. continue;
  3450. }
  3451. $gid = $this->extractScydgyRowId($mr);
  3452. if ($this->isValidScydgyRowId($gid)) {
  3453. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3454. $orderedSids[] = $gid;
  3455. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3456. if ($qty === '') {
  3457. $qty = trim((string)($mr['NGZL'] ?? ''));
  3458. }
  3459. $qtyBySid[$gid] = $qty;
  3460. }
  3461. }
  3462. foreach ($bundle['pos'] ?? [] as $po) {
  3463. if (!is_array($po)) {
  3464. continue;
  3465. }
  3466. $gid = (int)($po['scydgy_id'] ?? 0);
  3467. if ($this->isValidScydgyRowId($gid)) {
  3468. $nm = trim((string)($po['CGYMC'] ?? ''));
  3469. if ($nm !== '') {
  3470. $gymcMap[$gid] = $nm;
  3471. }
  3472. }
  3473. }
  3474. try {
  3475. $details = Db::table('purchase_order_detail')
  3476. ->where('scydgy_id', 'in', array_keys($sids))
  3477. ->order('company_name', 'asc')
  3478. ->order('id', 'asc')
  3479. ->select();
  3480. } catch (\Throwable $e) {
  3481. try {
  3482. $details = Db::table('purchase_order_detail')
  3483. ->where('scydgy_id', 'in', array_keys($sids))
  3484. ->order('company_name', 'asc')
  3485. ->order('ID', 'asc')
  3486. ->select();
  3487. } catch (\Throwable $e2) {
  3488. $details = [];
  3489. }
  3490. }
  3491. if (!is_array($details)) {
  3492. $details = [];
  3493. }
  3494. $byCompany = [];
  3495. foreach ($details as $d) {
  3496. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3497. continue;
  3498. }
  3499. $cn = trim((string)($d['company_name'] ?? ''));
  3500. if ($cn === '') {
  3501. continue;
  3502. }
  3503. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  3504. $sid = (int)($d['scydgy_id'] ?? 0);
  3505. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  3506. continue;
  3507. }
  3508. if (!isset($byCompany[$cn])) {
  3509. $ph = trim((string)($d['phone'] ?? ''));
  3510. $username = trim((string)($d['username'] ?? ''));
  3511. if ($username === '') {
  3512. $username = $this->resolveCustomerContactName($ph, $cn);
  3513. }
  3514. $byCompany[$cn] = [
  3515. 'name' => $cn,
  3516. 'email' => trim((string)($d['email'] ?? '')),
  3517. 'phone' => $ph,
  3518. 'username' => $username,
  3519. 'remark' => '',
  3520. 'pick_lines' => [],
  3521. 'detail_picks' => [],
  3522. ];
  3523. }
  3524. if ($byCompany[$cn]['remark'] === '') {
  3525. $rm = '';
  3526. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3527. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3528. $rm = trim((string)$d[$rk]);
  3529. break;
  3530. }
  3531. }
  3532. if ($rm !== '') {
  3533. $byCompany[$cn]['remark'] = $rm;
  3534. }
  3535. }
  3536. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3537. if ($gymc === '') {
  3538. $gymc = '工序';
  3539. }
  3540. $am = trim((string)($d['amount'] ?? ''));
  3541. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3542. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3543. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3544. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3545. $deliveryShow = $deliveryRaw;
  3546. }
  3547. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3548. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3549. $subtotal = null;
  3550. if ($amountNum !== null) {
  3551. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3552. }
  3553. $unitPriceText = $amountFilled
  3554. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3555. : '未填写';
  3556. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3557. $leadFilled = ($leadDays !== null);
  3558. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3559. $pickLine = [
  3560. 'cgymc' => $gymc,
  3561. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  3562. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  3563. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  3564. 'amount_filled' => $amountFilled,
  3565. 'delivery_filled' => $deliveryFilled,
  3566. 'unit_price_text' => $unitPriceText,
  3567. 'lead_days' => $leadFilled ? $leadDays : '',
  3568. 'lead_days_filled'=> $leadFilled,
  3569. 'lead_days_show' => $leadText,
  3570. 'lead_days_text' => $leadText,
  3571. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3572. 'subtotal_num' => $subtotal,
  3573. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3574. 'is_quoted' => $amountFilled,
  3575. ];
  3576. if (!$quoteVisible) {
  3577. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  3578. }
  3579. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  3580. $byCompany[$cn]['detail_picks'][$sid] = [
  3581. 'scydgy_id' => $sid,
  3582. 'detail_id' => $detailId,
  3583. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  3584. 'cgymc' => $gymc,
  3585. ];
  3586. }
  3587. $out = [];
  3588. foreach ($byCompany as $g) {
  3589. $pickLinesMap = $g['pick_lines'] ?? [];
  3590. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  3591. continue;
  3592. }
  3593. $pickLines = [];
  3594. $usedLineSids = [];
  3595. foreach ($orderedSids as $sid) {
  3596. if (!isset($pickLinesMap[$sid])) {
  3597. continue;
  3598. }
  3599. $pickLines[] = $pickLinesMap[$sid];
  3600. $usedLineSids[$sid] = true;
  3601. }
  3602. foreach ($pickLinesMap as $sid => $ln) {
  3603. if (isset($usedLineSids[$sid])) {
  3604. continue;
  3605. }
  3606. $pickLines[] = $ln;
  3607. }
  3608. $groupTotal = 0.0;
  3609. $groupHasTotal = false;
  3610. if ($quoteVisible) {
  3611. foreach ($pickLines as $ln) {
  3612. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3613. $groupTotal += (float)$ln['subtotal_num'];
  3614. $groupHasTotal = true;
  3615. }
  3616. }
  3617. }
  3618. $lineCount = count($pickLines);
  3619. $g['pick_lines'] = $pickLines;
  3620. $g['line_count'] = $lineCount;
  3621. $g['has_total'] = $lineCount > 0;
  3622. $g['has_remark'] = $lineCount > 0;
  3623. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  3624. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3625. // 工序行 + 备注行 + 总计行
  3626. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  3627. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  3628. $detailPicks = [];
  3629. $usedPickSids = [];
  3630. foreach ($orderedSids as $sid) {
  3631. if (!isset($detailPicksMap[$sid])) {
  3632. continue;
  3633. }
  3634. $detailPicks[] = $detailPicksMap[$sid];
  3635. $usedPickSids[$sid] = true;
  3636. }
  3637. foreach ($detailPicksMap as $sid => $dp) {
  3638. if (isset($usedPickSids[$sid])) {
  3639. continue;
  3640. }
  3641. $detailPicks[] = $dp;
  3642. }
  3643. $g['detail_picks'] = $detailPicks;
  3644. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  3645. unset($g['detail_picks']);
  3646. $out[] = $g;
  3647. }
  3648. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3649. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  3650. }
  3651. /**
  3652. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  3653. * @return array<int, int[]> scydgy_id => detail_id[]
  3654. */
  3655. protected function mapDetailIdsByScydgyId(array $details): array
  3656. {
  3657. $out = [];
  3658. foreach ($details as $d) {
  3659. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3660. continue;
  3661. }
  3662. $sid = (int)($d['scydgy_id'] ?? 0);
  3663. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  3664. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  3665. continue;
  3666. }
  3667. if (!isset($out[$sid])) {
  3668. $out[$sid] = [];
  3669. }
  3670. $out[$sid][] = $pk;
  3671. }
  3672. foreach ($out as $sid => $ids) {
  3673. $out[$sid] = array_values(array_unique($ids));
  3674. }
  3675. return $out;
  3676. }
  3677. /**
  3678. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  3679. *
  3680. * @param array<string, mixed> $dbRow
  3681. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  3682. */
  3683. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  3684. {
  3685. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  3686. $r = [
  3687. 'ID' => $sid,
  3688. 'scydgy_id' => $sid,
  3689. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  3690. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  3691. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  3692. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  3693. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  3694. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  3695. 'CDW' => $dbRow['CDW'] ?? '',
  3696. 'czlyq' => $dbRow['czlyq'] ?? '',
  3697. 'NGZL' => $dbRow['NGZL'] ?? '',
  3698. 'CDF' => $dbRow['CDF'] ?? '',
  3699. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  3700. 'MBZ' => $dbRow['MBZ'] ?? '',
  3701. 'bwjg' => $dbRow['bwjg'] ?? '',
  3702. 'iStatus' => $dbRow['iStatus'] ?? '',
  3703. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  3704. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  3705. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  3706. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  3707. 'dStamp' => $dbRow['dStamp'] ?? '',
  3708. 'pick_time' => $dbRow['pick_time'] ?? '',
  3709. ];
  3710. $r['This_quantity'] = $this->resolveProcuremenThisQuantity($r);
  3711. $r['ceilingPrice'] = $this->resolveProcuremenCeilingPrice($r);
  3712. if ($sid > 0 && isset($dStampMap[$sid])) {
  3713. $t = trim((string)$dStampMap[$sid]);
  3714. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  3715. $r['dStamp'] = $dStampMap[$sid];
  3716. }
  3717. }
  3718. $dsOut = trim((string)($r['dStamp'] ?? ''));
  3719. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  3720. $ct = $dbRow['createtime'];
  3721. if (is_numeric($ct) && (int)$ct > 946684800) {
  3722. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  3723. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  3724. $r['dStamp'] = trim($ct);
  3725. }
  3726. }
  3727. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  3728. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  3729. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  3730. $fallback = trim((string)($r['dStamp'] ?? ''));
  3731. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  3732. $r['dputrecord'] = $fallback;
  3733. }
  3734. }
  3735. if (array_key_exists('id', $dbRow)) {
  3736. $r['purchase_order_id'] = (int)$dbRow['id'];
  3737. }
  3738. if ($sid < 0) {
  3739. $r['_is_manual'] = 1;
  3740. }
  3741. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  3742. $pickOut = trim((string)($r['pick_time'] ?? ''));
  3743. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  3744. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  3745. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  3746. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  3747. $r['pick_time'] = $pickFallback;
  3748. break;
  3749. }
  3750. }
  3751. }
  3752. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  3753. if ($pickNm !== '') {
  3754. $r['pick_company_name'] = $pickNm;
  3755. $r['picked_supplier_name'] = $pickNm;
  3756. }
  3757. return $r;
  3758. }
  3759. /**
  3760. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  3761. *
  3762. * @return array<int, array<string, mixed>>
  3763. */
  3764. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  3765. {
  3766. $pool = [];
  3767. if (!is_array($dbRows) || $dbRows === []) {
  3768. return $pool;
  3769. }
  3770. $dStampMap = [];
  3771. $sidList = [];
  3772. foreach ($dbRows as $tmpRow) {
  3773. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  3774. $sid = (int)$tmpRow['scydgy_id'];
  3775. if ($sid > 0) {
  3776. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  3777. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3778. $sidList[$sid] = true;
  3779. }
  3780. }
  3781. }
  3782. }
  3783. if ($sidList !== []) {
  3784. try {
  3785. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  3786. } catch (\Throwable $e) {
  3787. $dStampMap = [];
  3788. }
  3789. }
  3790. foreach ($dbRows as $dbRow) {
  3791. if (!is_array($dbRow)) {
  3792. continue;
  3793. }
  3794. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  3795. }
  3796. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  3797. $needCcydh = [];
  3798. foreach ($pool as $row) {
  3799. if (!is_array($row)) {
  3800. continue;
  3801. }
  3802. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3803. continue;
  3804. }
  3805. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3806. if ($ccydh !== '') {
  3807. $needCcydh[$ccydh] = true;
  3808. }
  3809. }
  3810. if ($needCcydh !== []) {
  3811. $czMap = [];
  3812. try {
  3813. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  3814. } catch (\Throwable $e) {
  3815. $czMap = [];
  3816. }
  3817. if (is_array($czMap) && $czMap !== []) {
  3818. foreach ($pool as &$row) {
  3819. if (!is_array($row)) {
  3820. continue;
  3821. }
  3822. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3823. continue;
  3824. }
  3825. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3826. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  3827. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  3828. }
  3829. }
  3830. unset($row);
  3831. }
  3832. }
  3833. return $pool;
  3834. }
  3835. /**
  3836. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  3837. *
  3838. * @param int[] $scydgyIds
  3839. * @return array<int, array<string, mixed>>
  3840. */
  3841. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  3842. {
  3843. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3844. if ($scydgyIds === []) {
  3845. return [];
  3846. }
  3847. try {
  3848. $list = Db::table('purchase_order_detail')
  3849. ->where('scydgy_id', 'in', $scydgyIds)
  3850. ->field('scydgy_id,company_name,amount,delivery')
  3851. ->select();
  3852. } catch (\Throwable $e) {
  3853. $list = [];
  3854. }
  3855. return is_array($list) ? $list : [];
  3856. }
  3857. /**
  3858. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  3859. *
  3860. * @param int[] $scydgyIds
  3861. * @param array<int, array<string, mixed>> $allRows
  3862. * @return array{cnt:int, amt:int, deliv:int}
  3863. */
  3864. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  3865. {
  3866. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3867. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3868. if ($scydgyIds === [] || $allRows === []) {
  3869. return $out;
  3870. }
  3871. $idSet = array_flip($scydgyIds);
  3872. $all = [];
  3873. $withAmt = [];
  3874. $withDeliv = [];
  3875. foreach ($allRows as $r) {
  3876. if (!is_array($r)) {
  3877. continue;
  3878. }
  3879. $sid = (int)($r['scydgy_id'] ?? 0);
  3880. if (!isset($idSet[$sid])) {
  3881. continue;
  3882. }
  3883. $cn = trim((string)($r['company_name'] ?? ''));
  3884. if ($cn === '') {
  3885. continue;
  3886. }
  3887. $all[$cn] = true;
  3888. $am = $r['amount'] ?? null;
  3889. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  3890. $withAmt[$cn] = true;
  3891. }
  3892. $dv = $r['delivery'] ?? null;
  3893. if ($dv !== null && trim((string)$dv) !== '') {
  3894. $withDeliv[$cn] = true;
  3895. }
  3896. }
  3897. return [
  3898. 'cnt' => count($all),
  3899. 'amt' => count($withAmt),
  3900. 'deliv' => count($withDeliv),
  3901. ];
  3902. }
  3903. /**
  3904. * 本次数量:优先 This_quantity,空则回退工作量 NGZL(与下发/确认/审批弹窗一致)
  3905. *
  3906. * @param array<string, mixed> $row
  3907. */
  3908. protected function resolveProcuremenThisQuantity(array $row): string
  3909. {
  3910. $q = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  3911. if ($q !== '') {
  3912. return $q;
  3913. }
  3914. $ngzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  3915. if (!is_scalar($ngzl)) {
  3916. return '';
  3917. }
  3918. $s = trim((string)$ngzl);
  3919. if ($s === '') {
  3920. return '';
  3921. }
  3922. if (is_numeric($s) && (float)$s === 0.0) {
  3923. return '';
  3924. }
  3925. return $s;
  3926. }
  3927. /**
  3928. * @param array<string, mixed> $row
  3929. */
  3930. protected function resolveProcuremenCeilingPrice(array $row): string
  3931. {
  3932. return trim((string)($row['ceilingPrice'] ?? $row['ceiling_price'] ?? ''));
  3933. }
  3934. /**
  3935. * 多工序数量/限价拼接:跳过空值,避免出现「、10」「304、」
  3936. *
  3937. * @param array<int, mixed> $parts
  3938. */
  3939. protected function joinProcuremenNonEmpty(array $parts, string $sep = '、'): string
  3940. {
  3941. $out = [];
  3942. foreach ($parts as $p) {
  3943. $s = trim((string)$p);
  3944. if ($s !== '') {
  3945. $out[] = $s;
  3946. }
  3947. }
  3948. return $out === [] ? '' : implode($sep, $out);
  3949. }
  3950. /**
  3951. * 确认/审批列表:合并行按各工序同步本次数量、最高限价(顿号间隔)
  3952. *
  3953. * @param array<int, array<string, mixed>> $rows
  3954. */
  3955. protected function syncCollapsedOrderQtyPriceForList(array &$rows): void
  3956. {
  3957. if ($rows === []) {
  3958. return;
  3959. }
  3960. $idList = [];
  3961. foreach ($rows as $rw) {
  3962. if (!is_array($rw)) {
  3963. continue;
  3964. }
  3965. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3966. foreach ($rw['_order_merge_rows'] as $mr) {
  3967. if (!is_array($mr)) {
  3968. continue;
  3969. }
  3970. $mid = (int)($mr['ID'] ?? 0);
  3971. if ($this->isValidScydgyRowId($mid)) {
  3972. $idList[$mid] = true;
  3973. }
  3974. }
  3975. }
  3976. $id = (int)($rw['ID'] ?? 0);
  3977. if ($this->isValidScydgyRowId($id)) {
  3978. $idList[$id] = true;
  3979. }
  3980. }
  3981. if ($idList === []) {
  3982. return;
  3983. }
  3984. try {
  3985. $list = Db::table('purchase_order')
  3986. ->where('scydgy_id', 'in', array_keys($idList))
  3987. ->field('scydgy_id,This_quantity,ceilingPrice,NGZL,pick_company_name')
  3988. ->select();
  3989. } catch (\Throwable $e) {
  3990. return;
  3991. }
  3992. if (!is_array($list)) {
  3993. return;
  3994. }
  3995. $byId = [];
  3996. foreach ($list as $dbRow) {
  3997. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  3998. continue;
  3999. }
  4000. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4001. }
  4002. foreach ($rows as &$rw) {
  4003. if (!is_array($rw)) {
  4004. continue;
  4005. }
  4006. $mergeRows = [];
  4007. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4008. $mergeRows = $rw['_order_merge_rows'];
  4009. } else {
  4010. $mergeRows = [$rw];
  4011. }
  4012. $qtyList = [];
  4013. $priceList = [];
  4014. $picked = '';
  4015. foreach ($mergeRows as $mr) {
  4016. if (!is_array($mr)) {
  4017. continue;
  4018. }
  4019. $sid = (int)($mr['ID'] ?? 0);
  4020. $db = ($sid !== 0 && isset($byId[$sid])) ? $byId[$sid] : null;
  4021. $src = $mr;
  4022. if (is_array($db)) {
  4023. $qDb = trim((string)($db['This_quantity'] ?? $db['this_quantity'] ?? ''));
  4024. $pDb = trim((string)($db['ceilingPrice'] ?? $db['ceiling_price'] ?? ''));
  4025. $ngzlDb = $db['NGZL'] ?? $db['ngzl'] ?? null;
  4026. if ($qDb !== '') {
  4027. $src['This_quantity'] = $qDb;
  4028. }
  4029. if ($pDb !== '') {
  4030. $src['ceilingPrice'] = $pDb;
  4031. }
  4032. if ($ngzlDb !== null && trim((string)$ngzlDb) !== '') {
  4033. $src['NGZL'] = $ngzlDb;
  4034. }
  4035. if ($picked === '') {
  4036. $picked = trim((string)($db['pick_company_name'] ?? ''));
  4037. }
  4038. }
  4039. if ($picked === '') {
  4040. $picked = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  4041. }
  4042. $qtyList[] = $this->resolveProcuremenThisQuantity($src);
  4043. $priceList[] = $this->resolveProcuremenCeilingPrice($src);
  4044. }
  4045. $rw['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  4046. $rw['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  4047. if ($picked !== '') {
  4048. $rw['pick_company_name'] = $picked;
  4049. $rw['picked_supplier_name'] = $picked;
  4050. }
  4051. }
  4052. unset($rw);
  4053. }
  4054. /**
  4055. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  4056. *
  4057. * @param int[] $scydgyIds
  4058. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  4059. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  4060. */
  4061. protected function OrderDetailSummary(array $scydgyIds)
  4062. {
  4063. $out = [];
  4064. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4065. if ($scydgyIds === []) {
  4066. return $out;
  4067. }
  4068. $list = [];
  4069. try {
  4070. $list = Db::table('purchase_order_detail')
  4071. ->where('scydgy_id', 'in', $scydgyIds)
  4072. ->field('id,scydgy_id,amount,delivery')
  4073. ->select();
  4074. } catch (\Throwable $e) {
  4075. $list = [];
  4076. }
  4077. if (!is_array($list)) {
  4078. return $out;
  4079. }
  4080. foreach ($list as $r) {
  4081. if (!is_array($r)) {
  4082. continue;
  4083. }
  4084. $ids = (int)($r['scydgy_id'] ?? 0);
  4085. if (!$this->isValidScydgyRowId($ids)) {
  4086. continue;
  4087. }
  4088. if (!isset($out[$ids])) {
  4089. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4090. }
  4091. $out[$ids]['cnt']++;
  4092. $am = $r['amount'] ?? null;
  4093. if ($am !== null && $am !== '') {
  4094. if (!(is_string($am) && trim($am) === '')) {
  4095. $out[$ids]['amt']++;
  4096. }
  4097. }
  4098. $dv = $r['delivery'] ?? null;
  4099. if ($dv !== null && trim((string)$dv) !== '') {
  4100. $out[$ids]['deliv']++;
  4101. }
  4102. }
  4103. return $out;
  4104. }
  4105. /**
  4106. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  4107. *
  4108. * @return array
  4109. */
  4110. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  4111. {
  4112. $strContains = function ($haystack, $needle) {
  4113. if ($needle === '') {
  4114. return false;
  4115. }
  4116. $haystack = (string)$haystack;
  4117. if (function_exists('mb_stripos')) {
  4118. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  4119. }
  4120. return stripos($haystack, $needle) !== false;
  4121. };
  4122. $stripAlias = function ($f) {
  4123. return preg_replace('/^[ab]\./i', '', (string)$f);
  4124. };
  4125. $searchColNames = [];
  4126. foreach (explode(',', $this->searchFields) as $colRaw) {
  4127. $c = $stripAlias(trim($colRaw));
  4128. if ($c !== '') {
  4129. $searchColNames[] = $c;
  4130. }
  4131. }
  4132. // 等值条件先行(表头下拉),减少后续日期解析量
  4133. $eqFilters = [];
  4134. $otherFilters = [];
  4135. foreach ($filterArr as $fk => $fv) {
  4136. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  4137. continue;
  4138. }
  4139. if (is_array($fv)) {
  4140. continue;
  4141. }
  4142. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  4143. continue;
  4144. }
  4145. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  4146. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  4147. $field = $stripAlias($fk);
  4148. if ($sym === '=' || $sym === '') {
  4149. $eqFilters[$field] = trim((string)$fv);
  4150. } else {
  4151. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  4152. }
  4153. }
  4154. $ymTarget = '';
  4155. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  4156. $ymTarget = $ymM[1];
  4157. }
  4158. $filtered = [];
  4159. foreach ($pool as $r) {
  4160. if (!is_array($r)) {
  4161. continue;
  4162. }
  4163. foreach ($eqFilters as $field => $fv) {
  4164. if (trim((string)($r[$field] ?? '')) !== $fv) {
  4165. continue 2;
  4166. }
  4167. }
  4168. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  4169. // 初选池不应含手工单;若混入则直接剔除
  4170. if ($isManual) {
  4171. continue;
  4172. }
  4173. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  4174. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  4175. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  4176. continue;
  4177. }
  4178. if ($applyMonthRange) {
  4179. $mo = (int)$m[2];
  4180. if ($mo < 1 || $mo > 12) {
  4181. continue;
  4182. }
  4183. if ($ymTarget !== '') {
  4184. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4185. if ($ymRow !== $ymTarget) {
  4186. continue;
  4187. }
  4188. } else {
  4189. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4190. $rowMonthStart = $ymRow . '-01 00:00:00';
  4191. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  4192. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  4193. continue;
  4194. }
  4195. }
  4196. }
  4197. if ($search !== '') {
  4198. $hitSearch = false;
  4199. foreach ($searchColNames as $c) {
  4200. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  4201. if ($cell !== '' && $strContains($cell, $search)) {
  4202. $hitSearch = true;
  4203. break;
  4204. }
  4205. }
  4206. if (!$hitSearch) {
  4207. continue;
  4208. }
  4209. }
  4210. foreach ($otherFilters as $item) {
  4211. $fv = $item['fv'];
  4212. $sym = $item['sym'];
  4213. $field = $item['field'];
  4214. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  4215. $cellStr = trim((string)$cell);
  4216. switch ($sym) {
  4217. case '<>':
  4218. if ((string)$cell === (string)$fv) {
  4219. continue 3;
  4220. }
  4221. break;
  4222. case 'LIKE':
  4223. case 'NOT LIKE':
  4224. $needle = trim((string)$fv);
  4225. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  4226. if ($sym === 'LIKE' && !$hit) {
  4227. continue 3;
  4228. }
  4229. if ($sym === 'NOT LIKE' && $hit) {
  4230. continue 3;
  4231. }
  4232. break;
  4233. case 'BETWEEN':
  4234. case 'RANGE':
  4235. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  4236. if (count($parts) < 2) {
  4237. $parts = is_string($fv) ? explode(',', $fv) : [];
  4238. }
  4239. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  4240. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  4241. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  4242. continue 3;
  4243. }
  4244. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  4245. continue 3;
  4246. }
  4247. break;
  4248. case '>':
  4249. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  4250. continue 3;
  4251. }
  4252. break;
  4253. case '>=':
  4254. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  4255. continue 3;
  4256. }
  4257. break;
  4258. case '<':
  4259. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  4260. continue 3;
  4261. }
  4262. break;
  4263. case '<=':
  4264. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  4265. continue 3;
  4266. }
  4267. break;
  4268. default:
  4269. if ((string)$cell !== (string)$fv) {
  4270. continue 3;
  4271. }
  4272. break;
  4273. }
  4274. }
  4275. $filtered[] = $r;
  4276. }
  4277. return $filtered;
  4278. }
  4279. /**
  4280. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  4281. */
  4282. public function snapshotToProcure()
  4283. {
  4284. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4285. $this->error(__('Invalid parameters'));
  4286. }
  4287. $row = json_decode($this->request->post('row_json', ''), true);
  4288. if (!is_array($row)) {
  4289. $this->error(__('Invalid parameters'));
  4290. }
  4291. try {
  4292. $ids = $this->extractScydgyRowId($row);
  4293. if (!$this->isValidScydgyRowId($ids)) {
  4294. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4295. }
  4296. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4297. $data = [
  4298. 'scydgy_id' => $ids,
  4299. 'CCYDH' => $row['CCYDH'] ?? null,
  4300. 'CYJMC' => $row['CYJMC'] ?? null,
  4301. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4302. 'CDXMC' => $row['CDXMC'] ?? null,
  4303. 'CGYBH' => $row['CGYBH'] ?? null,
  4304. 'CGYMC' => $row['CGYMC'] ?? null,
  4305. 'CDW' => $row['CDW'] ?? null,
  4306. 'czlyq' => $row['czlyq'] ?? null,
  4307. 'NGZL' => $row['NGZL'] ?? null,
  4308. 'CDF' => $row['CDF'] ?? null,
  4309. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4310. 'MBZ' => $row['MBZ'] ?? null,
  4311. 'bwjg' => $row['bwjg'] ?? null,
  4312. 'iStatus' => $row['iStatus'] ?? null,
  4313. 'dStamp' => $row['dStamp'] ?? null,
  4314. 'dputrecord' => $row['dputrecord'] ?? null,
  4315. 'cywyxm' => $row['cywyxm'] ?? null,
  4316. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4317. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4318. ];
  4319. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  4320. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  4321. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  4322. $this->success('操作成功');
  4323. return;
  4324. }
  4325. if ($exists) {
  4326. $upd = $data;
  4327. unset($upd['scydgy_id'], $upd['status']);
  4328. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4329. } else {
  4330. // 新增:不写 status(空/走库默认);仅写创建时间
  4331. $data['createtime'] = date('Y-m-d H:i:s');
  4332. Db::table('purchase_order')->insert($data);
  4333. }
  4334. } catch (\Throwable $e) {
  4335. $this->error($e->getMessage());
  4336. }
  4337. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  4338. $this->success('操作成功');
  4339. }
  4340. /**
  4341. * 未发列表
  4342. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  4343. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  4344. */
  4345. public function completeDirectly()
  4346. {
  4347. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4348. $this->error(__('参数错误'));
  4349. }
  4350. if (!$this->procuremenCanComplete()) {
  4351. $this->error(__('You have no permission'));
  4352. }
  4353. $row = json_decode($this->request->post('row_json', ''), true);
  4354. if (!is_array($row)) {
  4355. $this->error(__('Invalid parameters'));
  4356. }
  4357. $finishRaw = $this->request->post('finish', '1');
  4358. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  4359. $poIdLog = null;
  4360. try {
  4361. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  4362. $ids = $this->extractScydgyRowId($row);
  4363. if (!$this->isValidScydgyRowId($ids)) {
  4364. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4365. }
  4366. if ($asComplete) {
  4367. $this->assertPickRowCanComplete($ids, $row);
  4368. }
  4369. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4370. $data = [
  4371. 'scydgy_id' => $ids,
  4372. 'CCYDH' => $row['CCYDH'] ?? null,
  4373. 'CYJMC' => $row['CYJMC'] ?? null,
  4374. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4375. 'CDXMC' => $row['CDXMC'] ?? null,
  4376. 'CGYBH' => $row['CGYBH'] ?? null,
  4377. 'CGYMC' => $row['CGYMC'] ?? null,
  4378. 'CDW' => $row['CDW'] ?? null,
  4379. 'czlyq' => $row['czlyq'] ?? null,
  4380. 'NGZL' => $row['NGZL'] ?? null,
  4381. 'CDF' => $row['CDF'] ?? null,
  4382. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4383. 'MBZ' => $row['MBZ'] ?? null,
  4384. 'bwjg' => $row['bwjg'] ?? null,
  4385. 'iStatus' => $row['iStatus'] ?? null,
  4386. 'dStamp' => $row['dStamp'] ?? null,
  4387. 'dputrecord' => $row['dputrecord'] ?? null,
  4388. 'cywyxm' => $row['cywyxm'] ?? null,
  4389. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4390. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4391. ];
  4392. if ($asComplete) {
  4393. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  4394. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  4395. }
  4396. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  4397. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  4398. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  4399. $this->success('操作成功');
  4400. return;
  4401. }
  4402. if ($exists) {
  4403. $upd = $data;
  4404. unset($upd['scydgy_id']);
  4405. if (!$asComplete) {
  4406. unset($upd['status']);
  4407. }
  4408. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4409. } else {
  4410. // 新增:不写 status;完结时 $data 已含 status=1
  4411. $data['createtime'] = date('Y-m-d H:i:s');
  4412. Db::table('purchase_order')->insert($data);
  4413. }
  4414. } catch (\Throwable $e) {
  4415. $this->error($e->getMessage());
  4416. }
  4417. try {
  4418. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4419. if (is_array($rpo)) {
  4420. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4421. $poIdLog = $tid > 0 ? $tid : null;
  4422. }
  4423. } catch (\Throwable $e) {
  4424. $poIdLog = null;
  4425. }
  4426. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  4427. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  4428. if ($asComplete) {
  4429. $this->addOrderLog(
  4430. $ids,
  4431. 'mark_complete',
  4432. '点击「完结」,已标记为已完结',
  4433. $poIdLog
  4434. );
  4435. try {
  4436. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  4437. if ($pdfPublicPath === '') {
  4438. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  4439. }
  4440. } catch (\Throwable $e) {
  4441. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  4442. }
  4443. } else {
  4444. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  4445. $qtyPart = '本次数量「' . ($q !== '' ? $q : '') . '」';
  4446. $pricePart = '最高限价「' . ($p !== '' ? $p : '') . '」';
  4447. $detail = ($gymc !== '' ? ($gymc . $qtyPart) : $qtyPart) . ',' . $pricePart;
  4448. $this->addOrderLog(
  4449. $ids,
  4450. 'save_qty_price',
  4451. '保存本次数量、最高限价:' . $detail,
  4452. $poIdLog
  4453. );
  4454. }
  4455. $this->pickHiddenScydgySetCache = null;
  4456. $this->success("操作成功");
  4457. }
  4458. /**
  4459. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  4460. *
  4461. * @param array<int, array> $rows 引用传递当前页行
  4462. */
  4463. protected function mergePurchaseOrder(array &$rows)
  4464. {
  4465. if ($rows === []) {
  4466. return;
  4467. }
  4468. $ids = [];
  4469. foreach ($rows as $rw) {
  4470. if (!is_array($rw)) {
  4471. continue;
  4472. }
  4473. $id = (int)($rw['ID'] ?? 0);
  4474. // 含手工新增负数 scydgy_id,避免限价/数量不同步
  4475. if ($this->isValidScydgyRowId($id)) {
  4476. $ids[$id] = true;
  4477. }
  4478. }
  4479. $idList = array_keys($ids);
  4480. if ($idList === []) {
  4481. return;
  4482. }
  4483. try {
  4484. $list = Db::table('purchase_order')
  4485. ->where('scydgy_id', 'in', $idList)
  4486. ->field('scydgy_id,This_quantity,ceilingPrice')
  4487. ->select();
  4488. } catch (\Throwable $e) {
  4489. return;
  4490. }
  4491. if (!is_array($list)) {
  4492. return;
  4493. }
  4494. $byId = [];
  4495. foreach ($list as $dbRow) {
  4496. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4497. continue;
  4498. }
  4499. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4500. }
  4501. foreach ($rows as &$rw) {
  4502. if (!is_array($rw)) {
  4503. continue;
  4504. }
  4505. $sid = (int)($rw['ID'] ?? 0);
  4506. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  4507. continue;
  4508. }
  4509. $db = $byId[$sid];
  4510. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  4511. if (array_key_exists('This_quantity', $db)) {
  4512. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  4513. }
  4514. if (array_key_exists('ceilingPrice', $db)) {
  4515. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  4516. } elseif (array_key_exists('ceiling_price', $db)) {
  4517. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  4518. }
  4519. }
  4520. unset($rw);
  4521. }
  4522. /**
  4523. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  4524. */
  4525. public function purchaseConfirmPick()
  4526. {
  4527. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4528. $this->error(__('Invalid parameters'));
  4529. }
  4530. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  4531. $this->error(__('You have no permission'));
  4532. }
  4533. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  4534. if ($batchRaw !== '') {
  4535. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  4536. return;
  4537. }
  4538. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  4539. $sid = (int)$scydgyId;
  4540. if (!$this->isValidScydgyRowId($sid)) {
  4541. $this->error('参数无效');
  4542. }
  4543. $parseIdList = function ($raw) {
  4544. if (is_array($raw)) {
  4545. $arr = $raw;
  4546. } else {
  4547. $decoded = json_decode((string)$raw, true);
  4548. $arr = is_array($decoded) ? $decoded : [];
  4549. }
  4550. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  4551. };
  4552. $selectedRaw = $this->request->post('selected_ids', null);
  4553. if ($selectedRaw === null || $selectedRaw === '') {
  4554. $legacy = (int)$this->request->post('selected_id', 0);
  4555. $selectedIds = $legacy > 0 ? [$legacy] : [];
  4556. } else {
  4557. $selectedIds = $parseIdList($selectedRaw);
  4558. }
  4559. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  4560. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  4561. try {
  4562. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  4563. } catch (\InvalidArgumentException $e) {
  4564. $this->error($e->getMessage());
  4565. } catch (\Throwable $e) {
  4566. $this->error($e->getMessage());
  4567. }
  4568. $this->pickHiddenScydgySetCache = null;
  4569. $this->success('操作成功', '', $result);
  4570. }
  4571. /**
  4572. * 整单采购确认(多道工序一次提交)
  4573. */
  4574. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  4575. {
  4576. $decoded = json_decode($batchRaw, true);
  4577. if (!is_array($decoded) || $decoded === []) {
  4578. $this->error('提交数据无效');
  4579. }
  4580. $picks = [];
  4581. foreach ($decoded as $item) {
  4582. if (!is_array($item)) {
  4583. continue;
  4584. }
  4585. $sid = (int)($item['scydgy_id'] ?? 0);
  4586. if (!$this->isValidScydgyRowId($sid)) {
  4587. continue;
  4588. }
  4589. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  4590. if (!is_array($sel)) {
  4591. $sel = [(int)$sel];
  4592. }
  4593. $unsel = $item['unselected_ids'] ?? [];
  4594. if (!is_array($unsel)) {
  4595. $unsel = json_decode((string)$unsel, true);
  4596. $unsel = is_array($unsel) ? $unsel : [];
  4597. }
  4598. $picks[] = [
  4599. 'scydgy_id' => $sid,
  4600. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  4601. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  4602. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  4603. ];
  4604. }
  4605. if ($picks === []) {
  4606. $this->error('提交数据无效');
  4607. }
  4608. Db::startTrans();
  4609. $results = [];
  4610. try {
  4611. foreach ($picks as $pick) {
  4612. $results[] = $this->runPurchaseConfirmPick(
  4613. (int)$pick['scydgy_id'],
  4614. $pick['selected_ids'],
  4615. $pick['unselected_ids'],
  4616. (int)$pick['purchase_order_id'],
  4617. false,
  4618. false
  4619. );
  4620. }
  4621. Db::commit();
  4622. } catch (\Throwable $e) {
  4623. Db::rollback();
  4624. $msg = $e->getMessage();
  4625. $this->error($msg !== '' ? $msg : '提交失败');
  4626. }
  4627. try {
  4628. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  4629. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  4630. } catch (\Throwable $e) {
  4631. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  4632. }
  4633. $this->pickHiddenScydgySetCache = null;
  4634. $this->success('操作成功', '', ['batch' => $results]);
  4635. }
  4636. /**
  4637. * @return array<string, mixed>
  4638. */
  4639. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  4640. {
  4641. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  4642. ProcuremenGuard::assertWflowPendingApproval($poRow);
  4643. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  4644. $scydgyId = (string)$sid;
  4645. if ($selectedIds === []) {
  4646. throw new \InvalidArgumentException('请至少勾选一条明细');
  4647. }
  4648. $inter = array_intersect($selectedIds, $unselectedIds);
  4649. if ($inter !== []) {
  4650. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  4651. }
  4652. $allIds = $this->purchaseOrderDetail($sid);
  4653. if ($allIds === []) {
  4654. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  4655. }
  4656. foreach ($selectedIds as $id) {
  4657. if (!in_array($id, $allIds, true)) {
  4658. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  4659. }
  4660. }
  4661. foreach ($unselectedIds as $id) {
  4662. if (!in_array($id, $allIds, true)) {
  4663. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  4664. }
  4665. }
  4666. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  4667. sort($union, SORT_NUMERIC);
  4668. $expect = $allIds;
  4669. sort($expect, SORT_NUMERIC);
  4670. if ($union !== $expect) {
  4671. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  4672. }
  4673. if ($manageTransaction) {
  4674. Db::startTrans();
  4675. }
  4676. try {
  4677. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  4678. $aff = 0;
  4679. try {
  4680. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4681. } catch (\Throwable $e) {
  4682. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4683. }
  4684. if ($aff < 1) {
  4685. throw new \Exception('更新选中状态失败');
  4686. }
  4687. $poPayload = [
  4688. // 审核通过后进入「待入库评分」;合格/不合格后才置已完结
  4689. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  4690. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  4691. ];
  4692. if ($purchaseOrderId > 0) {
  4693. $poAff = (int)Db::table('purchase_order')
  4694. ->where('id', $purchaseOrderId)
  4695. ->where('scydgy_id', $sid)
  4696. ->update($poPayload);
  4697. if ($poAff < 1) {
  4698. throw new \Exception('主表订单不存在或与工序行不匹配');
  4699. }
  4700. } else {
  4701. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  4702. if ($poAff < 1) {
  4703. throw new \Exception('未找到');
  4704. }
  4705. }
  4706. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  4707. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  4708. if ($manageTransaction) {
  4709. Db::commit();
  4710. }
  4711. } catch (\Throwable $e) {
  4712. if ($manageTransaction) {
  4713. Db::rollback();
  4714. }
  4715. throw $e;
  4716. }
  4717. $poIdFinal = $purchaseOrderId;
  4718. if ($poIdFinal <= 0) {
  4719. try {
  4720. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4721. if (is_array($rpo)) {
  4722. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4723. }
  4724. } catch (\Throwable $e) {
  4725. $poIdFinal = 0;
  4726. }
  4727. }
  4728. $pickNames = [];
  4729. foreach ($selectedIds as $pid) {
  4730. $dr = $this->purchaseOrderDetai($sid, $pid);
  4731. $nm = trim((string)($dr['company_name'] ?? ''));
  4732. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  4733. }
  4734. $this->addOrderLog(
  4735. $sid,
  4736. 'purchase_confirm',
  4737. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  4738. $poIdFinal > 0 ? $poIdFinal : null
  4739. );
  4740. if ($sendNotifications) {
  4741. try {
  4742. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  4743. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  4744. 'scydgy_id' => $sid,
  4745. 'selected_ids' => $selectedIds,
  4746. 'unselected_ids' => $unselectedIds,
  4747. 'purchase_order_id' => $purchaseOrderId,
  4748. ]]);
  4749. } catch (\Throwable $e) {
  4750. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  4751. }
  4752. }
  4753. Log::write(sprintf(
  4754. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  4755. $scydgyId,
  4756. $purchaseOrderId,
  4757. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  4758. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  4759. ), 'notice');
  4760. $pdfPublicPath = '';
  4761. try {
  4762. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  4763. } catch (\Throwable $e) {
  4764. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  4765. }
  4766. return [
  4767. 'scydgy_id' => $scydgyId,
  4768. 'purchase_order_id' => $purchaseOrderId,
  4769. 'selected_ids' => $selectedIds,
  4770. 'unselected_ids' => $unselectedIds,
  4771. 'purchase_confirm_pdf' => $pdfPublicPath,
  4772. ];
  4773. }
  4774. /**
  4775. * 审批通过短信:按本次涉及的工序汇总 process_lines
  4776. *
  4777. * @param int[]|string[] $scydgyIds
  4778. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4779. */
  4780. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  4781. {
  4782. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4783. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4784. if ($scydgyIds === []) {
  4785. return $empty;
  4786. }
  4787. $pos = [];
  4788. try {
  4789. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  4790. } catch (\Throwable $e) {
  4791. $rows = [];
  4792. }
  4793. if (is_array($rows)) {
  4794. foreach ($rows as $po) {
  4795. if (is_array($po)) {
  4796. $pos[] = $po;
  4797. }
  4798. }
  4799. }
  4800. if ($pos === []) {
  4801. return $empty;
  4802. }
  4803. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  4804. return [
  4805. 'ccydh' => $ccydh,
  4806. 'pos' => $pos,
  4807. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4808. ];
  4809. }
  4810. /**
  4811. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  4812. *
  4813. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  4814. * @param array<int, array<string, mixed>> $picks
  4815. */
  4816. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  4817. {
  4818. if ($picks === []) {
  4819. return;
  4820. }
  4821. $fallbackDetailId = 0;
  4822. $winners = [];
  4823. $losers = [];
  4824. foreach ($picks as $pick) {
  4825. if (!is_array($pick)) {
  4826. continue;
  4827. }
  4828. $sid = (int)($pick['scydgy_id'] ?? 0);
  4829. if (!$this->isValidScydgyRowId($sid)) {
  4830. continue;
  4831. }
  4832. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  4833. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  4834. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  4835. $fallbackDetailId = (int)$selectedIds[0];
  4836. }
  4837. foreach ($selectedIds as $pid) {
  4838. $dr = $this->purchaseOrderDetai($sid, $pid);
  4839. if (!is_array($dr)) {
  4840. continue;
  4841. }
  4842. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  4843. }
  4844. foreach ($unselectedIds as $pid) {
  4845. $dr = $this->purchaseOrderDetai($sid, $pid);
  4846. if (!is_array($dr)) {
  4847. continue;
  4848. }
  4849. $key = $this->notifySupplierDedupeKey($dr);
  4850. if (!isset($winners[$key])) {
  4851. $losers[$key] = $dr;
  4852. }
  4853. }
  4854. }
  4855. if ($winners === [] && $losers === []) {
  4856. return;
  4857. }
  4858. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  4859. $sendSmsSafe = function ($phone, $content) {
  4860. $phone = trim((string)$phone);
  4861. if ($phone === '') {
  4862. return;
  4863. }
  4864. try {
  4865. $this->smsbao($phone, $content);
  4866. } catch (\Throwable $e) {
  4867. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  4868. }
  4869. };
  4870. foreach ($winners as $dr) {
  4871. $cname = trim((string)($dr['company_name'] ?? ''));
  4872. $ph = trim((string)($dr['phone'] ?? ''));
  4873. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  4874. 'company_name' => $cname,
  4875. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4876. 'phone' => $ph,
  4877. ]));
  4878. $sendSmsSafe($ph, $sms);
  4879. }
  4880. foreach ($losers as $dr) {
  4881. $cname = trim((string)($dr['company_name'] ?? ''));
  4882. $ph = trim((string)($dr['phone'] ?? ''));
  4883. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  4884. 'company_name' => $cname,
  4885. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4886. 'phone' => $ph,
  4887. ]));
  4888. $sendSmsSafe($ph, $sms);
  4889. }
  4890. }
  4891. /**
  4892. * 短信去重键:优先手机号,否则公司名
  4893. */
  4894. protected function notifySupplierDedupeKey(array $detailRow): string
  4895. {
  4896. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  4897. if ($ph !== '') {
  4898. return 'p:' . $ph;
  4899. }
  4900. $cn = trim((string)($detailRow['company_name'] ?? ''));
  4901. return 'c:' . $cn;
  4902. }
  4903. /**
  4904. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  4905. *
  4906. * @param int[] $detailIds
  4907. */
  4908. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  4909. {
  4910. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  4911. if ($detailIds === []) {
  4912. return;
  4913. }
  4914. $payload = ['status_name' => $statusName];
  4915. try {
  4916. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  4917. } catch (\Throwable $e) {
  4918. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  4919. }
  4920. }
  4921. /**
  4922. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  4923. */
  4924. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  4925. {
  4926. try {
  4927. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  4928. } catch (\Throwable $e) {
  4929. return;
  4930. }
  4931. if (!is_array($rows)) {
  4932. return;
  4933. }
  4934. foreach ($rows as $dr) {
  4935. if (!is_array($dr)) {
  4936. continue;
  4937. }
  4938. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  4939. if ($id <= 0) {
  4940. continue;
  4941. }
  4942. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  4943. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  4944. try {
  4945. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  4946. } catch (\Throwable $e) {
  4947. }
  4948. }
  4949. }
  4950. /**
  4951. * @param array<string, mixed> $detailRow
  4952. */
  4953. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  4954. {
  4955. $am = $detailRow['amount'] ?? null;
  4956. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  4957. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  4958. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  4959. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  4960. }
  4961. /**
  4962. * @return int[]
  4963. */
  4964. protected function purchaseOrderDetail(int $scydgyId): array
  4965. {
  4966. if (!$this->isValidScydgyRowId($scydgyId)) {
  4967. return [];
  4968. }
  4969. try {
  4970. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  4971. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  4972. $list = $listQuery->select();
  4973. } catch (\Throwable $e) {
  4974. return [];
  4975. }
  4976. if (!is_array($list)) {
  4977. return [];
  4978. }
  4979. $ids = [];
  4980. foreach ($list as $r) {
  4981. if (!is_array($r)) {
  4982. continue;
  4983. }
  4984. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  4985. if ($pk > 0) {
  4986. $ids[] = $pk;
  4987. }
  4988. }
  4989. return array_values(array_unique($ids));
  4990. }
  4991. /**
  4992. * 获取当前登录用户信息 [id, 展示名]
  4993. */
  4994. protected function GetUseName(): array
  4995. {
  4996. $id = 0;
  4997. $name = '';
  4998. try {
  4999. if ($this->auth && $this->auth->isLogin()) {
  5000. $u = $this->auth->getUserInfo();
  5001. if (is_array($u)) {
  5002. $id = (int)($u['id'] ?? 0);
  5003. $name = trim((string)($u['nickname'] ?? ''));
  5004. if ($name === '') {
  5005. $name = trim((string)($u['username'] ?? ''));
  5006. }
  5007. }
  5008. }
  5009. } catch (\Throwable $e) {
  5010. }
  5011. if ($name === '') {
  5012. $name = '未知用户';
  5013. }
  5014. return [$id, $name];
  5015. }
  5016. /**
  5017. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  5018. */
  5019. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  5020. {
  5021. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  5022. }
  5023. /**
  5024. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  5025. *
  5026. * @param array<int, array<string, mixed>> $rows
  5027. */
  5028. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  5029. {
  5030. $sidList = [];
  5031. foreach ($rows as $rw) {
  5032. if (!is_array($rw)) {
  5033. continue;
  5034. }
  5035. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5036. foreach ($rw['_order_merge_rows'] as $mr) {
  5037. $mid = (int)($mr['ID'] ?? 0);
  5038. if ($this->isValidScydgyRowId($mid)) {
  5039. $sidList[$mid] = true;
  5040. }
  5041. }
  5042. }
  5043. $id = (int)($rw['ID'] ?? 0);
  5044. if ($this->isValidScydgyRowId($id)) {
  5045. $sidList[$id] = true;
  5046. }
  5047. }
  5048. $sids = array_keys($sidList);
  5049. $issueBySid = [];
  5050. $confirmBySid = [];
  5051. $approveBySid = [];
  5052. if ($sids !== []) {
  5053. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  5054. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  5055. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  5056. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  5057. try {
  5058. $logs = Db::table('purchase_order_oper_log')
  5059. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  5060. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  5061. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  5062. ->order('id', 'asc')
  5063. ->select();
  5064. } catch (\Throwable $e) {
  5065. $logs = [];
  5066. }
  5067. if (is_array($logs)) {
  5068. $issueSet = array_fill_keys($issueActs, true);
  5069. $confirmSet = array_fill_keys($confirmActs, true);
  5070. $approveSet = array_fill_keys($approveActs, true);
  5071. foreach ($logs as $lg) {
  5072. if (!is_array($lg)) {
  5073. continue;
  5074. }
  5075. $lg = ProcuremenOperLog::normalizeRow($lg);
  5076. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  5077. if ($sid === 0) {
  5078. continue;
  5079. }
  5080. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  5081. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  5082. if ($t === '') {
  5083. continue;
  5084. }
  5085. if (isset($issueSet[$action])) {
  5086. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  5087. $issueBySid[$sid] = $t;
  5088. }
  5089. }
  5090. if (isset($confirmSet[$action])) {
  5091. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  5092. $confirmBySid[$sid] = $t;
  5093. }
  5094. }
  5095. if (isset($approveSet[$action])) {
  5096. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  5097. $approveBySid[$sid] = $t;
  5098. }
  5099. }
  5100. }
  5101. }
  5102. }
  5103. foreach ($rows as &$rw) {
  5104. if (!is_array($rw)) {
  5105. continue;
  5106. }
  5107. $mergeSids = [];
  5108. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5109. foreach ($rw['_order_merge_rows'] as $mr) {
  5110. $mid = (int)($mr['ID'] ?? 0);
  5111. if ($this->isValidScydgyRowId($mid)) {
  5112. $mergeSids[] = $mid;
  5113. }
  5114. }
  5115. }
  5116. $rid = (int)($rw['ID'] ?? 0);
  5117. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  5118. $mergeSids[] = $rid;
  5119. }
  5120. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  5121. $issue = $pick;
  5122. $confirm = '';
  5123. $approve = '';
  5124. foreach ($mergeSids as $sid) {
  5125. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  5126. $issue = $issueBySid[$sid];
  5127. }
  5128. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  5129. $confirm = $confirmBySid[$sid];
  5130. }
  5131. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  5132. $approve = $approveBySid[$sid];
  5133. }
  5134. }
  5135. if ($issue === '' && $pick !== '') {
  5136. $issue = $pick;
  5137. }
  5138. $rw['issue_time'] = $issue;
  5139. $rw['confirm_time'] = $confirm;
  5140. $rw['approve_time'] = $approve;
  5141. }
  5142. unset($rw);
  5143. }
  5144. /**
  5145. * 按主键取一条
  5146. */
  5147. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  5148. {
  5149. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  5150. return [];
  5151. }
  5152. try {
  5153. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  5154. if (is_array($one)) {
  5155. return $one;
  5156. }
  5157. } catch (\Throwable $e) {
  5158. }
  5159. try {
  5160. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  5161. if (is_array($one)) {
  5162. return $one;
  5163. }
  5164. } catch (\Throwable $e) {
  5165. }
  5166. return [];
  5167. }
  5168. /**
  5169. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  5170. */
  5171. protected function formatProcuremenDetailTime($v): string
  5172. {
  5173. if ($v === null || $v === '') {
  5174. return '';
  5175. }
  5176. if (is_numeric($v) && (int)$v > 946684800) {
  5177. return date('Y-m-d H:i:s', (int)$v);
  5178. }
  5179. return ProcuremenTime::formatDisplayDateTime($v);
  5180. }
  5181. /**
  5182. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  5183. */
  5184. protected function formatDeliveryYmd($v): string
  5185. {
  5186. if ($v === null || $v === '') {
  5187. return '';
  5188. }
  5189. $s = trim((string)$v);
  5190. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  5191. return '';
  5192. }
  5193. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5194. return $m[1];
  5195. }
  5196. $ts = strtotime($s);
  5197. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  5198. }
  5199. /**
  5200. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  5201. */
  5202. protected function detailRowSupplierOperated(array $r): bool
  5203. {
  5204. $am = $r['amount'] ?? null;
  5205. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5206. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5207. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5208. return $okAmt || $okDel;
  5209. }
  5210. /**
  5211. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  5212. */
  5213. protected function resolveDetailSupplierOperTime(array $r): string
  5214. {
  5215. if (!$this->detailRowSupplierOperated($r)) {
  5216. return '';
  5217. }
  5218. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  5219. if ($t !== '') {
  5220. return $t;
  5221. }
  5222. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  5223. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  5224. continue;
  5225. }
  5226. $t = $this->formatProcuremenDetailTime($r[$col]);
  5227. if ($t !== '') {
  5228. return $t;
  5229. }
  5230. }
  5231. return '';
  5232. }
  5233. /**
  5234. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  5235. */
  5236. protected function detailRowSupplierAccepted(array $r): bool
  5237. {
  5238. $am = $r['amount'] ?? null;
  5239. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5240. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5241. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5242. return $okAmt && $okDel;
  5243. }
  5244. /**
  5245. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  5246. */
  5247. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  5248. {
  5249. if ($detailCount > 0) {
  5250. return true;
  5251. }
  5252. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  5253. return true;
  5254. }
  5255. $pickTime = trim((string)($main['pick_time'] ?? ''));
  5256. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  5257. return true;
  5258. }
  5259. return false;
  5260. }
  5261. /**
  5262. * 下发时间:优先 pick_time,其次首条下发明细时间
  5263. */
  5264. protected function resolveProcuremenIssueTime(array $main, array $details): string
  5265. {
  5266. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  5267. if ($issueTime !== '') {
  5268. return $issueTime;
  5269. }
  5270. foreach ($details as $dr) {
  5271. if (!is_array($dr)) {
  5272. continue;
  5273. }
  5274. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5275. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  5276. $issueTime = $t;
  5277. }
  5278. }
  5279. if ($issueTime !== '') {
  5280. return $issueTime;
  5281. }
  5282. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5283. }
  5284. /**
  5285. * 直接点「完结」时间:优先操作记录 mark_complete
  5286. */
  5287. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  5288. {
  5289. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  5290. }
  5291. /**
  5292. * 操作记录时间(取指定 action 最近一条)
  5293. *
  5294. * @param string|array<int, string> $actions
  5295. */
  5296. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  5297. {
  5298. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  5299. }
  5300. /**
  5301. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  5302. *
  5303. * @param array $main purchase_order 一行
  5304. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  5305. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  5306. */
  5307. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  5308. {
  5309. $issueCnt = count($details);
  5310. $acceptCnt = 0;
  5311. $pickedName = '';
  5312. $pickedTime = '';
  5313. foreach ($details as $dr) {
  5314. if (!is_array($dr)) {
  5315. continue;
  5316. }
  5317. if ($this->detailRowSupplierAccepted($dr)) {
  5318. $acceptCnt++;
  5319. }
  5320. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5321. if ($pickedName === '') {
  5322. $pickedName = trim((string)($dr['company_name'] ?? ''));
  5323. }
  5324. if ($pickedTime === '') {
  5325. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  5326. if ($pickedTime === '') {
  5327. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5328. }
  5329. }
  5330. }
  5331. }
  5332. $hasMain = $main !== [];
  5333. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  5334. if ($poTime === '') {
  5335. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  5336. }
  5337. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  5338. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  5339. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  5340. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  5341. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  5342. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  5343. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  5344. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  5345. $inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
  5346. $inboundResult = '';
  5347. if ($scydgyId > 0) {
  5348. try {
  5349. $inRow = Db::table('purchase_order_inbound_score')
  5350. ->where('scydgy_id', $scydgyId)
  5351. ->field('result,updatetime,createtime')
  5352. ->find();
  5353. } catch (\Throwable $e) {
  5354. $inRow = null;
  5355. }
  5356. if (is_array($inRow) && $inRow !== []) {
  5357. $inboundResult = trim((string)($inRow['result'] ?? ''));
  5358. if ($inboundScoreTime === '') {
  5359. $inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
  5360. }
  5361. }
  5362. }
  5363. $inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
  5364. $supplierTime = '';
  5365. if ($acceptCnt > 0) {
  5366. foreach ($details as $dr) {
  5367. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  5368. continue;
  5369. }
  5370. $t = $this->resolveDetailSupplierOperTime($dr);
  5371. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  5372. $supplierTime = $t;
  5373. }
  5374. }
  5375. }
  5376. $directComplete = ($mainCompleted && !$issued);
  5377. $doneTime = '';
  5378. if ($mainCompleted) {
  5379. if ($directComplete) {
  5380. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  5381. }
  5382. if ($doneTime === '' && $inboundScoreTime !== '') {
  5383. $doneTime = $inboundScoreTime;
  5384. }
  5385. if ($doneTime === '') {
  5386. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5387. }
  5388. if ($doneTime === '') {
  5389. foreach ($details as $dr) {
  5390. if (!is_array($dr)) {
  5391. continue;
  5392. }
  5393. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  5394. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  5395. $doneTime = $t;
  5396. }
  5397. }
  5398. }
  5399. if ($doneTime === '') {
  5400. $doneTime = $poTime;
  5401. }
  5402. // 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
  5403. if ($doneTime === '' && $confirmApproveTime !== '') {
  5404. $doneTime = $confirmApproveTime;
  5405. }
  5406. }
  5407. if ($directComplete) {
  5408. // 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
  5409. $step1Done = $hasMain;
  5410. $step2Done = false;
  5411. $step3Done = false;
  5412. $step4Done = false;
  5413. $step5Done = false;
  5414. $stepInboundDone = $inboundScored;
  5415. $step6Done = $mainCompleted && $inboundScored;
  5416. } else {
  5417. $step1Done = $issued;
  5418. $step2Done = $issued;
  5419. $step3Done = $acceptCnt > 0;
  5420. $step4Done = $wflowPendingApproval;
  5421. if (!$step4Done) {
  5422. foreach ($details as $dr) {
  5423. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5424. $step4Done = true;
  5425. break;
  5426. }
  5427. }
  5428. }
  5429. $step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
  5430. $stepInboundDone = $inboundScored;
  5431. // 未确认合格/不合格时,「已完结」保持未点亮(灰色)
  5432. $step6Done = $mainCompleted && $inboundScored;
  5433. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  5434. if ($mainCompleted && $issued) {
  5435. $step3Done = true;
  5436. $step4Done = true;
  5437. $step5Done = true;
  5438. // 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
  5439. if ($supplierTime === '') {
  5440. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5441. if ($fillT !== '') {
  5442. $supplierTime = $fillT;
  5443. }
  5444. }
  5445. if ($pickedTime === '') {
  5446. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5447. if ($fillT !== '') {
  5448. $pickedTime = $fillT;
  5449. }
  5450. }
  5451. if ($auditSelectTime === '') {
  5452. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5453. if ($fillT !== '') {
  5454. $auditSelectTime = $fillT;
  5455. }
  5456. }
  5457. if ($confirmApproveTime === '') {
  5458. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5459. if ($fillT !== '') {
  5460. $confirmApproveTime = $fillT;
  5461. }
  5462. }
  5463. }
  5464. }
  5465. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  5466. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  5467. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  5468. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  5469. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  5470. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  5471. $inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
  5472. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  5473. $deadlineLines = [];
  5474. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  5475. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  5476. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  5477. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  5478. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  5479. }
  5480. }
  5481. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  5482. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  5483. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  5484. if ($deliveryDisp === '') {
  5485. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  5486. }
  5487. if ($deliveryDisp !== '') {
  5488. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  5489. }
  5490. }
  5491. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  5492. $deadlineText = implode("\n", $deadlineLines);
  5493. $prefixOperTime = static function (string $t): string {
  5494. $t = trim($t);
  5495. if ($t === '' || $t === '—') {
  5496. return $t;
  5497. }
  5498. if (strpos($t, '操作时间') === 0) {
  5499. return $t;
  5500. }
  5501. return '操作时间:' . $t;
  5502. };
  5503. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  5504. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  5505. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
  5506. $stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5507. $step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5508. $steps = [
  5509. [
  5510. 'title' => '未发',
  5511. 'subtitle' => '',
  5512. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  5513. 'done' => $step1Done,
  5514. ],
  5515. [
  5516. 'title' => '下发',
  5517. 'subtitle' => $deadlineText,
  5518. 'time' => $prefixOperTime($step2Time),
  5519. 'done' => $step2Done,
  5520. ],
  5521. [
  5522. 'title' => '供应商接单',
  5523. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  5524. 'time' => '',
  5525. 'done' => $step3Done,
  5526. ],
  5527. [
  5528. 'title' => '待确认',
  5529. 'subtitle' => $step4Done
  5530. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  5531. : ($issued ? '待选供应商' : ''),
  5532. 'time' => $prefixOperTime($step4Time),
  5533. 'done' => $step4Done,
  5534. ],
  5535. [
  5536. 'title' => '待审批',
  5537. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  5538. 'time' => $prefixOperTime($step5Time),
  5539. 'done' => $step5Done,
  5540. ],
  5541. [
  5542. 'title' => '是否合格',
  5543. 'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
  5544. 'time' => $prefixOperTime($stepInboundTime),
  5545. 'done' => $stepInboundDone,
  5546. ],
  5547. [
  5548. 'title' => '已完结',
  5549. 'subtitle' => '',
  5550. 'time' => $prefixOperTime($step6Time),
  5551. 'done' => $step6Done,
  5552. ],
  5553. ];
  5554. $currentIdx = count($steps) - 1;
  5555. if ($directComplete) {
  5556. // 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
  5557. if (!$step6Done) {
  5558. foreach ($steps as $i => $s) {
  5559. if (($s['title'] ?? '') === '是否合格') {
  5560. $currentIdx = $i;
  5561. break;
  5562. }
  5563. }
  5564. }
  5565. } else {
  5566. foreach ($steps as $i => $s) {
  5567. if (!$s['done']) {
  5568. $currentIdx = $i;
  5569. break;
  5570. }
  5571. }
  5572. }
  5573. $nSteps = count($steps);
  5574. foreach ($steps as $idx => &$s) {
  5575. $s['current'] = ($idx === $currentIdx);
  5576. if ($idx === 0) {
  5577. $s['pdf_left_bg'] = '';
  5578. } else {
  5579. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  5580. }
  5581. if ($idx >= $nSteps - 1) {
  5582. $s['pdf_right_bg'] = '';
  5583. } else {
  5584. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  5585. }
  5586. }
  5587. unset($s);
  5588. $labelMap = [
  5589. 'CCYDH' => '订单号',
  5590. 'CYJMC' => '印件名称',
  5591. 'CCLBMMC' => '承揽部门',
  5592. 'CGYMC' => '工序名称',
  5593. 'CDW' => '单位',
  5594. 'czlyq' => '类型',
  5595. 'NGZL' => '工作量',
  5596. 'CDF' => '单价',
  5597. 'cGzzxMc' => '工作中心',
  5598. 'MBZ' => '备注',
  5599. 'This_quantity' => '本次数量',
  5600. 'ceilingPrice' => '最高限价',
  5601. ];
  5602. $orderSummary = [];
  5603. foreach ($labelMap as $key => $lab) {
  5604. if (!array_key_exists($key, $main)) {
  5605. continue;
  5606. }
  5607. $val = $main[$key];
  5608. if ($val === null) {
  5609. $val = '';
  5610. } elseif (!is_scalar($val)) {
  5611. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  5612. } else {
  5613. $val = (string)$val;
  5614. }
  5615. $orderSummary[] = ['label' => $lab, 'value' => $val];
  5616. }
  5617. $orderSummary[] = [
  5618. 'label' => '是否合格',
  5619. 'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
  5620. ];
  5621. $orderSummaryGrid = [];
  5622. $n = count($orderSummary);
  5623. for ($i = 0; $i < $n; $i += 2) {
  5624. $left = $orderSummary[$i];
  5625. $hasRight = ($i + 1) < $n;
  5626. $orderSummaryGrid[] = [
  5627. 'l1' => $left['label'],
  5628. 'v1' => $left['value'],
  5629. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  5630. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  5631. ];
  5632. }
  5633. return [
  5634. 'steps' => $steps,
  5635. 'orderSummary' => $orderSummary,
  5636. 'orderSummaryGrid' => $orderSummaryGrid,
  5637. 'inbound_result' => $inboundResult,
  5638. 'inbound_score_time'=> $inboundScoreTime,
  5639. 'detailRows' => $details,
  5640. ];
  5641. }
  5642. /**
  5643. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  5644. *
  5645. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  5646. */
  5647. protected function prepareProcuremenDetailsView(string $ids): array
  5648. {
  5649. $main = [];
  5650. try {
  5651. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5652. $main = is_array($one) ? $one : [];
  5653. } catch (\Throwable $e) {
  5654. $main = [];
  5655. }
  5656. $details = [];
  5657. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  5658. if ($mergeRows === []) {
  5659. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  5660. if ($mergeRows === [] && $main !== []) {
  5661. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  5662. }
  5663. }
  5664. $detailSidList = [];
  5665. $anchorSid = (int)$ids;
  5666. if ($anchorSid !== 0) {
  5667. $detailSidList[$anchorSid] = true;
  5668. }
  5669. foreach ($mergeRows as $mr) {
  5670. if (!is_array($mr)) {
  5671. continue;
  5672. }
  5673. $sid = $this->extractScydgyRowId($mr);
  5674. if ($sid !== 0) {
  5675. $detailSidList[$sid] = true;
  5676. }
  5677. }
  5678. try {
  5679. if ($detailSidList !== []) {
  5680. $details = Db::table('purchase_order_detail')
  5681. ->where('scydgy_id', 'in', array_keys($detailSidList))
  5682. ->order('id', 'asc')
  5683. ->select();
  5684. }
  5685. } catch (\Throwable $e) {
  5686. $details = [];
  5687. }
  5688. if (!is_array($details)) {
  5689. $details = [];
  5690. }
  5691. foreach ($details as &$r) {
  5692. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  5693. $r['id'] = $r['ID'];
  5694. }
  5695. if (isset($r['createtime'])) {
  5696. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  5697. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  5698. } else {
  5699. $r['createtime_text'] = (string)$r['createtime'];
  5700. }
  5701. } else {
  5702. $r['createtime_text'] = '';
  5703. }
  5704. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  5705. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  5706. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  5707. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  5708. if (is_array($r)) {
  5709. $r = $this->maskSupplierContactFields($r);
  5710. }
  5711. }
  5712. unset($r);
  5713. $activeDetails = [];
  5714. foreach ($details as $r) {
  5715. if (is_array($r) && empty($r['is_void'])) {
  5716. $activeDetails[] = $r;
  5717. }
  5718. }
  5719. $operLogs = [];
  5720. try {
  5721. $operSidList = array_keys($detailSidList);
  5722. if ($operSidList === [] && (int)$ids !== 0) {
  5723. $operSidList = [(int)$ids];
  5724. }
  5725. if ($operSidList !== []) {
  5726. $operLogs = Db::table('purchase_order_oper_log')
  5727. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  5728. ->order('id', 'asc')
  5729. ->select();
  5730. }
  5731. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  5732. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  5733. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  5734. if ($poId > 0) {
  5735. $operLogs = Db::table('purchase_order_oper_log')
  5736. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  5737. ->order('id', 'asc')
  5738. ->select();
  5739. }
  5740. }
  5741. } catch (\Throwable $e) {
  5742. $operLogs = [];
  5743. }
  5744. if (!is_array($operLogs)) {
  5745. $operLogs = [];
  5746. }
  5747. $operLogsRaw = $operLogs;
  5748. $processNameBySid = [];
  5749. foreach ($mergeRows as $mr) {
  5750. if (!is_array($mr)) {
  5751. continue;
  5752. }
  5753. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  5754. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5755. if ($psid !== 0 && $gymc !== '') {
  5756. $processNameBySid[$psid] = $gymc;
  5757. }
  5758. }
  5759. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  5760. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
  5761. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  5762. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  5763. if ($ccydh === '') {
  5764. foreach ($details as $r) {
  5765. if (!is_array($r)) {
  5766. continue;
  5767. }
  5768. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  5769. if ($ccydh !== '') {
  5770. break;
  5771. }
  5772. }
  5773. }
  5774. $this->view->assign('ccydh', $ccydh);
  5775. $this->view->assign('steps', $bundle['steps']);
  5776. $this->view->assign('orderSummary', $bundle['orderSummary']);
  5777. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  5778. $this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
  5779. $this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
  5780. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  5781. $this->view->assign('processCount', count($mergeRows));
  5782. $this->view->assign('detailRows', $details);
  5783. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  5784. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  5785. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  5786. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  5787. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  5788. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  5789. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  5790. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  5791. $this->view->assign('operLogs', $operLogs);
  5792. $sg = $quoteView['supplier_groups'] ?? [];
  5793. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
  5794. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  5795. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
  5796. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
  5797. return [
  5798. 'ok' => $main !== [] || $details !== [],
  5799. 'ccydh' => $ccydh,
  5800. ];
  5801. }
  5802. /**
  5803. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  5804. */
  5805. public function details()
  5806. {
  5807. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5808. if (is_array($ids)) {
  5809. $ids = isset($ids[0]) ? $ids[0] : '';
  5810. }
  5811. $ids = trim((string)$ids);
  5812. if ($ids === '') {
  5813. $this->error(__('Invalid parameters'));
  5814. }
  5815. $this->assertManualOrderDetailsViewable((int)$ids);
  5816. $this->prepareProcuremenDetailsView($ids);
  5817. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  5818. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  5819. $this->view->engine->layout(false);
  5820. try {
  5821. return $this->view->fetch('procuremen/details_dialog_shell');
  5822. } finally {
  5823. if ($restoreLayout) {
  5824. $this->view->engine->layout($restoreLayout);
  5825. }
  5826. }
  5827. }
  5828. /**
  5829. * 解析合并审核工序行(订单号须一致,且均未协助)
  5830. *
  5831. * @return array<int, array<string, mixed>>
  5832. */
  5833. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  5834. {
  5835. $primary = json_decode($rowJson, true);
  5836. if (!is_array($primary)) {
  5837. $this->error(__('Invalid parameters'));
  5838. }
  5839. $merge = json_decode($mergeRowsJson, true);
  5840. if (!is_array($merge) || $merge === []) {
  5841. $merge = [$primary];
  5842. }
  5843. $seen = [];
  5844. $out = [];
  5845. foreach ($merge as $r) {
  5846. if (!is_array($r)) {
  5847. continue;
  5848. }
  5849. $id = $this->extractScydgyRowId($r);
  5850. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  5851. continue;
  5852. }
  5853. $seen[$id] = true;
  5854. $out[] = $r;
  5855. }
  5856. if ($out === []) {
  5857. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  5858. }
  5859. $ccydh = null;
  5860. foreach ($out as $r) {
  5861. $dh = trim((string)($r['CCYDH'] ?? ''));
  5862. if ($ccydh === null) {
  5863. $ccydh = $dh;
  5864. } elseif ($dh !== $ccydh) {
  5865. $this->error('合并审核要求所选行的订单号一致');
  5866. }
  5867. }
  5868. $ids = [];
  5869. foreach ($out as $r) {
  5870. $id = $this->extractScydgyRowId($r);
  5871. if ($this->isValidScydgyRowId($id)) {
  5872. $ids[$id] = true;
  5873. }
  5874. }
  5875. $poBySid = [];
  5876. $detCntBySid = [];
  5877. if ($ids !== []) {
  5878. $idList = array_keys($ids);
  5879. try {
  5880. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  5881. if (is_array($poList)) {
  5882. foreach ($poList as $po) {
  5883. if (!is_array($po)) {
  5884. continue;
  5885. }
  5886. $sid = (int)($po['scydgy_id'] ?? 0);
  5887. if ($this->isValidScydgyRowId($sid)) {
  5888. $poBySid[$sid] = $po;
  5889. }
  5890. }
  5891. }
  5892. } catch (\Throwable $e) {
  5893. }
  5894. try {
  5895. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  5896. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  5897. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  5898. if (is_array($detRows)) {
  5899. foreach ($detRows as $dr) {
  5900. if (!is_array($dr)) {
  5901. continue;
  5902. }
  5903. $sid = (int)($dr['scydgy_id'] ?? 0);
  5904. if ($this->isValidScydgyRowId($sid)) {
  5905. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  5906. }
  5907. }
  5908. }
  5909. } catch (\Throwable $e) {
  5910. }
  5911. }
  5912. foreach ($out as $r) {
  5913. $id = $this->extractScydgyRowId($r);
  5914. if (!$this->isValidScydgyRowId($id)) {
  5915. continue;
  5916. }
  5917. $po = $poBySid[$id] ?? null;
  5918. if (!is_array($po)) {
  5919. continue;
  5920. }
  5921. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  5922. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5923. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  5924. }
  5925. $detCnt = (int)($detCntBySid[$id] ?? 0);
  5926. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  5927. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5928. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  5929. }
  5930. }
  5931. return $out;
  5932. }
  5933. /**
  5934. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  5935. */
  5936. protected function maskSupplierContactFields(array $item): array
  5937. {
  5938. if (array_key_exists('email', $item)) {
  5939. $item['email'] = mask_email((string)$item['email']);
  5940. }
  5941. if (array_key_exists('phone', $item)) {
  5942. $item['phone'] = mask_phone((string)$item['phone']);
  5943. }
  5944. return $item;
  5945. }
  5946. /**
  5947. * @param array<int, array<string, mixed>> $list
  5948. * @return array<int, array<string, mixed>>
  5949. */
  5950. protected function maskSupplierContactList(array $list): array
  5951. {
  5952. $out = [];
  5953. foreach ($list as $item) {
  5954. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  5955. }
  5956. return $out;
  5957. }
  5958. /**
  5959. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  5960. *
  5961. * @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
  5962. * @return array<string, string>|null
  5963. */
  5964. protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
  5965. {
  5966. if (!is_array($row)) {
  5967. return null;
  5968. }
  5969. $norm = [];
  5970. foreach ($row as $k => $v) {
  5971. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  5972. }
  5973. $row = $norm;
  5974. $st = $row['status'] ?? '';
  5975. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  5976. return null;
  5977. }
  5978. $companyName = '';
  5979. foreach (['company_name', 'name'] as $nk) {
  5980. if (!empty($row[$nk])) {
  5981. $companyName = trim((string)$row[$nk]);
  5982. break;
  5983. }
  5984. }
  5985. if ($companyName === '') {
  5986. return null;
  5987. }
  5988. $username = '';
  5989. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  5990. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  5991. $username = trim((string)$row[$uk]);
  5992. break;
  5993. }
  5994. }
  5995. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  5996. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  5997. if ($phone === '' && isset($row['account'])) {
  5998. $phone = trim((string)$row['account']);
  5999. }
  6000. if ($phone === '' && isset($row['mobile'])) {
  6001. $phone = trim((string)$row['mobile']);
  6002. }
  6003. if ($requireContactChannels && $email === '' && $phone === '') {
  6004. return null;
  6005. }
  6006. $category = '';
  6007. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6008. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6009. $category = trim((string)$row[$ck]);
  6010. break;
  6011. }
  6012. }
  6013. return [
  6014. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  6015. 'name' => $companyName,
  6016. 'company_name' => $companyName,
  6017. 'username' => $username,
  6018. 'email' => $email,
  6019. 'phone' => $phone,
  6020. 'category' => $category,
  6021. 'company_type' => $category,
  6022. ];
  6023. }
  6024. /**
  6025. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  6026. */
  6027. protected function resolveCustomerContactById(string $id): ?array
  6028. {
  6029. $id = trim($id);
  6030. if ($id === '' || !ctype_digit($id)) {
  6031. return null;
  6032. }
  6033. try {
  6034. $row = Db::table('customer')->where('id', (int)$id)->find();
  6035. } catch (\Throwable $e) {
  6036. return null;
  6037. }
  6038. return $this->buildCustomerContactPayloadFromRow($row);
  6039. }
  6040. /**
  6041. * 按供应商名称解析联系信息(兼容旧提交数据)
  6042. *
  6043. * @param bool $requireContactChannels true 时须有邮箱或手机
  6044. */
  6045. protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
  6046. {
  6047. $name = trim($name);
  6048. if ($name === '') {
  6049. return null;
  6050. }
  6051. try {
  6052. // customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
  6053. $row = Db::table('customer')
  6054. ->where('company_name', $name)
  6055. ->order('id', 'desc')
  6056. ->find();
  6057. } catch (\Throwable $e) {
  6058. return null;
  6059. }
  6060. return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
  6061. }
  6062. /**
  6063. * 规范化下发/确认时勾选的供应商
  6064. *
  6065. * @param array<int, mixed> $companies
  6066. * @return array<int, array<string, string>>
  6067. */
  6068. protected function normalizePickCompanies(array $companies): array
  6069. {
  6070. $out = [];
  6071. foreach ($companies as $c) {
  6072. if (!is_array($c)) {
  6073. continue;
  6074. }
  6075. $resolved = null;
  6076. $cid = trim((string)($c['id'] ?? ''));
  6077. if ($cid !== '') {
  6078. $resolved = $this->resolveCustomerContactById($cid);
  6079. }
  6080. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  6081. if ($resolved === null && $name !== '') {
  6082. $resolved = $this->resolveCustomerContactByCompanyName($name);
  6083. }
  6084. if ($resolved === null) {
  6085. continue;
  6086. }
  6087. $out[] = $resolved;
  6088. }
  6089. return $out;
  6090. }
  6091. /**
  6092. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  6093. *
  6094. * @param array<int, array<string, mixed>> $pool
  6095. * @return array<int, array<string, mixed>>
  6096. */
  6097. protected function collapseProcuremenPoolByOrder(array $pool): array
  6098. {
  6099. if ($pool === []) {
  6100. return [];
  6101. }
  6102. $groups = [];
  6103. foreach ($pool as $row) {
  6104. if (!is_array($row)) {
  6105. continue;
  6106. }
  6107. $dh = trim((string)($row['CCYDH'] ?? ''));
  6108. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  6109. if (!isset($groups[$key])) {
  6110. $groups[$key] = [];
  6111. }
  6112. $groups[$key][] = $row;
  6113. }
  6114. $out = [];
  6115. foreach ($groups as $ccydh => $rows) {
  6116. if ($rows === []) {
  6117. continue;
  6118. }
  6119. usort($rows, function ($a, $b) {
  6120. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  6121. });
  6122. $head = $rows[0];
  6123. $gymcList = [];
  6124. foreach ($rows as $r) {
  6125. $g = trim((string)($r['CGYMC'] ?? ''));
  6126. if ($g !== '' && !in_array($g, $gymcList, true)) {
  6127. $gymcList[] = $g;
  6128. }
  6129. }
  6130. $merged = $head;
  6131. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  6132. $merged['process_count'] = count($rows);
  6133. $merged['_order_merge_rows'] = $rows;
  6134. $qtyList = [];
  6135. $priceList = [];
  6136. foreach ($rows as $r) {
  6137. if (!is_array($r)) {
  6138. continue;
  6139. }
  6140. $qtyList[] = $this->resolveProcuremenThisQuantity($r);
  6141. $priceList[] = $this->resolveProcuremenCeilingPrice($r);
  6142. }
  6143. if (count($rows) > 1) {
  6144. $merged['CGYMC'] = implode('、', $gymcList);
  6145. // 多工序:数量/限价按有值项顿号间隔(空值不占位)
  6146. $merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  6147. $merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  6148. } else {
  6149. $merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
  6150. $merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
  6151. }
  6152. // 已选供应商:取合并行中首个非空 pick_company_name
  6153. $pickedName = '';
  6154. foreach ($rows as $r) {
  6155. if (!is_array($r)) {
  6156. continue;
  6157. }
  6158. $pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
  6159. if ($pn !== '') {
  6160. $pickedName = $pn;
  6161. break;
  6162. }
  6163. }
  6164. if ($pickedName !== '') {
  6165. $merged['pick_company_name'] = $pickedName;
  6166. $merged['picked_supplier_name'] = $pickedName;
  6167. }
  6168. $mergedPickTime = '';
  6169. foreach ($rows as $r) {
  6170. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  6171. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  6172. $mergedPickTime = $t;
  6173. }
  6174. }
  6175. if ($mergedPickTime !== '') {
  6176. $merged['pick_time'] = $mergedPickTime;
  6177. }
  6178. $out[] = $merged;
  6179. }
  6180. usort($out, function ($a, $b) {
  6181. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  6182. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  6183. if ($ta === $tb) {
  6184. $ida = (int)($a['purchase_order_id'] ?? 0);
  6185. $idb = (int)($b['purchase_order_id'] ?? 0);
  6186. if ($ida !== $idb) {
  6187. return $idb <=> $ida;
  6188. }
  6189. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  6190. }
  6191. if ($ta === '') {
  6192. return 1;
  6193. }
  6194. if ($tb === '') {
  6195. return -1;
  6196. }
  6197. return strcmp($tb, $ta);
  6198. });
  6199. return $out;
  6200. }
  6201. /**
  6202. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  6203. *
  6204. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6205. */
  6206. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  6207. {
  6208. $scydgyId = trim($scydgyId);
  6209. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6210. if ($scydgyId === '') {
  6211. return $empty;
  6212. }
  6213. try {
  6214. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6215. } catch (\Throwable $e) {
  6216. $anchor = null;
  6217. }
  6218. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  6219. return $empty;
  6220. }
  6221. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6222. if ($ccydh === '') {
  6223. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  6224. }
  6225. try {
  6226. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  6227. } catch (\Throwable $e) {
  6228. $pos = [$anchor];
  6229. }
  6230. if (!is_array($pos) || $pos === []) {
  6231. $pos = [$anchor];
  6232. }
  6233. return [
  6234. 'ccydh' => $ccydh,
  6235. 'pos' => $pos,
  6236. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6237. ];
  6238. }
  6239. /**
  6240. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  6241. */
  6242. protected function purchaseOrderRowInConfirmStage(array $po): bool
  6243. {
  6244. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6245. return false;
  6246. }
  6247. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  6248. return false;
  6249. }
  6250. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  6251. return true;
  6252. }
  6253. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  6254. $sid = (int)($po['scydgy_id'] ?? 0);
  6255. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  6256. }
  6257. return false;
  6258. }
  6259. /**
  6260. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  6261. *
  6262. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6263. */
  6264. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  6265. {
  6266. $scydgyId = trim($scydgyId);
  6267. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6268. if ($scydgyId === '') {
  6269. return $empty;
  6270. }
  6271. try {
  6272. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6273. } catch (\Throwable $e) {
  6274. $anchor = null;
  6275. }
  6276. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  6277. return $empty;
  6278. }
  6279. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6280. if ($ccydh === '') {
  6281. return [
  6282. 'ccydh' => '',
  6283. 'pos' => [$anchor],
  6284. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  6285. ];
  6286. }
  6287. try {
  6288. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  6289. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  6290. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  6291. } catch (\Throwable $e) {
  6292. $pos = [$anchor];
  6293. }
  6294. if (!is_array($pos) || $pos === []) {
  6295. $pos = [$anchor];
  6296. }
  6297. $pos = array_values(array_filter($pos, function ($po) {
  6298. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  6299. }));
  6300. if ($pos === []) {
  6301. $pos = [$anchor];
  6302. }
  6303. return [
  6304. 'ccydh' => $ccydh,
  6305. 'pos' => $pos,
  6306. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6307. ];
  6308. }
  6309. /**
  6310. * @param array<int, array<string, mixed>> $purchaseOrders
  6311. * @return array<int, array<string, mixed>>
  6312. */
  6313. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  6314. {
  6315. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  6316. $byId = [];
  6317. foreach ($pool as $r) {
  6318. if (!is_array($r)) {
  6319. continue;
  6320. }
  6321. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  6322. if ($this->isValidScydgyRowId($sid)) {
  6323. $byId[$sid] = $r;
  6324. }
  6325. }
  6326. $out = [];
  6327. foreach ($purchaseOrders as $po) {
  6328. if (!is_array($po)) {
  6329. continue;
  6330. }
  6331. $sid = (int)($po['scydgy_id'] ?? 0);
  6332. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  6333. $out[] = $byId[$sid];
  6334. }
  6335. }
  6336. return $out;
  6337. }
  6338. /**
  6339. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  6340. *
  6341. * @return array<int, array<string, mixed>>
  6342. */
  6343. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  6344. {
  6345. $scydgyId = trim($scydgyId);
  6346. if ($scydgyId === '') {
  6347. return [];
  6348. }
  6349. try {
  6350. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6351. } catch (\Throwable $e) {
  6352. $anchor = null;
  6353. }
  6354. if (!is_array($anchor)) {
  6355. return [];
  6356. }
  6357. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  6358. return [];
  6359. }
  6360. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6361. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  6362. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  6363. try {
  6364. $q = Db::table('purchase_order');
  6365. if ($ccydh !== '') {
  6366. $q->where('CCYDH', $ccydh);
  6367. } else {
  6368. $q->where('scydgy_id', $scydgyId);
  6369. }
  6370. if ($isValidPick) {
  6371. $q->where('pick_time', $pickTime);
  6372. }
  6373. $pos = $q->order('scydgy_id', 'asc')->select();
  6374. } catch (\Throwable $e) {
  6375. $pos = [$anchor];
  6376. }
  6377. if (!is_array($pos) || $pos === []) {
  6378. $pos = [$anchor];
  6379. }
  6380. $pos = array_values(array_filter($pos, function ($po) {
  6381. if (!is_array($po)) {
  6382. return false;
  6383. }
  6384. $mr = $po['mod_rq'] ?? null;
  6385. if ($mr === null || $mr === '') {
  6386. return true;
  6387. }
  6388. $mrs = trim((string)$mr);
  6389. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  6390. }));
  6391. if ($pos === []) {
  6392. $pos = [$anchor];
  6393. }
  6394. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  6395. if ($rows === []) {
  6396. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  6397. }
  6398. return $rows;
  6399. }
  6400. /**
  6401. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  6402. *
  6403. * @param array<int, array<string, mixed>> $mergeRows
  6404. * @return array<int, array<string, mixed>>
  6405. */
  6406. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  6407. {
  6408. $list = array_values($mergeRows);
  6409. $n = count($list);
  6410. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  6411. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  6412. $mergeSame = $n > 1 && $orderKey0 !== '';
  6413. if ($mergeSame) {
  6414. foreach ($list as $rr) {
  6415. if (!is_array($rr)) {
  6416. $mergeSame = false;
  6417. break;
  6418. }
  6419. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  6420. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  6421. $mergeSame = false;
  6422. break;
  6423. }
  6424. }
  6425. }
  6426. $out = [];
  6427. foreach ($list as $idx => $r) {
  6428. if (!is_array($r)) {
  6429. continue;
  6430. }
  6431. $qty = $this->resolveProcuremenThisQuantity($r);
  6432. $price = $this->resolveProcuremenCeilingPrice($r);
  6433. $sid = $this->extractScydgyRowId($r);
  6434. $out[] = [
  6435. 'seq' => $idx + 1,
  6436. 'scydgy_id' => $sid,
  6437. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6438. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6439. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6440. 'CDW' => trim((string)($r['CDW'] ?? '')),
  6441. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  6442. 'NGZL' => $r['NGZL'] ?? '',
  6443. 'This_quantity' => $qty,
  6444. 'ceilingPrice' => $price,
  6445. 'CDF' => trim((string)($r['CDF'] ?? '')),
  6446. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  6447. 'show_order_cells' => !$mergeSame || $idx === 0,
  6448. 'order_rowspan' => $mergeSame ? $n : 1,
  6449. ];
  6450. }
  6451. return $out;
  6452. }
  6453. /**
  6454. * 解析金额/数量(去千分位等非数字字符)
  6455. */
  6456. protected function parseProcuremenMoneyNumber($value): ?float
  6457. {
  6458. if ($value === null || $value === '') {
  6459. return null;
  6460. }
  6461. if (is_numeric($value)) {
  6462. return (float)$value;
  6463. }
  6464. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  6465. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  6466. }
  6467. protected function formatProcuremenMoneyDisplay(?float $amount): string
  6468. {
  6469. if ($amount === null) {
  6470. return '';
  6471. }
  6472. // 保留小数(最多 5 位),去掉末尾无意义的 0,避免 0.25 被显示成 0
  6473. $s = rtrim(rtrim(sprintf('%.5F', (float)$amount), '0'), '.');
  6474. return $s === '' ? '0' : $s;
  6475. }
  6476. /**
  6477. * 列表/详情展示:工作量为 0 时显示空
  6478. */
  6479. protected function formatProcuremenWorkloadDisplay($value): string
  6480. {
  6481. if ($value === null || $value === '') {
  6482. return '';
  6483. }
  6484. $s = trim((string)$value);
  6485. if ($s === '') {
  6486. return '';
  6487. }
  6488. if (is_numeric($s) && (float)$s == 0) {
  6489. return '';
  6490. }
  6491. return $s;
  6492. }
  6493. /**
  6494. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  6495. */
  6496. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  6497. {
  6498. foreach ($details as $d) {
  6499. if (!is_array($d)) {
  6500. continue;
  6501. }
  6502. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  6503. $cn = trim((string)($d['company_name'] ?? ''));
  6504. if ($cn !== '') {
  6505. return $cn;
  6506. }
  6507. }
  6508. }
  6509. return trim((string)($main['pick_company_name'] ?? ''));
  6510. }
  6511. /**
  6512. * 详情报价小计:单价 × 本工序本次数量
  6513. */
  6514. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  6515. {
  6516. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  6517. if ($unit === null) {
  6518. return null;
  6519. }
  6520. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  6521. if ($qty === null || $qty <= 0) {
  6522. return null;
  6523. }
  6524. return $unit * $qty;
  6525. }
  6526. /**
  6527. * 详情页:工序小计 + 供应商分组报价与总计
  6528. *
  6529. * @param array<int, array<string, mixed>> $mergeRows
  6530. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  6531. * @return array{
  6532. * process_rows: array,
  6533. * supplier_groups: array,
  6534. * order_total_text: string,
  6535. * order_total_has: bool,
  6536. * selected_company: string
  6537. * }
  6538. */
  6539. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  6540. {
  6541. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  6542. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  6543. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
  6544. || ((int)($main['manual_pick'] ?? 0) === 1);
  6545. $qtyBySid = [];
  6546. $gymcBySid = [];
  6547. $orderedSids = [];
  6548. foreach ($mergeRows as $mr) {
  6549. if (!is_array($mr)) {
  6550. continue;
  6551. }
  6552. $sid = $this->extractScydgyRowId($mr);
  6553. if ($this->isValidScydgyRowId($sid)) {
  6554. $orderedSids[] = $sid;
  6555. }
  6556. $qty = trim((string)($mr['This_quantity'] ?? ''));
  6557. if ($qty === '') {
  6558. $qty = trim((string)($mr['NGZL'] ?? ''));
  6559. }
  6560. $qtyBySid[$sid] = $qty;
  6561. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  6562. }
  6563. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  6564. $detailByCompanySid = [];
  6565. foreach ($details as $d) {
  6566. if (!is_array($d)) {
  6567. continue;
  6568. }
  6569. $cn = trim((string)($d['company_name'] ?? ''));
  6570. $sid = (int)($d['scydgy_id'] ?? 0);
  6571. if ($cn === '' || $sid === 0) {
  6572. continue;
  6573. }
  6574. if (!isset($detailByCompanySid[$cn])) {
  6575. $detailByCompanySid[$cn] = [];
  6576. }
  6577. $detailByCompanySid[$cn][$sid] = $d;
  6578. }
  6579. $supplierGroups = [];
  6580. foreach ($detailByCompanySid as $cn => $bySid) {
  6581. $lines = [];
  6582. $groupTotal = 0.0;
  6583. $groupHas = false;
  6584. $groupVoid = true;
  6585. $usedSids = [];
  6586. $appendLine = function (int $sid, array $d) use (
  6587. &$lines,
  6588. &$groupTotal,
  6589. &$groupHas,
  6590. &$groupVoid,
  6591. $qtyBySid,
  6592. $gymcBySid,
  6593. $quoteVisible
  6594. ) {
  6595. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  6596. if (!$isVoid) {
  6597. $groupVoid = false;
  6598. }
  6599. $qtyStr = $qtyBySid[$sid] ?? '';
  6600. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  6601. $am = trim((string)($d['amount'] ?? ''));
  6602. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  6603. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  6604. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  6605. $sub = null;
  6606. if (!$isVoid && $amountNum !== null) {
  6607. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  6608. }
  6609. $ct = $this->resolveDetailSupplierOperTime($d);
  6610. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  6611. $leadFilled = ($leadDays !== null);
  6612. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  6613. $line = [
  6614. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  6615. 'amount' => $am,
  6616. 'unit_price_text' => $amountFilled
  6617. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  6618. : '未填写',
  6619. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  6620. 'delivery_ymd' => $deliveryYmd,
  6621. 'amount_filled' => $amountFilled,
  6622. 'delivery_filled' => $deliveryFilled,
  6623. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  6624. 'lead_days' => $leadFilled ? $leadDays : '',
  6625. 'lead_days_filled'=> $leadFilled,
  6626. 'lead_days_show' => $leadText,
  6627. 'lead_days_text' => $leadText,
  6628. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  6629. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  6630. 'is_void' => $isVoid,
  6631. 'oper_time_text' => $ct,
  6632. ];
  6633. if (!$quoteVisible && !$isVoid) {
  6634. $this->maskSupplierQuoteLineBeforeDeadline($line);
  6635. } elseif ($sub !== null) {
  6636. $groupTotal += $sub;
  6637. $groupHas = true;
  6638. }
  6639. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  6640. };
  6641. foreach ($orderedSids as $sid) {
  6642. if (!isset($bySid[$sid])) {
  6643. continue;
  6644. }
  6645. $usedSids[$sid] = true;
  6646. $appendLine($sid, $bySid[$sid]);
  6647. }
  6648. foreach ($bySid as $sid => $d) {
  6649. if (isset($usedSids[$sid])) {
  6650. continue;
  6651. }
  6652. $appendLine((int)$sid, $d);
  6653. }
  6654. $firstDetail = null;
  6655. foreach ($bySid as $d) {
  6656. if (is_array($d)) {
  6657. $firstDetail = $d;
  6658. break;
  6659. }
  6660. }
  6661. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  6662. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  6663. if ($username === '' && $ph !== '') {
  6664. $username = $this->resolveCustomerContactName($ph, $cn);
  6665. }
  6666. $remark = '';
  6667. foreach ($bySid as $d) {
  6668. if (!is_array($d)) {
  6669. continue;
  6670. }
  6671. $rm = '';
  6672. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  6673. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  6674. $rm = trim((string)$d[$rk]);
  6675. break;
  6676. }
  6677. }
  6678. if ($rm !== '') {
  6679. $remark = $rm;
  6680. break;
  6681. }
  6682. }
  6683. $lineCount = count($lines);
  6684. $hasRemark = $lineCount > 0;
  6685. $supplierGroup = [
  6686. 'company_name' => $cn,
  6687. 'username' => $username,
  6688. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  6689. 'phone' => $ph,
  6690. 'remark' => $remark,
  6691. 'has_remark' => $hasRemark,
  6692. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  6693. 'is_void' => $groupVoid,
  6694. 'lines' => $lines,
  6695. 'line_count' => $lineCount,
  6696. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  6697. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  6698. 'has_total' => $lineCount > 0,
  6699. ];
  6700. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  6701. $supplierGroups[] = $supplierGroup;
  6702. }
  6703. usort($supplierGroups, function ($a, $b) {
  6704. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  6705. return ($a['is_void'] ?? false) ? 1 : -1;
  6706. }
  6707. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  6708. return ($a['is_selected'] ?? false) ? -1 : 1;
  6709. }
  6710. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  6711. });
  6712. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  6713. return [
  6714. 'process_rows' => $processRows,
  6715. 'supplier_groups' => $supplierGroups,
  6716. 'order_total_text' => '',
  6717. 'order_total_has' => false,
  6718. 'selected_company' => $selectedCompany,
  6719. ];
  6720. }
  6721. /**
  6722. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  6723. */
  6724. protected function buildProcessLinesPlain(array $mergeRows): string
  6725. {
  6726. $lines = [];
  6727. $i = 1;
  6728. foreach ($mergeRows as $r) {
  6729. if (!is_array($r)) {
  6730. continue;
  6731. }
  6732. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6733. $dw = trim((string)($r['CDW'] ?? ''));
  6734. $gzl = trim((string)($r['NGZL'] ?? ''));
  6735. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  6736. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  6737. if ($dw !== '') {
  6738. $parts[] = '单位:' . $dw;
  6739. }
  6740. if ($gzl !== '') {
  6741. $parts[] = '工作量:' . $gzl;
  6742. }
  6743. if ($qty !== '') {
  6744. $parts[] = '本次数量:' . $qty;
  6745. }
  6746. $lines[] = implode(' ', $parts);
  6747. $i++;
  6748. }
  6749. return implode("\n", $lines);
  6750. }
  6751. /**
  6752. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  6753. *
  6754. * @return array<string, string>
  6755. */
  6756. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  6757. {
  6758. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  6759. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  6760. }
  6761. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  6762. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  6763. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6764. $cyjmc = '';
  6765. foreach ($mergeRows as $mr) {
  6766. if (!is_array($mr)) {
  6767. continue;
  6768. }
  6769. if ($ccydh === '') {
  6770. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  6771. }
  6772. if ($cyjmc === '') {
  6773. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  6774. }
  6775. }
  6776. if ($pos !== []) {
  6777. $firstPo = $pos[0];
  6778. if (is_array($firstPo)) {
  6779. if ($ccydh === '') {
  6780. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  6781. }
  6782. if ($cyjmc === '') {
  6783. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  6784. }
  6785. }
  6786. }
  6787. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  6788. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  6789. if (is_array($any)) {
  6790. if ($ccydh === '') {
  6791. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  6792. }
  6793. if ($cyjmc === '') {
  6794. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  6795. }
  6796. }
  6797. }
  6798. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  6799. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  6800. $cgymc = '';
  6801. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  6802. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  6803. }
  6804. return [
  6805. 'ccydh' => $ccydh,
  6806. 'cyjmc' => $cyjmc,
  6807. 'cgymc' => $cgymc,
  6808. 'process_lines' => $processLines,
  6809. 'process_lines_html' => '',
  6810. ];
  6811. }
  6812. /**
  6813. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  6814. */
  6815. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  6816. {
  6817. $lines = [];
  6818. if ($ccydh !== '') {
  6819. $lines[] = '订单号:' . $ccydh;
  6820. }
  6821. if ($cyjmc !== '') {
  6822. $lines[] = '印件名称:' . $cyjmc;
  6823. }
  6824. if ($processPlain !== '') {
  6825. $lines[] = $processPlain;
  6826. }
  6827. return implode("\n", $lines);
  6828. }
  6829. /**
  6830. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  6831. *
  6832. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6833. */
  6834. protected function buildPlatformLinksPlain(array $detailLinks): string
  6835. {
  6836. $lines = [];
  6837. $i = 1;
  6838. foreach ($detailLinks as $lk) {
  6839. if (!is_array($lk)) {
  6840. continue;
  6841. }
  6842. $url = trim((string)($lk['url'] ?? ''));
  6843. if ($url === '') {
  6844. continue;
  6845. }
  6846. $label = trim((string)($lk['cgymc'] ?? ''));
  6847. if ($label === '') {
  6848. $label = '工序' . $i;
  6849. }
  6850. $lines[] = $label . ':' . $url;
  6851. $i++;
  6852. }
  6853. return implode("\n", $lines);
  6854. }
  6855. /**
  6856. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  6857. *
  6858. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6859. */
  6860. protected function buildPlatformLinksHtml(array $detailLinks): string
  6861. {
  6862. $parts = [];
  6863. $i = 1;
  6864. foreach ($detailLinks as $lk) {
  6865. if (!is_array($lk)) {
  6866. continue;
  6867. }
  6868. $url = trim((string)($lk['url'] ?? ''));
  6869. if ($url === '') {
  6870. continue;
  6871. }
  6872. $label = trim((string)($lk['cgymc'] ?? ''));
  6873. if ($label === '') {
  6874. $label = '工序' . $i;
  6875. }
  6876. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  6877. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  6878. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  6879. $i++;
  6880. }
  6881. return implode("<br>\n", $parts);
  6882. }
  6883. /**
  6884. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  6885. *
  6886. * @return array<string, mixed>
  6887. */
  6888. protected function loadMailerConfig(): array
  6889. {
  6890. try {
  6891. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  6892. } catch (\Throwable $e) {
  6893. $cfg = [];
  6894. }
  6895. return is_array($cfg) ? $cfg : [];
  6896. }
  6897. protected function loadNotifyTemplateRow(string $scene): ?array
  6898. {
  6899. try {
  6900. $row = Db::table('purchase_sms_template')
  6901. ->where('scene', $scene)
  6902. ->where(function ($q) {
  6903. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  6904. })
  6905. ->order('id', 'asc')
  6906. ->find();
  6907. } catch (\Throwable $e) {
  6908. return null;
  6909. }
  6910. if (!is_array($row) || $row === []) {
  6911. return null;
  6912. }
  6913. return [
  6914. 'title' => trim((string)($row['title'] ?? '')),
  6915. 'content' => trim((string)($row['content'] ?? '')),
  6916. ];
  6917. }
  6918. /**
  6919. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  6920. */
  6921. protected function buildProcessLinesHtml(array $mergeRows): string
  6922. {
  6923. if (count($mergeRows) <= 1) {
  6924. $r = $mergeRows[0] ?? [];
  6925. if (!is_array($r)) {
  6926. return '';
  6927. }
  6928. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6929. $dw = trim((string)($r['CDW'] ?? ''));
  6930. $gzl = trim((string)($r['NGZL'] ?? ''));
  6931. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  6932. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  6933. if ($dw !== '') {
  6934. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  6935. }
  6936. if ($gzl !== '') {
  6937. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  6938. }
  6939. if ($qty !== '') {
  6940. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  6941. }
  6942. return $html;
  6943. }
  6944. $rows = '';
  6945. $i = 1;
  6946. foreach ($mergeRows as $r) {
  6947. if (!is_array($r)) {
  6948. continue;
  6949. }
  6950. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  6951. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  6952. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  6953. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  6954. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  6955. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  6956. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  6957. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  6958. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  6959. $i++;
  6960. }
  6961. if ($rows === '') {
  6962. return '';
  6963. }
  6964. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  6965. . '<thead><tr style="background:#f5f5f5;">'
  6966. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  6967. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  6968. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  6969. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  6970. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  6971. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  6972. }
  6973. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  6974. {
  6975. $sysRq = trim($sysRq);
  6976. if ($sysRq === '') {
  6977. if ($required) {
  6978. $this->error('请选择招标截止日期');
  6979. }
  6980. return '';
  6981. }
  6982. $ts = strtotime($sysRq);
  6983. if ($ts === false || $ts <= 0) {
  6984. $this->error('招标截止日期格式无效');
  6985. }
  6986. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  6987. if (!$allowPast) {
  6988. $ymd = date('Y-m-d', $ts);
  6989. if ($ymd < date('Y-m-d')) {
  6990. $this->error('招标截止日期不能早于今天');
  6991. }
  6992. if ($ts <= time()) {
  6993. $this->error('招标截止时间不能早于当前时间');
  6994. }
  6995. }
  6996. return date('Y-m-d H:i:s', $ts);
  6997. }
  6998. /**
  6999. * 确保 purchase_order.czlyq(类型)存在
  7000. */
  7001. protected function ensurePurchaseOrderCzlyqColumn(): void
  7002. {
  7003. static $done = false;
  7004. if ($done) {
  7005. return;
  7006. }
  7007. $done = true;
  7008. try {
  7009. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  7010. if (empty($cols)) {
  7011. Db::execute(
  7012. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  7013. );
  7014. }
  7015. } catch (\Throwable $e) {
  7016. // ignore
  7017. }
  7018. }
  7019. /**
  7020. * 确保 purchase_order.delivery_deadline 存在
  7021. */
  7022. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  7023. {
  7024. static $done = false;
  7025. if ($done) {
  7026. return;
  7027. }
  7028. $done = true;
  7029. try {
  7030. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  7031. if (empty($cols)) {
  7032. Db::execute(
  7033. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  7034. );
  7035. }
  7036. } catch (\Throwable $e) {
  7037. // ignore
  7038. }
  7039. }
  7040. /**
  7041. * 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
  7042. */
  7043. protected function ensurePurchaseOrderScoreRuleIdColumn(): void
  7044. {
  7045. static $done = false;
  7046. if ($done) {
  7047. return;
  7048. }
  7049. $done = true;
  7050. // 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
  7051. $adds = [
  7052. 'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
  7053. 'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
  7054. 'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
  7055. 'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
  7056. 'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
  7057. ];
  7058. $changed = false;
  7059. foreach ($adds as $col => $ddl) {
  7060. try {
  7061. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  7062. if (!is_array($cols) || $cols === []) {
  7063. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  7064. $changed = true;
  7065. }
  7066. } catch (\Throwable $e) {
  7067. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  7068. }
  7069. }
  7070. if ($changed) {
  7071. $this->clearPurchaseOrderTableFieldsCache();
  7072. }
  7073. }
  7074. /**
  7075. * ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
  7076. */
  7077. protected function clearPurchaseOrderTableFieldsCache(): void
  7078. {
  7079. try {
  7080. $db = (string)Config::get('database.database');
  7081. $key = $db . '.purchase_order';
  7082. $ref = new \ReflectionProperty(\think\db\Query::class, 'info');
  7083. $ref->setAccessible(true);
  7084. $info = $ref->getValue();
  7085. if (is_array($info) && isset($info[$key])) {
  7086. unset($info[$key]);
  7087. $ref->setValue(null, $info);
  7088. }
  7089. } catch (\Throwable $e) {
  7090. }
  7091. try {
  7092. $db = (string)Config::get('database.database');
  7093. $schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
  7094. if (is_file($schemaFile)) {
  7095. @unlink($schemaFile);
  7096. }
  7097. } catch (\Throwable $e) {
  7098. }
  7099. }
  7100. /**
  7101. * @return array<string, bool>
  7102. */
  7103. protected function loadPurchaseOrderColumnSet(): array
  7104. {
  7105. static $set = null;
  7106. if (is_array($set)) {
  7107. return $set;
  7108. }
  7109. $set = [];
  7110. try {
  7111. $cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
  7112. } catch (\Throwable $e) {
  7113. return $set;
  7114. }
  7115. if (!is_array($cols)) {
  7116. return $set;
  7117. }
  7118. foreach ($cols as $c) {
  7119. if (!is_array($c)) {
  7120. continue;
  7121. }
  7122. $f = (string)($c['Field'] ?? $c['field'] ?? '');
  7123. if ($f !== '') {
  7124. $set[$f] = true;
  7125. }
  7126. }
  7127. return $set;
  7128. }
  7129. /**
  7130. * 解析交货截止日期(仅年月日)
  7131. */
  7132. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  7133. {
  7134. $raw = trim($raw);
  7135. if ($raw === '') {
  7136. if ($required) {
  7137. $this->error('请选择交货截止日期');
  7138. }
  7139. return '';
  7140. }
  7141. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  7142. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  7143. } else {
  7144. $ts = strtotime(str_replace('/', '-', $raw));
  7145. if ($ts === false || $ts <= 0) {
  7146. $this->error('交货截止日期格式无效');
  7147. }
  7148. $ymd = date('Y-m-d', $ts);
  7149. }
  7150. if ($ymd < date('Y-m-d')) {
  7151. $this->error('交货截止日期不能早于今天');
  7152. }
  7153. return $ymd;
  7154. }
  7155. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  7156. {
  7157. $s = trim((string)$value);
  7158. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  7159. return '';
  7160. }
  7161. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  7162. return $m[1];
  7163. }
  7164. $ts = strtotime(str_replace('/', '-', $s));
  7165. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  7166. }
  7167. /**
  7168. * @param array{pos?:array} $bundle
  7169. */
  7170. protected function resolveBundleDeliveryDeadline(array $bundle): string
  7171. {
  7172. foreach ($bundle['pos'] ?? [] as $po) {
  7173. if (!is_array($po)) {
  7174. continue;
  7175. }
  7176. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7177. if ($d !== '') {
  7178. return $d;
  7179. }
  7180. }
  7181. return '';
  7182. }
  7183. protected function formatProcuremenSysRqForInput($sysRq): string
  7184. {
  7185. $sr = trim((string)$sysRq);
  7186. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  7187. return '';
  7188. }
  7189. $ts = strtotime($sr);
  7190. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  7191. }
  7192. protected function formatProcuremenSysRqForDisplay($sysRq): string
  7193. {
  7194. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  7195. if ($sr === '') {
  7196. return '—';
  7197. }
  7198. $ts = strtotime($sr);
  7199. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  7200. }
  7201. /**
  7202. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  7203. *
  7204. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  7205. * @return array{ccydh?:string,pos:array,merge_rows:array}
  7206. */
  7207. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  7208. {
  7209. return $bundle;
  7210. }
  7211. /**
  7212. * 写入/更新 purchase_order(单道工序行)
  7213. *
  7214. * @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
  7215. */
  7216. protected function upsertPurchaseOrderFromRow(
  7217. array $row,
  7218. string $sysRqDb,
  7219. $wflowStatus = null,
  7220. ?string $pickTime = null,
  7221. ?array $exists = null,
  7222. ?string $deliveryDeadline = null,
  7223. $scoreRuleId = null
  7224. ): void {
  7225. $ids = $this->extractScydgyRowId($row);
  7226. if (!$this->isValidScydgyRowId($ids)) {
  7227. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  7228. }
  7229. if ($exists === null) {
  7230. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7231. }
  7232. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  7233. $this->ensurePurchaseOrderScoreRuleIdColumn();
  7234. $this->ensurePurchaseOrderCzlyqColumn();
  7235. $data = [
  7236. 'scydgy_id' => $ids,
  7237. 'CCYDH' => $row['CCYDH'] ?? null,
  7238. 'CYJMC' => $row['CYJMC'] ?? null,
  7239. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  7240. 'CDXMC' => $row['CDXMC'] ?? null,
  7241. 'CGYBH' => $row['CGYBH'] ?? null,
  7242. 'CGYMC' => $row['CGYMC'] ?? null,
  7243. 'CDW' => $row['CDW'] ?? null,
  7244. 'czlyq' => $row['czlyq'] ?? null,
  7245. 'NGZL' => $row['NGZL'] ?? null,
  7246. 'CDF' => $row['CDF'] ?? null,
  7247. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  7248. 'MBZ' => $row['MBZ'] ?? null,
  7249. 'bwjg' => $row['bwjg'] ?? null,
  7250. 'iStatus' => $row['iStatus'] ?? null,
  7251. 'dStamp' => $row['dStamp'] ?? null,
  7252. 'dputrecord' => $row['dputrecord'] ?? null,
  7253. 'cywyxm' => $row['cywyxm'] ?? null,
  7254. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  7255. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  7256. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7257. 'sys_rq' => $sysRqDb,
  7258. ];
  7259. // 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
  7260. $qtyUp = trim((string)($data['This_quantity'] ?? ''));
  7261. if ($qtyUp === '') {
  7262. $qtyFallback = $this->resolveProcuremenThisQuantity([
  7263. 'This_quantity' => '',
  7264. 'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
  7265. ]);
  7266. if ($qtyFallback !== '') {
  7267. $data['This_quantity'] = $qtyFallback;
  7268. }
  7269. }
  7270. if ($deliveryDeadline !== null) {
  7271. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  7272. }
  7273. // 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
  7274. $scoreRule = null;
  7275. if (is_array($scoreRuleId)) {
  7276. $scoreRule = $scoreRuleId;
  7277. $scoreRuleId = (int)($scoreRule['id'] ?? 0);
  7278. } else {
  7279. $scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
  7280. }
  7281. if ($scoreRuleId !== null && $scoreRuleId > 0) {
  7282. $poCols = $this->loadPurchaseOrderColumnSet();
  7283. if (!empty($poCols['score_rule_id'])) {
  7284. $data['score_rule_id'] = $scoreRuleId;
  7285. if (is_array($scoreRule)) {
  7286. if (!empty($poCols['score_rule_name'])) {
  7287. $data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
  7288. }
  7289. if (!empty($poCols['score_quality_weight'])) {
  7290. $data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
  7291. }
  7292. if (!empty($poCols['score_price_weight'])) {
  7293. $data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
  7294. }
  7295. if (!empty($poCols['score_lead_weight'])) {
  7296. $data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
  7297. }
  7298. }
  7299. }
  7300. }
  7301. if ($wflowStatus !== null && $wflowStatus !== '') {
  7302. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  7303. }
  7304. if ($pickTime !== null && $pickTime !== '') {
  7305. $data['pick_time'] = $pickTime;
  7306. $data['pick_company_name'] = '';
  7307. }
  7308. if ($exists) {
  7309. $upd = $data;
  7310. unset($upd['scydgy_id']);
  7311. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  7312. } else {
  7313. $data['createtime'] = date('Y-m-d H:i:s');
  7314. Db::table('purchase_order')->insert($data);
  7315. }
  7316. }
  7317. /**
  7318. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  7319. *
  7320. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  7321. */
  7322. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
  7323. {
  7324. $toDb = function ($value) {
  7325. if ($value === null) {
  7326. return null;
  7327. }
  7328. if (is_scalar($value)) {
  7329. return $value;
  7330. }
  7331. return json_encode($value, JSON_UNESCAPED_UNICODE);
  7332. };
  7333. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7334. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7335. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7336. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  7337. if ($username === '') {
  7338. $username = $this->resolveCustomerContactName($phone, $companyName);
  7339. }
  7340. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  7341. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  7342. }
  7343. if ($requirePhone && $phone === '') {
  7344. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  7345. }
  7346. $detailLinks = [];
  7347. foreach ($mergeRows as $row) {
  7348. if (!is_array($row)) {
  7349. continue;
  7350. }
  7351. $sid = $this->extractScydgyRowId($row);
  7352. $detailId = 0;
  7353. if ($skipExisting) {
  7354. try {
  7355. $existsQuery = Db::table('purchase_order_detail')
  7356. ->where('scydgy_id', $sid)
  7357. ->where('company_name', $companyName);
  7358. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  7359. $exists = $existsQuery->find();
  7360. } catch (\Throwable $e) {
  7361. $exists = null;
  7362. }
  7363. if (is_array($exists)) {
  7364. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  7365. }
  7366. }
  7367. if ($detailId <= 0) {
  7368. $one = [
  7369. 'scydgy_id' => $toDb($sid),
  7370. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  7371. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  7372. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  7373. 'username' => $username !== '' ? $username : null,
  7374. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  7375. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  7376. 'createtime' => date('Y-m-d H:i:s'),
  7377. 'status' => ProcuremenStatus::POD_UNPICKED,
  7378. 'status_name' => '未提交',
  7379. ];
  7380. Db::table('purchase_order_detail')->insert($one);
  7381. $detailId = (int)Db::getLastInsID();
  7382. }
  7383. $mprocUrl = '';
  7384. if ($buildMobileLinks && $detailId > 0) {
  7385. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  7386. }
  7387. $detailLinks[] = [
  7388. 'detail_id' => $detailId,
  7389. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  7390. 'url' => $mprocUrl,
  7391. ];
  7392. }
  7393. $this->invalidatePickHiddenScydgyCache();
  7394. return $detailLinks;
  7395. }
  7396. /**
  7397. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  7398. * @return array<string, mixed>
  7399. */
  7400. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  7401. {
  7402. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7403. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7404. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7405. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  7406. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  7407. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  7408. $isMerge = !empty($ctx['is_merge']);
  7409. $contactName = trim((string)($c['username'] ?? ''));
  7410. if ($contactName === '') {
  7411. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  7412. }
  7413. $notifyVars = [
  7414. 'company_name' => $companyName,
  7415. 'contact_name' => $contactName,
  7416. 'phone' => $phone,
  7417. 'email' => $toEmail,
  7418. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  7419. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  7420. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  7421. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  7422. 'deadline' => (string)($ctx['deadline'] ?? ''),
  7423. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  7424. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  7425. 'platform_url' => $platformUrl,
  7426. 'platform_links' => $platformLinksPlain,
  7427. 'platform_links_html' => $platformLinksHtml,
  7428. ];
  7429. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  7430. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  7431. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  7432. return [
  7433. 'company_name' => $companyName,
  7434. 'phone' => $phone,
  7435. 'email' => $toEmail,
  7436. 'sms_content' => $smsContent,
  7437. 'mail_plain' => $mailPlain,
  7438. 'mail_body' => $mailBody,
  7439. 'notify_vars' => $notifyVars,
  7440. 'detail_links' => $detailLinks,
  7441. ];
  7442. }
  7443. /**
  7444. * @param array<string, mixed> $chosen
  7445. * @param array<int, array<string, mixed>> $mergeRows
  7446. * @param array{ccydh:string, pos:array} $bundle
  7447. */
  7448. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue'): void
  7449. {
  7450. if (!$sendSms && !$sendEmail) {
  7451. return;
  7452. }
  7453. $companyName = trim((string)($chosen['name'] ?? ''));
  7454. $phone = trim((string)($chosen['phone'] ?? ''));
  7455. $toEmail = trim((string)($chosen['email'] ?? ''));
  7456. if ($companyName === '') {
  7457. throw new \Exception('供应商名称无效');
  7458. }
  7459. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  7460. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  7461. }
  7462. if ($sendSms && $phone === '') {
  7463. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  7464. }
  7465. $sids = [];
  7466. foreach ($mergeRows as $mr) {
  7467. if (!is_array($mr)) {
  7468. continue;
  7469. }
  7470. $sid = $this->extractScydgyRowId($mr);
  7471. if ($this->isValidScydgyRowId($sid)) {
  7472. $sids[$sid] = true;
  7473. }
  7474. }
  7475. if ($sids === []) {
  7476. throw new \Exception('未找到工序行,无法发送通知');
  7477. }
  7478. $sysRqNotify = '';
  7479. $pos = $bundle['pos'] ?? [];
  7480. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7481. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  7482. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  7483. $ts = strtotime($sr);
  7484. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  7485. }
  7486. }
  7487. try {
  7488. $detailsQuery = Db::table('purchase_order_detail')
  7489. ->where('scydgy_id', 'in', array_keys($sids))
  7490. ->where('company_name', $companyName);
  7491. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7492. $details = $detailsQuery->order('id', 'asc')->select();
  7493. } catch (\Throwable $e) {
  7494. $details = [];
  7495. }
  7496. if (!is_array($details) || $details === []) {
  7497. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  7498. try {
  7499. $detailsQuery = Db::table('purchase_order_detail')
  7500. ->where('scydgy_id', 'in', array_keys($sids))
  7501. ->where('company_name', $companyName);
  7502. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7503. $details = $detailsQuery->order('id', 'asc')->select();
  7504. } catch (\Throwable $e) {
  7505. $details = [];
  7506. }
  7507. }
  7508. if (!is_array($details) || $details === []) {
  7509. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  7510. }
  7511. $detailLinks = [];
  7512. foreach ($details as $d) {
  7513. if (!is_array($d)) {
  7514. continue;
  7515. }
  7516. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  7517. if ($detailId <= 0) {
  7518. continue;
  7519. }
  7520. $sid = (int)($d['scydgy_id'] ?? 0);
  7521. $gymc = '';
  7522. foreach ($mergeRows as $mr) {
  7523. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  7524. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  7525. break;
  7526. }
  7527. }
  7528. $detailLinks[] = [
  7529. 'detail_id' => $detailId,
  7530. 'cgymc' => $gymc,
  7531. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  7532. ];
  7533. }
  7534. if ($detailLinks === []) {
  7535. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  7536. }
  7537. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  7538. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  7539. $notifyBundle['email_log_scene'] = $emailLogScene;
  7540. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  7541. $poIdLog = 0;
  7542. $pos = $bundle['pos'] ?? [];
  7543. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7544. $poIdLog = (int)($pos[0]['id'] ?? 0);
  7545. }
  7546. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  7547. if ($sendEmail) {
  7548. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  7549. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  7550. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  7551. }
  7552. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  7553. $mailConfig = $this->loadMailerConfig();
  7554. if (!$this->isProcuremenNotifyDryRun()) {
  7555. if (empty($mailConfig['host'])) {
  7556. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  7557. }
  7558. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  7559. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  7560. }
  7561. }
  7562. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  7563. }
  7564. if ($sendSms) {
  7565. $this->issueSendSupplierSms($notifyBundle);
  7566. }
  7567. }
  7568. /**
  7569. * @param array<int, array<string, mixed>> $quoteGroups
  7570. * @return array<int, array<string, mixed>>
  7571. */
  7572. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  7573. {
  7574. $names = [];
  7575. if (is_string($companiesJson) && $companiesJson !== '') {
  7576. $decoded = json_decode($companiesJson, true);
  7577. if (is_array($decoded)) {
  7578. foreach ($decoded as $nm) {
  7579. $nm = trim((string)$nm);
  7580. if ($nm !== '') {
  7581. $names[] = $nm;
  7582. }
  7583. }
  7584. }
  7585. }
  7586. $names = array_values(array_unique($names));
  7587. if ($names === [] && $selectedCompany !== '') {
  7588. $names = [$selectedCompany];
  7589. }
  7590. if ($names === []) {
  7591. return $quoteGroups;
  7592. }
  7593. $targets = [];
  7594. foreach ($quoteGroups as $g) {
  7595. if (!is_array($g)) {
  7596. continue;
  7597. }
  7598. $cn = trim((string)($g['name'] ?? ''));
  7599. if ($cn !== '' && in_array($cn, $names, true)) {
  7600. $targets[] = $g;
  7601. }
  7602. }
  7603. return $targets;
  7604. }
  7605. /**
  7606. * @return array{pos:array, merge_rows:array, bundle:array}
  7607. */
  7608. protected function loadAuditResendBundle(string $scydgyId): array
  7609. {
  7610. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7611. $pos = $bundle['pos'];
  7612. $mergeRows = $bundle['merge_rows'];
  7613. if ($pos === [] || $mergeRows === []) {
  7614. $this->error('该订单不在待确认供应商状态');
  7615. }
  7616. $sysRqDb = '';
  7617. if (isset($pos[0]) && is_array($pos[0])) {
  7618. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  7619. }
  7620. foreach ($pos as $i => $poRow) {
  7621. if (is_array($pos[$i]) && $sysRqDb !== '') {
  7622. $pos[$i]['sys_rq'] = $sysRqDb;
  7623. }
  7624. }
  7625. $bundle['pos'] = $pos;
  7626. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  7627. }
  7628. /**
  7629. * @param array<int, array<string, mixed>> $targets
  7630. */
  7631. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  7632. {
  7633. if ($targets === []) {
  7634. $this->error('未找到可通知的供应商');
  7635. }
  7636. $notifyErrors = [];
  7637. try {
  7638. $this->notifyDryRunPreview = [];
  7639. foreach ($targets as $g) {
  7640. if (!is_array($g)) {
  7641. continue;
  7642. }
  7643. $cname = trim((string)($g['name'] ?? ''));
  7644. if ($cname === '') {
  7645. continue;
  7646. }
  7647. $chosen = [
  7648. 'name' => $cname,
  7649. 'company_name' => $cname,
  7650. 'email' => trim((string)($g['email'] ?? '')),
  7651. 'phone' => trim((string)($g['phone'] ?? '')),
  7652. 'username' => trim((string)($g['username'] ?? '')),
  7653. ];
  7654. try {
  7655. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  7656. } catch (\Throwable $e) {
  7657. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7658. }
  7659. }
  7660. } catch (\Throwable $e) {
  7661. $this->error('通知发送失败:' . $e->getMessage());
  7662. }
  7663. if ($notifyErrors !== []) {
  7664. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  7665. }
  7666. if ($this->isProcuremenNotifyDryRun()) {
  7667. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  7668. 'notify_dry_run' => true,
  7669. 'notify_preview' => $this->notifyDryRunPreview,
  7670. ]);
  7671. }
  7672. $nameLabels = [];
  7673. foreach ($targets as $g) {
  7674. if (!is_array($g)) {
  7675. continue;
  7676. }
  7677. $n = trim((string)($g['name'] ?? ''));
  7678. if ($n !== '') {
  7679. $nameLabels[] = $n;
  7680. }
  7681. }
  7682. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  7683. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  7684. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  7685. $seenLogSid = [];
  7686. foreach ($bundle['pos'] ?? [] as $poRow) {
  7687. if (!is_array($poRow)) {
  7688. continue;
  7689. }
  7690. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7691. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  7692. continue;
  7693. }
  7694. $seenLogSid[$sid] = true;
  7695. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7696. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7697. }
  7698. if ($seenLogSid === []) {
  7699. foreach ($mergeRows as $mr) {
  7700. if (!is_array($mr)) {
  7701. continue;
  7702. }
  7703. $sid = $this->extractScydgyRowId($mr);
  7704. if ($this->isValidScydgyRowId($sid)) {
  7705. $this->addOrderLog($sid, $logAction, $logMsg, null);
  7706. break;
  7707. }
  7708. }
  7709. }
  7710. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  7711. }
  7712. /**
  7713. * 协助下发 — 发送短信(一家供应商)
  7714. *
  7715. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  7716. */
  7717. protected function issueSendSupplierSms(array $bundle): void
  7718. {
  7719. $companyName = (string)($bundle['company_name'] ?? '');
  7720. $phone = (string)($bundle['phone'] ?? '');
  7721. $smsContent = (string)($bundle['sms_content'] ?? '');
  7722. $this->logIssueNotifyDebug('短信', [
  7723. 'company' => $companyName,
  7724. 'phone' => $phone,
  7725. 'sms_content' => $smsContent,
  7726. ]);
  7727. if ($this->isProcuremenNotifyDryRun()) {
  7728. $this->recordNotifyDryRunPreview([
  7729. 'scene' => 'issue_sms',
  7730. 'company_name' => $companyName,
  7731. 'phone' => $phone,
  7732. 'sms_content' => $smsContent,
  7733. ]);
  7734. return;
  7735. }
  7736. $this->smsbao($phone, $smsContent);
  7737. }
  7738. /**
  7739. * 协助下发 — 发送邮件(一家供应商)
  7740. *
  7741. * @param array<string, mixed> $bundle
  7742. * @param array<string, mixed> $mailConfig
  7743. */
  7744. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  7745. {
  7746. $companyName = (string)($bundle['company_name'] ?? '');
  7747. $toEmail = (string)($bundle['email'] ?? '');
  7748. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  7749. $mailBody = (string)($bundle['mail_body'] ?? '');
  7750. $this->logIssueNotifyDebug('邮件', [
  7751. 'company' => $companyName,
  7752. 'email' => $toEmail,
  7753. 'mail_subject' => $mailSubject,
  7754. 'mail_body' => $mailPlain,
  7755. ]);
  7756. if ($this->isProcuremenNotifyDryRun()) {
  7757. $this->recordNotifyDryRunPreview([
  7758. 'scene' => 'issue_email',
  7759. 'company_name' => $companyName,
  7760. 'email' => $toEmail,
  7761. 'mail_subject' => $mailSubject,
  7762. 'mail_body' => $mailPlain,
  7763. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  7764. 'notify_vars' => $bundle['notify_vars'] ?? [],
  7765. 'detail_links' => $bundle['detail_links'] ?? [],
  7766. ]);
  7767. return;
  7768. }
  7769. $mail = new PHPMailer(true);
  7770. $mail->isSMTP();
  7771. $mail->Host = $mailConfig['host'];
  7772. $mail->SMTPAuth = true;
  7773. $mail->Username = $mailConfig['addr'];
  7774. $mail->Password = $mailConfig['pass'];
  7775. $mail->SMTPSecure = $mailConfig['security'];
  7776. $mail->Port = $mailConfig['port'];
  7777. $mail->CharSet = $mailConfig['charset'];
  7778. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  7779. $mail->addAddress($toEmail, $companyName);
  7780. $mail->isHTML(true);
  7781. $mail->Subject = $mailSubject;
  7782. $mail->Body = $mailBody;
  7783. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  7784. $sendOk = true;
  7785. $failReason = '';
  7786. try {
  7787. $mail->send();
  7788. } catch (\Throwable $e) {
  7789. $sendOk = false;
  7790. $failReason = $e->getMessage();
  7791. $this->persistEmailSendLog([
  7792. 'from_email' => $fromEmail,
  7793. 'to_email' => $toEmail,
  7794. 'send_time' => date('Y-m-d H:i:s'),
  7795. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7796. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7797. 'company_name' => $companyName,
  7798. 'mail_subject' => $mailSubject,
  7799. 'status' => 0,
  7800. 'fail_reason' => $failReason,
  7801. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7802. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7803. ]);
  7804. throw $e;
  7805. }
  7806. $this->persistEmailSendLog([
  7807. 'from_email' => $fromEmail,
  7808. 'to_email' => $toEmail,
  7809. 'send_time' => date('Y-m-d H:i:s'),
  7810. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7811. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7812. 'company_name' => $companyName,
  7813. 'mail_subject' => $mailSubject,
  7814. 'status' => 1,
  7815. 'fail_reason' => '',
  7816. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7817. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7818. ]);
  7819. }
  7820. /**
  7821. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  7822. *
  7823. * @param array<int, array<string, mixed>> $mergeRows
  7824. * @return array<string, mixed>
  7825. */
  7826. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  7827. {
  7828. $head = $mergeRows[0] ?? [];
  7829. $isMerge = count($mergeRows) > 1;
  7830. return [
  7831. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  7832. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  7833. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  7834. 'is_merge' => $isMerge,
  7835. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  7836. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  7837. 'deadline' => $sysRqNotify,
  7838. ];
  7839. }
  7840. /**
  7841. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  7842. *
  7843. * @param array<string, mixed> $data
  7844. */
  7845. protected function logIssueNotifyDebug(string $type, array $data): void
  7846. {
  7847. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  7848. return;
  7849. }
  7850. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  7851. }
  7852. protected function ensurePurchaseEmailSendLogTableOnce(): void
  7853. {
  7854. try {
  7855. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  7856. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  7857. return;
  7858. } catch (\Throwable $e) {
  7859. }
  7860. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  7861. if (is_file($sqlFile)) {
  7862. $sql = file_get_contents($sqlFile);
  7863. if (is_string($sql) && $sql !== '') {
  7864. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  7865. $stmt = trim($stmt);
  7866. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  7867. continue;
  7868. }
  7869. try {
  7870. Db::execute($stmt);
  7871. } catch (\Throwable $ignore) {
  7872. }
  7873. }
  7874. }
  7875. }
  7876. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  7877. }
  7878. /**
  7879. * @param array<string, mixed> $row
  7880. */
  7881. protected function persistEmailSendLog(array $row): void
  7882. {
  7883. try {
  7884. $this->ensurePurchaseEmailSendLogTableOnce();
  7885. } catch (\Throwable $e) {
  7886. return;
  7887. }
  7888. list($adminId, $adminName) = $this->GetUseName();
  7889. $cut = function ($s, $max) {
  7890. $s = (string)$s;
  7891. if (function_exists('mb_substr')) {
  7892. return mb_substr($s, 0, $max, 'UTF-8');
  7893. }
  7894. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  7895. };
  7896. $data = [
  7897. 'from_email' => $cut($row['from_email'] ?? '', 128),
  7898. 'to_email' => $cut($row['to_email'] ?? '', 128),
  7899. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  7900. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  7901. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  7902. 'company_name' => $cut($row['company_name'] ?? '', 128),
  7903. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  7904. 'status' => !empty($row['status']) ? 1 : 0,
  7905. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  7906. 'admin_id' => (int)$adminId,
  7907. 'admin_name' => $cut($adminName, 64),
  7908. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  7909. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  7910. 'createtime' => date('Y-m-d H:i:s'),
  7911. ];
  7912. try {
  7913. Db::table('purchase_email_send_log')->insert($data);
  7914. } catch (\Throwable $e) {
  7915. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  7916. }
  7917. }
  7918. protected function formatEmailLogSceneText(string $scene): string
  7919. {
  7920. $map = [
  7921. 'pick_issue' => '初选下发',
  7922. 'audit_resend' => '确认页重发',
  7923. 'rfq_salesman' => '询价通知业务员',
  7924. ];
  7925. return $map[$scene] ?? $scene;
  7926. }
  7927. /**
  7928. * 邮件发送日志列表
  7929. */
  7930. public function emailLog()
  7931. {
  7932. $this->relationSearch = false;
  7933. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  7934. $this->request->filter(['strip_tags', 'trim']);
  7935. $bakModel = $this->model;
  7936. $this->model = new \app\admin\model\Purchaseemailsendlog;
  7937. if ($this->request->isAjax()) {
  7938. $this->ensurePurchaseEmailSendLogTableOnce();
  7939. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  7940. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  7941. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  7942. $list = $this->model
  7943. ->where($where)
  7944. ->order($sortField, $orderDir)
  7945. ->paginate($limit);
  7946. $rows = [];
  7947. foreach ($list->items() as $item) {
  7948. $row = is_array($item) ? $item : $item->toArray();
  7949. $scene = trim((string)($row['scene'] ?? ''));
  7950. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  7951. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  7952. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  7953. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  7954. $rows[] = $row;
  7955. }
  7956. $this->model = $bakModel;
  7957. return json(['total' => $list->total(), 'rows' => $rows]);
  7958. }
  7959. $this->model = $bakModel;
  7960. return $this->view->fetch('procuremen/emaillog');
  7961. }
  7962. /**
  7963. * 协助下发弹窗(选多家供应商并通知)
  7964. */
  7965. public function pickReview()
  7966. {
  7967. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  7968. $this->error(__('You have no permission'));
  7969. }
  7970. if ($this->request->isPost()) {
  7971. $this->error('请使用弹窗内「确认下发」提交');
  7972. }
  7973. $this->view->assign('pickMode', 1);
  7974. $this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
  7975. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  7976. }
  7977. /**
  7978. * 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
  7979. */
  7980. protected function ensurePurchaseOrderNotifySalesmanColumn(): void
  7981. {
  7982. static $done = false;
  7983. if ($done) {
  7984. return;
  7985. }
  7986. $done = true;
  7987. try {
  7988. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'notify_salesman'");
  7989. if (empty($cols)) {
  7990. Db::execute(
  7991. "ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
  7992. );
  7993. } else {
  7994. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  7995. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
  7996. Db::execute(
  7997. "ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
  7998. );
  7999. }
  8000. }
  8001. } catch (\Throwable $e) {
  8002. // ignore
  8003. }
  8004. }
  8005. /**
  8006. * 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
  8007. */
  8008. protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
  8009. {
  8010. static $done = false;
  8011. if ($done) {
  8012. return;
  8013. }
  8014. $done = true;
  8015. try {
  8016. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
  8017. if (empty($cols)) {
  8018. Db::execute(
  8019. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
  8020. );
  8021. }
  8022. } catch (\Throwable $e) {
  8023. // ignore
  8024. }
  8025. try {
  8026. $cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
  8027. if (empty($cols2)) {
  8028. Db::execute(
  8029. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
  8030. );
  8031. }
  8032. } catch (\Throwable $e) {
  8033. // ignore
  8034. }
  8035. }
  8036. /**
  8037. * 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
  8038. */
  8039. protected function ensureRfqSalesmanEmailTemplate(): void
  8040. {
  8041. static $done = false;
  8042. if ($done) {
  8043. return;
  8044. }
  8045. $done = true;
  8046. $content = "您好,{contact_name}:\n\n"
  8047. . "有新的协助采购询价需求,请知悉。\n"
  8048. . "印件名称:{cyjmc}\n"
  8049. . "工序名称:{cgymc}\n"
  8050. . "本次数量:{this_quantity}\n"
  8051. . "供应商:{supplier_name}\n"
  8052. . "需求发起人:{cywyxm}\n";
  8053. try {
  8054. $row = Db::table('purchase_sms_template')
  8055. ->where('scene', 'rfq_salesman_email')
  8056. ->find();
  8057. } catch (\Throwable $e) {
  8058. return;
  8059. }
  8060. $now = date('Y-m-d H:i:s');
  8061. if (is_array($row) && $row !== []) {
  8062. $old = (string)($row['content'] ?? '');
  8063. $needMigrate = (strpos($old, '需求编号:{ccydh}') !== false)
  8064. || (strpos($old, '{supplier_name}') === false && strpos($old, '供应商:') === false);
  8065. if ($needMigrate) {
  8066. $data = ['content' => $content];
  8067. try {
  8068. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
  8069. if (!empty($cols)) {
  8070. $data['updatetime'] = $now;
  8071. }
  8072. } catch (\Throwable $e) {
  8073. }
  8074. try {
  8075. Db::table('purchase_sms_template')
  8076. ->where('id', (int)($row['id'] ?? 0))
  8077. ->update($data);
  8078. } catch (\Throwable $e) {
  8079. }
  8080. }
  8081. return;
  8082. }
  8083. try {
  8084. $data = [
  8085. 'scene' => 'rfq_salesman_email',
  8086. 'title' => '询价邮箱通知',
  8087. 'content' => $content,
  8088. 'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
  8089. 'status' => 1,
  8090. ];
  8091. try {
  8092. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8093. } catch (\Throwable $e) {
  8094. $cols = [];
  8095. }
  8096. $colNames = [];
  8097. foreach ($cols as $c) {
  8098. if (!is_array($c)) {
  8099. continue;
  8100. }
  8101. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8102. if ($n !== '') {
  8103. $colNames[$n] = true;
  8104. }
  8105. }
  8106. if (isset($colNames['updatetime'])) {
  8107. $data['updatetime'] = $now;
  8108. }
  8109. if (isset($colNames['createtime'])) {
  8110. $data['createtime'] = $now;
  8111. }
  8112. Db::table('purchase_sms_template')->insert($data);
  8113. } catch (\Throwable $e) {
  8114. // ignore
  8115. }
  8116. }
  8117. /**
  8118. * 询价多选字段:数组或字符串统一为顿号拼接
  8119. *
  8120. * @param mixed $raw
  8121. */
  8122. protected function joinRfqMultiSelectValues($raw): string
  8123. {
  8124. $parts = [];
  8125. if (is_array($raw)) {
  8126. foreach ($raw as $item) {
  8127. if (is_array($item)) {
  8128. continue;
  8129. }
  8130. $v = trim((string)$item);
  8131. if ($v !== '') {
  8132. $parts[] = $v;
  8133. }
  8134. }
  8135. } else {
  8136. $s = trim((string)$raw);
  8137. if ($s !== '') {
  8138. foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
  8139. $v = trim((string)$piece);
  8140. if ($v !== '') {
  8141. $parts[] = $v;
  8142. }
  8143. }
  8144. }
  8145. }
  8146. $parts = array_values(array_unique($parts));
  8147. return implode('、', $parts);
  8148. }
  8149. /**
  8150. * 新增询价:可选供应商名称(仅落库记录,不发通知)
  8151. *
  8152. * @return string[]
  8153. */
  8154. protected function loadRfqSupplierNameOptions(): array
  8155. {
  8156. $out = [];
  8157. try {
  8158. $rows = Db::table('customer')
  8159. ->where(function ($q) {
  8160. $q->where('status', 1)
  8161. ->whereOr('status', '1')
  8162. ->whereOr('status', '')
  8163. ->whereNull('status');
  8164. })
  8165. ->order('id', 'desc')
  8166. ->column('company_name');
  8167. } catch (\Throwable $e) {
  8168. return [];
  8169. }
  8170. if (!is_array($rows)) {
  8171. return [];
  8172. }
  8173. foreach ($rows as $name) {
  8174. $name = trim((string)$name);
  8175. if ($name === '' || isset($out[$name])) {
  8176. continue;
  8177. }
  8178. $out[$name] = $name;
  8179. }
  8180. return array_values($out);
  8181. }
  8182. /**
  8183. * 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
  8184. */
  8185. protected function rfqNotifySalesmanAuthGroupId(): int
  8186. {
  8187. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  8188. if ($id > 0) {
  8189. return $id;
  8190. }
  8191. try {
  8192. $found = Db::name('auth_group')
  8193. ->where('name', '业务员')
  8194. ->where('status', 'normal')
  8195. ->order('id', 'asc')
  8196. ->value('id');
  8197. $id = (int)$found;
  8198. } catch (\Throwable $e) {
  8199. $id = 0;
  8200. }
  8201. return $id > 0 ? $id : 12;
  8202. }
  8203. /**
  8204. * 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
  8205. *
  8206. * @return string[]
  8207. */
  8208. protected function loadRfqSalesmanNameOptions(): array
  8209. {
  8210. $out = [];
  8211. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8212. $name = trim((string)($row['name'] ?? ''));
  8213. if ($name !== '') {
  8214. $out[] = $name;
  8215. }
  8216. }
  8217. return $out;
  8218. }
  8219. /**
  8220. * 业务员角色组下管理员:姓名、邮箱、手机
  8221. *
  8222. * @return array<int, array{name:string,email:string,mobile:string}>
  8223. */
  8224. protected function loadRfqSalesmanContactOptions(): array
  8225. {
  8226. $out = [];
  8227. $seen = [];
  8228. $groupId = $this->rfqNotifySalesmanAuthGroupId();
  8229. if ($groupId <= 0) {
  8230. return [];
  8231. }
  8232. try {
  8233. $adminIds = Db::name('auth_group_access')
  8234. ->where('group_id', $groupId)
  8235. ->column('uid');
  8236. } catch (\Throwable $e) {
  8237. return [];
  8238. }
  8239. $adminIds = is_array($adminIds)
  8240. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  8241. : [];
  8242. if ($adminIds === []) {
  8243. return [];
  8244. }
  8245. try {
  8246. $rows = Db::name('admin')
  8247. ->where('status', 'normal')
  8248. ->where('id', 'in', $adminIds)
  8249. ->order('id', 'asc')
  8250. ->field('id,nickname,username,email,mobile')
  8251. ->select();
  8252. } catch (\Throwable $e) {
  8253. return [];
  8254. }
  8255. if (!is_array($rows)) {
  8256. return [];
  8257. }
  8258. foreach ($rows as $row) {
  8259. if (!is_array($row)) {
  8260. continue;
  8261. }
  8262. $name = trim((string)($row['nickname'] ?? ''));
  8263. if ($name === '') {
  8264. $name = trim((string)($row['username'] ?? ''));
  8265. }
  8266. if ($name === '' || isset($seen[$name])) {
  8267. continue;
  8268. }
  8269. $seen[$name] = true;
  8270. $out[] = [
  8271. 'name' => $name,
  8272. 'email' => trim((string)($row['email'] ?? '')),
  8273. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  8274. ];
  8275. }
  8276. return $out;
  8277. }
  8278. /**
  8279. * 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
  8280. *
  8281. * @return string[]
  8282. */
  8283. protected function loadRfqDeptNameOptions(): array
  8284. {
  8285. $out = [];
  8286. // ERP 承揽部门(主来源)
  8287. try {
  8288. $vals = Db::table('mcyd')
  8289. ->where('CCLBMMC', '<>', '')
  8290. ->whereNotNull('CCLBMMC')
  8291. ->distinct(true)
  8292. ->limit(300)
  8293. ->column('CCLBMMC');
  8294. } catch (\Throwable $e) {
  8295. $vals = [];
  8296. }
  8297. if (is_array($vals)) {
  8298. foreach ($vals as $v) {
  8299. $v = trim((string)$v);
  8300. if ($v === '' || isset($out[$v])) {
  8301. continue;
  8302. }
  8303. $out[$v] = $v;
  8304. }
  8305. }
  8306. // 手工询价历史部门补全
  8307. try {
  8308. $poVals = Db::table('purchase_order')
  8309. ->where('CCLBMMC', '<>', '')
  8310. ->whereNotNull('CCLBMMC')
  8311. ->distinct(true)
  8312. ->limit(200)
  8313. ->column('CCLBMMC');
  8314. } catch (\Throwable $e) {
  8315. $poVals = [];
  8316. }
  8317. if (is_array($poVals)) {
  8318. foreach ($poVals as $v) {
  8319. $v = trim((string)$v);
  8320. if ($v === '' || isset($out[$v])) {
  8321. continue;
  8322. }
  8323. $out[$v] = $v;
  8324. }
  8325. }
  8326. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  8327. if (!isset($out[$preset])) {
  8328. $out[$preset] = $preset;
  8329. }
  8330. }
  8331. $list = array_values($out);
  8332. // 常用部门靠前
  8333. usort($list, static function ($a, $b) {
  8334. $weight = [
  8335. '营销中心' => 1,
  8336. '业务部' => 2,
  8337. '市场部' => 3,
  8338. '外贸部' => 4,
  8339. '新华技术业务部' => 5,
  8340. ];
  8341. $wa = $weight[$a] ?? 100;
  8342. $wb = $weight[$b] ?? 100;
  8343. if ($wa !== $wb) {
  8344. return $wa <=> $wb;
  8345. }
  8346. return strcmp((string)$a, (string)$b);
  8347. });
  8348. return $list;
  8349. }
  8350. /**
  8351. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  8352. */
  8353. public function add()
  8354. {
  8355. if ($this->request->isPost()) {
  8356. $params = $this->request->post('row/a');
  8357. if (!is_array($params)) {
  8358. $this->error(__('Parameter %s can not be empty', ''));
  8359. }
  8360. [, $adminName] = $this->GetUseName();
  8361. $params['cywyxm'] = $adminName;
  8362. try {
  8363. $sid = $this->saveManualPickOrder($params);
  8364. } catch (\InvalidArgumentException $e) {
  8365. $this->error($e->getMessage());
  8366. } catch (\Throwable $e) {
  8367. $this->error($e->getMessage());
  8368. }
  8369. $this->success('新增成功', '', [
  8370. 'scydgy_id' => $sid,
  8371. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  8372. ]);
  8373. }
  8374. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8375. [, $adminName] = $this->GetUseName();
  8376. $this->view->assign('adminNickname', $adminName);
  8377. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  8378. $this->view->assign('defaultCclbmmc', '营销中心');
  8379. $this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
  8380. $this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
  8381. $this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
  8382. return $this->view->fetch();
  8383. }
  8384. /**
  8385. * 业务员新增进度查询(手工询价;发起人 / 通知业务员可见,超管看全部)
  8386. */
  8387. public function rfqlist()
  8388. {
  8389. $this->relationSearch = false;
  8390. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ';
  8391. $this->request->filter(['strip_tags', 'trim']);
  8392. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8393. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8394. $this->ensureRfqSalesmanEmailTemplate();
  8395. if ($this->request->isAjax()) {
  8396. try {
  8397. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  8398. $limit = max(10, min(500, (int)$limit));
  8399. $filterYm = trim((string)$this->request->param('filter_ym', ''));
  8400. if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
  8401. $filterYm = date('Y-m');
  8402. }
  8403. $applyFilters = function ($query) use ($where, $filterYm) {
  8404. $query->where('scydgy_id', '<', 0);
  8405. $this->applyPurchaseOrderNotDeletedWhere($query);
  8406. $this->applyManualRfqViewerWhere($query);
  8407. $this->applyRfqListMonthFilter($query, $filterYm);
  8408. if (!empty($where)) {
  8409. // 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
  8410. $safeWhere = [];
  8411. $skipFields = [
  8412. 'supplier_name' => true,
  8413. 'progress_text' => true,
  8414. 'createtime_text' => true,
  8415. 'notify_time_text' => true,
  8416. 'can_notify_salesman' => true,
  8417. 'has_issued' => true,
  8418. 'has_quoted' => true,
  8419. ];
  8420. foreach ((array)$where as $cond) {
  8421. if (!is_array($cond) || !isset($cond[0])) {
  8422. continue;
  8423. }
  8424. $field = (string)$cond[0];
  8425. $fieldBase = (string)preg_replace('/\|.*$/', '', $field);
  8426. $fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
  8427. if (isset($skipFields[$fieldBase])) {
  8428. continue;
  8429. }
  8430. if ($fieldBase === 'supplier_name') {
  8431. continue;
  8432. }
  8433. $safeWhere[] = $cond;
  8434. }
  8435. if ($safeWhere !== []) {
  8436. $query->where($safeWhere);
  8437. }
  8438. }
  8439. };
  8440. $countQuery = Db::table('purchase_order');
  8441. $applyFilters($countQuery);
  8442. $total = (int)$countQuery->count();
  8443. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  8444. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  8445. $listQuery = Db::table('purchase_order');
  8446. $applyFilters($listQuery);
  8447. $rows = $listQuery
  8448. ->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')
  8449. ->order($sortField, $orderDir)
  8450. ->limit($offset, $limit)
  8451. ->select();
  8452. if (!is_array($rows)) {
  8453. $rows = [];
  8454. }
  8455. $sidList = [];
  8456. foreach ($rows as $r) {
  8457. if (!is_array($r)) {
  8458. continue;
  8459. }
  8460. $sid = (int)($r['scydgy_id'] ?? 0);
  8461. if ($sid < 0) {
  8462. $sidList[$sid] = true;
  8463. }
  8464. }
  8465. $issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
  8466. $quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
  8467. $out = [];
  8468. foreach ($rows as $r) {
  8469. if (!is_array($r)) {
  8470. continue;
  8471. }
  8472. $sid = (int)($r['scydgy_id'] ?? 0);
  8473. if ($sid >= 0) {
  8474. continue;
  8475. }
  8476. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  8477. if ($createdText === '') {
  8478. $createdText = trim((string)($r['dStamp'] ?? ''));
  8479. }
  8480. $notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
  8481. $supplier = trim((string)($r['cGzzxMc'] ?? ''));
  8482. if ($supplier === '') {
  8483. $supplier = trim((string)($r['pick_company_name'] ?? ''));
  8484. }
  8485. $hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
  8486. || isset($issuedSidSet[$sid]);
  8487. $hasQuoted = isset($quotedSidSet[$sid]);
  8488. $salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
  8489. $canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
  8490. $out[] = [
  8491. 'id' => (int)($r['id'] ?? 0),
  8492. 'scydgy_id' => $sid,
  8493. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  8494. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  8495. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  8496. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  8497. 'CDW' => trim((string)($r['CDW'] ?? '')),
  8498. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  8499. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  8500. 'CDF' => trim((string)($r['CDF'] ?? '')),
  8501. 'supplier_name' => $supplier,
  8502. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  8503. 'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
  8504. 'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
  8505. 'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
  8506. 'notify_time_text' => $notifyTimeText,
  8507. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  8508. 'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
  8509. 'has_issued' => $hasIssued ? 1 : 0,
  8510. 'has_quoted' => $hasQuoted ? 1 : 0,
  8511. 'can_notify_salesman' => $canNotifySalesman,
  8512. 'createtime' => $r['createtime'] ?? null,
  8513. 'createtime_text' => $createdText,
  8514. ];
  8515. }
  8516. return json(['total' => $total, 'rows' => $out]);
  8517. } catch (\Throwable $e) {
  8518. Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
  8519. return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
  8520. }
  8521. }
  8522. $sidebar = $this->loadRfqSidebarYearMonths();
  8523. $defaultYm = $this->resolveRfqListDefaultYm($sidebar);
  8524. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  8525. [, $adminName] = $this->GetUseName();
  8526. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  8527. $this->view->assign('adminNickname', $adminName);
  8528. $this->view->assign('defaultYm', $defaultYm);
  8529. $this->view->assign('sidebarYearMonths', $sidebar);
  8530. return $this->view->fetch('procuremen/rfqlist');
  8531. }
  8532. /**
  8533. * 列表默认月份:当月有数据用当月,否则取最近有数据的月份
  8534. *
  8535. * @param array<int, array{year:string, months:array}> $sidebar
  8536. */
  8537. protected function resolveRfqListDefaultYm(array $sidebar): string
  8538. {
  8539. $current = date('Y-m');
  8540. $yms = $this->flattenProcuremenSidebarYms($sidebar);
  8541. if (in_array($current, $yms, true)) {
  8542. return $current;
  8543. }
  8544. if ($yms !== []) {
  8545. rsort($yms, SORT_STRING);
  8546. return (string)$yms[0];
  8547. }
  8548. return $current;
  8549. }
  8550. /**
  8551. * 手工询价列表左侧月份(按 createtime / dStamp)
  8552. *
  8553. * @return array<int, array{year:string, months:array}>
  8554. */
  8555. protected function loadRfqSidebarYearMonths(): array
  8556. {
  8557. $ymSet = [];
  8558. try {
  8559. $q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
  8560. $this->applyPurchaseOrderNotDeletedWhere($q);
  8561. $this->applyManualRfqViewerWhere($q);
  8562. $rows = $q->field('createtime,dStamp')->limit(5000)->select();
  8563. } catch (\Throwable $e) {
  8564. $rows = [];
  8565. }
  8566. if (!is_array($rows)) {
  8567. $rows = [];
  8568. }
  8569. foreach ($rows as $r) {
  8570. if (!is_array($r)) {
  8571. continue;
  8572. }
  8573. $t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  8574. if ($t === '') {
  8575. $t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
  8576. }
  8577. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  8578. $ymSet[$m[1] . '-' . $m[2]] = true;
  8579. }
  8580. }
  8581. return $this->buildYearMonthSidebar(array_keys($ymSet));
  8582. }
  8583. /**
  8584. * 手工询价可见范围:仅「需求发起人」或「通知业务员」与当前登录账号一致(超管看全部)
  8585. */
  8586. protected function applyManualRfqViewerWhere($query): void
  8587. {
  8588. if ($this->auth->isSuperAdmin()) {
  8589. return;
  8590. }
  8591. [, $adminName] = $this->GetUseName();
  8592. $adminName = trim((string)$adminName);
  8593. if ($adminName === '') {
  8594. $query->whereRaw('1 = 0');
  8595. return;
  8596. }
  8597. // 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
  8598. $query->where(function ($q) use ($adminName) {
  8599. $q->where('cywyxm', $adminName)
  8600. ->whereOr('notify_salesman', $adminName)
  8601. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  8602. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  8603. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  8604. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  8605. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  8606. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  8607. });
  8608. }
  8609. /**
  8610. * 当前用户是否可查看/操作该手工询价单(需求发起人或通知业务员;超管全部)
  8611. */
  8612. protected function canViewManualRfqOrder(array $po): bool
  8613. {
  8614. if ($this->auth->isSuperAdmin()) {
  8615. return true;
  8616. }
  8617. [, $adminName] = $this->GetUseName();
  8618. $adminName = trim((string)$adminName);
  8619. if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
  8620. return true;
  8621. }
  8622. if ($adminName !== '') {
  8623. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  8624. if ($n === $adminName) {
  8625. return true;
  8626. }
  8627. }
  8628. }
  8629. return false;
  8630. }
  8631. /**
  8632. * 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
  8633. */
  8634. protected function applyRfqListMonthFilter($query, string $ym): void
  8635. {
  8636. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  8637. $ym = date('Y-m');
  8638. }
  8639. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  8640. // 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
  8641. $query->whereRaw(
  8642. "("
  8643. . "CASE "
  8644. . "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  8645. . "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
  8646. . "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
  8647. . "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  8648. . "THEN TRIM(CAST(createtime AS CHAR(32))) "
  8649. . "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
  8650. . "END"
  8651. . ") LIKE '{$ymEsc}-%'"
  8652. );
  8653. }
  8654. /**
  8655. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  8656. */
  8657. public function rfqlistDetails()
  8658. {
  8659. return $this->details();
  8660. }
  8661. /**
  8662. * 查询询价 — 弹窗:可选通知业务员名单(勾选后确认通知)
  8663. */
  8664. public function rfqnotifysalesmen()
  8665. {
  8666. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen'])) {
  8667. $this->error(__('You have no permission'));
  8668. }
  8669. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8670. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8671. $sid = (int)$this->request->param('scydgy_id', 0);
  8672. if ($sid >= 0) {
  8673. $this->error('仅支持手工新增询价单');
  8674. }
  8675. $po = $this->loadManualRfqOrderForNotify($sid);
  8676. $selectedMap = [];
  8677. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  8678. $selectedMap[$n] = true;
  8679. }
  8680. $list = [];
  8681. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8682. $name = trim((string)($row['name'] ?? ''));
  8683. if ($name === '') {
  8684. continue;
  8685. }
  8686. $email = trim((string)($row['email'] ?? ''));
  8687. $mobile = trim((string)($row['mobile'] ?? ''));
  8688. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  8689. $list[] = [
  8690. 'name' => $name,
  8691. 'email' => $email,
  8692. 'mobile' => $mobile,
  8693. 'can_select' => $hasEmail ? 1 : 0,
  8694. 'checked' => (!empty($selectedMap[$name]) && $hasEmail) ? 1 : 0,
  8695. ];
  8696. }
  8697. $canNotify = $this->canRfqNotifySalesman($po);
  8698. $this->success('', null, [
  8699. 'scydgy_id' => $sid,
  8700. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  8701. 'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
  8702. 'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
  8703. 'can_notify_salesman' => $canNotify ? 1 : 0,
  8704. 'list' => $list,
  8705. ]);
  8706. }
  8707. /**
  8708. * 查询询价 — 补加通知业务员可选名单
  8709. */
  8710. public function rfqsalesmanoptions()
  8711. {
  8712. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen', 'rfqsalesmanoptions', 'rfqappendsalesmen'])) {
  8713. $this->error(__('You have no permission'));
  8714. }
  8715. $out = [];
  8716. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8717. $email = trim((string)($row['email'] ?? ''));
  8718. $mobile = trim((string)($row['mobile'] ?? ''));
  8719. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  8720. $out[] = [
  8721. 'name' => (string)($row['name'] ?? ''),
  8722. 'email' => $email,
  8723. 'mobile' => $mobile,
  8724. 'can_select' => $hasEmail ? 1 : 0,
  8725. ];
  8726. }
  8727. $this->success('', null, ['list' => $out]);
  8728. }
  8729. /**
  8730. * 查询询价 — 补加通知业务员(合并更新 notify_salesman)
  8731. */
  8732. public function rfqappendsalesmen()
  8733. {
  8734. if (!$this->request->isPost()) {
  8735. $this->error(__('Invalid parameters'));
  8736. }
  8737. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen', 'rfqappendsalesmen'])) {
  8738. $this->error(__('You have no permission'));
  8739. }
  8740. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8741. $sid = (int)$this->request->post('scydgy_id', 0);
  8742. if ($sid >= 0) {
  8743. $this->error('仅支持手工新增询价单');
  8744. }
  8745. $po = $this->loadManualRfqOrderForNotify($sid);
  8746. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  8747. $this->error('订单已完结,无法添加业务员');
  8748. }
  8749. $raw = $this->request->post('salesmen/a', []);
  8750. if (!is_array($raw) || $raw === []) {
  8751. $salesmenJson = $this->request->post('salesmen_json', '');
  8752. if (is_string($salesmenJson) && $salesmenJson !== '') {
  8753. $decoded = json_decode($salesmenJson, true);
  8754. $raw = is_array($decoded) ? $decoded : [];
  8755. }
  8756. }
  8757. $addNames = [];
  8758. foreach ((array)$raw as $item) {
  8759. if (is_array($item)) {
  8760. $n = trim((string)($item['name'] ?? ''));
  8761. } else {
  8762. $n = trim((string)$item);
  8763. }
  8764. if ($n !== '') {
  8765. $addNames[] = $n;
  8766. }
  8767. }
  8768. $addNames = array_values(array_unique($addNames));
  8769. if ($addNames === []) {
  8770. $this->error('请选择要添加的业务员');
  8771. }
  8772. $allowedOptions = $this->loadRfqSalesmanContactOptions();
  8773. $allowedMap = [];
  8774. foreach ($allowedOptions as $opt) {
  8775. $n = trim((string)($opt['name'] ?? ''));
  8776. if ($n === '') {
  8777. continue;
  8778. }
  8779. $email = trim((string)($opt['email'] ?? ''));
  8780. $allowedMap[$n] = ($email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL));
  8781. }
  8782. foreach ($addNames as $n) {
  8783. if (!array_key_exists($n, $allowedMap)) {
  8784. $this->error('业务员不在可选名单中:' . $n);
  8785. }
  8786. if (!$allowedMap[$n]) {
  8787. $this->error('业务员未填写有效邮箱,无法添加:' . $n);
  8788. }
  8789. }
  8790. $existingRaw = trim((string)($po['notify_salesman'] ?? ''));
  8791. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  8792. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  8793. try {
  8794. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['notify_salesman' => $mergedStr]);
  8795. } catch (\Throwable $e) {
  8796. $this->error('保存失败:' . $e->getMessage());
  8797. }
  8798. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  8799. $this->addOrderLog($sid, 'rfq_append_salesman', '添加通知业务员:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  8800. $this->success('已添加业务员', null, [
  8801. 'scydgy_id' => $sid,
  8802. 'notify_salesman' => $mergedStr,
  8803. 'added_count' => count($addNames),
  8804. ]);
  8805. }
  8806. /**
  8807. * 查询询价 — 勾选业务员后邮箱通知(salesmen_json)
  8808. */
  8809. public function rfqnotifysalesman()
  8810. {
  8811. if (!$this->request->isPost()) {
  8812. $this->error(__('Invalid parameters'));
  8813. }
  8814. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesman'])) {
  8815. $this->error(__('You have no permission'));
  8816. }
  8817. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8818. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8819. $sid = (int)$this->request->post('scydgy_id', 0);
  8820. if ($sid >= 0) {
  8821. $this->error('仅支持手工新增询价单');
  8822. }
  8823. $po = $this->loadManualRfqOrderForNotify($sid);
  8824. $this->assertRfqCanNotifySalesman($po);
  8825. $raw = $this->request->post('salesmen/a', []);
  8826. if (!is_array($raw) || $raw === []) {
  8827. $salesmenJson = $this->request->post('salesmen_json', '');
  8828. if (is_string($salesmenJson) && $salesmenJson !== '') {
  8829. $decoded = json_decode($salesmenJson, true);
  8830. $raw = is_array($decoded) ? $decoded : [];
  8831. }
  8832. }
  8833. // 兼容旧参数:notify_all / 单人 name
  8834. if ((!is_array($raw) || $raw === []) && (int)$this->request->post('notify_all', 0) === 1) {
  8835. $raw = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  8836. }
  8837. if ((!is_array($raw) || $raw === [])) {
  8838. $oneName = trim((string)$this->request->post('name', ''));
  8839. if ($oneName !== '') {
  8840. $raw = [$oneName];
  8841. }
  8842. }
  8843. $selectedNames = [];
  8844. foreach ((array)$raw as $item) {
  8845. if (is_array($item)) {
  8846. $n = trim((string)($item['name'] ?? ''));
  8847. } else {
  8848. $n = trim((string)$item);
  8849. }
  8850. if ($n !== '') {
  8851. $selectedNames[] = $n;
  8852. }
  8853. }
  8854. $selectedNames = array_values(array_unique($selectedNames));
  8855. if ($selectedNames === []) {
  8856. $this->error('请选择要通知的业务员');
  8857. }
  8858. $optionMap = [];
  8859. foreach ($this->loadRfqSalesmanContactOptions() as $opt) {
  8860. $n = trim((string)($opt['name'] ?? ''));
  8861. if ($n === '') {
  8862. continue;
  8863. }
  8864. $optionMap[$n] = $opt;
  8865. }
  8866. $targets = [];
  8867. foreach ($selectedNames as $n) {
  8868. if (!isset($optionMap[$n])) {
  8869. $this->error('业务员不在可选名单中:' . $n);
  8870. }
  8871. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  8872. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  8873. $this->error('业务员未填写有效邮箱,无法通知:' . $n);
  8874. }
  8875. $resolved = $this->resolveRfqSalesmanContactRows([$n]);
  8876. $targets[] = $resolved[0] ?? [
  8877. 'admin_id' => 0,
  8878. 'name' => $n,
  8879. 'email' => $email,
  8880. ];
  8881. }
  8882. $mergedStr = $this->joinRfqMultiSelectValues($selectedNames);
  8883. try {
  8884. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  8885. 'notify_salesman' => $mergedStr,
  8886. ]);
  8887. } catch (\Throwable $e) {
  8888. $this->error('保存通知业务员失败:' . $e->getMessage());
  8889. }
  8890. $po['notify_salesman'] = $mergedStr;
  8891. $mailConfig = $this->loadMailerConfig();
  8892. if (empty($mailConfig['host'])) {
  8893. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  8894. }
  8895. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  8896. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  8897. }
  8898. $this->ensureRfqSalesmanEmailTemplate();
  8899. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  8900. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  8901. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  8902. $qty = trim((string)($po['This_quantity'] ?? ''));
  8903. $cywyxm = trim((string)($po['cywyxm'] ?? ''));
  8904. $supplier = trim((string)($po['cGzzxMc'] ?? ''));
  8905. if ($supplier === '') {
  8906. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  8907. }
  8908. try {
  8909. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
  8910. } catch (\Throwable $e) {
  8911. $this->error($e->getMessage());
  8912. }
  8913. $okNames = [];
  8914. $failMsgs = [];
  8915. foreach ($targets as $contact) {
  8916. $toEmail = trim((string)($contact['email'] ?? ''));
  8917. $toName = trim((string)($contact['name'] ?? ''));
  8918. $notifyVars = [
  8919. 'contact_name' => $toName,
  8920. 'salesman_name' => $toName,
  8921. 'company_name' => $toName,
  8922. 'email' => $toEmail,
  8923. 'ccydh' => $ccydh,
  8924. 'cyjmc' => $cyjmc,
  8925. 'cgymc' => $cgymc,
  8926. 'this_quantity' => $qty,
  8927. 'supplier_name' => $supplier,
  8928. 'cywyxm' => $cywyxm,
  8929. ];
  8930. try {
  8931. $mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
  8932. $mailSubject = $mailSubjectTpl;
  8933. foreach ($notifyVars as $k => $v) {
  8934. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  8935. }
  8936. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  8937. $mailSubject = trim((string)$mailSubject);
  8938. if ($mailSubject === '') {
  8939. $mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  8940. }
  8941. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  8942. $bundle = [
  8943. 'company_name' => $toName,
  8944. 'email' => $toEmail,
  8945. 'mail_plain' => $mailPlain,
  8946. 'mail_body' => $mailBody,
  8947. 'ccydh' => $ccydh,
  8948. 'email_log_scene' => 'rfq_salesman',
  8949. 'email_log_scydgy_id' => $sid,
  8950. 'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
  8951. 'notify_vars' => $notifyVars,
  8952. ];
  8953. $this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
  8954. $okNames[] = $toName . '(' . $toEmail . ')';
  8955. } catch (\Throwable $e) {
  8956. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  8957. }
  8958. }
  8959. if ($okNames === []) {
  8960. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  8961. }
  8962. $now = date('Y-m-d H:i:s');
  8963. try {
  8964. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  8965. 'rfq_salesman_notified' => 1,
  8966. 'rfq_salesman_notify_time' => $now,
  8967. ]);
  8968. } catch (\Throwable $e) {
  8969. // ignore
  8970. }
  8971. $this->addOrderLog(
  8972. $sid,
  8973. 'rfq_notify_salesman',
  8974. '邮箱通知业务员:' . implode('、', $okNames),
  8975. (int)($po['id'] ?? 0)
  8976. );
  8977. $msg = '已通知 ' . count($okNames) . ' 人';
  8978. if ($failMsgs !== []) {
  8979. $msg .= ';部分失败:' . implode(';', $failMsgs);
  8980. }
  8981. $this->success($msg, null, [
  8982. 'scydgy_id' => $sid,
  8983. 'notify_salesman' => $mergedStr,
  8984. 'rfq_salesman_notified' => 1,
  8985. 'rfq_salesman_notify_time' => $now,
  8986. 'notify_time_text' => $now,
  8987. 'ok_count' => count($okNames),
  8988. 'fail_count' => count($failMsgs),
  8989. ]);
  8990. }
  8991. /**
  8992. * 查询询价 — 下发前:返回将通知的供应商表格数据
  8993. */
  8994. public function rfqissuesuppliers()
  8995. {
  8996. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqissuesuppliers'])) {
  8997. $this->error(__('You have no permission'));
  8998. }
  8999. $sid = (int)$this->request->param('scydgy_id', 0);
  9000. if ($sid >= 0) {
  9001. $this->error('仅支持手工新增询价单');
  9002. }
  9003. $po = $this->loadManualRfqOrderForNotify($sid);
  9004. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9005. if ($supplierRaw === '') {
  9006. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9007. }
  9008. $names = $this->splitRfqSalesmanNames($supplierRaw);
  9009. $list = [];
  9010. foreach ($names as $name) {
  9011. // 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
  9012. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9013. $email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
  9014. $phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
  9015. $username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
  9016. $okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
  9017. $list[] = [
  9018. 'name' => $name,
  9019. 'username' => $username,
  9020. 'email' => $email,
  9021. 'phone' => $phone,
  9022. 'can_notify' => $okEmail ? 1 : 0,
  9023. 'found' => is_array($contact) ? 1 : 0,
  9024. ];
  9025. }
  9026. $this->success('', null, [
  9027. 'scydgy_id' => $sid,
  9028. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9029. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9030. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9031. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9032. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9033. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9034. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9035. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9036. 'list' => $list,
  9037. ]);
  9038. }
  9039. /**
  9040. * 查询询价 — 补加供应商可选名单
  9041. */
  9042. public function rfqsupplieroptions()
  9043. {
  9044. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
  9045. $this->error(__('You have no permission'));
  9046. }
  9047. $names = array_values($this->loadRfqSupplierNameOptions());
  9048. $out = [];
  9049. foreach ($names as $name) {
  9050. $out[] = ['name' => $name];
  9051. }
  9052. $this->success('', null, ['list' => $out]);
  9053. }
  9054. /**
  9055. * 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
  9056. */
  9057. public function rfqappendsuppliers()
  9058. {
  9059. if (!$this->request->isPost()) {
  9060. $this->error(__('Invalid parameters'));
  9061. }
  9062. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqappendsuppliers'])) {
  9063. $this->error(__('You have no permission'));
  9064. }
  9065. $sid = (int)$this->request->post('scydgy_id', 0);
  9066. if ($sid >= 0) {
  9067. $this->error('仅支持手工新增询价单');
  9068. }
  9069. $po = $this->loadManualRfqOrderForNotify($sid);
  9070. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9071. $this->error('订单已完结,无法补加供应商');
  9072. }
  9073. $raw = $this->request->post('suppliers/a', []);
  9074. if (!is_array($raw) || $raw === []) {
  9075. $suppliersJson = $this->request->post('suppliers_json', '');
  9076. if (is_string($suppliersJson) && $suppliersJson !== '') {
  9077. $decoded = json_decode($suppliersJson, true);
  9078. $raw = is_array($decoded) ? $decoded : [];
  9079. }
  9080. }
  9081. $addNames = [];
  9082. foreach ((array)$raw as $item) {
  9083. if (is_array($item)) {
  9084. $n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
  9085. } else {
  9086. $n = trim((string)$item);
  9087. }
  9088. if ($n !== '') {
  9089. $addNames[] = $n;
  9090. }
  9091. }
  9092. $addNames = array_values(array_unique($addNames));
  9093. if ($addNames === []) {
  9094. $this->error('请选择要补加的供应商');
  9095. }
  9096. $existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9097. if ($existingRaw === '') {
  9098. $existingRaw = trim((string)($po['pick_company_name'] ?? ''));
  9099. }
  9100. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9101. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9102. try {
  9103. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
  9104. } catch (\Throwable $e) {
  9105. $this->error('保存失败:' . $e->getMessage());
  9106. }
  9107. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9108. $this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9109. $this->success('已补加供应商', null, [
  9110. 'scydgy_id' => $sid,
  9111. 'cGzzxMc' => $mergedStr,
  9112. 'added_count' => count($addNames),
  9113. ]);
  9114. }
  9115. /**
  9116. * 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
  9117. */
  9118. public function rfqissue()
  9119. {
  9120. if (!$this->request->isPost()) {
  9121. $this->error(__('Invalid parameters'));
  9122. }
  9123. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue'])) {
  9124. $this->error(__('You have no permission'));
  9125. }
  9126. $sid = (int)$this->request->post('scydgy_id', 0);
  9127. if ($sid >= 0) {
  9128. $this->error('仅支持手工新增询价单');
  9129. }
  9130. $po = $this->loadManualRfqOrderForNotify($sid);
  9131. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9132. $this->error('订单已完结,无法下发');
  9133. }
  9134. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9135. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9136. $this->error('订单已进入后续流程,无法再下发');
  9137. }
  9138. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9139. if ($supplierRaw === '') {
  9140. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9141. }
  9142. $supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
  9143. if ($supplierNames === []) {
  9144. $this->error('请先在新增询价时选择供应商');
  9145. }
  9146. $companies = [];
  9147. $missing = [];
  9148. $noEmail = [];
  9149. foreach ($supplierNames as $name) {
  9150. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9151. if ($contact === null) {
  9152. $missing[] = $name;
  9153. continue;
  9154. }
  9155. $em = trim((string)($contact['email'] ?? ''));
  9156. if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
  9157. $noEmail[] = $name;
  9158. continue;
  9159. }
  9160. $companies[] = $contact;
  9161. }
  9162. if ($missing !== []) {
  9163. $this->error('未找到供应商档案:' . implode('、', $missing));
  9164. }
  9165. if ($noEmail !== []) {
  9166. $this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
  9167. }
  9168. if ($companies === []) {
  9169. $this->error('没有可通知的供应商');
  9170. }
  9171. $mailConfig = $this->loadMailerConfig();
  9172. if (empty($mailConfig['host'])) {
  9173. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9174. }
  9175. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9176. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9177. }
  9178. $mergeRow = $po;
  9179. $mergeRow['ID'] = $sid;
  9180. $mergeRow['id'] = $sid;
  9181. $mergeRows = [$mergeRow];
  9182. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9183. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9184. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9185. }
  9186. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9187. $issueTime = date('Y-m-d H:i:s');
  9188. $nameLabels = [];
  9189. foreach ($companies as $c) {
  9190. $nameLabels[] = trim((string)($c['name'] ?? ''));
  9191. }
  9192. $logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
  9193. Db::startTrans();
  9194. try {
  9195. $this->upsertPurchaseOrderFromRow(
  9196. $mergeRow,
  9197. $sysRqDb,
  9198. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9199. $issueTime,
  9200. $po,
  9201. null,
  9202. $scoreRule
  9203. );
  9204. foreach ($companies as $c) {
  9205. $this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
  9206. }
  9207. Db::commit();
  9208. } catch (\Throwable $e) {
  9209. Db::rollback();
  9210. $this->error($e->getMessage());
  9211. }
  9212. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9213. if ($poId <= 0) {
  9214. try {
  9215. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9216. } catch (\Throwable $e) {
  9217. $poId = 0;
  9218. }
  9219. }
  9220. $this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
  9221. $posNotify = [];
  9222. try {
  9223. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9224. if (is_array($fresh)) {
  9225. $fresh['sys_rq'] = $sysRqDb;
  9226. $posNotify = [$fresh];
  9227. }
  9228. } catch (\Throwable $e) {
  9229. $posNotify = [$po];
  9230. $posNotify[0]['sys_rq'] = $sysRqDb;
  9231. }
  9232. $notifyBundle = [
  9233. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9234. 'pos' => $posNotify,
  9235. 'merge_rows' => $mergeRows,
  9236. ];
  9237. $notifyErrors = [];
  9238. foreach ($companies as $c) {
  9239. $cname = trim((string)($c['name'] ?? ''));
  9240. try {
  9241. // 询价下发:仅邮箱通知供应商
  9242. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'pick_issue');
  9243. } catch (\Throwable $e) {
  9244. $notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
  9245. }
  9246. }
  9247. if ($notifyErrors !== []) {
  9248. $this->error('下发已保存,但邮件通知失败:' . implode(';', $notifyErrors));
  9249. }
  9250. $this->success('已询价并邮件通知供应商', null, [
  9251. 'scydgy_id' => $sid,
  9252. 'progress_text' => '待报价',
  9253. 'supplier_count' => count($companies),
  9254. ]);
  9255. }
  9256. /**
  9257. * 查询询价 — 弹窗内向单个供应商发送询价邮件
  9258. */
  9259. public function rfqissuesendmail()
  9260. {
  9261. if (!$this->request->isPost()) {
  9262. $this->error(__('Invalid parameters'));
  9263. }
  9264. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqissuesendmail'])) {
  9265. $this->error(__('You have no permission'));
  9266. }
  9267. $sid = (int)$this->request->post('scydgy_id', 0);
  9268. $companyName = trim((string)$this->request->post('company_name', ''));
  9269. if ($sid >= 0) {
  9270. $this->error('仅支持手工新增询价单');
  9271. }
  9272. if ($companyName === '') {
  9273. $this->error('请选择供应商');
  9274. }
  9275. $po = $this->loadManualRfqOrderForNotify($sid);
  9276. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9277. $this->error('订单已完结,无法发送');
  9278. }
  9279. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9280. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9281. $this->error('订单已进入后续流程,无法再发送');
  9282. }
  9283. $contact = $this->resolveCustomerContactByCompanyName($companyName, false);
  9284. if ($contact === null) {
  9285. $this->error('未找到供应商档案:' . $companyName);
  9286. }
  9287. $email = trim((string)($contact['email'] ?? ''));
  9288. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9289. $this->error('该供应商未填写有效邮箱');
  9290. }
  9291. $mailConfig = $this->loadMailerConfig();
  9292. if (empty($mailConfig['host'])) {
  9293. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9294. }
  9295. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9296. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9297. }
  9298. $mergeRow = $po;
  9299. $mergeRow['ID'] = $sid;
  9300. $mergeRow['id'] = $sid;
  9301. $mergeRows = [$mergeRow];
  9302. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9303. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9304. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9305. }
  9306. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9307. $issueTime = date('Y-m-d H:i:s');
  9308. Db::startTrans();
  9309. try {
  9310. $this->upsertPurchaseOrderFromRow(
  9311. $mergeRow,
  9312. $sysRqDb,
  9313. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9314. $issueTime,
  9315. $po,
  9316. null,
  9317. $scoreRule
  9318. );
  9319. $this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
  9320. Db::commit();
  9321. } catch (\Throwable $e) {
  9322. Db::rollback();
  9323. $this->error($e->getMessage());
  9324. }
  9325. $posNotify = [];
  9326. try {
  9327. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9328. if (is_array($fresh)) {
  9329. $fresh['sys_rq'] = $sysRqDb;
  9330. $posNotify = [$fresh];
  9331. }
  9332. } catch (\Throwable $e) {
  9333. $posNotify = [$po];
  9334. $posNotify[0]['sys_rq'] = $sysRqDb;
  9335. }
  9336. $notifyBundle = [
  9337. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9338. 'pos' => $posNotify,
  9339. 'merge_rows' => $mergeRows,
  9340. ];
  9341. try {
  9342. $this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'pick_issue');
  9343. } catch (\Throwable $e) {
  9344. $this->error('明细已保存,但邮件发送失败:' . $e->getMessage());
  9345. }
  9346. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9347. if ($poId <= 0) {
  9348. try {
  9349. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9350. } catch (\Throwable $e) {
  9351. $poId = 0;
  9352. }
  9353. }
  9354. $this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
  9355. $this->success('已向「' . $companyName . '」发送询价邮件', null, [
  9356. 'scydgy_id' => $sid,
  9357. 'company_name' => $companyName,
  9358. ]);
  9359. }
  9360. /**
  9361. * 查询询价 — 查看各供应商报价(单价)
  9362. */
  9363. public function rfqquotes()
  9364. {
  9365. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqquotes', 'rfqissue'])) {
  9366. $this->error(__('You have no permission'));
  9367. }
  9368. $sid = (int)$this->request->param('scydgy_id', 0);
  9369. if ($sid >= 0) {
  9370. $this->error('仅支持手工新增询价单');
  9371. }
  9372. $po = $this->loadManualRfqOrderForNotify($sid);
  9373. $rows = [];
  9374. try {
  9375. // 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
  9376. $q = Db::table('purchase_order_detail')
  9377. ->where('scydgy_id', $sid)
  9378. ->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
  9379. ->order('id', 'asc');
  9380. $this->applyActivePurchaseOrderDetailWhere($q);
  9381. $rows = $q->select();
  9382. } catch (\Throwable $e) {
  9383. try {
  9384. $q = Db::table('purchase_order_detail')
  9385. ->where('scydgy_id', $sid)
  9386. ->order('id', 'asc');
  9387. $this->applyActivePurchaseOrderDetailWhere($q);
  9388. $rows = $q->select();
  9389. } catch (\Throwable $e2) {
  9390. $rows = [];
  9391. }
  9392. }
  9393. if (!is_array($rows)) {
  9394. $rows = [];
  9395. }
  9396. $list = [];
  9397. foreach ($rows as $row) {
  9398. if (!is_array($row)) {
  9399. continue;
  9400. }
  9401. $amount = trim((string)($row['amount'] ?? ''));
  9402. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  9403. // 未报价不显示时间(createtime 是下发时间,不是报价时间)
  9404. $oper = '';
  9405. if ($isQuoted) {
  9406. $oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
  9407. if ($oper === '') {
  9408. $oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  9409. }
  9410. }
  9411. $list[] = [
  9412. 'id' => (int)($row['id'] ?? 0),
  9413. 'company_name' => trim((string)($row['company_name'] ?? '')),
  9414. 'amount' => $amount,
  9415. 'amount_text' => $isQuoted ? $amount : '',
  9416. 'is_quoted' => $isQuoted,
  9417. 'quote_label' => $isQuoted ? '已报价' : '未报价',
  9418. 'status_name' => trim((string)($row['status_name'] ?? '')),
  9419. 'oper_time' => $oper,
  9420. ];
  9421. }
  9422. $this->success('', null, [
  9423. 'scydgy_id' => $sid,
  9424. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9425. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9426. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9427. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9428. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9429. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9430. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9431. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9432. 'list' => $list,
  9433. ]);
  9434. }
  9435. /**
  9436. * 手工询价是否已下发(有下发明细或已进入待确认及之后)
  9437. */
  9438. protected function isRfqOrderIssued(array $po): bool
  9439. {
  9440. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  9441. return true;
  9442. }
  9443. $sid = (int)($po['scydgy_id'] ?? 0);
  9444. if ($sid >= 0) {
  9445. return false;
  9446. }
  9447. try {
  9448. $q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  9449. $this->applyActivePurchaseOrderDetailWhere($q);
  9450. return (int)$q->count() > 0;
  9451. } catch (\Throwable $e) {
  9452. return false;
  9453. }
  9454. }
  9455. /**
  9456. * 批量:已有下发明细的手工询价 scydgy_id
  9457. *
  9458. * @param int[] $scydgyIds
  9459. * @return array<int, bool>
  9460. */
  9461. protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
  9462. {
  9463. $set = [];
  9464. $ids = [];
  9465. foreach ($scydgyIds as $sid) {
  9466. $sid = (int)$sid;
  9467. if ($sid < 0) {
  9468. $ids[$sid] = true;
  9469. }
  9470. }
  9471. if ($ids === []) {
  9472. return $set;
  9473. }
  9474. try {
  9475. $q = Db::table('purchase_order_detail')
  9476. ->where('scydgy_id', 'in', array_keys($ids))
  9477. ->field('scydgy_id');
  9478. $this->applyActivePurchaseOrderDetailWhere($q);
  9479. $rows = $q->select();
  9480. } catch (\Throwable $e) {
  9481. return $set;
  9482. }
  9483. if (!is_array($rows)) {
  9484. return $set;
  9485. }
  9486. foreach ($rows as $row) {
  9487. if (!is_array($row)) {
  9488. continue;
  9489. }
  9490. $sid = (int)($row['scydgy_id'] ?? 0);
  9491. if ($sid < 0) {
  9492. $set[$sid] = true;
  9493. }
  9494. }
  9495. return $set;
  9496. }
  9497. /**
  9498. * 批量:已填单价(已报价)的手工询价 scydgy_id
  9499. *
  9500. * @param int[] $scydgyIds
  9501. * @return array<int, bool>
  9502. */
  9503. protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
  9504. {
  9505. $set = [];
  9506. $ids = [];
  9507. foreach ($scydgyIds as $sid) {
  9508. $sid = (int)$sid;
  9509. if ($sid < 0) {
  9510. $ids[$sid] = true;
  9511. }
  9512. }
  9513. if ($ids === []) {
  9514. return $set;
  9515. }
  9516. try {
  9517. $q = Db::table('purchase_order_detail')
  9518. ->where('scydgy_id', 'in', array_keys($ids))
  9519. ->field('scydgy_id,amount');
  9520. $this->applyActivePurchaseOrderDetailWhere($q);
  9521. $rows = $q->select();
  9522. } catch (\Throwable $e) {
  9523. return $set;
  9524. }
  9525. if (!is_array($rows)) {
  9526. return $set;
  9527. }
  9528. foreach ($rows as $row) {
  9529. if (!is_array($row)) {
  9530. continue;
  9531. }
  9532. $amount = trim((string)($row['amount'] ?? ''));
  9533. if ($amount === '' || $amount === '0' || $amount === '0.00') {
  9534. continue;
  9535. }
  9536. $sid = (int)($row['scydgy_id'] ?? 0);
  9537. if ($sid < 0) {
  9538. $set[$sid] = true;
  9539. }
  9540. }
  9541. return $set;
  9542. }
  9543. /**
  9544. * 已下发且至少一家供应商已报价,才允许通知业务员
  9545. */
  9546. protected function canRfqNotifySalesman(array $po): bool
  9547. {
  9548. if (!$this->isRfqOrderIssued($po)) {
  9549. return false;
  9550. }
  9551. $sid = (int)($po['scydgy_id'] ?? 0);
  9552. if ($sid >= 0) {
  9553. return false;
  9554. }
  9555. $quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
  9556. return isset($quoted[$sid]);
  9557. }
  9558. protected function assertRfqCanNotifySalesman(array $po): void
  9559. {
  9560. if (!$this->isRfqOrderIssued($po)) {
  9561. $this->error('请先询价并等待供应商报价后再通知业务员');
  9562. }
  9563. if (!$this->canRfqNotifySalesman($po)) {
  9564. $this->error('供应商尚未报价,暂不能通知业务员');
  9565. }
  9566. }
  9567. /**
  9568. * 加载手工询价单(含可见性校验)
  9569. *
  9570. * @return array<string, mixed>
  9571. */
  9572. protected function loadManualRfqOrderForNotify(int $scydgyId): array
  9573. {
  9574. try {
  9575. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  9576. } catch (\Throwable $e) {
  9577. $po = null;
  9578. }
  9579. if (!is_array($po)) {
  9580. $this->error('订单不存在');
  9581. }
  9582. $modRq = trim((string)($po['mod_rq'] ?? ''));
  9583. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  9584. $this->error('订单不存在');
  9585. }
  9586. if ($this->auth->isSuperAdmin()) {
  9587. return $po;
  9588. }
  9589. if ($this->canViewManualRfqOrder($po)) {
  9590. return $po;
  9591. }
  9592. $this->error('无权操作该订单');
  9593. }
  9594. /**
  9595. * @return string[]
  9596. */
  9597. protected function splitRfqSalesmanNames(string $raw): array
  9598. {
  9599. $parts = [];
  9600. $raw = trim($raw);
  9601. if ($raw === '') {
  9602. return [];
  9603. }
  9604. foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
  9605. $v = trim((string)$piece);
  9606. if ($v !== '' && !in_array($v, $parts, true)) {
  9607. $parts[] = $v;
  9608. }
  9609. }
  9610. return $parts;
  9611. }
  9612. /**
  9613. * 按姓名匹配 fa_admin 邮箱
  9614. *
  9615. * @param string[] $names
  9616. * @return array<int, array{admin_id:int,name:string,email:string}>
  9617. */
  9618. protected function resolveRfqSalesmanContactRows(array $names): array
  9619. {
  9620. $out = [];
  9621. foreach ($names as $name) {
  9622. $name = trim((string)$name);
  9623. if ($name === '') {
  9624. continue;
  9625. }
  9626. $adminId = 0;
  9627. $email = '';
  9628. try {
  9629. $row = Db::name('admin')
  9630. ->where(function ($q) use ($name) {
  9631. $q->where('nickname', $name)->whereOr('username', $name);
  9632. })
  9633. ->where('status', 'normal')
  9634. ->order('id', 'asc')
  9635. ->field('id,nickname,username,email')
  9636. ->find();
  9637. } catch (\Throwable $e) {
  9638. $row = null;
  9639. }
  9640. if (is_array($row)) {
  9641. $adminId = (int)($row['id'] ?? 0);
  9642. $email = trim((string)($row['email'] ?? ''));
  9643. $disp = trim((string)($row['nickname'] ?? ''));
  9644. if ($disp === '') {
  9645. $disp = trim((string)($row['username'] ?? ''));
  9646. }
  9647. if ($disp !== '') {
  9648. $name = $disp;
  9649. }
  9650. }
  9651. $out[] = [
  9652. 'admin_id' => $adminId,
  9653. 'name' => $name,
  9654. 'email' => $email,
  9655. ];
  9656. }
  9657. return $out;
  9658. }
  9659. /**
  9660. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  9661. */
  9662. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  9663. {
  9664. if ($scydgyId >= 0) {
  9665. return;
  9666. }
  9667. try {
  9668. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  9669. } catch (\Throwable $e) {
  9670. $po = null;
  9671. }
  9672. if (!is_array($po)) {
  9673. $this->error('订单不存在');
  9674. }
  9675. $modRq = trim((string)($po['mod_rq'] ?? ''));
  9676. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  9677. $this->error('订单不存在');
  9678. }
  9679. if ($this->auth->isSuperAdmin()) {
  9680. return;
  9681. }
  9682. [, $adminName] = $this->GetUseName();
  9683. $cywy = trim((string)($po['cywyxm'] ?? ''));
  9684. if ($cywy !== '' && $cywy === $adminName) {
  9685. return;
  9686. }
  9687. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  9688. try {
  9689. if ($this->auth->check($rule)) {
  9690. return;
  9691. }
  9692. } catch (\Throwable $e) {
  9693. }
  9694. }
  9695. $this->error('无权查看该订单');
  9696. }
  9697. /**
  9698. * 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
  9699. */
  9700. protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
  9701. {
  9702. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  9703. return ProcuremenStatus::PO_COMPLETED;
  9704. }
  9705. $sid = (int)($row['scydgy_id'] ?? 0);
  9706. if ($sid < 0) {
  9707. if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
  9708. return '已通知业务员';
  9709. }
  9710. if ($hasQuoted) {
  9711. return '供应商已报价';
  9712. }
  9713. if ($hasIssued
  9714. || ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
  9715. || ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
  9716. return '待报价';
  9717. }
  9718. try {
  9719. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  9720. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  9721. if ((int)$detCntQuery->count() > 0) {
  9722. return '待报价';
  9723. }
  9724. } catch (\Throwable $e) {
  9725. }
  9726. return '待询价';
  9727. }
  9728. if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
  9729. return '待入库评分';
  9730. }
  9731. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  9732. return '待采购确认';
  9733. }
  9734. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  9735. return '待确认供应商';
  9736. }
  9737. return '待协助下发';
  9738. }
  9739. /**
  9740. * 协助初选列表 — 批量软删除
  9741. */
  9742. public function pickDelete()
  9743. {
  9744. if (!$this->request->isPost() || !$this->request->isAjax()) {
  9745. $this->error(__('Invalid parameters'));
  9746. }
  9747. if (!$this->procuremenCanPickDelete()) {
  9748. $this->error(__('You have no permission'));
  9749. }
  9750. $rowsRaw = $this->request->post('rows_json', '[]');
  9751. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  9752. if (!is_array($rows) || $rows === []) {
  9753. $this->error('请至少勾选一条工序');
  9754. }
  9755. $done = 0;
  9756. Db::startTrans();
  9757. try {
  9758. foreach ($rows as $row) {
  9759. if (!is_array($row)) {
  9760. continue;
  9761. }
  9762. $this->softDeleteProcuremenPickRow($row);
  9763. $done++;
  9764. }
  9765. if ($done < 1) {
  9766. throw new \Exception('没有可删除的工序');
  9767. }
  9768. Db::commit();
  9769. } catch (\InvalidArgumentException $e) {
  9770. Db::rollback();
  9771. $this->error($e->getMessage());
  9772. } catch (\Throwable $e) {
  9773. Db::rollback();
  9774. $this->error($e->getMessage());
  9775. }
  9776. $this->pickHiddenScydgySetCache = null;
  9777. $this->success('已删除 ' . $done . ' 条工序');
  9778. }
  9779. /**
  9780. * 下发 — 手工新增工序(弹窗)
  9781. */
  9782. public function pickAdd()
  9783. {
  9784. if ($this->request->isPost()) {
  9785. $params = $this->request->post('row/a');
  9786. if (!is_array($params)) {
  9787. $this->error(__('Parameter %s can not be empty', ''));
  9788. }
  9789. try {
  9790. $sid = $this->saveManualPickOrder($params);
  9791. } catch (\InvalidArgumentException $e) {
  9792. $this->error($e->getMessage());
  9793. } catch (\Throwable $e) {
  9794. $this->error($e->getMessage());
  9795. }
  9796. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  9797. }
  9798. return $this->view->fetch('procuremen/pick_add');
  9799. }
  9800. /**
  9801. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  9802. */
  9803. public function pickSubmit()
  9804. {
  9805. if (!$this->request->isPost()) {
  9806. $this->error(__('Invalid parameters'));
  9807. }
  9808. // ---------- 接口订单数据 ----------
  9809. $rowJson = $this->request->post('row_json', '');
  9810. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  9811. $companiesJson = $this->request->post('companies_json', '[]');
  9812. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  9813. $companies = json_decode($companiesJson, true);
  9814. if (!is_array($companies)) {
  9815. $this->error('供应商数据无效');
  9816. }
  9817. $issueCompanies = $this->normalizePickCompanies($companies);
  9818. if ($issueCompanies === []) {
  9819. $this->error('请至少选择一家合作供应商');
  9820. }
  9821. $issueNameLabels = [];
  9822. foreach ($issueCompanies as $pc) {
  9823. $issueNameLabels[] = $pc['name'];
  9824. }
  9825. $issueNamesSummary = implode('、', $issueNameLabels);
  9826. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  9827. if ($sysRq === '') {
  9828. $this->error('请选择招标截止日期');
  9829. }
  9830. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  9831. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  9832. (string)$this->request->post('delivery_deadline', ''),
  9833. true
  9834. );
  9835. $scoreRuleId = (int)$this->request->post('score_rule_id', 0);
  9836. if ($scoreRuleId <= 0) {
  9837. $this->error('请选择订单类型');
  9838. }
  9839. $scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
  9840. if ((int)($scoreRule['id'] ?? 0) <= 0) {
  9841. $this->error('订单类型无效,请刷新后重选');
  9842. }
  9843. $scoreRuleId = (int)$scoreRule['id'];
  9844. $this->ensurePurchaseOrderScoreRuleIdColumn();
  9845. $isMerge = count($mergeRows) > 1;
  9846. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  9847. $logMsg = '下发' . $procPart
  9848. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  9849. $issueTime = date('Y-m-d H:i:s');
  9850. $logSidList = [];
  9851. foreach ($mergeRows as $row) {
  9852. if (!is_array($row)) {
  9853. continue;
  9854. }
  9855. $sid = $this->extractScydgyRowId($row);
  9856. if ($this->isValidScydgyRowId($sid)) {
  9857. $logSidList[$sid] = true;
  9858. }
  9859. }
  9860. $existingBySid = [];
  9861. if ($logSidList !== []) {
  9862. try {
  9863. $existingRows = Db::table('purchase_order')
  9864. ->where('scydgy_id', 'in', array_keys($logSidList))
  9865. ->select();
  9866. if (is_array($existingRows)) {
  9867. foreach ($existingRows as $poRow) {
  9868. if (!is_array($poRow)) {
  9869. continue;
  9870. }
  9871. $sid = (int)($poRow['scydgy_id'] ?? 0);
  9872. if ($this->isValidScydgyRowId($sid)) {
  9873. $existingBySid[$sid] = $poRow;
  9874. }
  9875. }
  9876. }
  9877. } catch (\Throwable $e) {
  9878. $existingBySid = [];
  9879. }
  9880. }
  9881. Db::startTrans();
  9882. try {
  9883. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  9884. foreach ($mergeRows as $row) {
  9885. if (!is_array($row)) {
  9886. continue;
  9887. }
  9888. $sid = $this->extractScydgyRowId($row);
  9889. $this->upsertPurchaseOrderFromRow(
  9890. $row,
  9891. $sysRqDb,
  9892. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9893. $issueTime,
  9894. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  9895. $deliveryDeadlineDb,
  9896. $scoreRule
  9897. );
  9898. }
  9899. foreach ($issueCompanies as $c) {
  9900. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  9901. }
  9902. Db::commit();
  9903. } catch (\Throwable $e) {
  9904. Db::rollback();
  9905. $this->error($e->getMessage());
  9906. }
  9907. $poIdBySid = [];
  9908. if ($logSidList !== []) {
  9909. try {
  9910. $poIdBySid = Db::table('purchase_order')
  9911. ->where('scydgy_id', 'in', array_keys($logSidList))
  9912. ->column('id', 'scydgy_id');
  9913. } catch (\Throwable $e) {
  9914. $poIdBySid = [];
  9915. }
  9916. }
  9917. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  9918. if ($logSidList !== []) {
  9919. list($adminId, $adminName) = $this->GetUseName();
  9920. $logRows = [];
  9921. $seenLogSid = [];
  9922. foreach ($mergeRows as $row) {
  9923. if (!is_array($row)) {
  9924. continue;
  9925. }
  9926. $ids = $this->extractScydgyRowId($row);
  9927. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  9928. continue;
  9929. }
  9930. $seenLogSid[$ids] = true;
  9931. $poIdLog = null;
  9932. if (isset($poIdBySid[$ids])) {
  9933. $tid = (int)$poIdBySid[$ids];
  9934. $poIdLog = $tid > 0 ? $tid : null;
  9935. }
  9936. $logRows[] = ProcuremenOperLog::buildInsertRow(
  9937. $ids,
  9938. 'issue_submit',
  9939. $logMsg,
  9940. $poIdLog,
  9941. (int)$adminId,
  9942. (string)$adminName
  9943. );
  9944. }
  9945. if ($logRows !== []) {
  9946. try {
  9947. Db::table('purchase_order_oper_log')->insertAll($logRows);
  9948. } catch (\Throwable $e) {
  9949. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  9950. }
  9951. }
  9952. }
  9953. $notifyErrors = [];
  9954. $posNotify = [];
  9955. if ($logSidList !== []) {
  9956. try {
  9957. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  9958. } catch (\Throwable $e) {
  9959. $posNotify = [];
  9960. }
  9961. }
  9962. if (!is_array($posNotify)) {
  9963. $posNotify = [];
  9964. }
  9965. foreach ($posNotify as $i => $prow) {
  9966. if (is_array($posNotify[$i])) {
  9967. $posNotify[$i]['sys_rq'] = $sysRqDb;
  9968. }
  9969. }
  9970. $ccydhPick = '';
  9971. foreach ($mergeRows as $row) {
  9972. if (!is_array($row)) {
  9973. continue;
  9974. }
  9975. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  9976. if ($ccydhPick !== '') {
  9977. break;
  9978. }
  9979. }
  9980. $notifyBundleBase = [
  9981. 'ccydh' => $ccydhPick,
  9982. 'pos' => $posNotify,
  9983. 'merge_rows' => $mergeRows,
  9984. ];
  9985. try {
  9986. $this->notifyDryRunPreview = [];
  9987. foreach ($issueCompanies as $c) {
  9988. if (!is_array($c)) {
  9989. continue;
  9990. }
  9991. $cname = trim((string)($c['name'] ?? ''));
  9992. if ($cname === '') {
  9993. continue;
  9994. }
  9995. try {
  9996. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  9997. } catch (\Throwable $e) {
  9998. $notifyErrors[] = $cname . ':' . $e->getMessage();
  9999. }
  10000. }
  10001. } catch (\Throwable $e) {
  10002. $this->error('通知发送失败:' . $e->getMessage());
  10003. }
  10004. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10005. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  10006. }
  10007. if ($this->isProcuremenNotifyDryRun()) {
  10008. $this->success('【演练模式】已保存并生成通知预览', '', [
  10009. 'notify_dry_run' => true,
  10010. 'notify_preview' => $this->notifyDryRunPreview,
  10011. ]);
  10012. }
  10013. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  10014. }
  10015. /**
  10016. * 确认供应商弹窗
  10017. */
  10018. public function auditIssue()
  10019. {
  10020. $ids = $this->request->param('ids', $this->request->param('id', ''));
  10021. if (is_array($ids)) {
  10022. $ids = isset($ids[0]) ? $ids[0] : '';
  10023. }
  10024. $ids = trim((string)$ids);
  10025. if ($ids === '') {
  10026. $this->error(__('Invalid parameters'));
  10027. }
  10028. if ($this->request->isPost()) {
  10029. $this->error('请使用弹窗内「确认」提交');
  10030. }
  10031. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10032. $pos = $bundle['pos'];
  10033. if ($pos === []) {
  10034. $this->error('该订单不在待确认供应商状态');
  10035. }
  10036. $po = $pos[0];
  10037. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10038. if ($quoteGroups === []) {
  10039. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  10040. }
  10041. $pickedName = '';
  10042. foreach ($pos as $poRow) {
  10043. if (!is_array($poRow)) {
  10044. continue;
  10045. }
  10046. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  10047. if ($pn !== '') {
  10048. $pickedName = $pn;
  10049. break;
  10050. }
  10051. }
  10052. $this->view->assign('po', $po);
  10053. $this->view->assign('scydgyId', $ids);
  10054. $this->view->assign('orderCcydh', $bundle['ccydh']);
  10055. $mergeRows = $bundle['merge_rows'];
  10056. $this->view->assign('processRows', $mergeRows);
  10057. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  10058. $this->view->assign('processCount', count($mergeRows));
  10059. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  10060. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  10061. $this->view->assign('pickedCompanyName', $pickedName);
  10062. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10063. if ($sysRqForView === '') {
  10064. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10065. }
  10066. $this->view->assign('sysRq', $sysRqForView);
  10067. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  10068. if ($deliveryDeadlineForView === '') {
  10069. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10070. }
  10071. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10072. $this->ensurePurchaseOrderManualPickColumns();
  10073. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
  10074. $manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
  10075. $manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
  10076. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  10077. if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
  10078. $pickedName = $manualPickInfo['company'];
  10079. $this->view->assign('pickedCompanyName', $pickedName);
  10080. }
  10081. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  10082. $this->view->assign('manualPicked', $manualPicked);
  10083. $this->view->assign('manualPickReason', $manualPickInfo['reason']);
  10084. $this->view->assign('quoteVisible', $quoteVisible);
  10085. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
  10086. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  10087. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
  10088. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
  10089. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  10090. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  10091. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  10092. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  10093. return $this->view->fetch('procuremen/audit_issue');
  10094. }
  10095. /**
  10096. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  10097. *
  10098. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10099. */
  10100. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  10101. {
  10102. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10103. return false;
  10104. }
  10105. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10106. return false;
  10107. }
  10108. return true;
  10109. }
  10110. /**
  10111. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  10112. *
  10113. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10114. */
  10115. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  10116. {
  10117. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10118. return false;
  10119. }
  10120. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10121. return false;
  10122. }
  10123. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  10124. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  10125. return true;
  10126. }
  10127. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  10128. }
  10129. /**
  10130. * 确认页 — 补加供应商弹窗
  10131. */
  10132. public function auditAppend()
  10133. {
  10134. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  10135. $this->error(__('You have no permission'));
  10136. }
  10137. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  10138. if (is_array($ids)) {
  10139. $ids = isset($ids[0]) ? $ids[0] : '';
  10140. }
  10141. $ids = trim((string)$ids);
  10142. if ($ids === '') {
  10143. $this->error(__('Invalid parameters'));
  10144. }
  10145. if ($this->request->isPost()) {
  10146. $this->error('请使用弹窗内「确认」提交');
  10147. }
  10148. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10149. if (($bundle['pos'] ?? []) === []) {
  10150. $this->error('该订单不在待确认供应商状态');
  10151. }
  10152. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10153. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10154. $this->error('已开标验证,不能再补加供应商');
  10155. }
  10156. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10157. $this->error('已指定供应商,不能再补加供应商');
  10158. }
  10159. $this->error('已经超过了招标截止日期,不可操作');
  10160. }
  10161. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10162. $existingNames = [];
  10163. foreach ($quoteGroups as $g) {
  10164. if (!is_array($g)) {
  10165. continue;
  10166. }
  10167. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  10168. if ($n !== '') {
  10169. $existingNames[$n] = true;
  10170. }
  10171. }
  10172. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  10173. $mergeRows = $bundle['merge_rows'] ?? [];
  10174. $this->view->assign('scydgyId', $ids);
  10175. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  10176. $this->view->assign('po', $po);
  10177. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  10178. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  10179. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  10180. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10181. if ($sysRqForView === '') {
  10182. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10183. }
  10184. $this->view->assign('sysRq', $sysRqForView);
  10185. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  10186. if ($deliveryDeadlineForView === '') {
  10187. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10188. }
  10189. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10190. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  10191. }
  10192. /**
  10193. * 确认页 — 补加供应商提交
  10194. */
  10195. public function auditAppendSubmit()
  10196. {
  10197. if (!$this->request->isPost()) {
  10198. $this->error(__('Invalid parameters'));
  10199. }
  10200. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  10201. $this->error(__('You have no permission'));
  10202. }
  10203. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  10204. if ($ids === '') {
  10205. $this->error(__('Invalid parameters'));
  10206. }
  10207. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10208. if (($bundle['pos'] ?? []) === []) {
  10209. $this->error('该订单不在待确认供应商状态');
  10210. }
  10211. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10212. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10213. $this->error('已开标验证,不能再补加供应商');
  10214. }
  10215. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10216. $this->error('已指定供应商,不能再补加供应商');
  10217. }
  10218. $this->error('已经超过了招标截止日期,不可操作');
  10219. }
  10220. $companiesJson = $this->request->post('companies_json', '[]');
  10221. $companies = json_decode((string)$companiesJson, true);
  10222. if (!is_array($companies)) {
  10223. $this->error('供应商数据无效');
  10224. }
  10225. $issueCompanies = $this->normalizePickCompanies($companies);
  10226. if ($issueCompanies === []) {
  10227. $this->error('请至少选择一家合作供应商');
  10228. }
  10229. $mergeRows = $bundle['merge_rows'] ?? [];
  10230. if (!is_array($mergeRows) || $mergeRows === []) {
  10231. $this->error('未找到工序行,无法补加');
  10232. }
  10233. $existingNames = [];
  10234. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  10235. if (!is_array($g)) {
  10236. continue;
  10237. }
  10238. $n = trim((string)($g['company_name'] ?? ''));
  10239. if ($n !== '') {
  10240. $existingNames[$n] = true;
  10241. }
  10242. }
  10243. $toAdd = [];
  10244. foreach ($issueCompanies as $c) {
  10245. if (!is_array($c)) {
  10246. continue;
  10247. }
  10248. $n = trim((string)($c['name'] ?? ''));
  10249. if ($n === '' || isset($existingNames[$n])) {
  10250. continue;
  10251. }
  10252. $toAdd[] = $c;
  10253. }
  10254. if ($toAdd === []) {
  10255. $this->error('所选供应商均已在本单中,请选择新的供应商');
  10256. }
  10257. $addedNames = [];
  10258. Db::startTrans();
  10259. try {
  10260. foreach ($toAdd as $c) {
  10261. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10262. $addedNames[] = trim((string)($c['name'] ?? ''));
  10263. }
  10264. Db::commit();
  10265. } catch (\Throwable $e) {
  10266. Db::rollback();
  10267. $this->error($e->getMessage());
  10268. }
  10269. $notifyErrors = [];
  10270. $notifyBundleBase = [
  10271. 'ccydh' => $bundle['ccydh'] ?? '',
  10272. 'pos' => $bundle['pos'] ?? [],
  10273. 'merge_rows' => $mergeRows,
  10274. ];
  10275. foreach ($toAdd as $c) {
  10276. if (!is_array($c)) {
  10277. continue;
  10278. }
  10279. $cname = trim((string)($c['name'] ?? ''));
  10280. if ($cname === '') {
  10281. continue;
  10282. }
  10283. try {
  10284. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  10285. } catch (\Throwable $e) {
  10286. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10287. }
  10288. }
  10289. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  10290. $seenLogSid = [];
  10291. foreach ($bundle['pos'] ?? [] as $poRow) {
  10292. if (!is_array($poRow)) {
  10293. continue;
  10294. }
  10295. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10296. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  10297. continue;
  10298. }
  10299. $seenLogSid[$sid] = true;
  10300. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10301. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10302. }
  10303. if ($seenLogSid === []) {
  10304. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  10305. if ($this->isValidScydgyRowId($logSid)) {
  10306. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  10307. }
  10308. }
  10309. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10310. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  10311. }
  10312. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  10313. }
  10314. /**
  10315. * 开标双重验证 — 可选验证人列表
  10316. */
  10317. public function bidOpenUsers()
  10318. {
  10319. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10320. $this->error('无权限');
  10321. }
  10322. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  10323. if ($scydgyId !== '') {
  10324. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10325. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10326. $this->success('已完成开标验证', null, [
  10327. 'verified' => 1,
  10328. 'users' => [],
  10329. ]);
  10330. }
  10331. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10332. $this->error('本单已指定供应商,无需再开标');
  10333. }
  10334. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10335. }
  10336. $this->success('', null, [
  10337. 'verified' => 0,
  10338. 'users' => $this->listBidOpenVerifierCandidates(),
  10339. ]);
  10340. }
  10341. /**
  10342. * 开标双重验证 — 向指定管理员发送短信验证码
  10343. */
  10344. public function bidOpenSendCode()
  10345. {
  10346. if (!$this->request->isPost()) {
  10347. $this->error(__('Invalid parameters'));
  10348. }
  10349. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10350. $this->error('无权限');
  10351. }
  10352. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10353. $adminId = (int)$this->request->post('admin_id', 0);
  10354. if ($scydgyId === '' || $adminId <= 0) {
  10355. $this->error('参数无效');
  10356. }
  10357. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10358. if ($bundle['pos'] === []) {
  10359. $this->error('该订单不在待确认供应商状态');
  10360. }
  10361. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10362. $this->success('已完成开标验证,无需重复发送');
  10363. }
  10364. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10365. $this->error('本单已指定供应商,无需再开标');
  10366. }
  10367. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10368. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10369. if ($ccydh === '') {
  10370. $this->error('订单号无效');
  10371. }
  10372. $admin = $this->loadBidOpenAdminUser($adminId);
  10373. if ($admin === null) {
  10374. $this->error('验证人无效或未绑定手机号');
  10375. }
  10376. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  10377. $cd = max(30, min(120, $cd));
  10378. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  10379. $this->error('发送过于频繁,请稍后再试');
  10380. }
  10381. $code = (string)random_int(100000, 999999);
  10382. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  10383. $ttl = max(60, min(600, $ttl));
  10384. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  10385. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  10386. try {
  10387. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  10388. } catch (\Throwable $e) {
  10389. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  10390. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  10391. $this->error($e->getMessage());
  10392. }
  10393. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  10394. }
  10395. /**
  10396. * 开标双重验证 — 两人验证码校验并记录
  10397. */
  10398. public function bidOpenVerify()
  10399. {
  10400. if (!$this->request->isPost()) {
  10401. $this->error(__('Invalid parameters'));
  10402. }
  10403. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10404. $this->error('无权限');
  10405. }
  10406. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10407. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  10408. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  10409. $code1 = trim((string)$this->request->post('code1', ''));
  10410. $code2 = trim((string)$this->request->post('code2', ''));
  10411. if ($scydgyId === '') {
  10412. $this->error('参数无效');
  10413. }
  10414. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  10415. $this->error('请选择两位验证人');
  10416. }
  10417. if ($verifier1Id === $verifier2Id) {
  10418. $this->error('两位验证人不能相同');
  10419. }
  10420. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  10421. $this->error('请输入6位短信验证码');
  10422. }
  10423. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10424. if ($bundle['pos'] === []) {
  10425. $this->error('该订单不在待确认供应商状态');
  10426. }
  10427. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10428. if ($ccydh === '') {
  10429. $this->error('订单号无效');
  10430. }
  10431. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10432. $this->success('已完成开标验证');
  10433. }
  10434. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10435. $this->error('本单已指定供应商,无需再开标');
  10436. }
  10437. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10438. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  10439. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  10440. if ($verifier1 === null || $verifier2 === null) {
  10441. $this->error('验证人无效或未绑定手机号');
  10442. }
  10443. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  10444. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  10445. }
  10446. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  10447. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  10448. }
  10449. try {
  10450. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  10451. } catch (\Throwable $e) {
  10452. $this->error($e->getMessage());
  10453. }
  10454. $this->success('开标验证成功,可查看供应商报价与交货日期');
  10455. }
  10456. /**
  10457. * 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
  10458. */
  10459. public function auditManualPick()
  10460. {
  10461. if (!$this->request->isPost()) {
  10462. $this->error(__('Invalid parameters'));
  10463. }
  10464. if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
  10465. $this->error('无权限');
  10466. }
  10467. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10468. if ($scydgyId === '') {
  10469. $this->error('参数无效');
  10470. }
  10471. $companyName = trim((string)$this->request->post('selected_company', ''));
  10472. $reason = trim((string)$this->request->post('pick_reason', ''));
  10473. if ($companyName === '') {
  10474. $this->error('请选择一家供应商');
  10475. }
  10476. if ($reason === '') {
  10477. $this->error('请填写选择说明');
  10478. }
  10479. if (mb_strlen($reason) > 500) {
  10480. $this->error('选择说明不能超过500字');
  10481. }
  10482. $this->ensurePurchaseOrderManualPickColumns();
  10483. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10484. $pos = $bundle['pos'];
  10485. if ($pos === []) {
  10486. $this->error('该订单不在待确认供应商状态');
  10487. }
  10488. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10489. $this->error('本单已开标验证,请直接在列表中选定供应商后确认');
  10490. }
  10491. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10492. if ($quoteGroups === []) {
  10493. $this->error('暂无供应商,请确认已完成协助初选通知');
  10494. }
  10495. $matched = null;
  10496. foreach ($quoteGroups as $g) {
  10497. if (!is_array($g)) {
  10498. continue;
  10499. }
  10500. if (trim((string)($g['name'] ?? '')) === $companyName) {
  10501. $matched = $g;
  10502. break;
  10503. }
  10504. }
  10505. if ($matched === null) {
  10506. $this->error('所选供应商不在本单报价列表中');
  10507. }
  10508. $logMsg = '指定供应商:已选定「' . $companyName . '」;说明:' . $reason;
  10509. Db::startTrans();
  10510. try {
  10511. foreach ($pos as $poRow) {
  10512. if (!is_array($poRow)) {
  10513. continue;
  10514. }
  10515. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10516. if (!$this->isValidScydgyRowId($sid)) {
  10517. continue;
  10518. }
  10519. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10520. 'pick_company_name' => $companyName,
  10521. 'manual_pick' => 1,
  10522. 'manual_pick_reason' => $reason,
  10523. ]);
  10524. }
  10525. Db::commit();
  10526. } catch (\Throwable $e) {
  10527. Db::rollback();
  10528. $this->error($e->getMessage());
  10529. }
  10530. foreach ($pos as $poRow) {
  10531. if (!is_array($poRow)) {
  10532. continue;
  10533. }
  10534. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10535. if (!$this->isValidScydgyRowId($sid)) {
  10536. continue;
  10537. }
  10538. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10539. $this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10540. }
  10541. // 自选后可见报价:按本单规则计算评分(与开标后一致)
  10542. try {
  10543. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10544. if ($ccydh !== '') {
  10545. // 重新加载以拿到未掩码报价参与计分
  10546. $bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10547. $groupsFresh = $this->loadAuditSupplierQuoteGroups($bundleFresh);
  10548. ProcuremenSupplierScore::saveForOrder($ccydh, $groupsFresh, date('Y-m'));
  10549. }
  10550. } catch (\Throwable $e) {
  10551. Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
  10552. }
  10553. $this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
  10554. }
  10555. /**
  10556. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  10557. */
  10558. public function auditSubmit()
  10559. {
  10560. if (!$this->request->isPost()) {
  10561. $this->error(__('Invalid parameters'));
  10562. }
  10563. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10564. if ($scydgyId === '') {
  10565. $this->error('参数无效');
  10566. }
  10567. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10568. $pos = $bundle['pos'];
  10569. $mergeRows = $bundle['merge_rows'];
  10570. if ($pos === [] || $mergeRows === []) {
  10571. $this->error('该订单不在待确认供应商状态');
  10572. }
  10573. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10574. if ($quoteGroups === []) {
  10575. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  10576. }
  10577. $companyName = trim((string)$this->request->post('selected_company', ''));
  10578. if ($companyName === '') {
  10579. $this->error('请选择一家供应商');
  10580. }
  10581. $matched = null;
  10582. foreach ($quoteGroups as $g) {
  10583. if (!is_array($g)) {
  10584. continue;
  10585. }
  10586. if (trim((string)($g['name'] ?? '')) === $companyName) {
  10587. $matched = $g;
  10588. break;
  10589. }
  10590. }
  10591. if ($matched === null) {
  10592. $this->error('所选供应商不在本单报价列表中');
  10593. }
  10594. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10595. if ($sysRqDb === '') {
  10596. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  10597. } else {
  10598. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  10599. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  10600. }
  10601. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  10602. $this->error('未到招标截止日期,暂不可确认');
  10603. }
  10604. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
  10605. && !$this->isProcuremenManualPickedForBundle($bundle)
  10606. ) {
  10607. $this->error('请先完成开标双重验证或指定供应商后再确认');
  10608. }
  10609. $procCnt = count($mergeRows);
  10610. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  10611. $logMsg = '确认供应商' . $procPart . ':已选定「' . $companyName . '」';
  10612. Db::startTrans();
  10613. try {
  10614. foreach ($pos as $poRow) {
  10615. if (!is_array($poRow)) {
  10616. continue;
  10617. }
  10618. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10619. if (!$this->isValidScydgyRowId($sid)) {
  10620. continue;
  10621. }
  10622. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10623. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  10624. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  10625. 'pick_company_name' => $companyName,
  10626. 'sys_rq' => $sysRqDb,
  10627. ]);
  10628. }
  10629. Db::commit();
  10630. } catch (\Throwable $e) {
  10631. Db::rollback();
  10632. $this->error($e->getMessage());
  10633. }
  10634. foreach ($pos as $poRow) {
  10635. if (!is_array($poRow)) {
  10636. continue;
  10637. }
  10638. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10639. if (!$this->isValidScydgyRowId($sid)) {
  10640. continue;
  10641. }
  10642. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10643. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10644. }
  10645. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  10646. }
  10647. /**
  10648. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  10649. */
  10650. public function auditResendSms()
  10651. {
  10652. if (!$this->request->isPost()) {
  10653. $this->error(__('Invalid parameters'));
  10654. }
  10655. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10656. if ($scydgyId === '') {
  10657. $this->error('参数无效');
  10658. }
  10659. $loaded = $this->loadAuditResendBundle($scydgyId);
  10660. $mergeRows = $loaded['merge_rows'];
  10661. $bundle = $loaded['bundle'];
  10662. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  10663. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10664. if ($quoteGroups === []) {
  10665. $this->error('暂无可通知的供应商');
  10666. }
  10667. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  10668. $companiesJson = (string)$this->request->post('companies_json', '');
  10669. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  10670. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  10671. }
  10672. /**
  10673. * 确认供应商 — 二次发送邮件(可选单家/批量)
  10674. */
  10675. public function auditResendEmail()
  10676. {
  10677. if (!$this->request->isPost()) {
  10678. $this->error(__('Invalid parameters'));
  10679. }
  10680. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10681. if ($scydgyId === '') {
  10682. $this->error('参数无效');
  10683. }
  10684. $loaded = $this->loadAuditResendBundle($scydgyId);
  10685. $mergeRows = $loaded['merge_rows'];
  10686. $bundle = $loaded['bundle'];
  10687. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  10688. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10689. if ($quoteGroups === []) {
  10690. $this->error('暂无可通知的供应商');
  10691. }
  10692. $companiesJson = (string)$this->request->post('companies_json', '');
  10693. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  10694. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  10695. if ($companiesJson === '' && $selectedCompany === '') {
  10696. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  10697. }
  10698. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  10699. }
  10700. /**
  10701. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  10702. *
  10703. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  10704. * @return array<int, true> 已处理的 scydgy_id 集合
  10705. */
  10706. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  10707. {
  10708. $pos = $bundle['pos'] ?? [];
  10709. if (!is_array($pos) || $pos === []) {
  10710. return [];
  10711. }
  10712. $sids = [];
  10713. $poIdBySid = [];
  10714. foreach ($pos as $poRow) {
  10715. if (!is_array($poRow)) {
  10716. continue;
  10717. }
  10718. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10719. if ($this->isValidScydgyRowId($sid)) {
  10720. $sids[$sid] = true;
  10721. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10722. if ($poId > 0) {
  10723. $poIdBySid[$sid] = $poId;
  10724. }
  10725. }
  10726. }
  10727. if ($sids === []) {
  10728. return [];
  10729. }
  10730. $logMsg = '重新下发';
  10731. $suffix = trim((string)$logSuffix, ',, ');
  10732. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  10733. $logMsg .= ':从历史存证退回协助初选';
  10734. } else {
  10735. $logMsg .= ':退回协助初选';
  10736. }
  10737. Db::table('purchase_order')
  10738. ->where('scydgy_id', 'in', array_keys($sids))
  10739. ->update([
  10740. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  10741. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  10742. 'pick_company_name' => '',
  10743. 'pick_time' => null,
  10744. 'sys_rq' => null,
  10745. 'mod_rq' => null,
  10746. ]);
  10747. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  10748. foreach (array_keys($sids) as $sid) {
  10749. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  10750. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10751. }
  10752. return $sids;
  10753. }
  10754. /**
  10755. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  10756. *
  10757. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  10758. */
  10759. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  10760. {
  10761. $scydgyId = trim($scydgyId);
  10762. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  10763. if ($scydgyId === '') {
  10764. return $empty;
  10765. }
  10766. try {
  10767. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10768. } catch (\Throwable $e) {
  10769. $anchor = null;
  10770. }
  10771. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  10772. return $empty;
  10773. }
  10774. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  10775. if ($ccydh === '') {
  10776. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  10777. }
  10778. try {
  10779. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  10780. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  10781. $pos = $query->order('scydgy_id', 'asc')->select();
  10782. } catch (\Throwable $e) {
  10783. $pos = [$anchor];
  10784. }
  10785. if (!is_array($pos) || $pos === []) {
  10786. $pos = [$anchor];
  10787. }
  10788. return [
  10789. 'ccydh' => $ccydh,
  10790. 'pos' => $pos,
  10791. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  10792. ];
  10793. }
  10794. protected function purchaseOrderRowIsCompleted(array $po): bool
  10795. {
  10796. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  10797. }
  10798. /**
  10799. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  10800. *
  10801. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  10802. */
  10803. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  10804. {
  10805. $scydgyId = trim($scydgyId);
  10806. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  10807. if ($scydgyId === '') {
  10808. return $empty;
  10809. }
  10810. try {
  10811. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10812. } catch (\Throwable $e) {
  10813. $anchor = null;
  10814. }
  10815. if (!is_array($anchor)) {
  10816. return $empty;
  10817. }
  10818. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  10819. if ($ccydh === '') {
  10820. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  10821. }
  10822. try {
  10823. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  10824. } catch (\Throwable $e) {
  10825. $pos = [$anchor];
  10826. }
  10827. if (!is_array($pos) || $pos === []) {
  10828. $pos = [$anchor];
  10829. }
  10830. return [
  10831. 'ccydh' => $ccydh,
  10832. 'pos' => $pos,
  10833. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  10834. ];
  10835. }
  10836. /**
  10837. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  10838. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  10839. */
  10840. public function auditAbandon()
  10841. {
  10842. if (!$this->request->isPost()) {
  10843. $this->error(__('Invalid parameters'));
  10844. }
  10845. $anchorIds = [];
  10846. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  10847. if ($batchRaw !== '') {
  10848. $decoded = json_decode($batchRaw, true);
  10849. if (is_array($decoded)) {
  10850. foreach ($decoded as $id) {
  10851. $s = trim((string)$id);
  10852. if ($s !== '') {
  10853. $anchorIds[] = $s;
  10854. }
  10855. }
  10856. }
  10857. }
  10858. if ($anchorIds === []) {
  10859. $single = trim((string)$this->request->post('scydgy_id', ''));
  10860. if ($single !== '') {
  10861. $anchorIds[] = $single;
  10862. }
  10863. }
  10864. if ($anchorIds === []) {
  10865. $this->error('请至少选择一条订单');
  10866. }
  10867. $processedCcydh = [];
  10868. $doneOrders = 0;
  10869. $allSids = [];
  10870. Db::startTrans();
  10871. try {
  10872. foreach ($anchorIds as $anchorId) {
  10873. $fromArchive = false;
  10874. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  10875. if (($bundle['pos'] ?? []) === []) {
  10876. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  10877. $fromArchive = ($bundle['pos'] ?? []) !== [];
  10878. }
  10879. if (($bundle['pos'] ?? []) === []) {
  10880. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  10881. $fromArchive = ($bundle['pos'] ?? []) !== [];
  10882. }
  10883. if (($bundle['pos'] ?? []) === []) {
  10884. continue;
  10885. }
  10886. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10887. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  10888. if (isset($processedCcydh[$dedupeKey])) {
  10889. continue;
  10890. }
  10891. $processedCcydh[$dedupeKey] = true;
  10892. $sids = $fromArchive
  10893. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回协助初选')
  10894. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  10895. if ($sids === []) {
  10896. continue;
  10897. }
  10898. $doneOrders++;
  10899. foreach (array_keys($sids) as $sid) {
  10900. $allSids[(int)$sid] = true;
  10901. }
  10902. }
  10903. if ($doneOrders < 1) {
  10904. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  10905. }
  10906. Db::commit();
  10907. } catch (\Throwable $e) {
  10908. Db::rollback();
  10909. $this->error($e->getMessage());
  10910. }
  10911. $this->pickHiddenScydgySetCache = null;
  10912. $msg = $doneOrders > 1
  10913. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  10914. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  10915. $this->success($msg);
  10916. }
  10917. /**
  10918. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  10919. */
  10920. public function archiveAbandon()
  10921. {
  10922. return $this->auditAbandon();
  10923. }
  10924. /**
  10925. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  10926. */
  10927. public function purchaseApprovalReject()
  10928. {
  10929. if (!$this->request->isPost() || !$this->request->isAjax()) {
  10930. $this->error(__('Invalid parameters'));
  10931. }
  10932. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  10933. $this->error(__('You have no permission'));
  10934. }
  10935. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  10936. $decoded = json_decode($batchRaw, true);
  10937. if (!is_array($decoded) || $decoded === []) {
  10938. $this->error('提交数据无效');
  10939. }
  10940. $done = 0;
  10941. Db::startTrans();
  10942. try {
  10943. foreach ($decoded as $item) {
  10944. if (!is_array($item)) {
  10945. continue;
  10946. }
  10947. $sid = (int)($item['scydgy_id'] ?? 0);
  10948. if (!$this->isValidScydgyRowId($sid)) {
  10949. continue;
  10950. }
  10951. $this->runPurchaseApprovalRejectForSid($sid);
  10952. $done++;
  10953. }
  10954. if ($done < 1) {
  10955. throw new \Exception('所选订单均不在待审批状态');
  10956. }
  10957. Db::commit();
  10958. } catch (\Throwable $e) {
  10959. Db::rollback();
  10960. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  10961. }
  10962. $this->pickHiddenScydgySetCache = null;
  10963. $this->success('已驳回并退回「协助审批下发」');
  10964. }
  10965. /**
  10966. * @throws \Exception
  10967. */
  10968. protected function runPurchaseApprovalRejectForSid(int $sid): void
  10969. {
  10970. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  10971. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  10972. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  10973. $allIds = $this->purchaseOrderDetail($sid);
  10974. if ($allIds === []) {
  10975. throw new \Exception('未找到下发明细');
  10976. }
  10977. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10978. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  10979. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  10980. 'pick_company_name' => '',
  10981. ]);
  10982. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  10983. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  10984. $poId = 0;
  10985. try {
  10986. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  10987. if (is_array($po)) {
  10988. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  10989. }
  10990. } catch (\Throwable $e) {
  10991. }
  10992. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  10993. }
  10994. /**
  10995. * 审核弹窗(旧入口,POST 已关闭)
  10996. */
  10997. public function review()
  10998. {
  10999. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  11000. $this->error(__('You have no permission'));
  11001. }
  11002. if ($this->request->isPost()) {
  11003. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  11004. }
  11005. $this->view->assign('pickMode', 0);
  11006. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  11007. }
  11008. /**
  11009. * 审核弹窗获取公司列表
  11010. */
  11011. public function reviewCompanies()
  11012. {
  11013. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  11014. $this->error(__('You have no permission'));
  11015. }
  11016. if (!$this->request->isAjax()) {
  11017. $this->error(__('Invalid parameters'));
  11018. }
  11019. $list = [];
  11020. try {
  11021. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  11022. $rows = Db::table('customer')
  11023. ->where(function ($q) {
  11024. $q->where('status', 1)
  11025. ->whereOr('status', '1')
  11026. ->whereOr('status', '')
  11027. ->whereNull('status');
  11028. })
  11029. ->order('id', 'desc')
  11030. ->select();
  11031. } catch (\Throwable $e) {
  11032. $this->success('', '', []);
  11033. return;
  11034. }
  11035. if (!is_array($rows)) {
  11036. $this->success('', '', []);
  11037. return;
  11038. }
  11039. $detailColCandidates = [
  11040. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  11041. 'company_detail', 'company_desc', 'address',
  11042. ];
  11043. foreach ($rows as $row) {
  11044. if (!is_array($row)) {
  11045. continue;
  11046. }
  11047. $norm = [];
  11048. foreach ($row as $k => $v) {
  11049. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  11050. }
  11051. $row = $norm;
  11052. $st = $row['status'] ?? '';
  11053. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  11054. continue;
  11055. }
  11056. $payload = $this->buildCustomerContactPayloadFromRow($row);
  11057. if ($payload === null) {
  11058. continue;
  11059. }
  11060. $detail = '';
  11061. foreach ($detailColCandidates as $dk) {
  11062. if (!isset($row[$dk])) {
  11063. continue;
  11064. }
  11065. $dv = trim((string)$row[$dk]);
  11066. if ($dv !== '') {
  11067. $detail = $dv;
  11068. break;
  11069. }
  11070. }
  11071. $payload['detail'] = $detail;
  11072. $list[] = $this->maskSupplierContactFields($payload);
  11073. }
  11074. $this->success('', '', $list);
  11075. }
  11076. /**
  11077. * 采购确认-下发明细弹窗:
  11078. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  11079. */
  11080. public function outward_detail()
  11081. {
  11082. $ids = $this->request->param('ids', $this->request->param('id', ''));
  11083. if (is_array($ids)) {
  11084. $ids = isset($ids[0]) ? $ids[0] : '';
  11085. }
  11086. $ids = trim((string)$ids);
  11087. if ($ids === '') {
  11088. $this->error(__('Invalid parameters'));
  11089. }
  11090. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  11091. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  11092. $wffTab = 'all';
  11093. }
  11094. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  11095. $purchaseOrderId = 0;
  11096. $po = null;
  11097. try {
  11098. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  11099. if (is_array($po)) {
  11100. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11101. }
  11102. } catch (\Throwable $e) {
  11103. $purchaseOrderId = 0;
  11104. $po = null;
  11105. }
  11106. if (!$isPurchaseConfirm && is_array($po)) {
  11107. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11108. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  11109. $isPurchaseConfirm = true;
  11110. }
  11111. }
  11112. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  11113. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11114. $confirmProcessCount = 1;
  11115. $confirmPickGroups = [];
  11116. $processDisplayRows = [];
  11117. $allDetailsBySid = [];
  11118. $requiredSidList = [];
  11119. $sidList = [$ids];
  11120. if ($isPurchaseConfirm) {
  11121. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  11122. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  11123. if ($mergeRows !== []) {
  11124. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  11125. }
  11126. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  11127. if ($confirmBundle['pos'] !== []) {
  11128. $sidList = [];
  11129. foreach ($confirmBundle['pos'] as $poRow) {
  11130. if (!is_array($poRow)) {
  11131. continue;
  11132. }
  11133. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11134. if (!$this->isValidScydgyRowId($sid)) {
  11135. continue;
  11136. }
  11137. $sidList[] = (string)$sid;
  11138. $requiredSidList[] = $sid;
  11139. }
  11140. }
  11141. if ($sidList === []) {
  11142. $sidList = [$ids];
  11143. $requiredSidList = [(int)$ids];
  11144. }
  11145. $confirmProcessCount = max(1, count($requiredSidList));
  11146. if (is_array($po) && $purchaseOrderId <= 0) {
  11147. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11148. }
  11149. }
  11150. $rows = [];
  11151. try {
  11152. if (count($sidList) === 1) {
  11153. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  11154. } else {
  11155. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  11156. }
  11157. } catch (\Throwable $e) {
  11158. $rows = [];
  11159. }
  11160. if ($isPurchaseConfirm) {
  11161. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  11162. }
  11163. foreach ($rows as &$r) {
  11164. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  11165. $r['id'] = $r['ID'];
  11166. }
  11167. if (isset($r['createtime'])) {
  11168. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  11169. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  11170. } else {
  11171. $r['createtime_text'] = (string)$r['createtime'];
  11172. }
  11173. } else {
  11174. $r['createtime_text'] = '';
  11175. }
  11176. if (is_array($r)) {
  11177. $r = $this->maskSupplierContactFields($r);
  11178. }
  11179. }
  11180. unset($r);
  11181. $pickedCompanyName = '';
  11182. $manualPicked = 0;
  11183. $manualPickReason = '';
  11184. $quoteVisible = 0;
  11185. $bidOpenVerified = 0;
  11186. if ($isPurchaseConfirm) {
  11187. // 确认包为空时,用当前主单兜底,避免指定说明读不到
  11188. if (($confirmBundle['ccydh'] ?? '') === '' && is_array($po)) {
  11189. $confirmBundle['ccydh'] = trim((string)($po['CCYDH'] ?? ''));
  11190. }
  11191. if (($confirmBundle['pos'] ?? []) === [] && is_array($po)) {
  11192. $confirmBundle['pos'] = [$po];
  11193. }
  11194. $manualPickInfo = $this->resolveProcuremenManualPickInfo($confirmBundle);
  11195. $manualPicked = $this->isProcuremenManualPickedForBundle($confirmBundle) ? 1 : 0;
  11196. $manualPickReason = (string)($manualPickInfo['reason'] ?? '');
  11197. if ($manualPickInfo['company'] !== '') {
  11198. $pickedCompanyName = $manualPickInfo['company'];
  11199. }
  11200. if ($pickedCompanyName === '') {
  11201. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  11202. if (!is_array($poRow)) {
  11203. continue;
  11204. }
  11205. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  11206. if ($pn !== '') {
  11207. $pickedCompanyName = $pn;
  11208. break;
  11209. }
  11210. }
  11211. }
  11212. // 再兜底:直接读当前主单字段
  11213. if (is_array($po) && (int)($po['manual_pick'] ?? 0) === 1) {
  11214. $manualPicked = 1;
  11215. if ($manualPickReason === '') {
  11216. $manualPickReason = trim((string)($po['manual_pick_reason'] ?? ''));
  11217. }
  11218. if ($pickedCompanyName === '') {
  11219. $pickedCompanyName = trim((string)($po['pick_company_name'] ?? ''));
  11220. }
  11221. }
  11222. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle) ? 1 : 0;
  11223. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  11224. }
  11225. $this->view->assign('rows', $rows ?: []);
  11226. $this->view->assign('rowCount', count($rows ?: []));
  11227. $this->view->assign('scydgyId', $ids);
  11228. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  11229. $this->view->assign('headTitle', $headTitle);
  11230. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  11231. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  11232. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  11233. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  11234. $this->view->assign('processDisplayRows', $processDisplayRows);
  11235. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  11236. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  11237. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  11238. $this->view->assign('manualPicked', $manualPicked);
  11239. $this->view->assign('manualPickReason', $manualPickReason);
  11240. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  11241. $this->view->assign('quoteVisible', $quoteVisible);
  11242. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
  11243. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  11244. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
  11245. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
  11246. $sysRqDisplay = '—';
  11247. if ($isPurchaseConfirm) {
  11248. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  11249. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  11250. );
  11251. }
  11252. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  11253. $this->view->assign('sysRq', $isPurchaseConfirm
  11254. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  11255. : '');
  11256. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  11257. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  11258. : '');
  11259. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  11260. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  11261. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  11262. if ($isPurchaseConfirm) {
  11263. return $this->view->fetch();
  11264. }
  11265. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  11266. $this->view->engine->layout(false);
  11267. try {
  11268. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  11269. $this->view->assign('dialogBody', $bodyHtml);
  11270. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  11271. } finally {
  11272. if ($restoreLayout) {
  11273. $this->view->engine->layout($restoreLayout);
  11274. }
  11275. }
  11276. }
  11277. /**
  11278. * 月度导出记录表(不存在时自动创建)
  11279. */
  11280. protected function ensurePurchaseMonthExportLogTable(): void
  11281. {
  11282. try {
  11283. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  11284. } catch (\Throwable $e) {
  11285. Db::execute(
  11286. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  11287. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  11288. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  11289. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  11290. `admin_name` varchar(64) NOT NULL DEFAULT '',
  11291. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  11292. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  11293. `createtime` int(10) unsigned DEFAULT NULL,
  11294. PRIMARY KEY (`id`),
  11295. KEY `idx_ym` (`ym`),
  11296. KEY `idx_ct` (`createtime`)
  11297. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  11298. );
  11299. }
  11300. }
  11301. /**
  11302. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  11303. *
  11304. * @param array<int, mixed> $dbRows
  11305. * @return array<int, array<string, mixed>>
  11306. */
  11307. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  11308. {
  11309. $keyword = trim((string)$this->request->get('search', ''));
  11310. if ($keyword === '') {
  11311. $keyword = trim((string)$this->request->request('search', ''));
  11312. }
  11313. $filter = $this->request->get('filter', '');
  11314. $op = $this->request->get('op', '');
  11315. if (is_string($filter) && $filter !== '') {
  11316. $filterArr = (array)json_decode($filter, true);
  11317. } else {
  11318. $filterArr = is_array($filter) ? $filter : [];
  11319. }
  11320. if (is_string($op) && $op !== '') {
  11321. $opArr = (array)json_decode($op, true);
  11322. } else {
  11323. $opArr = is_array($op) ? $op : [];
  11324. }
  11325. if ($keyword === '' && $filterArr === []) {
  11326. return array_values(array_filter($dbRows, 'is_array'));
  11327. }
  11328. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  11329. $out = [];
  11330. foreach ($dbRows as $row) {
  11331. if (!is_array($row)) {
  11332. continue;
  11333. }
  11334. if ($keyword !== '') {
  11335. $hit = false;
  11336. foreach ($searchFields as $f) {
  11337. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  11338. $hit = true;
  11339. break;
  11340. }
  11341. }
  11342. if (!$hit) {
  11343. continue;
  11344. }
  11345. }
  11346. $passFilter = true;
  11347. foreach ($filterArr as $field => $val) {
  11348. $field = (string)$field;
  11349. $val = trim((string)$val);
  11350. if ($field === '' || $val === '') {
  11351. continue;
  11352. }
  11353. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  11354. continue;
  11355. }
  11356. $cell = (string)($row[$field] ?? '');
  11357. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  11358. if ($mode === '=' || $mode === 'EQUAL') {
  11359. if (strcasecmp($cell, $val) !== 0) {
  11360. $passFilter = false;
  11361. break;
  11362. }
  11363. } elseif (mb_stripos($cell, $val) === false) {
  11364. $passFilter = false;
  11365. break;
  11366. }
  11367. }
  11368. if (!$passFilter) {
  11369. continue;
  11370. }
  11371. $out[] = $row;
  11372. }
  11373. return $out;
  11374. }
  11375. /**
  11376. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  11377. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  11378. */
  11379. public function export_month_outward()
  11380. {
  11381. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  11382. $this->error(__('You have no permission'));
  11383. }
  11384. $bundle = $this->prepareMonthOutwardExportBundle();
  11385. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  11386. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  11387. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  11388. $spreadsheet = new Spreadsheet();
  11389. $sheet = $spreadsheet->getActiveSheet();
  11390. $sheet->setTitle('外协加工明细');
  11391. $mon = (int)substr($ym, 5, 2);
  11392. $sheet->mergeCells('A1:H1');
  11393. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  11394. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  11395. $sheet->getStyle('A1')->getAlignment()
  11396. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11397. ->setVertical(Alignment::VERTICAL_CENTER);
  11398. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  11399. $col = 'A';
  11400. foreach ($headers as $h) {
  11401. $sheet->setCellValue($col . '2', $h);
  11402. $col++;
  11403. }
  11404. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  11405. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11406. $rowNum = 3;
  11407. $sumSubtotalCounts = 0;
  11408. $grandAmount = 0.0;
  11409. $globalSeq = 0;
  11410. if ($groups === []) {
  11411. $sheet->mergeCells('A3:H3');
  11412. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  11413. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11414. $rowNum = 4;
  11415. } else {
  11416. foreach ($groups as $items) {
  11417. if ($items === []) {
  11418. continue;
  11419. }
  11420. $groupLineCount = count($items);
  11421. $subAmount = 0.0;
  11422. foreach ($items as $line) {
  11423. $globalSeq++;
  11424. $dr = $line['detail'];
  11425. $amt = $this->procuremenExportAmount($dr);
  11426. $subAmount += $amt;
  11427. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  11428. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  11429. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  11430. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  11431. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  11432. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  11433. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  11434. $sheet->setCellValue('H' . $rowNum, $amt);
  11435. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  11436. $rowNum++;
  11437. }
  11438. $sumSubtotalCounts += $groupLineCount;
  11439. $grandAmount += $subAmount;
  11440. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11441. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  11442. $sheet->getStyle('G' . $rowNum)->getAlignment()
  11443. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  11444. ->setVertical(Alignment::VERTICAL_CENTER);
  11445. $rowNum++;
  11446. }
  11447. }
  11448. $sheet->setCellValue('A' . $rowNum, '总计');
  11449. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  11450. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11451. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  11452. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  11453. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  11454. $lastRow = $rowNum;
  11455. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  11456. 'borders' => [
  11457. 'allBorders' => [
  11458. 'borderStyle' => Border::BORDER_THIN,
  11459. 'color' => ['rgb' => '000000'],
  11460. ],
  11461. ],
  11462. ]);
  11463. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  11464. if ($lastRow >= 3) {
  11465. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11466. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11467. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11468. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11469. }
  11470. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  11471. $sheet->getColumnDimension('A')->setWidth(7);
  11472. $sheet->getColumnDimension('B')->setWidth(16);
  11473. $sheet->getColumnDimension('C')->setWidth(52);
  11474. $sheet->getColumnDimension('D')->setWidth(32);
  11475. $sheet->getColumnDimension('E')->setWidth(12);
  11476. $sheet->getColumnDimension('F')->setWidth(44);
  11477. $sheet->getColumnDimension('G')->setWidth(26);
  11478. $sheet->getColumnDimension('H')->setWidth(13);
  11479. $sheet->getRowDimension(1)->setRowHeight(28);
  11480. $ymCompact = str_replace('-', '', $ym);
  11481. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  11482. $filename = $fileBase . '.xlsx';
  11483. try {
  11484. $this->ensurePurchaseMonthExportLogTable();
  11485. list($adminId, $adminName) = $this->GetUseName();
  11486. Db::table('purchase_month_export_log')->insert([
  11487. 'ym' => $ym,
  11488. 'admin_id' => (int)$adminId,
  11489. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  11490. 'row_count' => count($exportLines),
  11491. 'total_amount' => round($grandAmount, 2),
  11492. 'createtime' => time(),
  11493. ]);
  11494. } catch (\Throwable $e) {
  11495. Log::write('month export log: ' . $e->getMessage(), 'error');
  11496. }
  11497. if (ob_get_length()) {
  11498. ob_end_clean();
  11499. }
  11500. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  11501. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  11502. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  11503. header('Cache-Control: max-age=0');
  11504. $writer = new Xlsx($spreadsheet);
  11505. $writer->save('php://output');
  11506. $spreadsheet->disconnectWorksheets();
  11507. unset($spreadsheet);
  11508. exit;
  11509. }
  11510. /**
  11511. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  11512. */
  11513. public function export_month_quote()
  11514. {
  11515. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  11516. $this->error(__('You have no permission'));
  11517. }
  11518. $bundle = $this->prepareMonthOutwardExportBundle();
  11519. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  11520. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  11521. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  11522. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  11523. $spreadsheet = new Spreadsheet();
  11524. $sheet = $spreadsheet->getActiveSheet();
  11525. $sheet->setTitle('供应商报价明细');
  11526. $mon = (int)substr($ym, 5, 2);
  11527. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  11528. $sheet->getColumnDimension('A')->setWidth(7);
  11529. $sheet->getColumnDimension('B')->setWidth(16);
  11530. $sheet->getColumnDimension('C')->setWidth(52);
  11531. $sheet->getColumnDimension('D')->setWidth(26);
  11532. $sheet->getColumnDimension('E')->setWidth(32);
  11533. $sheet->getColumnDimension('F')->setWidth(12);
  11534. $sheet->getColumnDimension('G')->setWidth(14);
  11535. $sheet->getColumnDimension('H')->setWidth(12);
  11536. if ($quoteLastRow < 1) {
  11537. $quoteLastRow = 3;
  11538. }
  11539. $ymCompact = str_replace('-', '', $ym);
  11540. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  11541. if (ob_get_length()) {
  11542. ob_end_clean();
  11543. }
  11544. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  11545. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  11546. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  11547. header('Cache-Control: max-age=0');
  11548. $writer = new Xlsx($spreadsheet);
  11549. $writer->save('php://output');
  11550. $spreadsheet->disconnectWorksheets();
  11551. unset($spreadsheet);
  11552. exit;
  11553. }
  11554. /**
  11555. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  11556. *
  11557. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  11558. */
  11559. protected function prepareMonthOutwardExportBundle(): array
  11560. {
  11561. $this->request->filter(['strip_tags', 'trim']);
  11562. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  11563. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  11564. $ym = date('Y-m');
  11565. }
  11566. $dbRows = [];
  11567. try {
  11568. $query = Db::table('purchase_order');
  11569. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  11570. $dbRows = $query->select();
  11571. } catch (\Throwable $e) {
  11572. $dbRows = [];
  11573. }
  11574. if (!is_array($dbRows)) {
  11575. $dbRows = [];
  11576. }
  11577. $completeTsMap = [];
  11578. $sidList = [];
  11579. foreach ($dbRows as $dbRow) {
  11580. if (!is_array($dbRow)) {
  11581. continue;
  11582. }
  11583. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  11584. if ($sid > 0) {
  11585. $sidList[$sid] = true;
  11586. }
  11587. }
  11588. if ($sidList !== []) {
  11589. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  11590. }
  11591. $searchKw = trim((string)$this->request->get('search', ''));
  11592. if ($searchKw === '') {
  11593. $searchKw = trim((string)$this->request->request('search', ''));
  11594. }
  11595. $filterRaw = $this->request->get('filter', '');
  11596. $filterArrTmp = [];
  11597. if (is_string($filterRaw) && $filterRaw !== '') {
  11598. $filterArrTmp = (array)json_decode($filterRaw, true);
  11599. } elseif (is_array($filterRaw)) {
  11600. $filterArrTmp = $filterRaw;
  11601. }
  11602. $hasSearch = ($searchKw !== '');
  11603. if (!$hasSearch) {
  11604. foreach ($filterArrTmp as $fv) {
  11605. if (trim((string)$fv) !== '') {
  11606. $hasSearch = true;
  11607. break;
  11608. }
  11609. }
  11610. }
  11611. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap, $hasSearch) {
  11612. if (!is_array($dbRow)) {
  11613. return false;
  11614. }
  11615. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  11616. if ($done['ts'] <= 0) {
  11617. return false;
  11618. }
  11619. if ($hasSearch) {
  11620. return true;
  11621. }
  11622. return date('Y-m', $done['ts']) === $ym;
  11623. }));
  11624. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  11625. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  11626. $mainBySid = [];
  11627. foreach ($pool as $rw) {
  11628. if (!is_array($rw)) {
  11629. continue;
  11630. }
  11631. $rid = (int)($rw['ID'] ?? 0);
  11632. if ($rid > 0) {
  11633. $mainBySid[$rid] = $rw;
  11634. }
  11635. }
  11636. if ($mainBySid === []) {
  11637. $detailRows = [];
  11638. } else {
  11639. try {
  11640. $detailRows = Db::table('purchase_order_detail')
  11641. ->where('scydgy_id', 'in', array_keys($mainBySid))
  11642. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  11643. ->order('status', 'desc')
  11644. ->order('CCYDH', 'asc')
  11645. ->order('company_name', 'asc')
  11646. ->order('id', 'asc')
  11647. ->select();
  11648. } catch (\Throwable $e) {
  11649. try {
  11650. $detailRows = Db::table('purchase_order_detail')
  11651. ->where('scydgy_id', 'in', array_keys($mainBySid))
  11652. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  11653. ->order('status', 'desc')
  11654. ->order('CCYDH', 'asc')
  11655. ->order('company_name', 'asc')
  11656. ->order('ID', 'asc')
  11657. ->select();
  11658. } catch (\Throwable $e2) {
  11659. $detailRows = [];
  11660. }
  11661. }
  11662. }
  11663. if (!is_array($detailRows)) {
  11664. $detailRows = [];
  11665. }
  11666. $exportLines = [];
  11667. $detailSidSeen = [];
  11668. foreach ($detailRows as $dr) {
  11669. if (!is_array($dr)) {
  11670. continue;
  11671. }
  11672. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11673. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  11674. continue;
  11675. }
  11676. if (isset($detailSidSeen[$sid])) {
  11677. continue;
  11678. }
  11679. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  11680. continue;
  11681. }
  11682. $detailSidSeen[$sid] = true;
  11683. $m = $mainBySid[$sid];
  11684. $exportLines[] = [
  11685. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11686. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11687. 'company_name' => (string)($dr['company_name'] ?? ''),
  11688. 'CDF' => (string)($m['CDF'] ?? ''),
  11689. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11690. 'gx' => $this->procuremenExportGxText($m),
  11691. 'detail' => $dr,
  11692. ];
  11693. }
  11694. foreach ($detailRows as $dr) {
  11695. if (!is_array($dr)) {
  11696. continue;
  11697. }
  11698. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11699. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  11700. continue;
  11701. }
  11702. $detailSidSeen[$sid] = true;
  11703. $m = $mainBySid[$sid];
  11704. $exportLines[] = [
  11705. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11706. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11707. 'company_name' => (string)($dr['company_name'] ?? ''),
  11708. 'CDF' => (string)($m['CDF'] ?? ''),
  11709. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11710. 'gx' => $this->procuremenExportGxText($m),
  11711. 'detail' => $dr,
  11712. ];
  11713. }
  11714. foreach ($mainBySid as $sid => $m) {
  11715. if (isset($detailSidSeen[$sid])) {
  11716. continue;
  11717. }
  11718. $company = trim((string)($m['pick_company_name'] ?? ''));
  11719. $exportLines[] = [
  11720. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  11721. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  11722. 'company_name' => $company,
  11723. 'CDF' => (string)($m['CDF'] ?? ''),
  11724. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11725. 'gx' => $this->procuremenExportGxText($m),
  11726. 'detail' => [],
  11727. ];
  11728. }
  11729. $groups = [];
  11730. foreach ($exportLines as $line) {
  11731. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  11732. if (!isset($groups[$k])) {
  11733. $groups[$k] = [];
  11734. }
  11735. $groups[$k][] = $line;
  11736. }
  11737. ksort($groups, SORT_STRING);
  11738. return [
  11739. 'ym' => $ym,
  11740. 'mainBySid' => $mainBySid,
  11741. 'detailRows' => $detailRows,
  11742. 'exportLines' => $exportLines,
  11743. 'groups' => $groups,
  11744. ];
  11745. }
  11746. /**
  11747. * 导出用:工序列文案
  11748. */
  11749. protected function procuremenExportGxText(array $r)
  11750. {
  11751. $a = trim((string)($r['CDXMC'] ?? ''));
  11752. $b = trim((string)($r['CGYMC'] ?? ''));
  11753. if ($a !== '' && $b !== '') {
  11754. return $a . ':' . $b;
  11755. }
  11756. return $a !== '' ? $a : $b;
  11757. }
  11758. /**
  11759. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  11760. */
  11761. protected function procuremenExportAmount(array $r)
  11762. {
  11763. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  11764. if (!array_key_exists($k, $r)) {
  11765. continue;
  11766. }
  11767. $v = $r[$k];
  11768. if ($v === null || $v === '') {
  11769. continue;
  11770. }
  11771. if (is_numeric($v)) {
  11772. return (float)$v;
  11773. }
  11774. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  11775. if ($v !== '' && is_numeric($v)) {
  11776. return (float)$v;
  11777. }
  11778. }
  11779. return 0.0;
  11780. }
  11781. /**
  11782. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  11783. *
  11784. * @param array<int, array<string, mixed>> $detailRows
  11785. * @param array<int, array<string, mixed>> $mainBySid
  11786. * @return array<int, array<string, mixed>>
  11787. */
  11788. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  11789. {
  11790. $lines = [];
  11791. foreach ($detailRows as $dr) {
  11792. if (!is_array($dr)) {
  11793. continue;
  11794. }
  11795. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11796. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  11797. continue;
  11798. }
  11799. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  11800. continue;
  11801. }
  11802. $cn = trim((string)($dr['company_name'] ?? ''));
  11803. if ($cn === '') {
  11804. continue;
  11805. }
  11806. $m = $mainBySid[$sid];
  11807. $am = trim((string)($dr['amount'] ?? ''));
  11808. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  11809. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  11810. $amountText = $amountFilled
  11811. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  11812. : '未填写';
  11813. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  11814. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  11815. if ($deliveryShow === '' && $deliveryRaw !== '') {
  11816. $deliveryShow = $deliveryRaw;
  11817. }
  11818. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  11819. ? $deliveryShow
  11820. : '未填写';
  11821. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  11822. $lines[] = [
  11823. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11824. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11825. 'gx' => $this->procuremenExportGxText($m),
  11826. 'company_name' => $cn,
  11827. 'amount_text' => $amountText,
  11828. 'amount_num' => $amountFilled ? $amountNum : null,
  11829. 'delivery_text' => $deliveryText,
  11830. 'picked_text' => $picked ? '中标' : '未中标',
  11831. 'picked' => $picked,
  11832. ];
  11833. }
  11834. $winnerSupplierByOrder = [];
  11835. foreach ($lines as $line) {
  11836. $dh = trim((string)($line['CCYDH'] ?? ''));
  11837. $cn = trim((string)($line['company_name'] ?? ''));
  11838. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  11839. $winnerSupplierByOrder[$dh][$cn] = true;
  11840. }
  11841. }
  11842. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  11843. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  11844. if ($c !== 0) {
  11845. return $c;
  11846. }
  11847. $dh = trim((string)($a['CCYDH'] ?? ''));
  11848. $aCn = trim((string)($a['company_name'] ?? ''));
  11849. $bCn = trim((string)($b['company_name'] ?? ''));
  11850. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  11851. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  11852. if ($aSupplierWin !== $bSupplierWin) {
  11853. return $aSupplierWin ? -1 : 1;
  11854. }
  11855. $c = strcmp($aCn, $bCn);
  11856. if ($c !== 0) {
  11857. return $c;
  11858. }
  11859. if (!empty($a['picked']) !== !empty($b['picked'])) {
  11860. return !empty($a['picked']) ? -1 : 1;
  11861. }
  11862. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  11863. if ($c !== 0) {
  11864. return $c;
  11865. }
  11866. return 0;
  11867. });
  11868. return $lines;
  11869. }
  11870. /**
  11871. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  11872. *
  11873. * @param array<int, array<string, mixed>> $quoteLines
  11874. */
  11875. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  11876. {
  11877. $mon = (int)substr($ym, 5, 2);
  11878. $titleRow = $startRow;
  11879. $headerRow = $startRow + 1;
  11880. $dataStartRow = $startRow + 2;
  11881. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  11882. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  11883. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  11884. $sheet->getStyle('A' . $titleRow)->getAlignment()
  11885. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11886. ->setVertical(Alignment::VERTICAL_CENTER);
  11887. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  11888. $col = 'A';
  11889. foreach ($headers as $h) {
  11890. $sheet->setCellValue($col . $headerRow, $h);
  11891. $col++;
  11892. }
  11893. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  11894. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11895. $rowNum = $dataStartRow;
  11896. if ($quoteLines === []) {
  11897. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  11898. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  11899. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11900. $rowNum = $dataStartRow + 1;
  11901. } else {
  11902. $i = 0;
  11903. foreach ($quoteLines as $line) {
  11904. $i++;
  11905. $sheet->setCellValue('A' . $rowNum, $i);
  11906. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  11907. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  11908. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  11909. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  11910. if ($line['amount_num'] !== null) {
  11911. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  11912. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  11913. } else {
  11914. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  11915. }
  11916. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  11917. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  11918. if (!empty($line['picked'])) {
  11919. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  11920. }
  11921. $rowNum++;
  11922. }
  11923. }
  11924. $lastRow = $rowNum - 1;
  11925. if ($lastRow >= $headerRow) {
  11926. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  11927. 'borders' => [
  11928. 'allBorders' => [
  11929. 'borderStyle' => Border::BORDER_THIN,
  11930. 'color' => ['rgb' => '000000'],
  11931. ],
  11932. ],
  11933. ]);
  11934. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  11935. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11936. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11937. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11938. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  11939. if ($lastRow >= $dataStartRow) {
  11940. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  11941. }
  11942. }
  11943. return $lastRow;
  11944. }
  11945. /**
  11946. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  11947. */
  11948. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  11949. {
  11950. if ($lastRow < $dataStartRow || $headerRow < 1) {
  11951. return;
  11952. }
  11953. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  11954. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11955. ->setVertical(Alignment::VERTICAL_CENTER);
  11956. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  11957. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11958. ->setVertical(Alignment::VERTICAL_CENTER);
  11959. if ($lastCol > 'B') {
  11960. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  11961. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  11962. ->setVertical(Alignment::VERTICAL_CENTER);
  11963. }
  11964. }
  11965. /**
  11966. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  11967. */
  11968. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  11969. {
  11970. $s = trim($ccydh);
  11971. if ($s === '') {
  11972. return 'ORDER';
  11973. }
  11974. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  11975. $s = trim($s, '._-');
  11976. if ($s === '') {
  11977. return 'ORDER';
  11978. }
  11979. if (function_exists('mb_substr')) {
  11980. return mb_substr($s, 0, 80, 'UTF-8');
  11981. }
  11982. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  11983. }
  11984. /**
  11985. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  11986. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  11987. *
  11988. * @return array{objectKey: string, webPath: string}
  11989. */
  11990. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  11991. {
  11992. $sid = (int)$scydgyId;
  11993. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  11994. $y = date('Y');
  11995. $m = date('m');
  11996. $d = date('d');
  11997. $basename = $safeOrder . '_' . $sid . '.pdf';
  11998. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  11999. return [
  12000. 'objectKey' => $objectKey,
  12001. 'webPath' => '/' . $objectKey,
  12002. ];
  12003. }
  12004. /**
  12005. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  12006. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  12007. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  12008. *
  12009. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  12010. */
  12011. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  12012. {
  12013. if (!$this->isValidScydgyRowId($scydgyId)) {
  12014. return '';
  12015. }
  12016. $ids = trim((string)$scydgyId);
  12017. $prep = $this->prepareProcuremenDetailsView($ids);
  12018. if (!$prep['ok']) {
  12019. return '';
  12020. }
  12021. $ccydh = $prep['ccydh'];
  12022. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  12023. $objectKey = $paths['objectKey'];
  12024. $webPath = $paths['webPath'];
  12025. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  12026. $this->view->assign([
  12027. 'pdf_export' => 1,
  12028. 'pdfMetaLine' => $meta,
  12029. ]);
  12030. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  12031. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  12032. $this->view->engine->layout(false);
  12033. try {
  12034. $html = $this->view->fetch('procuremen/details_pdf_shell');
  12035. } catch (\Throwable $e) {
  12036. if ($restoreLayout) {
  12037. $this->view->engine->layout($restoreLayout);
  12038. }
  12039. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  12040. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12041. return '';
  12042. }
  12043. if ($restoreLayout) {
  12044. $this->view->engine->layout($restoreLayout);
  12045. }
  12046. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12047. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  12048. if (!is_dir($tempDir)) {
  12049. @mkdir($tempDir, 0755, true);
  12050. }
  12051. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  12052. try {
  12053. $mpdf = new \Mpdf\Mpdf([
  12054. 'mode' => 'utf-8',
  12055. 'format' => 'A4',
  12056. 'margin_left' => 12,
  12057. 'margin_right' => 12,
  12058. 'margin_top' => 14,
  12059. 'margin_bottom' => 14,
  12060. 'tempDir' => $tempDir,
  12061. 'autoScriptToLang' => true,
  12062. 'autoLangToFont' => true,
  12063. ]);
  12064. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  12065. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  12066. $mpdf->SetBasePath('http://127.0.0.1/');
  12067. $mpdf->WriteHTML($html);
  12068. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  12069. } catch (\Throwable $e) {
  12070. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  12071. if (is_file($tempPdf)) {
  12072. @unlink($tempPdf);
  12073. }
  12074. return '';
  12075. }
  12076. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  12077. if ($ossUrl !== '') {
  12078. @unlink($tempPdf);
  12079. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12080. return $ossUrl;
  12081. }
  12082. $pi = pathinfo($objectKey);
  12083. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  12084. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  12085. if ($baseFile === '') {
  12086. @unlink($tempPdf);
  12087. return '';
  12088. }
  12089. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  12090. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  12091. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  12092. @unlink($tempPdf);
  12093. return '';
  12094. }
  12095. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  12096. if (!@copy($tempPdf, $fullPath)) {
  12097. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  12098. @unlink($tempPdf);
  12099. return '';
  12100. }
  12101. @unlink($tempPdf);
  12102. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12103. return $webPath;
  12104. }
  12105. /**
  12106. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  12107. */
  12108. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  12109. {
  12110. if ($scydgyId <= 0 || $webPath === '') {
  12111. return;
  12112. }
  12113. try {
  12114. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  12115. } catch (\Throwable $e) {
  12116. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  12117. }
  12118. }
  12119. /**
  12120. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  12121. *
  12122. * @param array<string, string> $vars
  12123. * @return array<string, string>
  12124. */
  12125. protected function normalizeSmsTemplateVars(array $vars): array
  12126. {
  12127. $out = [];
  12128. foreach ($vars as $k => $v) {
  12129. $out[(string)$k] = trim((string)$v);
  12130. }
  12131. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  12132. $out['contact_name'] = $out['company_name'];
  12133. }
  12134. return $out;
  12135. }
  12136. /**
  12137. * 按手机号或公司名称查 customer 表联系人姓名
  12138. */
  12139. protected function resolveCustomerContactName(string $phone, string $companyName): string
  12140. {
  12141. $phone = trim($phone);
  12142. $companyName = trim($companyName);
  12143. try {
  12144. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  12145. $row = Db::table('customer')
  12146. ->where(function ($q) use ($phone) {
  12147. $q->where('phone', $phone)->whereOr('account', $phone);
  12148. })
  12149. ->order('id', 'asc')
  12150. ->find();
  12151. if (is_array($row)) {
  12152. $nm = trim((string)($row['username'] ?? ''));
  12153. if ($nm !== '') {
  12154. return $nm;
  12155. }
  12156. }
  12157. }
  12158. if ($companyName !== '') {
  12159. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  12160. if (is_array($row)) {
  12161. return trim((string)($row['username'] ?? ''));
  12162. }
  12163. }
  12164. } catch (\Throwable $e) {
  12165. }
  12166. return '';
  12167. }
  12168. /**
  12169. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  12170. */
  12171. protected function plainTextToHtmlEmailBody(string $text): string
  12172. {
  12173. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  12174. $parts = explode("\n", $text);
  12175. $out = [];
  12176. foreach ($parts as $line) {
  12177. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  12178. $out[] = $line;
  12179. } else {
  12180. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  12181. }
  12182. }
  12183. return implode("<br>\n", $out);
  12184. }
  12185. /**
  12186. * 短信场景:去掉链接类变量,避免误填 URL
  12187. *
  12188. * @param array<string, string> $vars
  12189. * @return array<string, string>
  12190. */
  12191. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  12192. {
  12193. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  12194. return $vars;
  12195. }
  12196. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  12197. $vars[$k] = '';
  12198. }
  12199. return $vars;
  12200. }
  12201. /**
  12202. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  12203. *
  12204. * @param array<string, string> $vars
  12205. */
  12206. protected function renderNotifyTemplate(string $scene, array $vars): string
  12207. {
  12208. $vars = $this->normalizeSmsTemplateVars($vars);
  12209. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  12210. $row = $this->loadNotifyTemplateRow($scene);
  12211. if ($row === null) {
  12212. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12213. }
  12214. $tpl = trim((string)($row['content'] ?? ''));
  12215. if ($tpl === '') {
  12216. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12217. }
  12218. foreach ($vars as $k => $v) {
  12219. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  12220. }
  12221. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  12222. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  12223. return $tpl;
  12224. }
  12225. protected function resolveProcuremenEmailSubject(string $scene): string
  12226. {
  12227. // 询价通知业务员:模版名称即邮件主题(可含 {ccydh})
  12228. if ($scene === 'rfq_salesman_email') {
  12229. $row = $this->loadNotifyTemplateRow($scene);
  12230. $title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
  12231. if ($title !== '') {
  12232. return $title;
  12233. }
  12234. return '协助采购询价通知';
  12235. }
  12236. $map = [
  12237. 'review_email' => '您有新的协助加工订单',
  12238. ];
  12239. $subject = trim((string)($map[$scene] ?? ''));
  12240. if ($subject === '') {
  12241. $this->error('未配置邮件主题:' . $scene);
  12242. }
  12243. return $subject;
  12244. }
  12245. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  12246. {
  12247. $map = [
  12248. 'review_email' => '协助下发-邮箱',
  12249. 'review_sms' => '协助下发-短信',
  12250. 'confirm_ok' => '采购确认-通过',
  12251. 'confirm_fail' => '采购确认-未通过',
  12252. 'bid_open' => '开标双重验证',
  12253. 'rfq_salesman_email' => '询价通知业务员-邮箱',
  12254. ];
  12255. $label = $map[$scene] ?? $scene;
  12256. if ($titleRequired) {
  12257. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  12258. }
  12259. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  12260. }
  12261. /**
  12262. * 是否开启协助通知演练(不发真实短信/邮件)
  12263. */
  12264. protected function isProcuremenNotifyDryRun(): bool
  12265. {
  12266. return (bool)Config::get('procuremen_notify_dry_run');
  12267. }
  12268. /**
  12269. * @param array<string, mixed> $payload
  12270. */
  12271. protected function recordNotifyDryRunPreview(array $payload): void
  12272. {
  12273. $this->notifyDryRunPreview[] = $payload;
  12274. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  12275. }
  12276. /**
  12277. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  12278. * @throws \Exception
  12279. */
  12280. protected function smsbao($phone, $content)
  12281. {
  12282. if ($this->isProcuremenNotifyDryRun()) {
  12283. $this->recordNotifyDryRunPreview([
  12284. 'scene' => 'sms_only',
  12285. 'phone' => $phone,
  12286. 'sms_content' => $content,
  12287. ]);
  12288. return;
  12289. }
  12290. $statusStr = [
  12291. '0' => '短信发送成功',
  12292. '-1' => '参数不全',
  12293. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  12294. '30' => '密码错误',
  12295. '40' => '账号不存在',
  12296. '41' => '余额不足',
  12297. '42' => '帐户已过期',
  12298. '43' => 'IP地址限制',
  12299. '50' => '内容含有敏感词',
  12300. ];
  12301. $smsapi = 'http://api.smsbao.com/';
  12302. $user = 'zhuwei123';
  12303. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  12304. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  12305. $result = @file_get_contents($sendurl);
  12306. if ($result === false) {
  12307. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  12308. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  12309. }
  12310. $result = trim((string)$result);
  12311. if ($result !== '0') {
  12312. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  12313. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  12314. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  12315. }
  12316. }
  12317. }