Procuremen.php 496 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189
  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. * 优先 Redis 月份小键;为空时用轻量 DISTINCT 查库补齐(避免只显示空当月、漏掉有数据的月份)。
  506. */
  507. protected function GetIndexYearMonths()
  508. {
  509. $ymList = $this->ensureProcuremenPickSidebarYmList();
  510. if ($ymList === []) {
  511. $def = date('Y-m');
  512. $ymList = [preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m')];
  513. }
  514. return $this->buildYearMonthSidebar($ymList);
  515. }
  516. /**
  517. * 初选侧栏月份:以轻量 DISTINCT 查库为准(有数据才显示),并写回 Redis 小键。
  518. *
  519. * @return string[]
  520. */
  521. protected function ensureProcuremenPickSidebarYmList(bool $forceRefresh = false): array
  522. {
  523. static $memo = null;
  524. if (!$forceRefresh && is_array($memo)) {
  525. return $memo;
  526. }
  527. $fromDb = $this->queryProcuremenPickSidebarYmListLight();
  528. if ($fromDb !== []) {
  529. $this->saveProcuremenSidebarYmList($fromDb);
  530. $memo = $fromDb;
  531. return $memo;
  532. }
  533. // 库侧暂无初选数据时,再回退 Redis / 当月,避免侧栏空白
  534. $cached = $this->loadProcuremenSidebarYmList();
  535. if ($cached !== []) {
  536. $memo = $cached;
  537. return $memo;
  538. }
  539. $memo = [date('Y-m')];
  540. return $memo;
  541. }
  542. /**
  543. * @return string[] 形如 2026-07
  544. */
  545. protected function loadProcuremenSidebarYmList(): array
  546. {
  547. try {
  548. $raw = redis()->get('procuremen_redis_yms');
  549. if ($raw === false || $raw === null || $raw === '') {
  550. return [];
  551. }
  552. $decoded = json_decode((string)$raw, true);
  553. if (!is_array($decoded)) {
  554. return [];
  555. }
  556. $out = [];
  557. foreach ($decoded as $ym) {
  558. $ym = trim((string)$ym);
  559. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  560. $out[$ym] = true;
  561. }
  562. }
  563. return array_keys($out);
  564. } catch (\Throwable $e) {
  565. return [];
  566. }
  567. }
  568. /**
  569. * @param string[] $ymList
  570. */
  571. protected function saveProcuremenSidebarYmList(array $ymList): void
  572. {
  573. $out = [];
  574. foreach ($ymList as $ym) {
  575. $ym = trim((string)$ym);
  576. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  577. $out[$ym] = true;
  578. }
  579. }
  580. if ($out === []) {
  581. return;
  582. }
  583. try {
  584. redis()->set('procuremen_redis_yms', json_encode(array_keys($out), JSON_UNESCAPED_UNICODE));
  585. } catch (\Throwable $e) {
  586. }
  587. }
  588. /**
  589. * @param array<int, array<string, mixed>> $pool
  590. * @return string[]
  591. */
  592. protected function extractYearMonthsFromPoolRows(array $pool): array
  593. {
  594. $ymSet = [];
  595. foreach ($pool as $r) {
  596. if (!is_array($r)) {
  597. continue;
  598. }
  599. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  600. continue;
  601. }
  602. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  603. if ($ym !== null) {
  604. $ymSet[$ym] = true;
  605. }
  606. }
  607. return array_keys($ymSet);
  608. }
  609. /**
  610. * 轻量查询初选侧栏月份(只取 DISTINCT 年月,不拉整包工序)
  611. *
  612. * @return string[]
  613. */
  614. protected function queryProcuremenPickSidebarYmListLight(): array
  615. {
  616. try {
  617. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  618. $endTime = date('Y-m-d 23:59:59');
  619. $sql = 'SELECT DISTINCT DATE_FORMAT('
  620. . 'IF(b.dputrecord IS NOT NULL AND TRIM(CAST(b.dputrecord AS CHAR(32))) <> \'\''
  621. . ' AND TRIM(CAST(b.dputrecord AS CHAR(32))) NOT LIKE \'0000-00-00%\','
  622. . ' b.dputrecord, a.dStamp), \'%Y-%m\') AS ym'
  623. . ' FROM scydgy a'
  624. . ' INNER JOIN mcyd b ON b.ICYDID = a.ICYDID AND b.iStatus >= 10'
  625. . ' WHERE a.bwjg = 1 AND a.iEndBz = 0 AND a.iType = 0 AND a.iStatus = 10'
  626. . ' AND a.dStamp >= ? AND a.dStamp <= ?';
  627. $rows = Db::query($sql, [$startTime, $endTime]);
  628. if (!is_array($rows)) {
  629. return [];
  630. }
  631. $out = [];
  632. foreach ($rows as $r) {
  633. $ym = trim((string)($r['ym'] ?? ''));
  634. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  635. $out[$ym] = true;
  636. }
  637. }
  638. return array_keys($out);
  639. } catch (\Throwable $e) {
  640. Log::write('初选侧栏月份轻量查询失败:' . $e->getMessage(), 'warning');
  641. return [];
  642. }
  643. }
  644. /**
  645. * @return string[] 含当月在内的近 N 个自然月
  646. */
  647. protected function buildRecentCalendarYmList(int $months = 12): array
  648. {
  649. $months = max(1, min(24, $months));
  650. $out = [];
  651. $base = strtotime(date('Y-m-01'));
  652. for ($i = 0; $i < $months; $i++) {
  653. $out[] = date('Y-m', strtotime('-' . $i . ' month', $base));
  654. }
  655. return $out;
  656. }
  657. /**
  658. * 初选按月工序池:优先月缓存;未命中则直接按月查 ERP。
  659. * 禁止为列表去解近一年整包 Redis(解包/连接异常会造成长时间转圈)。
  660. *
  661. * @return array<int, array<string, mixed>>
  662. */
  663. protected function loadPickPoolForYm(string $ym): array
  664. {
  665. $ym = trim($ym);
  666. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  667. return [];
  668. }
  669. $hit = $this->readPickMonthPoolCache($ym);
  670. if ($hit !== null) {
  671. return $hit;
  672. }
  673. return $this->queryPickPoolForYmFromDb($ym);
  674. }
  675. /**
  676. * @return array<int, array<string, mixed>>|null null=无有效缓存(含旧版空数组误缓存)
  677. */
  678. protected function readPickMonthPoolCache(string $ym): ?array
  679. {
  680. try {
  681. $raw = redis()->get('procuremen_pick_pool:' . $ym);
  682. if ($raw === false || $raw === null || $raw === '') {
  683. return null;
  684. }
  685. $decoded = json_decode((string)$raw, true);
  686. if (!is_array($decoded)) {
  687. return null;
  688. }
  689. // 新格式:{ok:1, rows:[...]},空月也算有效(已从整包确认)
  690. if (isset($decoded['ok']) && (int)$decoded['ok'] === 1 && isset($decoded['rows']) && is_array($decoded['rows'])) {
  691. return $decoded['rows'];
  692. }
  693. // 旧格式:仅非空行列表可命中;[] 多半是错误 SQL 写入,视为未命中
  694. if ($decoded === []) {
  695. try {
  696. redis()->del('procuremen_pick_pool:' . $ym);
  697. } catch (\Throwable $e) {
  698. }
  699. return null;
  700. }
  701. if (isset($decoded[0]) && is_array($decoded[0])) {
  702. return $decoded;
  703. }
  704. return null;
  705. } catch (\Throwable $e) {
  706. return null;
  707. }
  708. }
  709. /**
  710. * @param array<int, array<string, mixed>> $rows
  711. */
  712. protected function writePickMonthPoolCache(string $ym, array $rows): void
  713. {
  714. try {
  715. redis()->setex(
  716. 'procuremen_pick_pool:' . $ym,
  717. 600,
  718. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  719. );
  720. } catch (\Throwable $e) {
  721. }
  722. }
  723. /**
  724. * @param array<int, array<string, mixed>> $pool
  725. * @return array<int, array<string, mixed>>
  726. */
  727. protected function filterPoolRowsByYm(array $pool, string $ym): array
  728. {
  729. $out = [];
  730. foreach ($pool as $r) {
  731. if (!is_array($r)) {
  732. continue;
  733. }
  734. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  735. continue;
  736. }
  737. if ($this->procuremenRowYearMonth($r, 'dputrecord') === $ym) {
  738. $out[] = $r;
  739. }
  740. }
  741. return $out;
  742. }
  743. /**
  744. * 按 dStamp 取当月附近数据,再用列表规则(dputrecord 优先)精确到 ym
  745. *
  746. * @return array<int, array<string, mixed>>
  747. */
  748. protected function queryPickPoolForYmFromDb(string $ym): array
  749. {
  750. $monthStart = $ym . '-01 00:00:00';
  751. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  752. // 略放大窗口,避免 dStamp 与 dputrecord 跨月导致漏数;最终仍按 ym 精确过滤
  753. $queryStart = date('Y-m-d 00:00:00', strtotime($monthStart . ' -7 days'));
  754. $queryEnd = date('Y-m-d 23:59:59', strtotime($monthEnd . ' +7 days'));
  755. try {
  756. $list = Db::table('scydgy')
  757. ->alias('a')
  758. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  759. ->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')
  760. ->where([
  761. 'a.bwjg' => 1,
  762. 'a.iEndBz' => 0,
  763. 'a.iType' => 0,
  764. 'a.iStatus' => 10,
  765. ])
  766. ->where('a.dStamp', '>=', $queryStart)
  767. ->where('a.dStamp', '<=', $queryEnd)
  768. ->order('a.dStamp', 'desc')
  769. ->select();
  770. } catch (\Throwable $e) {
  771. Log::write('初选按月取数失败 ym=' . $ym . ':' . $e->getMessage(), 'error');
  772. return [];
  773. }
  774. if (!is_array($list)) {
  775. $list = [];
  776. }
  777. $out = $this->filterPoolRowsByYm($list, $ym);
  778. // 新格式缓存(含空月),避免重复打库;读侧只认 ok=1
  779. $this->writePickMonthPoolCache($ym, $out);
  780. try {
  781. $yms = $this->loadProcuremenSidebarYmList();
  782. if ($out !== [] && ($yms === [] || !in_array($ym, $yms, true))) {
  783. $yms[] = $ym;
  784. $this->saveProcuremenSidebarYmList($yms);
  785. }
  786. } catch (\Throwable $e) {
  787. }
  788. return $out;
  789. }
  790. /**
  791. * 整包写入后拆成按月小缓存,供初选列表秒开
  792. *
  793. * @param array<int, array<string, mixed>> $pool
  794. */
  795. protected function warmPickMonthPoolCachesFromPool(array $pool): void
  796. {
  797. if ($pool === []) {
  798. return;
  799. }
  800. $byYm = [];
  801. foreach ($pool as $r) {
  802. if (!is_array($r)) {
  803. continue;
  804. }
  805. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  806. continue;
  807. }
  808. $rowYm = $this->procuremenRowYearMonth($r, 'dputrecord');
  809. if ($rowYm === null) {
  810. continue;
  811. }
  812. $byYm[$rowYm][] = $r;
  813. }
  814. if ($byYm === []) {
  815. return;
  816. }
  817. try {
  818. $redis = redis();
  819. foreach ($byYm as $rowYm => $rows) {
  820. $redis->setex(
  821. 'procuremen_pick_pool:' . $rowYm,
  822. 600,
  823. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  824. );
  825. }
  826. try {
  827. $redis->del('procuremen_pick_hidden_scydgy_v1');
  828. } catch (\Throwable $e) {
  829. }
  830. } catch (\Throwable $e) {
  831. }
  832. }
  833. /**
  834. * 刷新整包后清理近月缓存,避免脏读
  835. */
  836. protected function clearPickMonthPoolCaches(int $months = 24): void
  837. {
  838. try {
  839. $redis = redis();
  840. foreach ($this->buildRecentCalendarYmList($months) as $ym) {
  841. try {
  842. $redis->del('procuremen_pick_pool:' . $ym);
  843. } catch (\Throwable $e) {
  844. }
  845. }
  846. } catch (\Throwable $e) {
  847. }
  848. $this->invalidatePickHiddenScydgyCache();
  849. }
  850. /**
  851. * 下发/完结后清隐藏集缓存,避免初选列表最多 90 秒仍显示已下发行
  852. */
  853. protected function invalidatePickHiddenScydgyCache(): void
  854. {
  855. $this->pickHiddenScydgySetCache = null;
  856. try {
  857. redis()->del('procuremen_pick_hidden_scydgy_v1');
  858. } catch (\Throwable $e) {
  859. }
  860. }
  861. /** 列表/首屏读完鉴权后尽早释放 session,避免多 iframe 串行卡死 */
  862. protected function procuremenReleaseSessionLock(): void
  863. {
  864. if (session_status() === PHP_SESSION_ACTIVE) {
  865. @session_write_close();
  866. }
  867. }
  868. /**
  869. * @param string[] $ymList 形如 2026-06
  870. * @return array<int, array{year:string, months:array}>
  871. */
  872. protected function buildYearMonthSidebar(array $ymList): array
  873. {
  874. rsort($ymList, SORT_STRING);
  875. $byYear = [];
  876. foreach ($ymList as $ym) {
  877. $y = substr($ym, 0, 4);
  878. $mo = (int)substr($ym, 5, 2);
  879. if (!isset($byYear[$y])) {
  880. $byYear[$y] = [];
  881. }
  882. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  883. }
  884. krsort($byYear, SORT_NUMERIC);
  885. foreach ($byYear as $y => $items) {
  886. usort($byYear[$y], function ($a, $b) {
  887. return strcmp($b['ym'], $a['ym']);
  888. });
  889. }
  890. $sidebar = [];
  891. foreach ($byYear as $y => $months) {
  892. $sidebar[] = ['year' => $y, 'months' => $months];
  893. }
  894. return $sidebar;
  895. }
  896. /**
  897. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  898. */
  899. protected function GetIssuedOrderYearMonths(string $stage): array
  900. {
  901. $ymSet = [];
  902. try {
  903. $query = Db::table('purchase_order');
  904. $this->applyPurchaseOrderNotDeletedWhere($query);
  905. if ($stage === 'audit') {
  906. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  907. } elseif ($stage === 'confirm') {
  908. $this->applyPurchaseOrderConfirmStageWhere($query);
  909. } else {
  910. return $this->GetIndexYearMonths();
  911. }
  912. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  913. if (is_array($rows)) {
  914. foreach ($rows as $r) {
  915. if (!is_array($r)) {
  916. continue;
  917. }
  918. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  919. if ($ym !== null) {
  920. $ymSet[$ym] = true;
  921. }
  922. }
  923. }
  924. } catch (\Throwable $e) {
  925. $ymSet = [];
  926. }
  927. $ymList = array_keys($ymSet);
  928. if ($ymList === []) {
  929. $def = $this->resolveProcuremenDefaultYm($stage);
  930. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  931. }
  932. return $this->buildYearMonthSidebar($ymList);
  933. }
  934. /**
  935. * 列表默认月份:已下发类取最近有数据的月份;初选也取最近有数据月份(避免跨月后落到空当月)
  936. */
  937. protected function resolveProcuremenDefaultYm(string $stage): string
  938. {
  939. if ($stage === 'pick') {
  940. $yms = $this->ensureProcuremenPickSidebarYmList();
  941. if ($yms !== []) {
  942. rsort($yms, SORT_STRING);
  943. return $yms[0];
  944. }
  945. return date('Y-m');
  946. }
  947. try {
  948. $query = Db::table('purchase_order');
  949. $this->applyPurchaseOrderNotDeletedWhere($query);
  950. if ($stage === 'audit') {
  951. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  952. } elseif ($stage === 'confirm') {
  953. $this->applyPurchaseOrderConfirmStageWhere($query);
  954. } else {
  955. return date('Y-m');
  956. }
  957. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  958. if ($latest === null || $latest === '') {
  959. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  960. }
  961. $t = $this->formatProcuremenDetailTime($latest);
  962. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  963. return $m[1] . '-' . $m[2];
  964. }
  965. } catch (\Throwable $e) {
  966. }
  967. return date('Y-m');
  968. }
  969. protected function applyPurchaseOrderNotDeletedWhere($query): void
  970. {
  971. $query->whereRaw(
  972. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  973. );
  974. }
  975. /**
  976. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  977. */
  978. protected function applyPurchaseOrderConfirmStageWhere($query): void
  979. {
  980. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  981. $quoted = [];
  982. foreach ($vals as $v) {
  983. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  984. }
  985. if ($quoted === []) {
  986. $query->whereRaw('1 = 0');
  987. return;
  988. }
  989. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  990. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  991. }
  992. /**
  993. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  994. *
  995. * @param array<string, mixed> $row
  996. * @return array<string, mixed>
  997. */
  998. protected function normalizePurchaseOrderListTimeRow(array $row): array
  999. {
  1000. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  1001. $pick = trim((string)($row['pick_time'] ?? ''));
  1002. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  1003. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  1004. $t = trim((string)($row[$key] ?? ''));
  1005. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1006. $row['pick_time'] = $t;
  1007. break;
  1008. }
  1009. }
  1010. }
  1011. return $row;
  1012. }
  1013. /**
  1014. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  1015. */
  1016. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  1017. {
  1018. if (!in_array($stage, ['audit', 'confirm'], true)) {
  1019. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1020. }
  1021. if ($pool === []) {
  1022. $def = $this->resolveProcuremenDefaultYm($stage);
  1023. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  1024. }
  1025. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  1026. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1027. return false;
  1028. }
  1029. $monthStart = $ym . '-01 00:00:00';
  1030. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1031. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  1032. return $probe !== [];
  1033. };
  1034. if ($tryYm($requestedYm)) {
  1035. return $requestedYm;
  1036. }
  1037. $fallback = $this->resolveProcuremenDefaultYm($stage);
  1038. if ($tryYm($fallback)) {
  1039. return $fallback;
  1040. }
  1041. $bestYm = '';
  1042. $bestTime = '';
  1043. foreach ($pool as $row) {
  1044. if (!is_array($row)) {
  1045. continue;
  1046. }
  1047. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  1048. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  1049. continue;
  1050. }
  1051. $ymRow = $m[1];
  1052. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  1053. $bestTime = $t;
  1054. $bestYm = $ymRow;
  1055. }
  1056. }
  1057. if ($bestYm !== '') {
  1058. return $bestYm;
  1059. }
  1060. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1061. }
  1062. protected function isPurchaseOrderDetailVoid(array $row): bool
  1063. {
  1064. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  1065. return true;
  1066. }
  1067. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  1068. }
  1069. /**
  1070. * 仅当前有效下发明细(排除废弃归档)
  1071. */
  1072. protected function applyActivePurchaseOrderDetailWhere($query): void
  1073. {
  1074. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1075. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  1076. }
  1077. /**
  1078. * @param array<string, mixed> $detailRow
  1079. */
  1080. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  1081. {
  1082. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  1083. return false;
  1084. }
  1085. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  1086. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  1087. }
  1088. /**
  1089. * 废弃退回初选:下发明细标记归档,不物理删除
  1090. *
  1091. * @param array<int, int|string> $scydgyIds
  1092. */
  1093. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  1094. {
  1095. $ids = [];
  1096. foreach ($scydgyIds as $sid) {
  1097. $n = (int)$sid;
  1098. if ($this->isValidScydgyRowId($n) || $n < 0) {
  1099. $ids[$n] = true;
  1100. }
  1101. }
  1102. if ($ids === []) {
  1103. return;
  1104. }
  1105. $void = ProcuremenStatus::POD_VOID;
  1106. Db::table('purchase_order_detail')
  1107. ->where('scydgy_id', 'in', array_keys($ids))
  1108. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1109. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  1110. ->update([
  1111. 'status' => $void,
  1112. 'status_name' => $void,
  1113. ]);
  1114. }
  1115. /**
  1116. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  1117. */
  1118. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  1119. {
  1120. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  1121. $norm = function (string $col) use ($p): string {
  1122. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  1123. };
  1124. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  1125. $parts = [];
  1126. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  1127. if ($key === 'createtime') {
  1128. $parts[] = $createtime;
  1129. } else {
  1130. $parts[] = $norm($key);
  1131. }
  1132. }
  1133. return 'COALESCE(' . implode(', ', $parts) . ')';
  1134. }
  1135. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  1136. {
  1137. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  1138. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  1139. }
  1140. /**
  1141. * @return array<int, array<string, mixed>>
  1142. */
  1143. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  1144. {
  1145. $this->ensurePurchaseOrderCzlyqColumn();
  1146. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1147. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  1148. try {
  1149. $query = Db::table('purchase_order')->field($fields);
  1150. $this->applyPurchaseOrderNotDeletedWhere($query);
  1151. if ($stage === 'audit') {
  1152. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1153. } elseif ($stage === 'confirm') {
  1154. $this->applyPurchaseOrderConfirmStageWhere($query);
  1155. } else {
  1156. return [];
  1157. }
  1158. $query->order('pick_time', 'desc')->order('id', 'desc');
  1159. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  1160. $monthStart = $ym . '-01 00:00:00';
  1161. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1162. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  1163. }
  1164. $rows = $query->select();
  1165. } catch (\Throwable $e) {
  1166. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  1167. $rows = [];
  1168. }
  1169. return is_array($rows) ? $rows : [];
  1170. }
  1171. /**
  1172. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  1173. */
  1174. protected function resolveProcuremenListStage(): string
  1175. {
  1176. $tab = trim((string)$this->request->request('wff_tab', ''));
  1177. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  1178. return $tab;
  1179. }
  1180. $action = strtolower((string)$this->request->action());
  1181. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  1182. return $action;
  1183. }
  1184. return 'pick';
  1185. }
  1186. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  1187. {
  1188. $this->procuremenReleaseSessionLock();
  1189. $rootTrue = rtrim((string)$this->request->root(true), '/');
  1190. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  1191. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  1192. $indexPhpRoot = $rootTrue . '/index.php';
  1193. }
  1194. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  1195. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  1196. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  1197. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  1198. $this->view->assign('defaultYm', $defaultYm);
  1199. $this->view->assign('sidebarYearMonths', $sidebar);
  1200. $this->view->assign('procuremenStage', $stage);
  1201. $this->view->assign('procuremenPageTitle', $pageTitle);
  1202. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  1203. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  1204. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  1205. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  1206. $this->assignconfig('procuremenFilterOptions', $this->buildProcuremenFilterOptions($stage));
  1207. }
  1208. /**
  1209. * 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
  1210. *
  1211. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1212. */
  1213. protected function buildProcuremenFilterOptions(string $stage): array
  1214. {
  1215. $buckets = [
  1216. 'czlyq' => [],
  1217. 'CCLBMMC' => [],
  1218. 'cywyxm' => [],
  1219. 'CGYMC' => [],
  1220. ];
  1221. $maxPerField = 300;
  1222. try {
  1223. if ($stage === 'pick') {
  1224. // 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
  1225. return $buckets;
  1226. }
  1227. if (in_array($stage, ['audit', 'confirm'], true)) {
  1228. $this->ensurePurchaseOrderCzlyqColumn();
  1229. foreach (array_keys($buckets) as $field) {
  1230. try {
  1231. $query = Db::table('purchase_order')->field($field);
  1232. $this->applyPurchaseOrderNotDeletedWhere($query);
  1233. if ($stage === 'audit') {
  1234. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1235. } else {
  1236. $this->applyPurchaseOrderConfirmStageWhere($query);
  1237. }
  1238. $query->where($field, '<>', '')->whereNotNull($field);
  1239. $vals = $query->distinct(true)->limit($maxPerField)->column($field);
  1240. if (!is_array($vals)) {
  1241. continue;
  1242. }
  1243. foreach ($vals as $v) {
  1244. $v = trim((string)$v);
  1245. if ($v !== '') {
  1246. $buckets[$field][$v] = $v;
  1247. }
  1248. }
  1249. } catch (\Throwable $e) {
  1250. // 单字段失败不影响其它
  1251. }
  1252. }
  1253. }
  1254. } catch (\Throwable $e) {
  1255. Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
  1256. }
  1257. foreach ($buckets as &$set) {
  1258. if ($set !== []) {
  1259. ksort($set, SORT_STRING);
  1260. }
  1261. }
  1262. unset($set);
  1263. return $buckets;
  1264. }
  1265. /**
  1266. * filter JSON 是否含有效条件
  1267. *
  1268. * @param array<string, mixed> $filterArr
  1269. */
  1270. protected function procuremenFilterArrHasValue(array $filterArr): bool
  1271. {
  1272. foreach ($filterArr as $v) {
  1273. if (is_array($v)) {
  1274. if (array_filter($v, function ($x) {
  1275. return $x !== '' && $x !== null;
  1276. })) {
  1277. return true;
  1278. }
  1279. } elseif ($v !== '' && $v !== null) {
  1280. return true;
  1281. }
  1282. }
  1283. return false;
  1284. }
  1285. /**
  1286. * 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
  1287. *
  1288. * @param array<string, mixed> $filterArr
  1289. * @param array<string, mixed> $opArr
  1290. */
  1291. protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
  1292. {
  1293. if ($search !== '') {
  1294. return false;
  1295. }
  1296. foreach ($filterArr as $fk => $fv) {
  1297. if (is_array($fv)) {
  1298. continue;
  1299. }
  1300. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  1301. continue;
  1302. }
  1303. if ($fv === null) {
  1304. continue;
  1305. }
  1306. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  1307. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  1308. if ($sym === '' || $sym === '=') {
  1309. continue;
  1310. }
  1311. return false;
  1312. }
  1313. return true;
  1314. }
  1315. /**
  1316. * 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
  1317. *
  1318. * @param array<int, mixed> $rows
  1319. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1320. */
  1321. protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
  1322. {
  1323. $buckets = [
  1324. 'czlyq' => [],
  1325. 'CCLBMMC' => [],
  1326. 'cywyxm' => [],
  1327. 'CGYMC' => [],
  1328. ];
  1329. foreach ($rows as $r) {
  1330. if (!is_array($r)) {
  1331. continue;
  1332. }
  1333. foreach ($buckets as $field => &$set) {
  1334. if (count($set) >= $maxPerField) {
  1335. continue;
  1336. }
  1337. $v = trim((string)($r[$field] ?? ''));
  1338. if ($v !== '') {
  1339. $set[$v] = $v;
  1340. }
  1341. }
  1342. unset($set);
  1343. $full = true;
  1344. foreach ($buckets as $set) {
  1345. if (count($set) < $maxPerField) {
  1346. $full = false;
  1347. break;
  1348. }
  1349. }
  1350. if ($full) {
  1351. break;
  1352. }
  1353. }
  1354. foreach ($buckets as &$set) {
  1355. if ($set !== []) {
  1356. // 保证 json 编码为对象(避免 list 下标 0,1,2… 被前端当选项)
  1357. $normalized = [];
  1358. foreach ($set as $k => $v) {
  1359. $s = trim((string)(is_scalar($v) ? $v : $k));
  1360. if ($s === '') {
  1361. continue;
  1362. }
  1363. $normalized[$s] = $s;
  1364. }
  1365. ksort($normalized, SORT_STRING);
  1366. $set = $normalized;
  1367. }
  1368. }
  1369. unset($set);
  1370. return $buckets;
  1371. }
  1372. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  1373. public function pick()
  1374. {
  1375. $this->request->filter(['strip_tags', 'trim']);
  1376. if (!$this->request->isAjax()) {
  1377. $this->assignProcuremenListPage('pick', '协助下发');
  1378. return $this->view->fetch('procuremen/index');
  1379. }
  1380. return $this->index();
  1381. }
  1382. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  1383. public function audit()
  1384. {
  1385. $this->request->filter(['strip_tags', 'trim']);
  1386. if (!$this->request->isAjax()) {
  1387. $this->assignProcuremenListPage('audit', '确认供应商');
  1388. return $this->view->fetch('procuremen/index');
  1389. }
  1390. return $this->index();
  1391. }
  1392. /** 采购确认(定标) */
  1393. public function confirm()
  1394. {
  1395. $this->request->filter(['strip_tags', 'trim']);
  1396. if (!$this->request->isAjax()) {
  1397. $this->assignProcuremenListPage('confirm', '采购确认');
  1398. return $this->view->fetch('procuremen/index');
  1399. }
  1400. return $this->index();
  1401. }
  1402. /**
  1403. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  1404. */
  1405. public function index()
  1406. {
  1407. $this->request->filter(['strip_tags', 'trim']);
  1408. if (!$this->request->isAjax()) {
  1409. $this->assignProcuremenListPage('pick', '协助下发');
  1410. return $this->view->fetch('procuremen/index');
  1411. }
  1412. if ($this->request->request('keyField')) {
  1413. return $this->selectpage();
  1414. }
  1415. $this->procuremenReleaseSessionLock();
  1416. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  1417. $limit = max(10, min(500, (int)$limit));
  1418. $ym = $this->request->request('ym', '');
  1419. $ym = is_string($ym) ? trim($ym) : '';
  1420. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  1421. $wffTab = $this->resolveProcuremenListStage();
  1422. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1423. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  1424. ? $this->resolveProcuremenDefaultYm($wffTab)
  1425. : date('Y-m');
  1426. }
  1427. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1428. $ym = date('Y-m');
  1429. }
  1430. $monthStart = $ym . '-01 00:00:00';
  1431. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1432. $search = trim((string)$this->request->get('search', ''));
  1433. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  1434. $opArr = (array)json_decode($this->request->get('op', ''), true);
  1435. if (!is_array($filterArr)) {
  1436. $filterArr = [];
  1437. }
  1438. if (!is_array($opArr)) {
  1439. $opArr = [];
  1440. }
  1441. // 开标状态为计算字段,不能进池内等值筛选;单独抽出后在合并后再滤
  1442. $bidOpenStatusFilter = '';
  1443. foreach (['bid_open_status_text', 'a.bid_open_status_text'] as $bidFk) {
  1444. if (!array_key_exists($bidFk, $filterArr)) {
  1445. continue;
  1446. }
  1447. $bidOpenStatusFilter = trim((string)$filterArr[$bidFk]);
  1448. unset($filterArr[$bidFk], $opArr[$bidFk]);
  1449. }
  1450. // 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
  1451. $applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
  1452. $hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
  1453. try {
  1454. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  1455. if ($wffTab === 'audit') {
  1456. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  1457. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  1458. );
  1459. } elseif ($wffTab === 'confirm') {
  1460. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  1461. if ($dbRows === []) {
  1462. try {
  1463. $dbRows = Db::table('purchase_order')
  1464. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1465. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  1466. ->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%\')')
  1467. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  1468. ->order('pick_time', 'desc')->order('id', 'desc')
  1469. ->select();
  1470. } catch (\Throwable $e) {
  1471. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  1472. $dbRows = [];
  1473. }
  1474. }
  1475. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  1476. if ($pool === []) {
  1477. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1478. }
  1479. } else {
  1480. // 初选:按月直查 ERP(不解整包 Redis,避免长时间转圈)
  1481. if ($applyMonthRange) {
  1482. $pool = $this->loadPickPoolForYm($ym);
  1483. } else {
  1484. $pool = $this->procuremenEnsureRedisPool();
  1485. }
  1486. if (!is_array($pool)) {
  1487. $pool = [];
  1488. }
  1489. // 只针对本页候选 ID 查隐藏集,避免全表扫 purchase_order_detail
  1490. $hideSet = $this->loadPickHiddenScydgySetForIds($this->extractScydgyIdsFromPool($pool));
  1491. if ($pool !== [] && $hideSet !== []) {
  1492. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1493. if (!is_array($r)) {
  1494. return false;
  1495. }
  1496. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1497. return $id <= 0 || !isset($hideSet[$id]);
  1498. }));
  1499. }
  1500. // 手工新增(YW / scydgy_id<0)只走「新增询价/查询询价」,不进初选表格
  1501. if ($pool === []) {
  1502. return json([
  1503. 'total' => 0,
  1504. 'rows' => [],
  1505. 'activeYm' => $ym,
  1506. 'filterOptions' => (
  1507. (int)$offset === 0
  1508. && !$hasActiveSearch
  1509. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1510. )
  1511. ? $this->extractProcuremenFilterOptionsFromRows([])
  1512. : new \stdClass(),
  1513. ]);
  1514. }
  1515. }
  1516. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  1517. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  1518. $monthStart = $ym . '-01 00:00:00';
  1519. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1520. }
  1521. $filtered = $this->filterProcuremenIndexPool(
  1522. $pool,
  1523. $monthStart,
  1524. $monthEnd,
  1525. $applyMonthRange,
  1526. $search,
  1527. $filterArr,
  1528. $opArr,
  1529. $listTimePrimary
  1530. );
  1531. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1532. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1533. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1534. }
  1535. if ($wffTab === 'audit' && $bidOpenStatusFilter !== '') {
  1536. $filtered = $this->filterProcuremenPoolByBidOpenStatus($filtered, $bidOpenStatusFilter);
  1537. }
  1538. $sortField = 'ID';
  1539. if (is_string($sort) && $sort !== '') {
  1540. $parts = explode(',', $sort);
  1541. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1542. if ($sortField === '') {
  1543. $sortField = 'ID';
  1544. }
  1545. }
  1546. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1547. $nFiltered = count($filtered);
  1548. if ($nFiltered > 1) {
  1549. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1550. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1551. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1552. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1553. if ($ta === $tb) {
  1554. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1555. }
  1556. if ($ta === '') {
  1557. return 1;
  1558. }
  1559. if ($tb === '') {
  1560. return -1;
  1561. }
  1562. return strcmp($ta, $tb) * $ord;
  1563. });
  1564. } elseif ($sortField === 'ID') {
  1565. $sortKeys = [];
  1566. foreach ($filtered as $i => $row) {
  1567. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1568. }
  1569. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1570. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1571. } elseif ($sortField === 'CCYDH') {
  1572. usort($filtered, function ($a, $b) use ($ord) {
  1573. $sa = trim((string)($a['CCYDH'] ?? ''));
  1574. $sb = trim((string)($b['CCYDH'] ?? ''));
  1575. if ($sa === $sb) {
  1576. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1577. }
  1578. if ($sa === '') {
  1579. return 1;
  1580. }
  1581. if ($sb === '') {
  1582. return -1;
  1583. }
  1584. return strcmp($sa, $sb) * $ord;
  1585. });
  1586. } else {
  1587. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1588. $va = $a[$sortField] ?? null;
  1589. $vb = $b[$sortField] ?? null;
  1590. $sa = (string)$va;
  1591. $sb = (string)$vb;
  1592. if ($sa === $sb) {
  1593. return 0;
  1594. }
  1595. return strcmp($sa, $sb) * $ord;
  1596. });
  1597. }
  1598. }
  1599. $offset = max(0, (int)$offset);
  1600. $limit = max(1, (int)$limit);
  1601. $rows = array_slice($filtered, $offset, $limit);
  1602. foreach ($rows as &$rw) {
  1603. if (!is_array($rw)) {
  1604. continue;
  1605. }
  1606. $rid = (int)($rw['ID'] ?? 0);
  1607. $rw['_iss_out'] = ($wffTab !== 'pick');
  1608. }
  1609. unset($rw);
  1610. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1611. $idList = [];
  1612. foreach ($rows as $rw) {
  1613. if (!is_array($rw)) {
  1614. continue;
  1615. }
  1616. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1617. foreach ($rw['_order_merge_rows'] as $mr) {
  1618. $mid = (int)($mr['ID'] ?? 0);
  1619. if ($this->isValidScydgyRowId($mid)) {
  1620. $idList[$mid] = true;
  1621. }
  1622. }
  1623. }
  1624. $id = (int)($rw['ID'] ?? 0);
  1625. if ($this->isValidScydgyRowId($id)) {
  1626. $idList[$id] = true;
  1627. }
  1628. }
  1629. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1630. foreach ($rows as &$rw) {
  1631. if (!is_array($rw)) {
  1632. continue;
  1633. }
  1634. $mergeIds = [];
  1635. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1636. foreach ($rw['_order_merge_rows'] as $mr) {
  1637. $mid = (int)($mr['ID'] ?? 0);
  1638. if ($this->isValidScydgyRowId($mid)) {
  1639. $mergeIds[$mid] = true;
  1640. }
  1641. }
  1642. }
  1643. $rid = (int)($rw['ID'] ?? 0);
  1644. if ($this->isValidScydgyRowId($rid)) {
  1645. $mergeIds[$rid] = true;
  1646. }
  1647. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1648. $rw['po_detail_count'] = $s['cnt'];
  1649. $rw['po_amount_fill_cnt'] = $s['amt'];
  1650. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1651. }
  1652. unset($rw);
  1653. }
  1654. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1655. $idList = [];
  1656. foreach ($rows as $rw) {
  1657. if (!is_array($rw)) {
  1658. continue;
  1659. }
  1660. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1661. foreach ($rw['_order_merge_rows'] as $mr) {
  1662. $mid = (int)($mr['ID'] ?? 0);
  1663. if ($this->isValidScydgyRowId($mid)) {
  1664. $idList[$mid] = true;
  1665. }
  1666. }
  1667. }
  1668. $id = (int)($rw['ID'] ?? 0);
  1669. if ($this->isValidScydgyRowId($id)) {
  1670. $idList[$id] = true;
  1671. }
  1672. }
  1673. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1674. $bidOpenSet = [];
  1675. $manualPickSet = [];
  1676. if ($wffTab === 'audit') {
  1677. $ccydhList = [];
  1678. foreach ($rows as $rw0) {
  1679. if (!is_array($rw0)) {
  1680. continue;
  1681. }
  1682. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1683. if ($c0 !== '') {
  1684. $ccydhList[] = $c0;
  1685. }
  1686. }
  1687. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1688. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  1689. }
  1690. foreach ($rows as &$rw) {
  1691. if (!is_array($rw)) {
  1692. continue;
  1693. }
  1694. $mergeIds = [];
  1695. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1696. foreach ($rw['_order_merge_rows'] as $mr) {
  1697. $mid = (int)($mr['ID'] ?? 0);
  1698. if ($this->isValidScydgyRowId($mid)) {
  1699. $mergeIds[$mid] = true;
  1700. }
  1701. }
  1702. }
  1703. $rid = (int)($rw['ID'] ?? 0);
  1704. if ($this->isValidScydgyRowId($rid)) {
  1705. $mergeIds[$rid] = true;
  1706. }
  1707. $buckets = [];
  1708. foreach (array_keys($mergeIds) as $mid) {
  1709. if (isset($quoteBucket[$mid])) {
  1710. $buckets[] = $quoteBucket[$mid];
  1711. }
  1712. }
  1713. $supplierText = $buckets !== []
  1714. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1715. : '';
  1716. if ($wffTab === 'confirm') {
  1717. $picked = trim((string)($rw['pick_company_name'] ?? $rw['picked_supplier_name'] ?? ''));
  1718. if ($picked === '') {
  1719. // 兜底:从合并工序行取
  1720. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1721. foreach ($rw['_order_merge_rows'] as $mr) {
  1722. if (!is_array($mr)) {
  1723. continue;
  1724. }
  1725. $pn = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  1726. if ($pn !== '') {
  1727. $picked = $pn;
  1728. break;
  1729. }
  1730. }
  1731. }
  1732. }
  1733. $rw['picked_supplier_name'] = $picked;
  1734. } else {
  1735. $rw['notify_supplier_text'] = $supplierText;
  1736. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1737. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1738. $manualPicked = ($ccydh !== '' && isset($manualPickSet[$ccydh]));
  1739. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1740. $rw['manual_picked'] = $manualPicked ? 1 : 0;
  1741. if ($verified) {
  1742. $rw['bid_open_status_text'] = '已开标';
  1743. } elseif ($manualPicked) {
  1744. $rw['bid_open_status_text'] = '已指定供应商';
  1745. } else {
  1746. $rw['bid_open_status_text'] = '待开标';
  1747. }
  1748. }
  1749. }
  1750. unset($rw);
  1751. }
  1752. if (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
  1753. $this->enrichProcuremenListMilestoneTimes($rows);
  1754. $this->syncCollapsedOrderQtyPriceForList($rows);
  1755. }
  1756. if ($wffTab === 'all' && count($rows) > 0) {
  1757. $this->mergePurchaseOrder($rows);
  1758. }
  1759. if ($wffTab === 'pick' && count($rows) > 0) {
  1760. $this->mergePurchaseOrder($rows);
  1761. }
  1762. foreach ($rows as &$rwClean) {
  1763. if (is_array($rwClean)) {
  1764. unset($rwClean['_order_merge_rows']);
  1765. if (array_key_exists('NGZL', $rwClean)) {
  1766. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1767. }
  1768. }
  1769. }
  1770. unset($rwClean);
  1771. return json([
  1772. 'total' => count($filtered),
  1773. 'rows' => $rows,
  1774. 'activeYm' => $ym,
  1775. // 初选:把有数据的月份带回,替换「空月份日历」侧栏
  1776. 'sidebarYms' => ($wffTab === 'pick' && (int)$offset === 0)
  1777. ? $this->ensureProcuremenPickSidebarYmList()
  1778. : [],
  1779. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1780. 'filterOptions' => (
  1781. (int)$offset === 0
  1782. && !$hasActiveSearch
  1783. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1784. )
  1785. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1786. : new \stdClass(),
  1787. ]);
  1788. } catch (\Throwable $e) {
  1789. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1790. return json([
  1791. 'total' => 0,
  1792. 'rows' => [],
  1793. ]);
  1794. }
  1795. }
  1796. /**
  1797. * @param array<int, array<string, mixed>> $pool
  1798. * @return int[]
  1799. */
  1800. protected function extractScydgyIdsFromPool(array $pool): array
  1801. {
  1802. $ids = [];
  1803. foreach ($pool as $r) {
  1804. if (!is_array($r)) {
  1805. continue;
  1806. }
  1807. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1808. if ($id > 0) {
  1809. $ids[$id] = $id;
  1810. }
  1811. }
  1812. return array_values($ids);
  1813. }
  1814. /**
  1815. * 仅查询指定工序 ID 是否已下发/进入后续流程(初选列表加速)
  1816. *
  1817. * @param int[] $scydgyIds
  1818. * @return array<int, true>
  1819. */
  1820. protected function loadPickHiddenScydgySetForIds(array $scydgyIds): array
  1821. {
  1822. $hideSet = [];
  1823. $scydgyIds = array_values(array_filter(array_map('intval', $scydgyIds), function ($id) {
  1824. return $id > 0;
  1825. }));
  1826. if ($scydgyIds === []) {
  1827. return $hideSet;
  1828. }
  1829. // 分批,避免 whereIn 过长
  1830. foreach (array_chunk($scydgyIds, 500) as $chunk) {
  1831. try {
  1832. $poIds = Db::table('purchase_order')
  1833. ->where('scydgy_id', 'in', $chunk)
  1834. ->where(function ($q) {
  1835. $q->whereIn('wflow_status', array_merge(
  1836. ProcuremenStatus::wflowPendingConfirmValues(),
  1837. ProcuremenStatus::wflowPendingApprovalValues()
  1838. ))
  1839. ->whereOr(function ($q1) {
  1840. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1841. })
  1842. ->whereOr(function ($q2) {
  1843. $q2->whereNotNull('pick_time')
  1844. ->where('pick_time', '<>', '')
  1845. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1846. })
  1847. ->whereOr(function ($q3) {
  1848. $q3->whereNotNull('mod_rq')
  1849. ->where('mod_rq', '<>', '')
  1850. ->where('mod_rq', 'not like', '0000-00-00%');
  1851. });
  1852. })
  1853. ->column('scydgy_id');
  1854. if (is_array($poIds)) {
  1855. foreach ($poIds as $pid) {
  1856. $k = (int)$pid;
  1857. if ($k !== 0) {
  1858. $hideSet[$k] = true;
  1859. }
  1860. }
  1861. }
  1862. } catch (\Throwable $e) {
  1863. }
  1864. try {
  1865. $detIdsQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $chunk);
  1866. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1867. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1868. if (is_array($detIds)) {
  1869. foreach ($detIds as $pid) {
  1870. $k = (int)$pid;
  1871. if ($this->isValidScydgyRowId($k)) {
  1872. $hideSet[$k] = true;
  1873. }
  1874. }
  1875. }
  1876. } catch (\Throwable $e) {
  1877. }
  1878. }
  1879. return $hideSet;
  1880. }
  1881. /**
  1882. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1883. *
  1884. * @return array<int, true>
  1885. */
  1886. protected function loadPickHiddenScydgySet(): array
  1887. {
  1888. if ($this->pickHiddenScydgySetCache !== null) {
  1889. return $this->pickHiddenScydgySetCache;
  1890. }
  1891. $cacheKey = 'procuremen_pick_hidden_scydgy_v1';
  1892. try {
  1893. $raw = redis()->get($cacheKey);
  1894. if ($raw !== false && $raw !== null && $raw !== '') {
  1895. $ids = json_decode((string)$raw, true);
  1896. if (is_array($ids)) {
  1897. $hideSet = [];
  1898. foreach ($ids as $pid) {
  1899. $k = (int)$pid;
  1900. if ($k !== 0) {
  1901. $hideSet[$k] = true;
  1902. }
  1903. }
  1904. $this->pickHiddenScydgySetCache = $hideSet;
  1905. return $hideSet;
  1906. }
  1907. }
  1908. } catch (\Throwable $e) {
  1909. }
  1910. $hideSet = [];
  1911. try {
  1912. $poIds = Db::table('purchase_order')
  1913. ->where(function ($q) {
  1914. $q->whereIn('wflow_status', array_merge(
  1915. ProcuremenStatus::wflowPendingConfirmValues(),
  1916. ProcuremenStatus::wflowPendingApprovalValues()
  1917. ))
  1918. ->whereOr(function ($q1) {
  1919. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1920. })
  1921. ->whereOr(function ($q2) {
  1922. $q2->whereNotNull('pick_time')
  1923. ->where('pick_time', '<>', '')
  1924. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1925. })
  1926. ->whereOr(function ($q3) {
  1927. $q3->whereNotNull('mod_rq')
  1928. ->where('mod_rq', '<>', '')
  1929. ->where('mod_rq', 'not like', '0000-00-00%');
  1930. });
  1931. })
  1932. ->column('scydgy_id');
  1933. if (is_array($poIds)) {
  1934. foreach ($poIds as $pid) {
  1935. $k = (int)$pid;
  1936. if ($k !== 0) {
  1937. $hideSet[$k] = true;
  1938. }
  1939. }
  1940. }
  1941. } catch (\Throwable $e) {
  1942. }
  1943. try {
  1944. $detIdsQuery = Db::table('purchase_order_detail');
  1945. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1946. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1947. if (is_array($detIds)) {
  1948. foreach ($detIds as $pid) {
  1949. $k = (int)$pid;
  1950. if ($this->isValidScydgyRowId($k)) {
  1951. $hideSet[$k] = true;
  1952. }
  1953. }
  1954. }
  1955. } catch (\Throwable $e) {
  1956. }
  1957. $this->pickHiddenScydgySetCache = $hideSet;
  1958. try {
  1959. redis()->setex($cacheKey, 90, json_encode(array_map('intval', array_keys($hideSet))));
  1960. } catch (\Throwable $e) {
  1961. }
  1962. return $hideSet;
  1963. }
  1964. /**
  1965. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1966. *
  1967. * @return array<int, array<string, mixed>>
  1968. */
  1969. protected function loadPickManualOrderRows(): array
  1970. {
  1971. try {
  1972. $dbRows = Db::table('purchase_order')
  1973. ->where('scydgy_id', '<', 0)
  1974. ->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%\')')
  1975. ->order('scydgy_id', 'asc')
  1976. ->select();
  1977. } catch (\Throwable $e) {
  1978. try {
  1979. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1980. } catch (\Throwable $e2) {
  1981. return [];
  1982. }
  1983. }
  1984. if (!is_array($dbRows) || $dbRows === []) {
  1985. return [];
  1986. }
  1987. $detailSidSet = [];
  1988. try {
  1989. $negIds = [];
  1990. foreach ($dbRows as $dbRow) {
  1991. if (!is_array($dbRow)) {
  1992. continue;
  1993. }
  1994. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  1995. if ($sid < 0) {
  1996. $negIds[$sid] = true;
  1997. }
  1998. }
  1999. if ($negIds !== []) {
  2000. $detQuery = Db::table('purchase_order_detail')
  2001. ->where('scydgy_id', 'in', array_keys($negIds));
  2002. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  2003. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  2004. if (is_array($detRows)) {
  2005. foreach ($detRows as $did) {
  2006. $detailSidSet[(int)$did] = true;
  2007. }
  2008. }
  2009. }
  2010. } catch (\Throwable $e) {
  2011. }
  2012. $pool = [];
  2013. foreach ($dbRows as $dbRow) {
  2014. if (!is_array($dbRow)) {
  2015. continue;
  2016. }
  2017. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2018. if ($sid >= 0) {
  2019. continue;
  2020. }
  2021. // 已进入确认/审批的不进初选;仅废弃明细残留的仍算可下发
  2022. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  2023. continue;
  2024. }
  2025. // 仅排除已完结;空 status / 「进行中」/ 0 均保留(新建手工单)
  2026. if (ProcuremenStatus::isPoCompleted($dbRow['status'] ?? '')) {
  2027. continue;
  2028. }
  2029. if (isset($detailSidSet[$sid])) {
  2030. continue;
  2031. }
  2032. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  2033. $r['_is_manual'] = 1;
  2034. $pool[] = $r;
  2035. }
  2036. return $pool;
  2037. }
  2038. /**
  2039. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  2040. */
  2041. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  2042. {
  2043. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  2044. foreach ($keys as $k) {
  2045. $t = trim((string)($row[$k] ?? ''));
  2046. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2047. return $t;
  2048. }
  2049. }
  2050. return '';
  2051. }
  2052. /**
  2053. * 分配手工新增工序行 ID(负数递减)
  2054. */
  2055. protected function allocateManualScydgyId(): int
  2056. {
  2057. try {
  2058. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  2059. $min = (int)$min;
  2060. return $min < 0 ? $min - 1 : -1;
  2061. } catch (\Throwable $e) {
  2062. return -1;
  2063. }
  2064. }
  2065. /**
  2066. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  2067. */
  2068. protected function allocateManualOrderCcydh(): string
  2069. {
  2070. $prefix = 'YW' . date('Ymd');
  2071. $maxSeq = 0;
  2072. try {
  2073. $rows = Db::table('purchase_order')
  2074. ->where('CCYDH', 'like', $prefix . '%')
  2075. ->column('CCYDH');
  2076. if (is_array($rows)) {
  2077. foreach ($rows as $ccydh) {
  2078. $ccydh = trim((string)$ccydh);
  2079. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3})$/', $ccydh, $m)) {
  2080. $maxSeq = max($maxSeq, (int)$m[1]);
  2081. }
  2082. }
  2083. }
  2084. } catch (\Throwable $e) {
  2085. }
  2086. return $prefix . str_pad((string)($maxSeq + 1), 3, '0', STR_PAD_LEFT);
  2087. }
  2088. /**
  2089. * purchase_order.mod_rq 是否有有效软删除时间
  2090. */
  2091. protected function isPurchaseOrderSoftDeleted($modRq): bool
  2092. {
  2093. $t = trim((string)$modRq);
  2094. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  2095. }
  2096. /**
  2097. * 列表行 → purchase_order 写入字段
  2098. *
  2099. * @return array<string, mixed>
  2100. */
  2101. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  2102. {
  2103. return [
  2104. 'scydgy_id' => $scydgyId,
  2105. 'CCYDH' => $row['CCYDH'] ?? null,
  2106. 'CYJMC' => $row['CYJMC'] ?? null,
  2107. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2108. 'CDXMC' => $row['CDXMC'] ?? null,
  2109. 'CGYBH' => $row['CGYBH'] ?? null,
  2110. 'CGYMC' => $row['CGYMC'] ?? null,
  2111. 'CDW' => $row['CDW'] ?? null,
  2112. 'czlyq' => $row['czlyq'] ?? null,
  2113. 'NGZL' => $row['NGZL'] ?? null,
  2114. 'CDF' => $row['CDF'] ?? null,
  2115. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2116. 'MBZ' => $row['MBZ'] ?? null,
  2117. 'bwjg' => $row['bwjg'] ?? null,
  2118. 'iStatus' => $row['iStatus'] ?? null,
  2119. 'dStamp' => $row['dStamp'] ?? null,
  2120. 'dputrecord' => $row['dputrecord'] ?? null,
  2121. 'cywyxm' => $row['cywyxm'] ?? null,
  2122. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2123. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2124. ];
  2125. }
  2126. /**
  2127. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  2128. *
  2129. * @return array{po:?array<string,mixed>, hidden:bool}
  2130. */
  2131. protected function resolvePickRowPoContext(int $sid): array
  2132. {
  2133. $po = null;
  2134. try {
  2135. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2136. if (is_array($found)) {
  2137. $po = $found;
  2138. }
  2139. } catch (\Throwable $e) {
  2140. }
  2141. $hideSet = $this->loadPickHiddenScydgySet();
  2142. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  2143. }
  2144. /**
  2145. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  2146. */
  2147. protected function assertPickRowCanDelete(int $sid, array $row): void
  2148. {
  2149. $ctx = $this->resolvePickRowPoContext($sid);
  2150. $po = $ctx['po'];
  2151. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2152. return;
  2153. }
  2154. if (is_array($po)) {
  2155. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2156. throw new \InvalidArgumentException('该工序已完结,无法删除');
  2157. }
  2158. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2159. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  2160. }
  2161. }
  2162. if ($ctx['hidden']) {
  2163. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2164. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  2165. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  2166. }
  2167. }
  2168. /**
  2169. * 初选直接完结前校验
  2170. */
  2171. protected function assertPickRowCanComplete(int $sid, array $row): void
  2172. {
  2173. $ctx = $this->resolvePickRowPoContext($sid);
  2174. $po = $ctx['po'];
  2175. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2176. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  2177. }
  2178. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2179. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  2180. }
  2181. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  2182. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  2183. }
  2184. }
  2185. /**
  2186. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  2187. */
  2188. protected function softDeleteProcuremenPickRow(array $row): void
  2189. {
  2190. $sid = $this->extractScydgyRowId($row);
  2191. if (!$this->isValidScydgyRowId($sid)) {
  2192. throw new \InvalidArgumentException('无效的行主键');
  2193. }
  2194. $this->assertPickRowCanDelete($sid, $row);
  2195. $po = $this->resolvePickRowPoContext($sid)['po'];
  2196. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2197. return;
  2198. }
  2199. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2200. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  2201. }
  2202. $now = date('Y-m-d H:i:s');
  2203. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2204. if (is_array($exists)) {
  2205. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  2206. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  2207. } else {
  2208. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  2209. $data['mod_rq'] = $now;
  2210. $data['createtime'] = $now;
  2211. Db::table('purchase_order')->insert($data);
  2212. $poIdLog = (int)Db::getLastInsID();
  2213. }
  2214. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  2215. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  2216. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  2217. if ($gymcLog !== '') {
  2218. $logTail .= ' / ' . $gymcLog;
  2219. }
  2220. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  2221. }
  2222. /**
  2223. * 手工新增协助工序(写入 purchase_order)
  2224. *
  2225. * @param array<string, mixed> $params
  2226. * @return int scydgy_id
  2227. */
  2228. protected function saveManualPickOrder(array $params): int
  2229. {
  2230. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  2231. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  2232. $ccydh = trim((string)($params['CCYDH'] ?? ''));
  2233. if ($ccydh === '') {
  2234. $ccydh = $this->allocateManualOrderCcydh();
  2235. }
  2236. $now = date('Y-m-d H:i:s');
  2237. $sid = $this->allocateManualScydgyId();
  2238. $this->ensurePurchaseOrderNotifySalesmanColumn();
  2239. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  2240. // 选择供应商 / 通知业务员:支持多选,落库用顿号拼接
  2241. $supplierName = $this->joinRfqMultiSelectValues($params['cGzzxMc'] ?? ($params['pick_company_name'] ?? ''));
  2242. $notifySalesman = $this->joinRfqMultiSelectValues($params['notify_salesman'] ?? '');
  2243. $data = [
  2244. 'scydgy_id' => $sid,
  2245. 'CCYDH' => $ccydh,
  2246. 'CYJMC' => $cyjmc,
  2247. 'CGYMC' => $cgymc,
  2248. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  2249. 'CDW' => trim((string)($params['CDW'] ?? '')),
  2250. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  2251. 'CDF' => trim((string)($params['CDF'] ?? '')),
  2252. 'cGzzxMc' => $supplierName,
  2253. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  2254. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  2255. 'notify_salesman' => $notifySalesman,
  2256. 'rfq_salesman_notified' => 0,
  2257. 'rfq_salesman_notify_time' => null,
  2258. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  2259. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  2260. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  2261. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  2262. 'createtime' => $now,
  2263. 'dStamp' => $now,
  2264. 'dputrecord' => $now,
  2265. ];
  2266. Db::table('purchase_order')->insert($data);
  2267. $poId = (int)Db::getLastInsID();
  2268. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  2269. return $sid;
  2270. }
  2271. protected function formatProcuremenRowLabel(array $row): string
  2272. {
  2273. $dh = trim((string)($row['CCYDH'] ?? ''));
  2274. $gymc = trim((string)($row['CGYMC'] ?? ''));
  2275. if ($dh !== '' && $gymc !== '') {
  2276. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  2277. }
  2278. if ($dh !== '') {
  2279. return '订单「' . $dh . '」';
  2280. }
  2281. if ($gymc !== '') {
  2282. return '工序「' . $gymc . '」';
  2283. }
  2284. $id = $this->extractScydgyRowId($row);
  2285. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  2286. }
  2287. /**
  2288. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  2289. */
  2290. protected function extractScydgyRowId(array $row): int
  2291. {
  2292. // 优先 scydgy_id,避免明细行 ID(自增主键)被误当成工序主键;手工单为负数
  2293. if (array_key_exists('scydgy_id', $row) && $row['scydgy_id'] !== null && $row['scydgy_id'] !== '') {
  2294. return (int)$row['scydgy_id'];
  2295. }
  2296. if (array_key_exists('SCYDGY_ID', $row) && $row['SCYDGY_ID'] !== null && $row['SCYDGY_ID'] !== '') {
  2297. return (int)$row['SCYDGY_ID'];
  2298. }
  2299. return (int)($row['ID'] ?? $row['id'] ?? 0);
  2300. }
  2301. protected function isValidScydgyRowId(int $id): bool
  2302. {
  2303. return ProcuremenGuard::isValidScydgyId($id);
  2304. }
  2305. protected function isManualScydgyRowId(int $id): bool
  2306. {
  2307. return $id < 0;
  2308. }
  2309. /**
  2310. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  2311. *
  2312. * @param int[] $scydgyIds
  2313. * @return array<int, string[]>
  2314. */
  2315. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  2316. {
  2317. $out = [];
  2318. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2319. if ($scydgyIds === []) {
  2320. return $out;
  2321. }
  2322. try {
  2323. $rows = Db::table('purchase_order_detail')
  2324. ->where('scydgy_id', 'in', $scydgyIds)
  2325. ->field('scydgy_id,company_name')
  2326. ->order('company_name', 'asc')
  2327. ->select();
  2328. } catch (\Throwable $e) {
  2329. $rows = [];
  2330. }
  2331. if (!is_array($rows)) {
  2332. return $out;
  2333. }
  2334. foreach ($rows as $r) {
  2335. if (!is_array($r)) {
  2336. continue;
  2337. }
  2338. $sid = (int)($r['scydgy_id'] ?? 0);
  2339. $cn = trim((string)($r['company_name'] ?? ''));
  2340. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2341. continue;
  2342. }
  2343. if (!isset($out[$sid])) {
  2344. $out[$sid] = [];
  2345. }
  2346. if (!in_array($cn, $out[$sid], true)) {
  2347. $out[$sid][] = $cn;
  2348. }
  2349. }
  2350. return $out;
  2351. }
  2352. /**
  2353. * 列表展示通知供应商(完整列表,前端单行省略展开)
  2354. *
  2355. * @param string[] $names
  2356. */
  2357. protected function formatNotifySupplierDisplay(array $names): string
  2358. {
  2359. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  2360. return trim((string)$n);
  2361. }, $names))));
  2362. if ($names === []) {
  2363. return '';
  2364. }
  2365. sort($names, SORT_STRING);
  2366. return implode("\n", $names);
  2367. }
  2368. /**
  2369. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  2370. *
  2371. * @param int[] $scydgyIds
  2372. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  2373. */
  2374. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  2375. {
  2376. $out = [];
  2377. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2378. if ($scydgyIds === []) {
  2379. return $out;
  2380. }
  2381. try {
  2382. $rows = Db::table('purchase_order_detail')
  2383. ->where('scydgy_id', 'in', $scydgyIds)
  2384. ->field('scydgy_id,company_name,amount')
  2385. ->select();
  2386. } catch (\Throwable $e) {
  2387. $rows = [];
  2388. }
  2389. if (!is_array($rows)) {
  2390. return $out;
  2391. }
  2392. foreach ($rows as $r) {
  2393. if (!is_array($r)) {
  2394. continue;
  2395. }
  2396. $sid = (int)($r['scydgy_id'] ?? 0);
  2397. $cn = trim((string)($r['company_name'] ?? ''));
  2398. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2399. continue;
  2400. }
  2401. if (!isset($out[$sid])) {
  2402. $out[$sid] = ['all' => [], 'quoted' => []];
  2403. }
  2404. $out[$sid]['all'][$cn] = true;
  2405. $am = trim((string)($r['amount'] ?? ''));
  2406. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2407. $out[$sid]['quoted'][$cn] = true;
  2408. }
  2409. }
  2410. return $out;
  2411. }
  2412. /**
  2413. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  2414. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  2415. */
  2416. protected function mergeQuotedSupplierBuckets(array $buckets): array
  2417. {
  2418. $merged = ['all' => [], 'quoted' => []];
  2419. foreach ($buckets as $b) {
  2420. if (!is_array($b)) {
  2421. continue;
  2422. }
  2423. foreach ($b['all'] ?? [] as $cn => $_) {
  2424. $merged['all'][$cn] = true;
  2425. }
  2426. foreach ($b['quoted'] ?? [] as $cn => $_) {
  2427. $merged['quoted'][$cn] = true;
  2428. }
  2429. }
  2430. return $merged;
  2431. }
  2432. /**
  2433. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  2434. */
  2435. protected function formatQuotedSupplierLines(array $bucket): string
  2436. {
  2437. $all = array_keys($bucket['all'] ?? []);
  2438. if ($all === []) {
  2439. return '';
  2440. }
  2441. sort($all, SORT_STRING);
  2442. $lines = [];
  2443. foreach ($all as $cn) {
  2444. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  2445. $lines[] = $cn . '(' . $status . ')';
  2446. }
  2447. return implode("\n", $lines);
  2448. }
  2449. /**
  2450. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  2451. */
  2452. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  2453. {
  2454. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2455. $this->view->engine->layout(false);
  2456. try {
  2457. $bodyHtml = $this->view->fetch($view);
  2458. $this->view->assign('dialogBody', $bodyHtml);
  2459. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  2460. return $this->view->fetch('procuremen/dialog_lite_shell');
  2461. } finally {
  2462. if ($restoreLayout) {
  2463. $this->view->engine->layout($restoreLayout);
  2464. }
  2465. }
  2466. }
  2467. /**
  2468. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  2469. */
  2470. protected function resolveBundleSysRq(array $bundle): string
  2471. {
  2472. foreach ($bundle['pos'] ?? [] as $po) {
  2473. if (!is_array($po)) {
  2474. continue;
  2475. }
  2476. $sr = trim((string)($po['sys_rq'] ?? ''));
  2477. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  2478. return $sr;
  2479. }
  2480. }
  2481. return '';
  2482. }
  2483. /**
  2484. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  2485. */
  2486. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  2487. {
  2488. $raw = trim((string)$sysRq);
  2489. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  2490. return true;
  2491. }
  2492. $ts = strtotime(str_replace('T', ' ', $raw));
  2493. if ($ts === false || $ts <= 0) {
  2494. return true;
  2495. }
  2496. return time() >= $ts;
  2497. }
  2498. /**
  2499. * 开标前校验:必须已过报价截止时间
  2500. *
  2501. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2502. */
  2503. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  2504. {
  2505. $sysRq = $this->resolveBundleSysRq($bundle);
  2506. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  2507. $this->error('未到招标截止日期');
  2508. }
  2509. }
  2510. /**
  2511. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  2512. *
  2513. * @param array<string, mixed> $d
  2514. * @param string $deliveryYmd
  2515. */
  2516. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  2517. {
  2518. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  2519. return max(0, (int)$d['lead_days']);
  2520. }
  2521. if ($deliveryYmd === '') {
  2522. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  2523. }
  2524. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  2525. return null;
  2526. }
  2527. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2528. $t2 = strtotime($m[1] . ' 00:00:00');
  2529. if ($t1 === false || $t2 === false) {
  2530. return null;
  2531. }
  2532. return max(0, (int)round(($t2 - $t1) / 86400));
  2533. }
  2534. /**
  2535. * @param int|null $days
  2536. */
  2537. protected function formatProcuremenLeadDaysText($days): string
  2538. {
  2539. if ($days === null || $days === '') {
  2540. return '未填写';
  2541. }
  2542. if (!is_numeric($days)) {
  2543. return '未填写';
  2544. }
  2545. return ((int)$days) . '天';
  2546. }
  2547. /**
  2548. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2549. *
  2550. * @param array<string, mixed> $line
  2551. */
  2552. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2553. {
  2554. $amountFilled = !empty($line['amount_filled']);
  2555. $deliveryFilled = !empty($line['delivery_filled']);
  2556. $leadFilled = !empty($line['lead_days_filled']);
  2557. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2558. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2559. $line['amount_show'] = '';
  2560. if (array_key_exists('amount_text', $line)) {
  2561. $line['amount_text'] = $line['unit_price_text'];
  2562. }
  2563. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2564. $line['delivery_show'] = $deliveryText;
  2565. if (array_key_exists('delivery_text', $line)) {
  2566. $line['delivery_text'] = $deliveryText;
  2567. }
  2568. $line['delivery_ymd'] = '';
  2569. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2570. $line['lead_days_show'] = $leadText;
  2571. $line['lead_days_text'] = $leadText;
  2572. $line['lead_days'] = '';
  2573. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2574. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2575. $line['subtotal_num'] = null;
  2576. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2577. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2578. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2579. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2580. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2581. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2582. $line['amount_filled'] = false;
  2583. $line['delivery_filled'] = false;
  2584. $line['lead_days_filled'] = false;
  2585. $line['is_quoted'] = false;
  2586. if (array_key_exists('quote_label', $line)) {
  2587. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2588. }
  2589. }
  2590. protected function ensurePurchaseOrderBidOpenTable(): void
  2591. {
  2592. static $ready = false;
  2593. if ($ready) {
  2594. return;
  2595. }
  2596. $cacheKey = 'procuremen_bid_open_table_ok_v1';
  2597. try {
  2598. if (Cache::get($cacheKey)) {
  2599. $ready = true;
  2600. return;
  2601. }
  2602. } catch (\Throwable $e) {
  2603. }
  2604. try {
  2605. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2606. $ready = true;
  2607. try {
  2608. Cache::set($cacheKey, 1, 86400);
  2609. } catch (\Throwable $e) {
  2610. }
  2611. } catch (\Throwable $e) {
  2612. Db::execute(
  2613. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2614. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2615. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2616. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2617. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2618. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2619. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2620. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2621. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2622. `createtime` datetime DEFAULT NULL,
  2623. PRIMARY KEY (`id`),
  2624. UNIQUE KEY `uk_ccydh` (`ccydh`)
  2625. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2626. );
  2627. $ready = true;
  2628. try {
  2629. Cache::set($cacheKey, 1, 86400);
  2630. } catch (\Throwable $e2) {
  2631. }
  2632. }
  2633. }
  2634. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  2635. {
  2636. $ccydh = trim($ccydh);
  2637. if ($ccydh === '') {
  2638. return false;
  2639. }
  2640. $this->ensurePurchaseOrderBidOpenTable();
  2641. try {
  2642. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2643. return is_array($row);
  2644. } catch (\Throwable $e) {
  2645. return false;
  2646. }
  2647. }
  2648. /**
  2649. * 批量查询订单是否已开标验证
  2650. *
  2651. * @param array<int, string> $ccydhs
  2652. * @return array<string, bool> ccydh => true
  2653. */
  2654. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  2655. {
  2656. $set = [];
  2657. $list = [];
  2658. foreach ($ccydhs as $c) {
  2659. $c = trim((string)$c);
  2660. if ($c !== '') {
  2661. $list[$c] = true;
  2662. }
  2663. }
  2664. if ($list === []) {
  2665. return $set;
  2666. }
  2667. $this->ensurePurchaseOrderBidOpenTable();
  2668. try {
  2669. $rows = Db::table('purchase_order_bid_open')
  2670. ->where('ccydh', 'in', array_keys($list))
  2671. ->field('ccydh')
  2672. ->select();
  2673. foreach ($rows as $row) {
  2674. if (!is_array($row)) {
  2675. continue;
  2676. }
  2677. $c = trim((string)($row['ccydh'] ?? ''));
  2678. if ($c !== '') {
  2679. $set[$c] = true;
  2680. }
  2681. }
  2682. } catch (\Throwable $e) {
  2683. return [];
  2684. }
  2685. return $set;
  2686. }
  2687. /**
  2688. * 批量查询订单是否已指定供应商(免开标)
  2689. *
  2690. * @param array<int, string> $ccydhs
  2691. * @return array<string, bool> ccydh => true
  2692. */
  2693. protected function loadProcuremenManualPickedCcydhSet(array $ccydhs): array
  2694. {
  2695. $set = [];
  2696. $list = [];
  2697. foreach ($ccydhs as $c) {
  2698. $c = trim((string)$c);
  2699. if ($c !== '') {
  2700. $list[$c] = true;
  2701. }
  2702. }
  2703. if ($list === []) {
  2704. return $set;
  2705. }
  2706. $this->ensurePurchaseOrderManualPickColumns();
  2707. try {
  2708. $rows = Db::table('purchase_order')
  2709. ->where('CCYDH', 'in', array_keys($list))
  2710. ->where('manual_pick', 1)
  2711. ->field('CCYDH')
  2712. ->select();
  2713. foreach ($rows as $row) {
  2714. if (!is_array($row)) {
  2715. continue;
  2716. }
  2717. $c = trim((string)($row['CCYDH'] ?? ''));
  2718. if ($c !== '') {
  2719. $set[$c] = true;
  2720. }
  2721. }
  2722. } catch (\Throwable $e) {
  2723. return [];
  2724. }
  2725. return $set;
  2726. }
  2727. /**
  2728. * 确认供应商列表:按开标状态筛选(已开标 / 已指定供应商 / 待开标)
  2729. *
  2730. * @param array<int, array<string, mixed>> $pool
  2731. * @return array<int, array<string, mixed>>
  2732. */
  2733. protected function filterProcuremenPoolByBidOpenStatus(array $pool, string $status): array
  2734. {
  2735. $status = trim($status);
  2736. if ($status === '' || !in_array($status, ['待开标', '已开标', '已指定供应商'], true)) {
  2737. return $pool;
  2738. }
  2739. $ccydhList = [];
  2740. foreach ($pool as $rw) {
  2741. if (!is_array($rw)) {
  2742. continue;
  2743. }
  2744. $c = trim((string)($rw['CCYDH'] ?? ''));
  2745. if ($c !== '') {
  2746. $ccydhList[] = $c;
  2747. }
  2748. }
  2749. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  2750. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  2751. $out = [];
  2752. foreach ($pool as $rw) {
  2753. if (!is_array($rw)) {
  2754. continue;
  2755. }
  2756. $c = trim((string)($rw['CCYDH'] ?? ''));
  2757. if ($c !== '' && isset($bidOpenSet[$c])) {
  2758. $t = '已开标';
  2759. } elseif ($c !== '' && isset($manualPickSet[$c])) {
  2760. $t = '已指定供应商';
  2761. } else {
  2762. $t = '待开标';
  2763. }
  2764. if ($t === $status) {
  2765. $out[] = $rw;
  2766. }
  2767. }
  2768. return $out;
  2769. }
  2770. /**
  2771. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  2772. *
  2773. * @param array<string, mixed> $group
  2774. */
  2775. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  2776. {
  2777. if ($quoteVisible) {
  2778. $group['remark_quote_pending'] = 0;
  2779. return;
  2780. }
  2781. $group['remark'] = '';
  2782. $group['remark_quote_pending'] = 0;
  2783. }
  2784. /**
  2785. * @param array{ccydh?:string} $bundle
  2786. */
  2787. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  2788. {
  2789. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  2790. }
  2791. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  2792. {
  2793. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  2794. return true;
  2795. }
  2796. return $this->isProcuremenManualPickedForBundle($bundle);
  2797. }
  2798. /**
  2799. * 确保 purchase_order 自选供应商字段
  2800. */
  2801. protected function ensurePurchaseOrderManualPickColumns(): void
  2802. {
  2803. static $done = false;
  2804. if ($done) {
  2805. return;
  2806. }
  2807. $done = true;
  2808. $adds = [
  2809. 'manual_pick' => "ADD COLUMN `manual_pick` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=自选供应商(免开标)' AFTER `pick_company_name`",
  2810. 'manual_pick_reason' => "ADD COLUMN `manual_pick_reason` varchar(500) NOT NULL DEFAULT '' COMMENT '自选供应商选择说明' AFTER `manual_pick`",
  2811. ];
  2812. foreach ($adds as $col => $ddl) {
  2813. try {
  2814. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  2815. if (!is_array($cols) || $cols === []) {
  2816. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  2817. }
  2818. } catch (\Throwable $e) {
  2819. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  2820. }
  2821. }
  2822. }
  2823. /**
  2824. * 是否已自选供应商(免开标查看报价)
  2825. *
  2826. * @param array{pos?:array} $bundle
  2827. */
  2828. protected function isProcuremenManualPickedForBundle(array $bundle): bool
  2829. {
  2830. $this->ensurePurchaseOrderManualPickColumns();
  2831. foreach ($bundle['pos'] ?? [] as $poRow) {
  2832. if (!is_array($poRow)) {
  2833. continue;
  2834. }
  2835. if ((int)($poRow['manual_pick'] ?? 0) === 1) {
  2836. return true;
  2837. }
  2838. }
  2839. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2840. if ($ccydh === '') {
  2841. return false;
  2842. }
  2843. try {
  2844. $v = Db::table('purchase_order')->where('CCYDH', $ccydh)->where('manual_pick', 1)->value('id');
  2845. return $v !== null && $v !== false && (int)$v > 0;
  2846. } catch (\Throwable $e) {
  2847. return false;
  2848. }
  2849. }
  2850. /**
  2851. * @param array{pos?:array} $bundle
  2852. * @return array{company:string,reason:string}
  2853. */
  2854. protected function resolveProcuremenManualPickInfo(array $bundle): array
  2855. {
  2856. $this->ensurePurchaseOrderManualPickColumns();
  2857. foreach ($bundle['pos'] ?? [] as $poRow) {
  2858. if (!is_array($poRow)) {
  2859. continue;
  2860. }
  2861. if ((int)($poRow['manual_pick'] ?? 0) !== 1) {
  2862. continue;
  2863. }
  2864. $cn = trim((string)($poRow['pick_company_name'] ?? ''));
  2865. $reason = trim((string)($poRow['manual_pick_reason'] ?? ''));
  2866. return ['company' => $cn, 'reason' => $reason];
  2867. }
  2868. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2869. if ($ccydh === '') {
  2870. return ['company' => '', 'reason' => ''];
  2871. }
  2872. try {
  2873. $row = Db::table('purchase_order')
  2874. ->where('CCYDH', $ccydh)
  2875. ->where('manual_pick', 1)
  2876. ->field('pick_company_name,manual_pick_reason')
  2877. ->order('id', 'asc')
  2878. ->find();
  2879. } catch (\Throwable $e) {
  2880. $row = null;
  2881. }
  2882. if (!is_array($row)) {
  2883. return ['company' => '', 'reason' => ''];
  2884. }
  2885. return [
  2886. 'company' => trim((string)($row['pick_company_name'] ?? '')),
  2887. 'reason' => trim((string)($row['manual_pick_reason'] ?? '')),
  2888. ];
  2889. }
  2890. protected function loadBidOpenAdminUser(int $adminId): ?array
  2891. {
  2892. if ($adminId <= 0) {
  2893. return null;
  2894. }
  2895. try {
  2896. $row = Db::name('admin')->where('id', $adminId)->find();
  2897. } catch (\Throwable $e) {
  2898. return null;
  2899. }
  2900. if (!is_array($row)) {
  2901. return null;
  2902. }
  2903. $status = strtolower(trim((string)($row['status'] ?? '')));
  2904. if ($status !== '' && $status !== 'normal') {
  2905. return null;
  2906. }
  2907. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  2908. return null;
  2909. }
  2910. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  2911. if (!preg_match('/^1\d{10}$/', $phone)) {
  2912. return null;
  2913. }
  2914. $name = trim((string)($row['nickname'] ?? ''));
  2915. if ($name === '') {
  2916. $name = trim((string)($row['username'] ?? ''));
  2917. }
  2918. return [
  2919. 'id' => (int)$row['id'],
  2920. 'username' => trim((string)($row['username'] ?? '')),
  2921. 'nickname' => $name,
  2922. 'mobile' => $phone,
  2923. ];
  2924. }
  2925. /**
  2926. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  2927. */
  2928. protected function bidOpenVerifierAuthGroupRootId(): int
  2929. {
  2930. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  2931. return $id > 0 ? $id : 10;
  2932. }
  2933. /**
  2934. * @return int[]
  2935. */
  2936. protected function loadBidOpenVerifierAuthGroupIds(): array
  2937. {
  2938. static $memo = [];
  2939. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  2940. if (isset($memo[$rootId])) {
  2941. return $memo[$rootId];
  2942. }
  2943. try {
  2944. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  2945. } catch (\Throwable $e) {
  2946. $memo[$rootId] = [$rootId];
  2947. return $memo[$rootId];
  2948. }
  2949. if (!is_array($groups) || $groups === []) {
  2950. $memo[$rootId] = [$rootId];
  2951. return $memo[$rootId];
  2952. }
  2953. $groupList = [];
  2954. foreach ($groups as $g) {
  2955. if (is_array($g)) {
  2956. $groupList[] = $g;
  2957. }
  2958. }
  2959. if ($groupList === []) {
  2960. $memo[$rootId] = [$rootId];
  2961. return $memo[$rootId];
  2962. }
  2963. $tree = \fast\Tree::instance();
  2964. $tree->init($groupList);
  2965. $ids = $tree->getChildrenIds($rootId, true);
  2966. if (!is_array($ids) || $ids === []) {
  2967. $memo[$rootId] = [$rootId];
  2968. return $memo[$rootId];
  2969. }
  2970. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  2971. return $memo[$rootId];
  2972. }
  2973. protected function isBidOpenVerifierAdmin(int $adminId): bool
  2974. {
  2975. if ($adminId <= 0) {
  2976. return false;
  2977. }
  2978. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2979. if ($groupIds === []) {
  2980. return false;
  2981. }
  2982. try {
  2983. return (bool)Db::name('auth_group_access')
  2984. ->where('uid', $adminId)
  2985. ->where('group_id', 'in', $groupIds)
  2986. ->count();
  2987. } catch (\Throwable $e) {
  2988. return false;
  2989. }
  2990. }
  2991. /**
  2992. * @return array<int, array<string, mixed>>
  2993. */
  2994. protected function listBidOpenVerifierCandidates(): array
  2995. {
  2996. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  2997. if ($groupIds === []) {
  2998. return [];
  2999. }
  3000. try {
  3001. $adminIds = Db::name('auth_group_access')
  3002. ->where('group_id', 'in', $groupIds)
  3003. ->column('uid');
  3004. } catch (\Throwable $e) {
  3005. $adminIds = [];
  3006. }
  3007. $adminIds = is_array($adminIds)
  3008. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  3009. : [];
  3010. if ($adminIds === []) {
  3011. return [];
  3012. }
  3013. try {
  3014. $rows = Db::name('admin')
  3015. ->where('status', 'normal')
  3016. ->where('id', 'in', $adminIds)
  3017. ->where('mobile', '<>', '')
  3018. ->order('id', 'asc')
  3019. ->select();
  3020. } catch (\Throwable $e) {
  3021. return [];
  3022. }
  3023. if (!is_array($rows)) {
  3024. return [];
  3025. }
  3026. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  3027. $out = [];
  3028. foreach ($rows as $row) {
  3029. if (!is_array($row)) {
  3030. continue;
  3031. }
  3032. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  3033. if ($one === null) {
  3034. continue;
  3035. }
  3036. $out[] = [
  3037. 'id' => $one['id'],
  3038. 'username' => $one['username'],
  3039. 'nickname' => $one['nickname'],
  3040. 'group_name' => $groupNameMap[$one['id']] ?? '',
  3041. 'mobile' => mask_phone($one['mobile']),
  3042. 'mobile_plain' => (string)$one['mobile'],
  3043. ];
  3044. }
  3045. return $out;
  3046. }
  3047. /**
  3048. * @param int[] $adminIds
  3049. * @return array<int, string>
  3050. */
  3051. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  3052. {
  3053. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  3054. if ($adminIds === []) {
  3055. return [];
  3056. }
  3057. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3058. try {
  3059. $rows = Db::name('auth_group_access')
  3060. ->alias('aga')
  3061. ->join('auth_group ag', 'aga.group_id = ag.id')
  3062. ->where('aga.uid', 'in', $adminIds)
  3063. ->where('aga.group_id', 'in', $groupIds)
  3064. ->field('aga.uid,ag.name')
  3065. ->order('aga.uid', 'asc')
  3066. ->order('aga.group_id', 'asc')
  3067. ->select();
  3068. } catch (\Throwable $e) {
  3069. return [];
  3070. }
  3071. if (!is_array($rows)) {
  3072. return [];
  3073. }
  3074. $out = [];
  3075. foreach ($rows as $row) {
  3076. if (!is_array($row)) {
  3077. continue;
  3078. }
  3079. $uid = (int)($row['uid'] ?? 0);
  3080. $name = trim((string)($row['name'] ?? ''));
  3081. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  3082. continue;
  3083. }
  3084. $out[$uid] = $name;
  3085. }
  3086. return $out;
  3087. }
  3088. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  3089. {
  3090. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  3091. }
  3092. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  3093. {
  3094. return 'procuremen_bidopen_wait_' . $adminId;
  3095. }
  3096. protected function renderBidOpenVerifySms(string $code): string
  3097. {
  3098. $tpl = '';
  3099. try {
  3100. $row = $this->loadNotifyTemplateRow('bid_open');
  3101. if (is_array($row)) {
  3102. $tpl = trim((string)($row['content'] ?? ''));
  3103. }
  3104. } catch (\Throwable $e) {
  3105. $tpl = '';
  3106. }
  3107. if ($tpl === '') {
  3108. $tpl = '【可集达】您的短信验证码是{code}';
  3109. }
  3110. return str_replace('{code}', $code, $tpl);
  3111. }
  3112. protected function sendBidOpenVerifySms(string $phone, string $code): void
  3113. {
  3114. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  3115. }
  3116. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  3117. {
  3118. $code = trim($code);
  3119. if (!preg_match('/^\d{6}$/', $code)) {
  3120. return false;
  3121. }
  3122. $mock = Config::get('mproc.mock_sms_code');
  3123. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3124. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3125. return true;
  3126. }
  3127. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3128. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3129. return false;
  3130. }
  3131. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3132. return true;
  3133. }
  3134. /**
  3135. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3136. */
  3137. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  3138. {
  3139. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3140. if ($ccydh === '') {
  3141. throw new \InvalidArgumentException('订单号无效');
  3142. }
  3143. $this->ensurePurchaseOrderBidOpenTable();
  3144. list($operatorId, $operatorName) = $this->GetUseName();
  3145. $now = date('Y-m-d H:i:s');
  3146. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3147. $payload = [
  3148. 'ccydh' => $ccydh,
  3149. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  3150. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  3151. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  3152. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  3153. 'operator_id' => (int)$operatorId,
  3154. 'operator_name' => trim((string)$operatorName),
  3155. 'createtime' => $now,
  3156. ];
  3157. if (is_array($exists)) {
  3158. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  3159. } else {
  3160. Db::table('purchase_order_bid_open')->insert($payload);
  3161. }
  3162. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  3163. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  3164. $labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
  3165. (int)$payload['verifier1_id'],
  3166. (int)$payload['verifier2_id'],
  3167. ]);
  3168. if (isset($labelMap[(int)$payload['verifier1_id']]) && (int)$payload['verifier1_id'] > 0) {
  3169. $name1 = $labelMap[(int)$payload['verifier1_id']];
  3170. }
  3171. if (isset($labelMap[(int)$payload['verifier2_id']]) && (int)$payload['verifier2_id'] > 0) {
  3172. $name2 = $labelMap[(int)$payload['verifier2_id']];
  3173. }
  3174. $logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
  3175. $seenSid = [];
  3176. foreach ($bundle['pos'] ?? [] as $poRow) {
  3177. if (!is_array($poRow)) {
  3178. continue;
  3179. }
  3180. $sid = (int)($poRow['scydgy_id'] ?? 0);
  3181. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  3182. continue;
  3183. }
  3184. $seenSid[$sid] = true;
  3185. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  3186. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  3187. }
  3188. if ($seenSid === []) {
  3189. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  3190. if ($this->isValidScydgyRowId($anchor)) {
  3191. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  3192. }
  3193. }
  3194. // 开标通过后计算并写入供应商服务评分
  3195. try {
  3196. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  3197. ProcuremenSupplierScore::saveForOrder($ccydh, $quoteGroups, date('Y-m', strtotime($now) ?: time()));
  3198. } catch (\Throwable $e) {
  3199. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  3200. }
  3201. }
  3202. /**
  3203. * 报价行展示字段默认值(模板安全访问)
  3204. *
  3205. * @param array<string, mixed> $line
  3206. * @return array<string, mixed>
  3207. */
  3208. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  3209. {
  3210. if (!array_key_exists('amount_quote_pending', $line)) {
  3211. $line['amount_quote_pending'] = 0;
  3212. }
  3213. if (!array_key_exists('delivery_quote_pending', $line)) {
  3214. $line['delivery_quote_pending'] = 0;
  3215. }
  3216. if (!array_key_exists('quote_before_deadline', $line)) {
  3217. $line['quote_before_deadline'] = 0;
  3218. }
  3219. if (!array_key_exists('amount_filled', $line)) {
  3220. $line['amount_filled'] = 0;
  3221. }
  3222. if (!array_key_exists('delivery_filled', $line)) {
  3223. $line['delivery_filled'] = 0;
  3224. }
  3225. if (!array_key_exists('lead_days_filled', $line)) {
  3226. $line['lead_days_filled'] = 0;
  3227. }
  3228. if (!array_key_exists('lead_days_quote_pending', $line)) {
  3229. $line['lead_days_quote_pending'] = 0;
  3230. }
  3231. if (!array_key_exists('lead_days_show', $line)) {
  3232. $line['lead_days_show'] = '未填写';
  3233. }
  3234. if (!array_key_exists('lead_days_text', $line)) {
  3235. $line['lead_days_text'] = $line['lead_days_show'];
  3236. }
  3237. return $line;
  3238. }
  3239. /**
  3240. * 审核弹窗:按供应商汇总报价明细
  3241. *
  3242. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3243. * @return array<int, array<string, mixed>>
  3244. */
  3245. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  3246. {
  3247. $sids = [];
  3248. foreach ($bundle['pos'] ?? [] as $po) {
  3249. if (!is_array($po)) {
  3250. continue;
  3251. }
  3252. $sid = (int)($po['scydgy_id'] ?? 0);
  3253. if ($this->isValidScydgyRowId($sid)) {
  3254. $sids[$sid] = true;
  3255. }
  3256. }
  3257. if ($sids === []) {
  3258. return [];
  3259. }
  3260. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3261. $gymcMap = [];
  3262. $qtyBySid = [];
  3263. $orderedSids = [];
  3264. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3265. if (!is_array($mr)) {
  3266. continue;
  3267. }
  3268. $gid = $this->extractScydgyRowId($mr);
  3269. if ($this->isValidScydgyRowId($gid)) {
  3270. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3271. $orderedSids[] = $gid;
  3272. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3273. if ($qty === '') {
  3274. $qty = trim((string)($mr['NGZL'] ?? ''));
  3275. }
  3276. $qtyBySid[$gid] = $qty;
  3277. }
  3278. }
  3279. foreach ($bundle['pos'] ?? [] as $po) {
  3280. if (!is_array($po)) {
  3281. continue;
  3282. }
  3283. $gid = (int)($po['scydgy_id'] ?? 0);
  3284. if ($this->isValidScydgyRowId($gid)) {
  3285. $nm = trim((string)($po['CGYMC'] ?? ''));
  3286. if ($nm !== '') {
  3287. $gymcMap[$gid] = $nm;
  3288. }
  3289. if (!in_array($gid, $orderedSids, true)) {
  3290. $orderedSids[] = $gid;
  3291. }
  3292. }
  3293. }
  3294. try {
  3295. $detailsQuery = Db::table('purchase_order_detail')
  3296. ->where('scydgy_id', 'in', array_keys($sids));
  3297. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3298. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  3299. } catch (\Throwable $e) {
  3300. try {
  3301. $detailsQuery = Db::table('purchase_order_detail')
  3302. ->where('scydgy_id', 'in', array_keys($sids));
  3303. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3304. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  3305. } catch (\Throwable $e2) {
  3306. $details = [];
  3307. }
  3308. }
  3309. if (!is_array($details)) {
  3310. $details = [];
  3311. }
  3312. $byCompany = [];
  3313. foreach ($details as $d) {
  3314. if (!is_array($d)) {
  3315. continue;
  3316. }
  3317. $cn = trim((string)($d['company_name'] ?? ''));
  3318. if ($cn === '') {
  3319. continue;
  3320. }
  3321. if (!isset($byCompany[$cn])) {
  3322. $ph = trim((string)($d['phone'] ?? ''));
  3323. $username = trim((string)($d['username'] ?? ''));
  3324. if ($username === '') {
  3325. $username = $this->resolveCustomerContactName($ph, $cn);
  3326. }
  3327. $byCompany[$cn] = [
  3328. 'name' => $cn,
  3329. 'email' => trim((string)($d['email'] ?? '')),
  3330. 'phone' => $ph,
  3331. 'username' => $username,
  3332. 'remark' => '',
  3333. 'has_quote' => false,
  3334. 'lines_map' => [],
  3335. ];
  3336. }
  3337. if ($byCompany[$cn]['remark'] === '') {
  3338. $rm = '';
  3339. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3340. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3341. $rm = trim((string)$d[$rk]);
  3342. break;
  3343. }
  3344. }
  3345. if ($rm !== '') {
  3346. $byCompany[$cn]['remark'] = $rm;
  3347. }
  3348. }
  3349. $sid = (int)($d['scydgy_id'] ?? 0);
  3350. $am = trim((string)($d['amount'] ?? ''));
  3351. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3352. if ($gymc === '') {
  3353. $gymc = '工序';
  3354. }
  3355. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3356. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3357. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3358. $deliveryShow = $deliveryRaw;
  3359. }
  3360. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3361. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3362. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3363. $subtotal = null;
  3364. if ($amountNum !== null) {
  3365. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3366. }
  3367. $unitPriceText = $amountFilled
  3368. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3369. : '未填写';
  3370. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3371. $leadFilled = ($leadDays !== null);
  3372. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3373. $lineRow = [
  3374. 'cgymc' => $gymc,
  3375. 'amount' => $am,
  3376. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  3377. 'amount_filled' => $amountFilled,
  3378. 'unit_price_text' => $unitPriceText,
  3379. 'delivery' => $deliveryRaw,
  3380. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  3381. 'delivery_filled' => $deliveryFilled,
  3382. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  3383. 'lead_days' => $leadFilled ? $leadDays : '',
  3384. 'lead_days_filled'=> $leadFilled,
  3385. 'lead_days_show' => $leadText,
  3386. 'lead_days_text' => $leadText,
  3387. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3388. 'subtotal_num' => $subtotal,
  3389. 'status_name' => trim((string)($d['status_name'] ?? '')),
  3390. 'is_quoted' => $amountFilled,
  3391. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  3392. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3393. ];
  3394. if (!$quoteVisible) {
  3395. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  3396. }
  3397. // 按工序 id 暂存,下面再按上方工序表顺序输出
  3398. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  3399. }
  3400. foreach ($byCompany as $cn => $g) {
  3401. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  3402. $lines = [];
  3403. $usedSids = [];
  3404. foreach ($orderedSids as $sid) {
  3405. if (!isset($linesMap[$sid])) {
  3406. continue;
  3407. }
  3408. $lines[] = $linesMap[$sid];
  3409. $usedSids[$sid] = true;
  3410. }
  3411. foreach ($linesMap as $sid => $ln) {
  3412. if (isset($usedSids[$sid])) {
  3413. continue;
  3414. }
  3415. $lines[] = $ln;
  3416. }
  3417. $total = count($lines);
  3418. $quoted = 0;
  3419. $groupTotal = 0.0;
  3420. $groupHasTotal = false;
  3421. if ($quoteVisible) {
  3422. foreach ($lines as $ln) {
  3423. $am = trim((string)($ln['amount'] ?? ''));
  3424. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  3425. $quoted++;
  3426. }
  3427. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3428. $groupTotal += (float)$ln['subtotal_num'];
  3429. $groupHasTotal = true;
  3430. }
  3431. }
  3432. }
  3433. unset($byCompany[$cn]['lines_map']);
  3434. $byCompany[$cn]['lines'] = $lines;
  3435. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  3436. $byCompany[$cn]['line_count'] = $total;
  3437. $byCompany[$cn]['has_total'] = $total > 0;
  3438. $byCompany[$cn]['has_remark'] = $total > 0;
  3439. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  3440. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3441. // 工序行 + 备注行 + 总计行
  3442. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  3443. }
  3444. $groups = array_values($byCompany);
  3445. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3446. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  3447. }
  3448. /**
  3449. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  3450. *
  3451. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3452. * @return array<int, array<string, mixed>>
  3453. */
  3454. protected function loadConfirmSupplierPickGroups(array $bundle): array
  3455. {
  3456. $sids = [];
  3457. $poIdMap = [];
  3458. foreach ($bundle['pos'] ?? [] as $po) {
  3459. if (!is_array($po)) {
  3460. continue;
  3461. }
  3462. $sid = (int)($po['scydgy_id'] ?? 0);
  3463. if ($this->isValidScydgyRowId($sid)) {
  3464. $sids[$sid] = true;
  3465. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  3466. }
  3467. }
  3468. if ($sids === []) {
  3469. return [];
  3470. }
  3471. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3472. $gymcMap = [];
  3473. $qtyBySid = [];
  3474. $orderedSids = [];
  3475. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3476. if (!is_array($mr)) {
  3477. continue;
  3478. }
  3479. $gid = $this->extractScydgyRowId($mr);
  3480. if ($this->isValidScydgyRowId($gid)) {
  3481. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3482. $orderedSids[] = $gid;
  3483. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3484. if ($qty === '') {
  3485. $qty = trim((string)($mr['NGZL'] ?? ''));
  3486. }
  3487. $qtyBySid[$gid] = $qty;
  3488. }
  3489. }
  3490. foreach ($bundle['pos'] ?? [] as $po) {
  3491. if (!is_array($po)) {
  3492. continue;
  3493. }
  3494. $gid = (int)($po['scydgy_id'] ?? 0);
  3495. if ($this->isValidScydgyRowId($gid)) {
  3496. $nm = trim((string)($po['CGYMC'] ?? ''));
  3497. if ($nm !== '') {
  3498. $gymcMap[$gid] = $nm;
  3499. }
  3500. }
  3501. }
  3502. try {
  3503. $details = Db::table('purchase_order_detail')
  3504. ->where('scydgy_id', 'in', array_keys($sids))
  3505. ->order('company_name', 'asc')
  3506. ->order('id', 'asc')
  3507. ->select();
  3508. } catch (\Throwable $e) {
  3509. try {
  3510. $details = Db::table('purchase_order_detail')
  3511. ->where('scydgy_id', 'in', array_keys($sids))
  3512. ->order('company_name', 'asc')
  3513. ->order('ID', 'asc')
  3514. ->select();
  3515. } catch (\Throwable $e2) {
  3516. $details = [];
  3517. }
  3518. }
  3519. if (!is_array($details)) {
  3520. $details = [];
  3521. }
  3522. $byCompany = [];
  3523. foreach ($details as $d) {
  3524. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3525. continue;
  3526. }
  3527. $cn = trim((string)($d['company_name'] ?? ''));
  3528. if ($cn === '') {
  3529. continue;
  3530. }
  3531. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  3532. $sid = (int)($d['scydgy_id'] ?? 0);
  3533. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  3534. continue;
  3535. }
  3536. if (!isset($byCompany[$cn])) {
  3537. $ph = trim((string)($d['phone'] ?? ''));
  3538. $username = trim((string)($d['username'] ?? ''));
  3539. if ($username === '') {
  3540. $username = $this->resolveCustomerContactName($ph, $cn);
  3541. }
  3542. $byCompany[$cn] = [
  3543. 'name' => $cn,
  3544. 'email' => trim((string)($d['email'] ?? '')),
  3545. 'phone' => $ph,
  3546. 'username' => $username,
  3547. 'remark' => '',
  3548. 'pick_lines' => [],
  3549. 'detail_picks' => [],
  3550. ];
  3551. }
  3552. if ($byCompany[$cn]['remark'] === '') {
  3553. $rm = '';
  3554. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3555. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3556. $rm = trim((string)$d[$rk]);
  3557. break;
  3558. }
  3559. }
  3560. if ($rm !== '') {
  3561. $byCompany[$cn]['remark'] = $rm;
  3562. }
  3563. }
  3564. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3565. if ($gymc === '') {
  3566. $gymc = '工序';
  3567. }
  3568. $am = trim((string)($d['amount'] ?? ''));
  3569. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3570. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3571. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3572. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3573. $deliveryShow = $deliveryRaw;
  3574. }
  3575. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3576. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3577. $subtotal = null;
  3578. if ($amountNum !== null) {
  3579. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3580. }
  3581. $unitPriceText = $amountFilled
  3582. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3583. : '未填写';
  3584. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3585. $leadFilled = ($leadDays !== null);
  3586. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3587. $pickLine = [
  3588. 'cgymc' => $gymc,
  3589. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  3590. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  3591. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  3592. 'amount_filled' => $amountFilled,
  3593. 'delivery_filled' => $deliveryFilled,
  3594. 'unit_price_text' => $unitPriceText,
  3595. 'lead_days' => $leadFilled ? $leadDays : '',
  3596. 'lead_days_filled'=> $leadFilled,
  3597. 'lead_days_show' => $leadText,
  3598. 'lead_days_text' => $leadText,
  3599. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3600. 'subtotal_num' => $subtotal,
  3601. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3602. 'is_quoted' => $amountFilled,
  3603. ];
  3604. if (!$quoteVisible) {
  3605. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  3606. }
  3607. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  3608. $byCompany[$cn]['detail_picks'][$sid] = [
  3609. 'scydgy_id' => $sid,
  3610. 'detail_id' => $detailId,
  3611. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  3612. 'cgymc' => $gymc,
  3613. ];
  3614. }
  3615. $out = [];
  3616. foreach ($byCompany as $g) {
  3617. $pickLinesMap = $g['pick_lines'] ?? [];
  3618. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  3619. continue;
  3620. }
  3621. $pickLines = [];
  3622. $usedLineSids = [];
  3623. foreach ($orderedSids as $sid) {
  3624. if (!isset($pickLinesMap[$sid])) {
  3625. continue;
  3626. }
  3627. $pickLines[] = $pickLinesMap[$sid];
  3628. $usedLineSids[$sid] = true;
  3629. }
  3630. foreach ($pickLinesMap as $sid => $ln) {
  3631. if (isset($usedLineSids[$sid])) {
  3632. continue;
  3633. }
  3634. $pickLines[] = $ln;
  3635. }
  3636. $groupTotal = 0.0;
  3637. $groupHasTotal = false;
  3638. if ($quoteVisible) {
  3639. foreach ($pickLines as $ln) {
  3640. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3641. $groupTotal += (float)$ln['subtotal_num'];
  3642. $groupHasTotal = true;
  3643. }
  3644. }
  3645. }
  3646. $lineCount = count($pickLines);
  3647. $g['pick_lines'] = $pickLines;
  3648. $g['line_count'] = $lineCount;
  3649. $g['has_total'] = $lineCount > 0;
  3650. $g['has_remark'] = $lineCount > 0;
  3651. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  3652. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3653. // 工序行 + 备注行 + 总计行
  3654. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  3655. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  3656. $detailPicks = [];
  3657. $usedPickSids = [];
  3658. foreach ($orderedSids as $sid) {
  3659. if (!isset($detailPicksMap[$sid])) {
  3660. continue;
  3661. }
  3662. $detailPicks[] = $detailPicksMap[$sid];
  3663. $usedPickSids[$sid] = true;
  3664. }
  3665. foreach ($detailPicksMap as $sid => $dp) {
  3666. if (isset($usedPickSids[$sid])) {
  3667. continue;
  3668. }
  3669. $detailPicks[] = $dp;
  3670. }
  3671. $g['detail_picks'] = $detailPicks;
  3672. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  3673. unset($g['detail_picks']);
  3674. $out[] = $g;
  3675. }
  3676. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3677. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  3678. }
  3679. /**
  3680. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  3681. * @return array<int, int[]> scydgy_id => detail_id[]
  3682. */
  3683. protected function mapDetailIdsByScydgyId(array $details): array
  3684. {
  3685. $out = [];
  3686. foreach ($details as $d) {
  3687. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3688. continue;
  3689. }
  3690. $sid = (int)($d['scydgy_id'] ?? 0);
  3691. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  3692. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  3693. continue;
  3694. }
  3695. if (!isset($out[$sid])) {
  3696. $out[$sid] = [];
  3697. }
  3698. $out[$sid][] = $pk;
  3699. }
  3700. foreach ($out as $sid => $ids) {
  3701. $out[$sid] = array_values(array_unique($ids));
  3702. }
  3703. return $out;
  3704. }
  3705. /**
  3706. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  3707. *
  3708. * @param array<string, mixed> $dbRow
  3709. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  3710. */
  3711. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  3712. {
  3713. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  3714. $r = [
  3715. 'ID' => $sid,
  3716. 'scydgy_id' => $sid,
  3717. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  3718. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  3719. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  3720. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  3721. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  3722. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  3723. 'CDW' => $dbRow['CDW'] ?? '',
  3724. 'czlyq' => $dbRow['czlyq'] ?? '',
  3725. 'NGZL' => $dbRow['NGZL'] ?? '',
  3726. 'CDF' => $dbRow['CDF'] ?? '',
  3727. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  3728. 'MBZ' => $dbRow['MBZ'] ?? '',
  3729. 'bwjg' => $dbRow['bwjg'] ?? '',
  3730. 'iStatus' => $dbRow['iStatus'] ?? '',
  3731. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  3732. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  3733. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  3734. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  3735. 'dStamp' => $dbRow['dStamp'] ?? '',
  3736. 'pick_time' => $dbRow['pick_time'] ?? '',
  3737. ];
  3738. $r['This_quantity'] = $this->resolveProcuremenThisQuantity($r);
  3739. $r['ceilingPrice'] = $this->resolveProcuremenCeilingPrice($r);
  3740. if ($sid > 0 && isset($dStampMap[$sid])) {
  3741. $t = trim((string)$dStampMap[$sid]);
  3742. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  3743. $r['dStamp'] = $dStampMap[$sid];
  3744. }
  3745. }
  3746. $dsOut = trim((string)($r['dStamp'] ?? ''));
  3747. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  3748. $ct = $dbRow['createtime'];
  3749. if (is_numeric($ct) && (int)$ct > 946684800) {
  3750. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  3751. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  3752. $r['dStamp'] = trim($ct);
  3753. }
  3754. }
  3755. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  3756. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  3757. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  3758. $fallback = trim((string)($r['dStamp'] ?? ''));
  3759. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  3760. $r['dputrecord'] = $fallback;
  3761. }
  3762. }
  3763. if (array_key_exists('id', $dbRow)) {
  3764. $r['purchase_order_id'] = (int)$dbRow['id'];
  3765. }
  3766. if ($sid < 0) {
  3767. $r['_is_manual'] = 1;
  3768. }
  3769. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  3770. $pickOut = trim((string)($r['pick_time'] ?? ''));
  3771. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  3772. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  3773. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  3774. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  3775. $r['pick_time'] = $pickFallback;
  3776. break;
  3777. }
  3778. }
  3779. }
  3780. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  3781. if ($pickNm !== '') {
  3782. $r['pick_company_name'] = $pickNm;
  3783. $r['picked_supplier_name'] = $pickNm;
  3784. }
  3785. return $r;
  3786. }
  3787. /**
  3788. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  3789. *
  3790. * @return array<int, array<string, mixed>>
  3791. */
  3792. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  3793. {
  3794. $pool = [];
  3795. if (!is_array($dbRows) || $dbRows === []) {
  3796. return $pool;
  3797. }
  3798. $dStampMap = [];
  3799. $sidList = [];
  3800. foreach ($dbRows as $tmpRow) {
  3801. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  3802. $sid = (int)$tmpRow['scydgy_id'];
  3803. if ($sid > 0) {
  3804. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  3805. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3806. $sidList[$sid] = true;
  3807. }
  3808. }
  3809. }
  3810. }
  3811. if ($sidList !== []) {
  3812. try {
  3813. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  3814. } catch (\Throwable $e) {
  3815. $dStampMap = [];
  3816. }
  3817. }
  3818. foreach ($dbRows as $dbRow) {
  3819. if (!is_array($dbRow)) {
  3820. continue;
  3821. }
  3822. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  3823. }
  3824. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  3825. $needCcydh = [];
  3826. foreach ($pool as $row) {
  3827. if (!is_array($row)) {
  3828. continue;
  3829. }
  3830. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3831. continue;
  3832. }
  3833. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3834. if ($ccydh !== '') {
  3835. $needCcydh[$ccydh] = true;
  3836. }
  3837. }
  3838. if ($needCcydh !== []) {
  3839. $czMap = [];
  3840. try {
  3841. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  3842. } catch (\Throwable $e) {
  3843. $czMap = [];
  3844. }
  3845. if (is_array($czMap) && $czMap !== []) {
  3846. foreach ($pool as &$row) {
  3847. if (!is_array($row)) {
  3848. continue;
  3849. }
  3850. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3851. continue;
  3852. }
  3853. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3854. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  3855. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  3856. }
  3857. }
  3858. unset($row);
  3859. }
  3860. }
  3861. return $pool;
  3862. }
  3863. /**
  3864. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  3865. *
  3866. * @param int[] $scydgyIds
  3867. * @return array<int, array<string, mixed>>
  3868. */
  3869. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  3870. {
  3871. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3872. if ($scydgyIds === []) {
  3873. return [];
  3874. }
  3875. try {
  3876. $list = Db::table('purchase_order_detail')
  3877. ->where('scydgy_id', 'in', $scydgyIds)
  3878. ->field('scydgy_id,company_name,amount,delivery')
  3879. ->select();
  3880. } catch (\Throwable $e) {
  3881. $list = [];
  3882. }
  3883. return is_array($list) ? $list : [];
  3884. }
  3885. /**
  3886. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  3887. *
  3888. * @param int[] $scydgyIds
  3889. * @param array<int, array<string, mixed>> $allRows
  3890. * @return array{cnt:int, amt:int, deliv:int}
  3891. */
  3892. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  3893. {
  3894. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3895. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3896. if ($scydgyIds === [] || $allRows === []) {
  3897. return $out;
  3898. }
  3899. $idSet = array_flip($scydgyIds);
  3900. $all = [];
  3901. $withAmt = [];
  3902. $withDeliv = [];
  3903. foreach ($allRows as $r) {
  3904. if (!is_array($r)) {
  3905. continue;
  3906. }
  3907. $sid = (int)($r['scydgy_id'] ?? 0);
  3908. if (!isset($idSet[$sid])) {
  3909. continue;
  3910. }
  3911. $cn = trim((string)($r['company_name'] ?? ''));
  3912. if ($cn === '') {
  3913. continue;
  3914. }
  3915. $all[$cn] = true;
  3916. $am = $r['amount'] ?? null;
  3917. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  3918. $withAmt[$cn] = true;
  3919. }
  3920. $dv = $r['delivery'] ?? null;
  3921. if ($dv !== null && trim((string)$dv) !== '') {
  3922. $withDeliv[$cn] = true;
  3923. }
  3924. }
  3925. return [
  3926. 'cnt' => count($all),
  3927. 'amt' => count($withAmt),
  3928. 'deliv' => count($withDeliv),
  3929. ];
  3930. }
  3931. /**
  3932. * 本次数量:优先 This_quantity,空则回退工作量 NGZL(与下发/确认/审批弹窗一致)
  3933. *
  3934. * @param array<string, mixed> $row
  3935. */
  3936. protected function resolveProcuremenThisQuantity(array $row): string
  3937. {
  3938. $q = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  3939. if ($q !== '') {
  3940. return $q;
  3941. }
  3942. $ngzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  3943. if (!is_scalar($ngzl)) {
  3944. return '';
  3945. }
  3946. $s = trim((string)$ngzl);
  3947. if ($s === '') {
  3948. return '';
  3949. }
  3950. if (is_numeric($s) && (float)$s === 0.0) {
  3951. return '';
  3952. }
  3953. return $s;
  3954. }
  3955. /**
  3956. * @param array<string, mixed> $row
  3957. */
  3958. protected function resolveProcuremenCeilingPrice(array $row): string
  3959. {
  3960. return trim((string)($row['ceilingPrice'] ?? $row['ceiling_price'] ?? ''));
  3961. }
  3962. /**
  3963. * 多工序数量/限价拼接:跳过空值,避免出现「、10」「304、」
  3964. *
  3965. * @param array<int, mixed> $parts
  3966. */
  3967. protected function joinProcuremenNonEmpty(array $parts, string $sep = '、'): string
  3968. {
  3969. $out = [];
  3970. foreach ($parts as $p) {
  3971. $s = trim((string)$p);
  3972. if ($s !== '') {
  3973. $out[] = $s;
  3974. }
  3975. }
  3976. return $out === [] ? '' : implode($sep, $out);
  3977. }
  3978. /**
  3979. * 确认/审批列表:合并行按各工序同步本次数量、最高限价(顿号间隔)
  3980. *
  3981. * @param array<int, array<string, mixed>> $rows
  3982. */
  3983. protected function syncCollapsedOrderQtyPriceForList(array &$rows): void
  3984. {
  3985. if ($rows === []) {
  3986. return;
  3987. }
  3988. $idList = [];
  3989. foreach ($rows as $rw) {
  3990. if (!is_array($rw)) {
  3991. continue;
  3992. }
  3993. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  3994. foreach ($rw['_order_merge_rows'] as $mr) {
  3995. if (!is_array($mr)) {
  3996. continue;
  3997. }
  3998. $mid = (int)($mr['ID'] ?? 0);
  3999. if ($this->isValidScydgyRowId($mid)) {
  4000. $idList[$mid] = true;
  4001. }
  4002. }
  4003. }
  4004. $id = (int)($rw['ID'] ?? 0);
  4005. if ($this->isValidScydgyRowId($id)) {
  4006. $idList[$id] = true;
  4007. }
  4008. }
  4009. if ($idList === []) {
  4010. return;
  4011. }
  4012. try {
  4013. $list = Db::table('purchase_order')
  4014. ->where('scydgy_id', 'in', array_keys($idList))
  4015. ->field('scydgy_id,This_quantity,ceilingPrice,NGZL,pick_company_name')
  4016. ->select();
  4017. } catch (\Throwable $e) {
  4018. return;
  4019. }
  4020. if (!is_array($list)) {
  4021. return;
  4022. }
  4023. $byId = [];
  4024. foreach ($list as $dbRow) {
  4025. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4026. continue;
  4027. }
  4028. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4029. }
  4030. foreach ($rows as &$rw) {
  4031. if (!is_array($rw)) {
  4032. continue;
  4033. }
  4034. $mergeRows = [];
  4035. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4036. $mergeRows = $rw['_order_merge_rows'];
  4037. } else {
  4038. $mergeRows = [$rw];
  4039. }
  4040. $qtyList = [];
  4041. $priceList = [];
  4042. $picked = '';
  4043. foreach ($mergeRows as $mr) {
  4044. if (!is_array($mr)) {
  4045. continue;
  4046. }
  4047. $sid = (int)($mr['ID'] ?? 0);
  4048. $db = ($sid !== 0 && isset($byId[$sid])) ? $byId[$sid] : null;
  4049. $src = $mr;
  4050. if (is_array($db)) {
  4051. $qDb = trim((string)($db['This_quantity'] ?? $db['this_quantity'] ?? ''));
  4052. $pDb = trim((string)($db['ceilingPrice'] ?? $db['ceiling_price'] ?? ''));
  4053. $ngzlDb = $db['NGZL'] ?? $db['ngzl'] ?? null;
  4054. if ($qDb !== '') {
  4055. $src['This_quantity'] = $qDb;
  4056. }
  4057. if ($pDb !== '') {
  4058. $src['ceilingPrice'] = $pDb;
  4059. }
  4060. if ($ngzlDb !== null && trim((string)$ngzlDb) !== '') {
  4061. $src['NGZL'] = $ngzlDb;
  4062. }
  4063. if ($picked === '') {
  4064. $picked = trim((string)($db['pick_company_name'] ?? ''));
  4065. }
  4066. }
  4067. if ($picked === '') {
  4068. $picked = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  4069. }
  4070. $qtyList[] = $this->resolveProcuremenThisQuantity($src);
  4071. $priceList[] = $this->resolveProcuremenCeilingPrice($src);
  4072. }
  4073. $rw['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  4074. $rw['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  4075. if ($picked !== '') {
  4076. $rw['pick_company_name'] = $picked;
  4077. $rw['picked_supplier_name'] = $picked;
  4078. }
  4079. }
  4080. unset($rw);
  4081. }
  4082. /**
  4083. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  4084. *
  4085. * @param int[] $scydgyIds
  4086. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  4087. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  4088. */
  4089. protected function OrderDetailSummary(array $scydgyIds)
  4090. {
  4091. $out = [];
  4092. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4093. if ($scydgyIds === []) {
  4094. return $out;
  4095. }
  4096. $list = [];
  4097. try {
  4098. $list = Db::table('purchase_order_detail')
  4099. ->where('scydgy_id', 'in', $scydgyIds)
  4100. ->field('id,scydgy_id,amount,delivery')
  4101. ->select();
  4102. } catch (\Throwable $e) {
  4103. $list = [];
  4104. }
  4105. if (!is_array($list)) {
  4106. return $out;
  4107. }
  4108. foreach ($list as $r) {
  4109. if (!is_array($r)) {
  4110. continue;
  4111. }
  4112. $ids = (int)($r['scydgy_id'] ?? 0);
  4113. if (!$this->isValidScydgyRowId($ids)) {
  4114. continue;
  4115. }
  4116. if (!isset($out[$ids])) {
  4117. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4118. }
  4119. $out[$ids]['cnt']++;
  4120. $am = $r['amount'] ?? null;
  4121. if ($am !== null && $am !== '') {
  4122. if (!(is_string($am) && trim($am) === '')) {
  4123. $out[$ids]['amt']++;
  4124. }
  4125. }
  4126. $dv = $r['delivery'] ?? null;
  4127. if ($dv !== null && trim((string)$dv) !== '') {
  4128. $out[$ids]['deliv']++;
  4129. }
  4130. }
  4131. return $out;
  4132. }
  4133. /**
  4134. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  4135. *
  4136. * @return array
  4137. */
  4138. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  4139. {
  4140. $strContains = function ($haystack, $needle) {
  4141. if ($needle === '') {
  4142. return false;
  4143. }
  4144. $haystack = (string)$haystack;
  4145. if (function_exists('mb_stripos')) {
  4146. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  4147. }
  4148. return stripos($haystack, $needle) !== false;
  4149. };
  4150. $stripAlias = function ($f) {
  4151. return preg_replace('/^[ab]\./i', '', (string)$f);
  4152. };
  4153. $searchColNames = [];
  4154. foreach (explode(',', $this->searchFields) as $colRaw) {
  4155. $c = $stripAlias(trim($colRaw));
  4156. if ($c !== '') {
  4157. $searchColNames[] = $c;
  4158. }
  4159. }
  4160. // 等值条件先行(表头下拉),减少后续日期解析量
  4161. $eqFilters = [];
  4162. $otherFilters = [];
  4163. foreach ($filterArr as $fk => $fv) {
  4164. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  4165. continue;
  4166. }
  4167. if (is_array($fv)) {
  4168. continue;
  4169. }
  4170. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  4171. continue;
  4172. }
  4173. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  4174. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  4175. $field = $stripAlias($fk);
  4176. if ($sym === '=' || $sym === '') {
  4177. $eqFilters[$field] = trim((string)$fv);
  4178. } else {
  4179. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  4180. }
  4181. }
  4182. $ymTarget = '';
  4183. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  4184. $ymTarget = $ymM[1];
  4185. }
  4186. $filtered = [];
  4187. foreach ($pool as $r) {
  4188. if (!is_array($r)) {
  4189. continue;
  4190. }
  4191. foreach ($eqFilters as $field => $fv) {
  4192. if (trim((string)($r[$field] ?? '')) !== $fv) {
  4193. continue 2;
  4194. }
  4195. }
  4196. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  4197. // 初选池不应含手工单;若混入则直接剔除
  4198. if ($isManual) {
  4199. continue;
  4200. }
  4201. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  4202. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  4203. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  4204. continue;
  4205. }
  4206. if ($applyMonthRange) {
  4207. $mo = (int)$m[2];
  4208. if ($mo < 1 || $mo > 12) {
  4209. continue;
  4210. }
  4211. if ($ymTarget !== '') {
  4212. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4213. if ($ymRow !== $ymTarget) {
  4214. continue;
  4215. }
  4216. } else {
  4217. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4218. $rowMonthStart = $ymRow . '-01 00:00:00';
  4219. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  4220. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  4221. continue;
  4222. }
  4223. }
  4224. }
  4225. if ($search !== '') {
  4226. $hitSearch = false;
  4227. foreach ($searchColNames as $c) {
  4228. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  4229. if ($cell !== '' && $strContains($cell, $search)) {
  4230. $hitSearch = true;
  4231. break;
  4232. }
  4233. }
  4234. if (!$hitSearch) {
  4235. continue;
  4236. }
  4237. }
  4238. foreach ($otherFilters as $item) {
  4239. $fv = $item['fv'];
  4240. $sym = $item['sym'];
  4241. $field = $item['field'];
  4242. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  4243. $cellStr = trim((string)$cell);
  4244. switch ($sym) {
  4245. case '<>':
  4246. if ((string)$cell === (string)$fv) {
  4247. continue 3;
  4248. }
  4249. break;
  4250. case 'LIKE':
  4251. case 'NOT LIKE':
  4252. $needle = trim((string)$fv);
  4253. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  4254. if ($sym === 'LIKE' && !$hit) {
  4255. continue 3;
  4256. }
  4257. if ($sym === 'NOT LIKE' && $hit) {
  4258. continue 3;
  4259. }
  4260. break;
  4261. case 'BETWEEN':
  4262. case 'RANGE':
  4263. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  4264. if (count($parts) < 2) {
  4265. $parts = is_string($fv) ? explode(',', $fv) : [];
  4266. }
  4267. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  4268. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  4269. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  4270. continue 3;
  4271. }
  4272. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  4273. continue 3;
  4274. }
  4275. break;
  4276. case '>':
  4277. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  4278. continue 3;
  4279. }
  4280. break;
  4281. case '>=':
  4282. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  4283. continue 3;
  4284. }
  4285. break;
  4286. case '<':
  4287. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  4288. continue 3;
  4289. }
  4290. break;
  4291. case '<=':
  4292. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  4293. continue 3;
  4294. }
  4295. break;
  4296. default:
  4297. if ((string)$cell !== (string)$fv) {
  4298. continue 3;
  4299. }
  4300. break;
  4301. }
  4302. }
  4303. $filtered[] = $r;
  4304. }
  4305. return $filtered;
  4306. }
  4307. /**
  4308. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  4309. */
  4310. public function snapshotToProcure()
  4311. {
  4312. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4313. $this->error(__('Invalid parameters'));
  4314. }
  4315. $row = json_decode($this->request->post('row_json', ''), true);
  4316. if (!is_array($row)) {
  4317. $this->error(__('Invalid parameters'));
  4318. }
  4319. try {
  4320. $ids = $this->extractScydgyRowId($row);
  4321. if (!$this->isValidScydgyRowId($ids)) {
  4322. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4323. }
  4324. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4325. $data = [
  4326. 'scydgy_id' => $ids,
  4327. 'CCYDH' => $row['CCYDH'] ?? null,
  4328. 'CYJMC' => $row['CYJMC'] ?? null,
  4329. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4330. 'CDXMC' => $row['CDXMC'] ?? null,
  4331. 'CGYBH' => $row['CGYBH'] ?? null,
  4332. 'CGYMC' => $row['CGYMC'] ?? null,
  4333. 'CDW' => $row['CDW'] ?? null,
  4334. 'czlyq' => $row['czlyq'] ?? null,
  4335. 'NGZL' => $row['NGZL'] ?? null,
  4336. 'CDF' => $row['CDF'] ?? null,
  4337. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4338. 'MBZ' => $row['MBZ'] ?? null,
  4339. 'bwjg' => $row['bwjg'] ?? null,
  4340. 'iStatus' => $row['iStatus'] ?? null,
  4341. 'dStamp' => $row['dStamp'] ?? null,
  4342. 'dputrecord' => $row['dputrecord'] ?? null,
  4343. 'cywyxm' => $row['cywyxm'] ?? null,
  4344. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4345. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4346. ];
  4347. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  4348. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  4349. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  4350. $this->success('操作成功');
  4351. return;
  4352. }
  4353. if ($exists) {
  4354. $upd = $data;
  4355. unset($upd['scydgy_id'], $upd['status']);
  4356. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4357. } else {
  4358. // 新增:不写 status(空/走库默认);仅写创建时间
  4359. $data['createtime'] = date('Y-m-d H:i:s');
  4360. Db::table('purchase_order')->insert($data);
  4361. }
  4362. } catch (\Throwable $e) {
  4363. $this->error($e->getMessage());
  4364. }
  4365. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  4366. $this->success('操作成功');
  4367. }
  4368. /**
  4369. * 未发列表
  4370. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  4371. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  4372. */
  4373. public function completeDirectly()
  4374. {
  4375. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4376. $this->error(__('参数错误'));
  4377. }
  4378. if (!$this->procuremenCanComplete()) {
  4379. $this->error(__('You have no permission'));
  4380. }
  4381. $row = json_decode($this->request->post('row_json', ''), true);
  4382. if (!is_array($row)) {
  4383. $this->error(__('Invalid parameters'));
  4384. }
  4385. $finishRaw = $this->request->post('finish', '1');
  4386. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  4387. $poIdLog = null;
  4388. try {
  4389. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  4390. $ids = $this->extractScydgyRowId($row);
  4391. if (!$this->isValidScydgyRowId($ids)) {
  4392. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4393. }
  4394. if ($asComplete) {
  4395. $this->assertPickRowCanComplete($ids, $row);
  4396. }
  4397. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4398. $data = [
  4399. 'scydgy_id' => $ids,
  4400. 'CCYDH' => $row['CCYDH'] ?? null,
  4401. 'CYJMC' => $row['CYJMC'] ?? null,
  4402. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4403. 'CDXMC' => $row['CDXMC'] ?? null,
  4404. 'CGYBH' => $row['CGYBH'] ?? null,
  4405. 'CGYMC' => $row['CGYMC'] ?? null,
  4406. 'CDW' => $row['CDW'] ?? null,
  4407. 'czlyq' => $row['czlyq'] ?? null,
  4408. 'NGZL' => $row['NGZL'] ?? null,
  4409. 'CDF' => $row['CDF'] ?? null,
  4410. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4411. 'MBZ' => $row['MBZ'] ?? null,
  4412. 'bwjg' => $row['bwjg'] ?? null,
  4413. 'iStatus' => $row['iStatus'] ?? null,
  4414. 'dStamp' => $row['dStamp'] ?? null,
  4415. 'dputrecord' => $row['dputrecord'] ?? null,
  4416. 'cywyxm' => $row['cywyxm'] ?? null,
  4417. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4418. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4419. ];
  4420. if ($asComplete) {
  4421. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  4422. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  4423. }
  4424. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  4425. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  4426. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  4427. $this->success('操作成功');
  4428. return;
  4429. }
  4430. if ($exists) {
  4431. $upd = $data;
  4432. unset($upd['scydgy_id']);
  4433. if (!$asComplete) {
  4434. unset($upd['status']);
  4435. }
  4436. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4437. } else {
  4438. // 新增:不写 status;完结时 $data 已含 status=1
  4439. $data['createtime'] = date('Y-m-d H:i:s');
  4440. Db::table('purchase_order')->insert($data);
  4441. }
  4442. } catch (\Throwable $e) {
  4443. $this->error($e->getMessage());
  4444. }
  4445. try {
  4446. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4447. if (is_array($rpo)) {
  4448. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4449. $poIdLog = $tid > 0 ? $tid : null;
  4450. }
  4451. } catch (\Throwable $e) {
  4452. $poIdLog = null;
  4453. }
  4454. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  4455. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  4456. if ($asComplete) {
  4457. $this->addOrderLog(
  4458. $ids,
  4459. 'mark_complete',
  4460. '点击「完结」,已标记为已完结',
  4461. $poIdLog
  4462. );
  4463. try {
  4464. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  4465. if ($pdfPublicPath === '') {
  4466. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  4467. }
  4468. } catch (\Throwable $e) {
  4469. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  4470. }
  4471. } else {
  4472. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  4473. $qtyPart = '本次数量「' . ($q !== '' ? $q : '') . '」';
  4474. $pricePart = '最高限价「' . ($p !== '' ? $p : '') . '」';
  4475. $detail = ($gymc !== '' ? ($gymc . $qtyPart) : $qtyPart) . ',' . $pricePart;
  4476. $this->addOrderLog(
  4477. $ids,
  4478. 'save_qty_price',
  4479. '保存本次数量、最高限价:' . $detail,
  4480. $poIdLog
  4481. );
  4482. }
  4483. $this->pickHiddenScydgySetCache = null;
  4484. $this->success("操作成功");
  4485. }
  4486. /**
  4487. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  4488. *
  4489. * @param array<int, array> $rows 引用传递当前页行
  4490. */
  4491. protected function mergePurchaseOrder(array &$rows)
  4492. {
  4493. if ($rows === []) {
  4494. return;
  4495. }
  4496. $ids = [];
  4497. foreach ($rows as $rw) {
  4498. if (!is_array($rw)) {
  4499. continue;
  4500. }
  4501. $id = (int)($rw['ID'] ?? 0);
  4502. // 含手工新增负数 scydgy_id,避免限价/数量不同步
  4503. if ($this->isValidScydgyRowId($id)) {
  4504. $ids[$id] = true;
  4505. }
  4506. }
  4507. $idList = array_keys($ids);
  4508. if ($idList === []) {
  4509. return;
  4510. }
  4511. try {
  4512. $list = Db::table('purchase_order')
  4513. ->where('scydgy_id', 'in', $idList)
  4514. ->field('scydgy_id,This_quantity,ceilingPrice')
  4515. ->select();
  4516. } catch (\Throwable $e) {
  4517. return;
  4518. }
  4519. if (!is_array($list)) {
  4520. return;
  4521. }
  4522. $byId = [];
  4523. foreach ($list as $dbRow) {
  4524. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4525. continue;
  4526. }
  4527. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4528. }
  4529. foreach ($rows as &$rw) {
  4530. if (!is_array($rw)) {
  4531. continue;
  4532. }
  4533. $sid = (int)($rw['ID'] ?? 0);
  4534. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  4535. continue;
  4536. }
  4537. $db = $byId[$sid];
  4538. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  4539. if (array_key_exists('This_quantity', $db)) {
  4540. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  4541. }
  4542. if (array_key_exists('ceilingPrice', $db)) {
  4543. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  4544. } elseif (array_key_exists('ceiling_price', $db)) {
  4545. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  4546. }
  4547. }
  4548. unset($rw);
  4549. }
  4550. /**
  4551. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  4552. */
  4553. public function purchaseConfirmPick()
  4554. {
  4555. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4556. $this->error(__('Invalid parameters'));
  4557. }
  4558. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  4559. $this->error(__('You have no permission'));
  4560. }
  4561. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  4562. if ($batchRaw !== '') {
  4563. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  4564. return;
  4565. }
  4566. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  4567. $sid = (int)$scydgyId;
  4568. if (!$this->isValidScydgyRowId($sid)) {
  4569. $this->error('参数无效');
  4570. }
  4571. $parseIdList = function ($raw) {
  4572. if (is_array($raw)) {
  4573. $arr = $raw;
  4574. } else {
  4575. $decoded = json_decode((string)$raw, true);
  4576. $arr = is_array($decoded) ? $decoded : [];
  4577. }
  4578. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  4579. };
  4580. $selectedRaw = $this->request->post('selected_ids', null);
  4581. if ($selectedRaw === null || $selectedRaw === '') {
  4582. $legacy = (int)$this->request->post('selected_id', 0);
  4583. $selectedIds = $legacy > 0 ? [$legacy] : [];
  4584. } else {
  4585. $selectedIds = $parseIdList($selectedRaw);
  4586. }
  4587. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  4588. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  4589. try {
  4590. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  4591. } catch (\InvalidArgumentException $e) {
  4592. $this->error($e->getMessage());
  4593. } catch (\Throwable $e) {
  4594. $this->error($e->getMessage());
  4595. }
  4596. $this->pickHiddenScydgySetCache = null;
  4597. $this->success('操作成功', '', $result);
  4598. }
  4599. /**
  4600. * 整单采购确认(多道工序一次提交)
  4601. */
  4602. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  4603. {
  4604. $decoded = json_decode($batchRaw, true);
  4605. if (!is_array($decoded) || $decoded === []) {
  4606. $this->error('提交数据无效');
  4607. }
  4608. $picks = [];
  4609. foreach ($decoded as $item) {
  4610. if (!is_array($item)) {
  4611. continue;
  4612. }
  4613. $sid = (int)($item['scydgy_id'] ?? 0);
  4614. if (!$this->isValidScydgyRowId($sid)) {
  4615. continue;
  4616. }
  4617. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  4618. if (!is_array($sel)) {
  4619. $sel = [(int)$sel];
  4620. }
  4621. $unsel = $item['unselected_ids'] ?? [];
  4622. if (!is_array($unsel)) {
  4623. $unsel = json_decode((string)$unsel, true);
  4624. $unsel = is_array($unsel) ? $unsel : [];
  4625. }
  4626. $picks[] = [
  4627. 'scydgy_id' => $sid,
  4628. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  4629. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  4630. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  4631. ];
  4632. }
  4633. if ($picks === []) {
  4634. $this->error('提交数据无效');
  4635. }
  4636. Db::startTrans();
  4637. $results = [];
  4638. try {
  4639. foreach ($picks as $pick) {
  4640. $results[] = $this->runPurchaseConfirmPick(
  4641. (int)$pick['scydgy_id'],
  4642. $pick['selected_ids'],
  4643. $pick['unselected_ids'],
  4644. (int)$pick['purchase_order_id'],
  4645. false,
  4646. false
  4647. );
  4648. }
  4649. Db::commit();
  4650. } catch (\Throwable $e) {
  4651. Db::rollback();
  4652. $msg = $e->getMessage();
  4653. $this->error($msg !== '' ? $msg : '提交失败');
  4654. }
  4655. try {
  4656. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  4657. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  4658. } catch (\Throwable $e) {
  4659. Log::write('采购确认短信批量发送异常: ' . $e->getMessage(), 'error');
  4660. }
  4661. $this->pickHiddenScydgySetCache = null;
  4662. $this->success('操作成功', '', ['batch' => $results]);
  4663. }
  4664. /**
  4665. * @return array<string, mixed>
  4666. */
  4667. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  4668. {
  4669. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  4670. ProcuremenGuard::assertWflowPendingApproval($poRow);
  4671. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  4672. $scydgyId = (string)$sid;
  4673. if ($selectedIds === []) {
  4674. throw new \InvalidArgumentException('请至少勾选一条明细');
  4675. }
  4676. $inter = array_intersect($selectedIds, $unselectedIds);
  4677. if ($inter !== []) {
  4678. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  4679. }
  4680. $allIds = $this->purchaseOrderDetail($sid);
  4681. if ($allIds === []) {
  4682. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  4683. }
  4684. foreach ($selectedIds as $id) {
  4685. if (!in_array($id, $allIds, true)) {
  4686. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  4687. }
  4688. }
  4689. foreach ($unselectedIds as $id) {
  4690. if (!in_array($id, $allIds, true)) {
  4691. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  4692. }
  4693. }
  4694. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  4695. sort($union, SORT_NUMERIC);
  4696. $expect = $allIds;
  4697. sort($expect, SORT_NUMERIC);
  4698. if ($union !== $expect) {
  4699. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  4700. }
  4701. if ($manageTransaction) {
  4702. Db::startTrans();
  4703. }
  4704. try {
  4705. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  4706. $aff = 0;
  4707. try {
  4708. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4709. } catch (\Throwable $e) {
  4710. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4711. }
  4712. if ($aff < 1) {
  4713. throw new \Exception('更新选中状态失败');
  4714. }
  4715. $poPayload = [
  4716. // 审核通过后进入「待入库评分」;合格/不合格后才置已完结
  4717. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  4718. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  4719. ];
  4720. if ($purchaseOrderId > 0) {
  4721. $poAff = (int)Db::table('purchase_order')
  4722. ->where('id', $purchaseOrderId)
  4723. ->where('scydgy_id', $sid)
  4724. ->update($poPayload);
  4725. if ($poAff < 1) {
  4726. throw new \Exception('主表订单不存在或与工序行不匹配');
  4727. }
  4728. } else {
  4729. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  4730. if ($poAff < 1) {
  4731. throw new \Exception('未找到');
  4732. }
  4733. }
  4734. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  4735. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  4736. if ($manageTransaction) {
  4737. Db::commit();
  4738. }
  4739. } catch (\Throwable $e) {
  4740. if ($manageTransaction) {
  4741. Db::rollback();
  4742. }
  4743. throw $e;
  4744. }
  4745. $poIdFinal = $purchaseOrderId;
  4746. if ($poIdFinal <= 0) {
  4747. try {
  4748. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4749. if (is_array($rpo)) {
  4750. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4751. }
  4752. } catch (\Throwable $e) {
  4753. $poIdFinal = 0;
  4754. }
  4755. }
  4756. $pickNames = [];
  4757. foreach ($selectedIds as $pid) {
  4758. $dr = $this->purchaseOrderDetai($sid, $pid);
  4759. $nm = trim((string)($dr['company_name'] ?? ''));
  4760. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  4761. }
  4762. $this->addOrderLog(
  4763. $sid,
  4764. 'purchase_confirm',
  4765. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  4766. $poIdFinal > 0 ? $poIdFinal : null
  4767. );
  4768. if ($sendNotifications) {
  4769. try {
  4770. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  4771. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  4772. 'scydgy_id' => $sid,
  4773. 'selected_ids' => $selectedIds,
  4774. 'unselected_ids' => $unselectedIds,
  4775. 'purchase_order_id' => $purchaseOrderId,
  4776. ]]);
  4777. } catch (\Throwable $e) {
  4778. Log::write('采购确认短信发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  4779. }
  4780. }
  4781. Log::write(sprintf(
  4782. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  4783. $scydgyId,
  4784. $purchaseOrderId,
  4785. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  4786. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  4787. ), 'notice');
  4788. $pdfPublicPath = '';
  4789. try {
  4790. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  4791. } catch (\Throwable $e) {
  4792. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  4793. }
  4794. return [
  4795. 'scydgy_id' => $scydgyId,
  4796. 'purchase_order_id' => $purchaseOrderId,
  4797. 'selected_ids' => $selectedIds,
  4798. 'unselected_ids' => $unselectedIds,
  4799. 'purchase_confirm_pdf' => $pdfPublicPath,
  4800. ];
  4801. }
  4802. /**
  4803. * 审批通过短信:按本次涉及的工序汇总 process_lines
  4804. *
  4805. * @param int[]|string[] $scydgyIds
  4806. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4807. */
  4808. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  4809. {
  4810. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4811. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4812. if ($scydgyIds === []) {
  4813. return $empty;
  4814. }
  4815. $pos = [];
  4816. try {
  4817. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  4818. } catch (\Throwable $e) {
  4819. $rows = [];
  4820. }
  4821. if (is_array($rows)) {
  4822. foreach ($rows as $po) {
  4823. if (is_array($po)) {
  4824. $pos[] = $po;
  4825. }
  4826. }
  4827. }
  4828. if ($pos === []) {
  4829. return $empty;
  4830. }
  4831. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  4832. return [
  4833. 'ccydh' => $ccydh,
  4834. 'pos' => $pos,
  4835. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4836. ];
  4837. }
  4838. /**
  4839. * 审批通过/未通过短信:同一供应商只发一条,process_lines 含本次全部工序
  4840. *
  4841. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  4842. * @param array<int, array<string, mixed>> $picks
  4843. */
  4844. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  4845. {
  4846. if ($picks === []) {
  4847. return;
  4848. }
  4849. $fallbackDetailId = 0;
  4850. $winners = [];
  4851. $losers = [];
  4852. foreach ($picks as $pick) {
  4853. if (!is_array($pick)) {
  4854. continue;
  4855. }
  4856. $sid = (int)($pick['scydgy_id'] ?? 0);
  4857. if (!$this->isValidScydgyRowId($sid)) {
  4858. continue;
  4859. }
  4860. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  4861. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  4862. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  4863. $fallbackDetailId = (int)$selectedIds[0];
  4864. }
  4865. foreach ($selectedIds as $pid) {
  4866. $dr = $this->purchaseOrderDetai($sid, $pid);
  4867. if (!is_array($dr)) {
  4868. continue;
  4869. }
  4870. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  4871. }
  4872. foreach ($unselectedIds as $pid) {
  4873. $dr = $this->purchaseOrderDetai($sid, $pid);
  4874. if (!is_array($dr)) {
  4875. continue;
  4876. }
  4877. $key = $this->notifySupplierDedupeKey($dr);
  4878. if (!isset($winners[$key])) {
  4879. $losers[$key] = $dr;
  4880. }
  4881. }
  4882. }
  4883. if ($winners === [] && $losers === []) {
  4884. return;
  4885. }
  4886. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  4887. $sendSmsSafe = function ($phone, $content) {
  4888. $phone = trim((string)$phone);
  4889. if ($phone === '') {
  4890. return;
  4891. }
  4892. try {
  4893. $this->smsbao($phone, $content);
  4894. } catch (\Throwable $e) {
  4895. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  4896. }
  4897. };
  4898. foreach ($winners as $dr) {
  4899. $cname = trim((string)($dr['company_name'] ?? ''));
  4900. $ph = trim((string)($dr['phone'] ?? ''));
  4901. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  4902. 'company_name' => $cname,
  4903. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4904. 'phone' => $ph,
  4905. ]));
  4906. $sendSmsSafe($ph, $sms);
  4907. }
  4908. foreach ($losers as $dr) {
  4909. $cname = trim((string)($dr['company_name'] ?? ''));
  4910. $ph = trim((string)($dr['phone'] ?? ''));
  4911. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  4912. 'company_name' => $cname,
  4913. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4914. 'phone' => $ph,
  4915. ]));
  4916. $sendSmsSafe($ph, $sms);
  4917. }
  4918. }
  4919. /**
  4920. * 短信去重键:优先手机号,否则公司名
  4921. */
  4922. protected function notifySupplierDedupeKey(array $detailRow): string
  4923. {
  4924. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  4925. if ($ph !== '') {
  4926. return 'p:' . $ph;
  4927. }
  4928. $cn = trim((string)($detailRow['company_name'] ?? ''));
  4929. return 'c:' . $cn;
  4930. }
  4931. /**
  4932. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  4933. *
  4934. * @param int[] $detailIds
  4935. */
  4936. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  4937. {
  4938. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  4939. if ($detailIds === []) {
  4940. return;
  4941. }
  4942. $payload = ['status_name' => $statusName];
  4943. try {
  4944. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  4945. } catch (\Throwable $e) {
  4946. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  4947. }
  4948. }
  4949. /**
  4950. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  4951. */
  4952. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  4953. {
  4954. try {
  4955. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  4956. } catch (\Throwable $e) {
  4957. return;
  4958. }
  4959. if (!is_array($rows)) {
  4960. return;
  4961. }
  4962. foreach ($rows as $dr) {
  4963. if (!is_array($dr)) {
  4964. continue;
  4965. }
  4966. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  4967. if ($id <= 0) {
  4968. continue;
  4969. }
  4970. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  4971. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  4972. try {
  4973. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  4974. } catch (\Throwable $e) {
  4975. }
  4976. }
  4977. }
  4978. /**
  4979. * @param array<string, mixed> $detailRow
  4980. */
  4981. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  4982. {
  4983. $am = $detailRow['amount'] ?? null;
  4984. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  4985. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  4986. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  4987. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  4988. }
  4989. /**
  4990. * @return int[]
  4991. */
  4992. protected function purchaseOrderDetail(int $scydgyId): array
  4993. {
  4994. if (!$this->isValidScydgyRowId($scydgyId)) {
  4995. return [];
  4996. }
  4997. try {
  4998. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  4999. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  5000. $list = $listQuery->select();
  5001. } catch (\Throwable $e) {
  5002. return [];
  5003. }
  5004. if (!is_array($list)) {
  5005. return [];
  5006. }
  5007. $ids = [];
  5008. foreach ($list as $r) {
  5009. if (!is_array($r)) {
  5010. continue;
  5011. }
  5012. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  5013. if ($pk > 0) {
  5014. $ids[] = $pk;
  5015. }
  5016. }
  5017. return array_values(array_unique($ids));
  5018. }
  5019. /**
  5020. * 获取当前登录用户信息 [id, 展示名]
  5021. */
  5022. protected function GetUseName(): array
  5023. {
  5024. $id = 0;
  5025. $name = '';
  5026. try {
  5027. if ($this->auth && $this->auth->isLogin()) {
  5028. $u = $this->auth->getUserInfo();
  5029. if (is_array($u)) {
  5030. $id = (int)($u['id'] ?? 0);
  5031. $name = trim((string)($u['nickname'] ?? ''));
  5032. if ($name === '') {
  5033. $name = trim((string)($u['username'] ?? ''));
  5034. }
  5035. }
  5036. }
  5037. } catch (\Throwable $e) {
  5038. }
  5039. if ($name === '') {
  5040. $name = '未知用户';
  5041. }
  5042. return [$id, $name];
  5043. }
  5044. /**
  5045. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  5046. */
  5047. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  5048. {
  5049. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  5050. }
  5051. /**
  5052. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  5053. *
  5054. * @param array<int, array<string, mixed>> $rows
  5055. */
  5056. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  5057. {
  5058. $sidList = [];
  5059. foreach ($rows as $rw) {
  5060. if (!is_array($rw)) {
  5061. continue;
  5062. }
  5063. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5064. foreach ($rw['_order_merge_rows'] as $mr) {
  5065. $mid = (int)($mr['ID'] ?? 0);
  5066. if ($this->isValidScydgyRowId($mid)) {
  5067. $sidList[$mid] = true;
  5068. }
  5069. }
  5070. }
  5071. $id = (int)($rw['ID'] ?? 0);
  5072. if ($this->isValidScydgyRowId($id)) {
  5073. $sidList[$id] = true;
  5074. }
  5075. }
  5076. $sids = array_keys($sidList);
  5077. $issueBySid = [];
  5078. $confirmBySid = [];
  5079. $approveBySid = [];
  5080. if ($sids !== []) {
  5081. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  5082. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  5083. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  5084. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  5085. try {
  5086. $logs = Db::table('purchase_order_oper_log')
  5087. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  5088. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  5089. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  5090. ->order('id', 'asc')
  5091. ->select();
  5092. } catch (\Throwable $e) {
  5093. $logs = [];
  5094. }
  5095. if (is_array($logs)) {
  5096. $issueSet = array_fill_keys($issueActs, true);
  5097. $confirmSet = array_fill_keys($confirmActs, true);
  5098. $approveSet = array_fill_keys($approveActs, true);
  5099. foreach ($logs as $lg) {
  5100. if (!is_array($lg)) {
  5101. continue;
  5102. }
  5103. $lg = ProcuremenOperLog::normalizeRow($lg);
  5104. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  5105. if ($sid === 0) {
  5106. continue;
  5107. }
  5108. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  5109. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  5110. if ($t === '') {
  5111. continue;
  5112. }
  5113. if (isset($issueSet[$action])) {
  5114. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  5115. $issueBySid[$sid] = $t;
  5116. }
  5117. }
  5118. if (isset($confirmSet[$action])) {
  5119. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  5120. $confirmBySid[$sid] = $t;
  5121. }
  5122. }
  5123. if (isset($approveSet[$action])) {
  5124. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  5125. $approveBySid[$sid] = $t;
  5126. }
  5127. }
  5128. }
  5129. }
  5130. }
  5131. foreach ($rows as &$rw) {
  5132. if (!is_array($rw)) {
  5133. continue;
  5134. }
  5135. $mergeSids = [];
  5136. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5137. foreach ($rw['_order_merge_rows'] as $mr) {
  5138. $mid = (int)($mr['ID'] ?? 0);
  5139. if ($this->isValidScydgyRowId($mid)) {
  5140. $mergeSids[] = $mid;
  5141. }
  5142. }
  5143. }
  5144. $rid = (int)($rw['ID'] ?? 0);
  5145. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  5146. $mergeSids[] = $rid;
  5147. }
  5148. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  5149. $issue = $pick;
  5150. $confirm = '';
  5151. $approve = '';
  5152. foreach ($mergeSids as $sid) {
  5153. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  5154. $issue = $issueBySid[$sid];
  5155. }
  5156. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  5157. $confirm = $confirmBySid[$sid];
  5158. }
  5159. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  5160. $approve = $approveBySid[$sid];
  5161. }
  5162. }
  5163. if ($issue === '' && $pick !== '') {
  5164. $issue = $pick;
  5165. }
  5166. $rw['issue_time'] = $issue;
  5167. $rw['confirm_time'] = $confirm;
  5168. $rw['approve_time'] = $approve;
  5169. }
  5170. unset($rw);
  5171. }
  5172. /**
  5173. * 按主键取一条
  5174. */
  5175. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  5176. {
  5177. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  5178. return [];
  5179. }
  5180. try {
  5181. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  5182. if (is_array($one)) {
  5183. return $one;
  5184. }
  5185. } catch (\Throwable $e) {
  5186. }
  5187. try {
  5188. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  5189. if (is_array($one)) {
  5190. return $one;
  5191. }
  5192. } catch (\Throwable $e) {
  5193. }
  5194. return [];
  5195. }
  5196. /**
  5197. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  5198. */
  5199. protected function formatProcuremenDetailTime($v): string
  5200. {
  5201. if ($v === null || $v === '') {
  5202. return '';
  5203. }
  5204. if (is_numeric($v) && (int)$v > 946684800) {
  5205. return date('Y-m-d H:i:s', (int)$v);
  5206. }
  5207. return ProcuremenTime::formatDisplayDateTime($v);
  5208. }
  5209. /**
  5210. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  5211. */
  5212. protected function formatDeliveryYmd($v): string
  5213. {
  5214. if ($v === null || $v === '') {
  5215. return '';
  5216. }
  5217. $s = trim((string)$v);
  5218. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  5219. return '';
  5220. }
  5221. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5222. return $m[1];
  5223. }
  5224. $ts = strtotime($s);
  5225. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  5226. }
  5227. /**
  5228. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  5229. */
  5230. protected function detailRowSupplierOperated(array $r): bool
  5231. {
  5232. $am = $r['amount'] ?? null;
  5233. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5234. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5235. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5236. return $okAmt || $okDel;
  5237. }
  5238. /**
  5239. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  5240. */
  5241. protected function resolveDetailSupplierOperTime(array $r): string
  5242. {
  5243. if (!$this->detailRowSupplierOperated($r)) {
  5244. return '';
  5245. }
  5246. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  5247. if ($t !== '') {
  5248. return $t;
  5249. }
  5250. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  5251. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  5252. continue;
  5253. }
  5254. $t = $this->formatProcuremenDetailTime($r[$col]);
  5255. if ($t !== '') {
  5256. return $t;
  5257. }
  5258. }
  5259. return '';
  5260. }
  5261. /**
  5262. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  5263. */
  5264. protected function detailRowSupplierAccepted(array $r): bool
  5265. {
  5266. $am = $r['amount'] ?? null;
  5267. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5268. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5269. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5270. return $okAmt && $okDel;
  5271. }
  5272. /**
  5273. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  5274. */
  5275. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  5276. {
  5277. if ($detailCount > 0) {
  5278. return true;
  5279. }
  5280. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  5281. return true;
  5282. }
  5283. $pickTime = trim((string)($main['pick_time'] ?? ''));
  5284. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  5285. return true;
  5286. }
  5287. return false;
  5288. }
  5289. /**
  5290. * 下发时间:优先 pick_time,其次首条下发明细时间
  5291. */
  5292. protected function resolveProcuremenIssueTime(array $main, array $details): string
  5293. {
  5294. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  5295. if ($issueTime !== '') {
  5296. return $issueTime;
  5297. }
  5298. foreach ($details as $dr) {
  5299. if (!is_array($dr)) {
  5300. continue;
  5301. }
  5302. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5303. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  5304. $issueTime = $t;
  5305. }
  5306. }
  5307. if ($issueTime !== '') {
  5308. return $issueTime;
  5309. }
  5310. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5311. }
  5312. /**
  5313. * 直接点「完结」时间:优先操作记录 mark_complete
  5314. */
  5315. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  5316. {
  5317. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  5318. }
  5319. /**
  5320. * 操作记录时间(取指定 action 最近一条)
  5321. *
  5322. * @param string|array<int, string> $actions
  5323. */
  5324. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  5325. {
  5326. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  5327. }
  5328. /**
  5329. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  5330. *
  5331. * @param array $main purchase_order 一行
  5332. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  5333. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  5334. */
  5335. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  5336. {
  5337. $issueCnt = count($details);
  5338. $acceptCnt = 0;
  5339. $pickedName = '';
  5340. $pickedTime = '';
  5341. foreach ($details as $dr) {
  5342. if (!is_array($dr)) {
  5343. continue;
  5344. }
  5345. if ($this->detailRowSupplierAccepted($dr)) {
  5346. $acceptCnt++;
  5347. }
  5348. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5349. if ($pickedName === '') {
  5350. $pickedName = trim((string)($dr['company_name'] ?? ''));
  5351. }
  5352. if ($pickedTime === '') {
  5353. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  5354. if ($pickedTime === '') {
  5355. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5356. }
  5357. }
  5358. }
  5359. }
  5360. $hasMain = $main !== [];
  5361. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  5362. if ($poTime === '') {
  5363. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  5364. }
  5365. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  5366. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  5367. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  5368. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  5369. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  5370. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  5371. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  5372. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  5373. $inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
  5374. $inboundResult = '';
  5375. if ($scydgyId > 0) {
  5376. try {
  5377. $inRow = Db::table('purchase_order_inbound_score')
  5378. ->where('scydgy_id', $scydgyId)
  5379. ->field('result,updatetime,createtime')
  5380. ->find();
  5381. } catch (\Throwable $e) {
  5382. $inRow = null;
  5383. }
  5384. if (is_array($inRow) && $inRow !== []) {
  5385. $inboundResult = trim((string)($inRow['result'] ?? ''));
  5386. if ($inboundScoreTime === '') {
  5387. $inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
  5388. }
  5389. }
  5390. }
  5391. $inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
  5392. $supplierTime = '';
  5393. if ($acceptCnt > 0) {
  5394. foreach ($details as $dr) {
  5395. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  5396. continue;
  5397. }
  5398. $t = $this->resolveDetailSupplierOperTime($dr);
  5399. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  5400. $supplierTime = $t;
  5401. }
  5402. }
  5403. }
  5404. $directComplete = ($mainCompleted && !$issued);
  5405. $doneTime = '';
  5406. if ($mainCompleted) {
  5407. if ($directComplete) {
  5408. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  5409. }
  5410. if ($doneTime === '' && $inboundScoreTime !== '') {
  5411. $doneTime = $inboundScoreTime;
  5412. }
  5413. if ($doneTime === '') {
  5414. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5415. }
  5416. if ($doneTime === '') {
  5417. foreach ($details as $dr) {
  5418. if (!is_array($dr)) {
  5419. continue;
  5420. }
  5421. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  5422. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  5423. $doneTime = $t;
  5424. }
  5425. }
  5426. }
  5427. if ($doneTime === '') {
  5428. $doneTime = $poTime;
  5429. }
  5430. // 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
  5431. if ($doneTime === '' && $confirmApproveTime !== '') {
  5432. $doneTime = $confirmApproveTime;
  5433. }
  5434. }
  5435. if ($directComplete) {
  5436. // 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
  5437. $step1Done = $hasMain;
  5438. $step2Done = false;
  5439. $step3Done = false;
  5440. $step4Done = false;
  5441. $step5Done = false;
  5442. $stepInboundDone = $inboundScored;
  5443. $step6Done = $mainCompleted && $inboundScored;
  5444. } else {
  5445. $step1Done = $issued;
  5446. $step2Done = $issued;
  5447. $step3Done = $acceptCnt > 0;
  5448. $step4Done = $wflowPendingApproval;
  5449. if (!$step4Done) {
  5450. foreach ($details as $dr) {
  5451. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5452. $step4Done = true;
  5453. break;
  5454. }
  5455. }
  5456. }
  5457. $step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
  5458. $stepInboundDone = $inboundScored;
  5459. // 未确认合格/不合格时,「已完结」保持未点亮(灰色)
  5460. $step6Done = $mainCompleted && $inboundScored;
  5461. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  5462. if ($mainCompleted && $issued) {
  5463. $step3Done = true;
  5464. $step4Done = true;
  5465. $step5Done = true;
  5466. // 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
  5467. if ($supplierTime === '') {
  5468. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5469. if ($fillT !== '') {
  5470. $supplierTime = $fillT;
  5471. }
  5472. }
  5473. if ($pickedTime === '') {
  5474. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5475. if ($fillT !== '') {
  5476. $pickedTime = $fillT;
  5477. }
  5478. }
  5479. if ($auditSelectTime === '') {
  5480. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5481. if ($fillT !== '') {
  5482. $auditSelectTime = $fillT;
  5483. }
  5484. }
  5485. if ($confirmApproveTime === '') {
  5486. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5487. if ($fillT !== '') {
  5488. $confirmApproveTime = $fillT;
  5489. }
  5490. }
  5491. }
  5492. }
  5493. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  5494. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  5495. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  5496. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  5497. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  5498. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  5499. $inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
  5500. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  5501. $deadlineLines = [];
  5502. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  5503. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  5504. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  5505. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  5506. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  5507. }
  5508. }
  5509. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  5510. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  5511. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  5512. if ($deliveryDisp === '') {
  5513. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  5514. }
  5515. if ($deliveryDisp !== '') {
  5516. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  5517. }
  5518. }
  5519. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  5520. $deadlineText = implode("\n", $deadlineLines);
  5521. $prefixOperTime = static function (string $t): string {
  5522. $t = trim($t);
  5523. if ($t === '' || $t === '—') {
  5524. return $t;
  5525. }
  5526. if (strpos($t, '操作时间') === 0) {
  5527. return $t;
  5528. }
  5529. return '操作时间:' . $t;
  5530. };
  5531. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  5532. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  5533. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
  5534. $stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5535. $step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5536. $steps = [
  5537. [
  5538. 'title' => '未发',
  5539. 'subtitle' => '',
  5540. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  5541. 'done' => $step1Done,
  5542. ],
  5543. [
  5544. 'title' => '下发',
  5545. 'subtitle' => $deadlineText,
  5546. 'time' => $prefixOperTime($step2Time),
  5547. 'done' => $step2Done,
  5548. ],
  5549. [
  5550. 'title' => '供应商接单',
  5551. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  5552. 'time' => '',
  5553. 'done' => $step3Done,
  5554. ],
  5555. [
  5556. 'title' => '待确认',
  5557. 'subtitle' => $step4Done
  5558. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  5559. : ($issued ? '待选供应商' : ''),
  5560. 'time' => $prefixOperTime($step4Time),
  5561. 'done' => $step4Done,
  5562. ],
  5563. [
  5564. 'title' => '待审批',
  5565. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  5566. 'time' => $prefixOperTime($step5Time),
  5567. 'done' => $step5Done,
  5568. ],
  5569. [
  5570. 'title' => '是否合格',
  5571. 'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
  5572. 'time' => $prefixOperTime($stepInboundTime),
  5573. 'done' => $stepInboundDone,
  5574. ],
  5575. [
  5576. 'title' => '已完结',
  5577. 'subtitle' => '',
  5578. 'time' => $prefixOperTime($step6Time),
  5579. 'done' => $step6Done,
  5580. ],
  5581. ];
  5582. $currentIdx = count($steps) - 1;
  5583. if ($directComplete) {
  5584. // 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
  5585. if (!$step6Done) {
  5586. foreach ($steps as $i => $s) {
  5587. if (($s['title'] ?? '') === '是否合格') {
  5588. $currentIdx = $i;
  5589. break;
  5590. }
  5591. }
  5592. }
  5593. } else {
  5594. foreach ($steps as $i => $s) {
  5595. if (!$s['done']) {
  5596. $currentIdx = $i;
  5597. break;
  5598. }
  5599. }
  5600. }
  5601. $nSteps = count($steps);
  5602. foreach ($steps as $idx => &$s) {
  5603. $s['current'] = ($idx === $currentIdx);
  5604. if ($idx === 0) {
  5605. $s['pdf_left_bg'] = '';
  5606. } else {
  5607. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  5608. }
  5609. if ($idx >= $nSteps - 1) {
  5610. $s['pdf_right_bg'] = '';
  5611. } else {
  5612. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  5613. }
  5614. }
  5615. unset($s);
  5616. $labelMap = [
  5617. 'CCYDH' => '订单号',
  5618. 'CYJMC' => '印件名称',
  5619. 'CCLBMMC' => '承揽部门',
  5620. 'CGYMC' => '工序名称',
  5621. 'CDW' => '单位',
  5622. 'czlyq' => '类型',
  5623. 'NGZL' => '工作量',
  5624. 'CDF' => '单价',
  5625. 'cGzzxMc' => '工作中心',
  5626. 'MBZ' => '备注',
  5627. 'This_quantity' => '本次数量',
  5628. 'ceilingPrice' => '最高限价',
  5629. ];
  5630. $orderSummary = [];
  5631. foreach ($labelMap as $key => $lab) {
  5632. if (!array_key_exists($key, $main)) {
  5633. continue;
  5634. }
  5635. $val = $main[$key];
  5636. if ($val === null) {
  5637. $val = '';
  5638. } elseif (!is_scalar($val)) {
  5639. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  5640. } else {
  5641. $val = (string)$val;
  5642. }
  5643. $orderSummary[] = ['label' => $lab, 'value' => $val];
  5644. }
  5645. $orderSummary[] = [
  5646. 'label' => '是否合格',
  5647. 'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
  5648. ];
  5649. $orderSummaryGrid = [];
  5650. $n = count($orderSummary);
  5651. for ($i = 0; $i < $n; $i += 2) {
  5652. $left = $orderSummary[$i];
  5653. $hasRight = ($i + 1) < $n;
  5654. $orderSummaryGrid[] = [
  5655. 'l1' => $left['label'],
  5656. 'v1' => $left['value'],
  5657. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  5658. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  5659. ];
  5660. }
  5661. return [
  5662. 'steps' => $steps,
  5663. 'orderSummary' => $orderSummary,
  5664. 'orderSummaryGrid' => $orderSummaryGrid,
  5665. 'inbound_result' => $inboundResult,
  5666. 'inbound_score_time'=> $inboundScoreTime,
  5667. 'detailRows' => $details,
  5668. ];
  5669. }
  5670. /**
  5671. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  5672. *
  5673. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  5674. */
  5675. protected function prepareProcuremenDetailsView(string $ids): array
  5676. {
  5677. $main = [];
  5678. try {
  5679. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5680. $main = is_array($one) ? $one : [];
  5681. } catch (\Throwable $e) {
  5682. $main = [];
  5683. }
  5684. $details = [];
  5685. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  5686. if ($mergeRows === []) {
  5687. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  5688. if ($mergeRows === [] && $main !== []) {
  5689. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  5690. }
  5691. }
  5692. $detailSidList = [];
  5693. $anchorSid = (int)$ids;
  5694. if ($anchorSid !== 0) {
  5695. $detailSidList[$anchorSid] = true;
  5696. }
  5697. foreach ($mergeRows as $mr) {
  5698. if (!is_array($mr)) {
  5699. continue;
  5700. }
  5701. $sid = $this->extractScydgyRowId($mr);
  5702. if ($sid !== 0) {
  5703. $detailSidList[$sid] = true;
  5704. }
  5705. }
  5706. try {
  5707. if ($detailSidList !== []) {
  5708. $details = Db::table('purchase_order_detail')
  5709. ->where('scydgy_id', 'in', array_keys($detailSidList))
  5710. ->order('id', 'asc')
  5711. ->select();
  5712. }
  5713. } catch (\Throwable $e) {
  5714. $details = [];
  5715. }
  5716. if (!is_array($details)) {
  5717. $details = [];
  5718. }
  5719. foreach ($details as &$r) {
  5720. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  5721. $r['id'] = $r['ID'];
  5722. }
  5723. if (isset($r['createtime'])) {
  5724. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  5725. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  5726. } else {
  5727. $r['createtime_text'] = (string)$r['createtime'];
  5728. }
  5729. } else {
  5730. $r['createtime_text'] = '';
  5731. }
  5732. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  5733. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  5734. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  5735. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  5736. if (is_array($r)) {
  5737. $r = $this->maskSupplierContactFields($r);
  5738. }
  5739. }
  5740. unset($r);
  5741. $activeDetails = [];
  5742. foreach ($details as $r) {
  5743. if (is_array($r) && empty($r['is_void'])) {
  5744. $activeDetails[] = $r;
  5745. }
  5746. }
  5747. $operLogs = [];
  5748. try {
  5749. $operSidList = array_keys($detailSidList);
  5750. if ($operSidList === [] && (int)$ids !== 0) {
  5751. $operSidList = [(int)$ids];
  5752. }
  5753. if ($operSidList !== []) {
  5754. $operLogs = Db::table('purchase_order_oper_log')
  5755. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  5756. ->order('id', 'asc')
  5757. ->select();
  5758. }
  5759. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  5760. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  5761. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  5762. if ($poId > 0) {
  5763. $operLogs = Db::table('purchase_order_oper_log')
  5764. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  5765. ->order('id', 'asc')
  5766. ->select();
  5767. }
  5768. }
  5769. } catch (\Throwable $e) {
  5770. $operLogs = [];
  5771. }
  5772. if (!is_array($operLogs)) {
  5773. $operLogs = [];
  5774. }
  5775. $operLogsRaw = $operLogs;
  5776. $processNameBySid = [];
  5777. foreach ($mergeRows as $mr) {
  5778. if (!is_array($mr)) {
  5779. continue;
  5780. }
  5781. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  5782. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5783. if ($psid !== 0 && $gymc !== '') {
  5784. $processNameBySid[$psid] = $gymc;
  5785. }
  5786. }
  5787. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  5788. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
  5789. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  5790. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  5791. if ($ccydh === '') {
  5792. foreach ($details as $r) {
  5793. if (!is_array($r)) {
  5794. continue;
  5795. }
  5796. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  5797. if ($ccydh !== '') {
  5798. break;
  5799. }
  5800. }
  5801. }
  5802. $this->view->assign('ccydh', $ccydh);
  5803. $this->view->assign('steps', $bundle['steps']);
  5804. $this->view->assign('orderSummary', $bundle['orderSummary']);
  5805. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  5806. $this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
  5807. $this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
  5808. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  5809. $this->view->assign('processCount', count($mergeRows));
  5810. $this->view->assign('detailRows', $details);
  5811. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  5812. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  5813. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  5814. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  5815. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  5816. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  5817. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  5818. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  5819. $this->view->assign('operLogs', $operLogs);
  5820. $sg = $quoteView['supplier_groups'] ?? [];
  5821. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
  5822. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  5823. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
  5824. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
  5825. return [
  5826. 'ok' => $main !== [] || $details !== [],
  5827. 'ccydh' => $ccydh,
  5828. ];
  5829. }
  5830. /**
  5831. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  5832. */
  5833. public function details()
  5834. {
  5835. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5836. if (is_array($ids)) {
  5837. $ids = isset($ids[0]) ? $ids[0] : '';
  5838. }
  5839. $ids = trim((string)$ids);
  5840. if ($ids === '') {
  5841. $this->error(__('Invalid parameters'));
  5842. }
  5843. $this->assertManualOrderDetailsViewable((int)$ids);
  5844. $this->prepareProcuremenDetailsView($ids);
  5845. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  5846. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  5847. $this->view->engine->layout(false);
  5848. try {
  5849. return $this->view->fetch('procuremen/details_dialog_shell');
  5850. } finally {
  5851. if ($restoreLayout) {
  5852. $this->view->engine->layout($restoreLayout);
  5853. }
  5854. }
  5855. }
  5856. /**
  5857. * 解析合并审核工序行(订单号须一致,且均未协助)
  5858. *
  5859. * @return array<int, array<string, mixed>>
  5860. */
  5861. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  5862. {
  5863. $primary = json_decode($rowJson, true);
  5864. if (!is_array($primary)) {
  5865. $this->error(__('Invalid parameters'));
  5866. }
  5867. $merge = json_decode($mergeRowsJson, true);
  5868. if (!is_array($merge) || $merge === []) {
  5869. $merge = [$primary];
  5870. }
  5871. $seen = [];
  5872. $out = [];
  5873. foreach ($merge as $r) {
  5874. if (!is_array($r)) {
  5875. continue;
  5876. }
  5877. $id = $this->extractScydgyRowId($r);
  5878. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  5879. continue;
  5880. }
  5881. $seen[$id] = true;
  5882. $out[] = $r;
  5883. }
  5884. if ($out === []) {
  5885. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  5886. }
  5887. $ccydh = null;
  5888. foreach ($out as $r) {
  5889. $dh = trim((string)($r['CCYDH'] ?? ''));
  5890. if ($ccydh === null) {
  5891. $ccydh = $dh;
  5892. } elseif ($dh !== $ccydh) {
  5893. $this->error('合并审核要求所选行的订单号一致');
  5894. }
  5895. }
  5896. $ids = [];
  5897. foreach ($out as $r) {
  5898. $id = $this->extractScydgyRowId($r);
  5899. if ($this->isValidScydgyRowId($id)) {
  5900. $ids[$id] = true;
  5901. }
  5902. }
  5903. $poBySid = [];
  5904. $detCntBySid = [];
  5905. if ($ids !== []) {
  5906. $idList = array_keys($ids);
  5907. try {
  5908. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  5909. if (is_array($poList)) {
  5910. foreach ($poList as $po) {
  5911. if (!is_array($po)) {
  5912. continue;
  5913. }
  5914. $sid = (int)($po['scydgy_id'] ?? 0);
  5915. if ($this->isValidScydgyRowId($sid)) {
  5916. $poBySid[$sid] = $po;
  5917. }
  5918. }
  5919. }
  5920. } catch (\Throwable $e) {
  5921. }
  5922. try {
  5923. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  5924. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  5925. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  5926. if (is_array($detRows)) {
  5927. foreach ($detRows as $dr) {
  5928. if (!is_array($dr)) {
  5929. continue;
  5930. }
  5931. $sid = (int)($dr['scydgy_id'] ?? 0);
  5932. if ($this->isValidScydgyRowId($sid)) {
  5933. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  5934. }
  5935. }
  5936. }
  5937. } catch (\Throwable $e) {
  5938. }
  5939. }
  5940. foreach ($out as $r) {
  5941. $id = $this->extractScydgyRowId($r);
  5942. if (!$this->isValidScydgyRowId($id)) {
  5943. continue;
  5944. }
  5945. $po = $poBySid[$id] ?? null;
  5946. if (!is_array($po)) {
  5947. continue;
  5948. }
  5949. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  5950. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5951. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  5952. }
  5953. $detCnt = (int)($detCntBySid[$id] ?? 0);
  5954. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  5955. $gymc = trim((string)($r['CGYMC'] ?? ''));
  5956. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  5957. }
  5958. }
  5959. return $out;
  5960. }
  5961. /**
  5962. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  5963. */
  5964. protected function maskSupplierContactFields(array $item): array
  5965. {
  5966. if (array_key_exists('email', $item)) {
  5967. $item['email'] = mask_email((string)$item['email']);
  5968. }
  5969. if (array_key_exists('phone', $item)) {
  5970. $item['phone'] = mask_phone((string)$item['phone']);
  5971. }
  5972. return $item;
  5973. }
  5974. /**
  5975. * @param array<int, array<string, mixed>> $list
  5976. * @return array<int, array<string, mixed>>
  5977. */
  5978. protected function maskSupplierContactList(array $list): array
  5979. {
  5980. $out = [];
  5981. foreach ($list as $item) {
  5982. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  5983. }
  5984. return $out;
  5985. }
  5986. /**
  5987. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  5988. *
  5989. * @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
  5990. * @return array<string, string>|null
  5991. */
  5992. protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
  5993. {
  5994. if (!is_array($row)) {
  5995. return null;
  5996. }
  5997. $norm = [];
  5998. foreach ($row as $k => $v) {
  5999. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  6000. }
  6001. $row = $norm;
  6002. $st = $row['status'] ?? '';
  6003. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  6004. return null;
  6005. }
  6006. $companyName = '';
  6007. foreach (['company_name', 'name'] as $nk) {
  6008. if (!empty($row[$nk])) {
  6009. $companyName = trim((string)$row[$nk]);
  6010. break;
  6011. }
  6012. }
  6013. if ($companyName === '') {
  6014. return null;
  6015. }
  6016. $username = '';
  6017. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  6018. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  6019. $username = trim((string)$row[$uk]);
  6020. break;
  6021. }
  6022. }
  6023. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  6024. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  6025. if ($phone === '' && isset($row['account'])) {
  6026. $phone = trim((string)$row['account']);
  6027. }
  6028. if ($phone === '' && isset($row['mobile'])) {
  6029. $phone = trim((string)$row['mobile']);
  6030. }
  6031. if ($requireContactChannels && $email === '' && $phone === '') {
  6032. return null;
  6033. }
  6034. $category = '';
  6035. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6036. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6037. $category = trim((string)$row[$ck]);
  6038. break;
  6039. }
  6040. }
  6041. return [
  6042. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  6043. 'name' => $companyName,
  6044. 'company_name' => $companyName,
  6045. 'username' => $username,
  6046. 'email' => $email,
  6047. 'phone' => $phone,
  6048. 'category' => $category,
  6049. 'company_type' => $category,
  6050. ];
  6051. }
  6052. /**
  6053. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  6054. */
  6055. protected function resolveCustomerContactById(string $id): ?array
  6056. {
  6057. $id = trim($id);
  6058. if ($id === '' || !ctype_digit($id)) {
  6059. return null;
  6060. }
  6061. try {
  6062. $row = Db::table('customer')->where('id', (int)$id)->find();
  6063. } catch (\Throwable $e) {
  6064. return null;
  6065. }
  6066. return $this->buildCustomerContactPayloadFromRow($row);
  6067. }
  6068. /**
  6069. * 按供应商名称解析联系信息(兼容旧提交数据)
  6070. *
  6071. * @param bool $requireContactChannels true 时须有邮箱或手机
  6072. */
  6073. protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
  6074. {
  6075. $name = trim($name);
  6076. if ($name === '') {
  6077. return null;
  6078. }
  6079. try {
  6080. // customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
  6081. $row = Db::table('customer')
  6082. ->where('company_name', $name)
  6083. ->order('id', 'desc')
  6084. ->find();
  6085. } catch (\Throwable $e) {
  6086. return null;
  6087. }
  6088. return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
  6089. }
  6090. /**
  6091. * 规范化下发/确认时勾选的供应商
  6092. *
  6093. * @param array<int, mixed> $companies
  6094. * @return array<int, array<string, string>>
  6095. */
  6096. protected function normalizePickCompanies(array $companies): array
  6097. {
  6098. $out = [];
  6099. foreach ($companies as $c) {
  6100. if (!is_array($c)) {
  6101. continue;
  6102. }
  6103. $resolved = null;
  6104. $cid = trim((string)($c['id'] ?? ''));
  6105. if ($cid !== '') {
  6106. $resolved = $this->resolveCustomerContactById($cid);
  6107. }
  6108. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  6109. if ($resolved === null && $name !== '') {
  6110. $resolved = $this->resolveCustomerContactByCompanyName($name);
  6111. }
  6112. if ($resolved === null) {
  6113. continue;
  6114. }
  6115. $out[] = $resolved;
  6116. }
  6117. return $out;
  6118. }
  6119. /**
  6120. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  6121. *
  6122. * @param array<int, array<string, mixed>> $pool
  6123. * @return array<int, array<string, mixed>>
  6124. */
  6125. protected function collapseProcuremenPoolByOrder(array $pool): array
  6126. {
  6127. if ($pool === []) {
  6128. return [];
  6129. }
  6130. $groups = [];
  6131. foreach ($pool as $row) {
  6132. if (!is_array($row)) {
  6133. continue;
  6134. }
  6135. $dh = trim((string)($row['CCYDH'] ?? ''));
  6136. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  6137. if (!isset($groups[$key])) {
  6138. $groups[$key] = [];
  6139. }
  6140. $groups[$key][] = $row;
  6141. }
  6142. $out = [];
  6143. foreach ($groups as $ccydh => $rows) {
  6144. if ($rows === []) {
  6145. continue;
  6146. }
  6147. usort($rows, function ($a, $b) {
  6148. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  6149. });
  6150. $head = $rows[0];
  6151. $gymcList = [];
  6152. foreach ($rows as $r) {
  6153. $g = trim((string)($r['CGYMC'] ?? ''));
  6154. if ($g !== '' && !in_array($g, $gymcList, true)) {
  6155. $gymcList[] = $g;
  6156. }
  6157. }
  6158. $merged = $head;
  6159. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  6160. $merged['process_count'] = count($rows);
  6161. $merged['_order_merge_rows'] = $rows;
  6162. $qtyList = [];
  6163. $priceList = [];
  6164. foreach ($rows as $r) {
  6165. if (!is_array($r)) {
  6166. continue;
  6167. }
  6168. $qtyList[] = $this->resolveProcuremenThisQuantity($r);
  6169. $priceList[] = $this->resolveProcuremenCeilingPrice($r);
  6170. }
  6171. if (count($rows) > 1) {
  6172. $merged['CGYMC'] = implode('、', $gymcList);
  6173. // 多工序:数量/限价按有值项顿号间隔(空值不占位)
  6174. $merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  6175. $merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  6176. } else {
  6177. $merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
  6178. $merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
  6179. }
  6180. // 已选供应商:取合并行中首个非空 pick_company_name
  6181. $pickedName = '';
  6182. foreach ($rows as $r) {
  6183. if (!is_array($r)) {
  6184. continue;
  6185. }
  6186. $pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
  6187. if ($pn !== '') {
  6188. $pickedName = $pn;
  6189. break;
  6190. }
  6191. }
  6192. if ($pickedName !== '') {
  6193. $merged['pick_company_name'] = $pickedName;
  6194. $merged['picked_supplier_name'] = $pickedName;
  6195. }
  6196. $mergedPickTime = '';
  6197. foreach ($rows as $r) {
  6198. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  6199. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  6200. $mergedPickTime = $t;
  6201. }
  6202. }
  6203. if ($mergedPickTime !== '') {
  6204. $merged['pick_time'] = $mergedPickTime;
  6205. }
  6206. $out[] = $merged;
  6207. }
  6208. usort($out, function ($a, $b) {
  6209. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  6210. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  6211. if ($ta === $tb) {
  6212. $ida = (int)($a['purchase_order_id'] ?? 0);
  6213. $idb = (int)($b['purchase_order_id'] ?? 0);
  6214. if ($ida !== $idb) {
  6215. return $idb <=> $ida;
  6216. }
  6217. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  6218. }
  6219. if ($ta === '') {
  6220. return 1;
  6221. }
  6222. if ($tb === '') {
  6223. return -1;
  6224. }
  6225. return strcmp($tb, $ta);
  6226. });
  6227. return $out;
  6228. }
  6229. /**
  6230. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  6231. *
  6232. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6233. */
  6234. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  6235. {
  6236. $scydgyId = trim($scydgyId);
  6237. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6238. if ($scydgyId === '') {
  6239. return $empty;
  6240. }
  6241. try {
  6242. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6243. } catch (\Throwable $e) {
  6244. $anchor = null;
  6245. }
  6246. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  6247. return $empty;
  6248. }
  6249. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6250. if ($ccydh === '') {
  6251. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  6252. }
  6253. try {
  6254. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  6255. } catch (\Throwable $e) {
  6256. $pos = [$anchor];
  6257. }
  6258. if (!is_array($pos) || $pos === []) {
  6259. $pos = [$anchor];
  6260. }
  6261. return [
  6262. 'ccydh' => $ccydh,
  6263. 'pos' => $pos,
  6264. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6265. ];
  6266. }
  6267. /**
  6268. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  6269. */
  6270. protected function purchaseOrderRowInConfirmStage(array $po): bool
  6271. {
  6272. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6273. return false;
  6274. }
  6275. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  6276. return false;
  6277. }
  6278. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  6279. return true;
  6280. }
  6281. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  6282. $sid = (int)($po['scydgy_id'] ?? 0);
  6283. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  6284. }
  6285. return false;
  6286. }
  6287. /**
  6288. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  6289. *
  6290. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6291. */
  6292. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  6293. {
  6294. $scydgyId = trim($scydgyId);
  6295. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6296. if ($scydgyId === '') {
  6297. return $empty;
  6298. }
  6299. try {
  6300. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6301. } catch (\Throwable $e) {
  6302. $anchor = null;
  6303. }
  6304. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  6305. return $empty;
  6306. }
  6307. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6308. if ($ccydh === '') {
  6309. return [
  6310. 'ccydh' => '',
  6311. 'pos' => [$anchor],
  6312. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  6313. ];
  6314. }
  6315. try {
  6316. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  6317. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  6318. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  6319. } catch (\Throwable $e) {
  6320. $pos = [$anchor];
  6321. }
  6322. if (!is_array($pos) || $pos === []) {
  6323. $pos = [$anchor];
  6324. }
  6325. $pos = array_values(array_filter($pos, function ($po) {
  6326. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  6327. }));
  6328. if ($pos === []) {
  6329. $pos = [$anchor];
  6330. }
  6331. return [
  6332. 'ccydh' => $ccydh,
  6333. 'pos' => $pos,
  6334. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6335. ];
  6336. }
  6337. /**
  6338. * @param array<int, array<string, mixed>> $purchaseOrders
  6339. * @return array<int, array<string, mixed>>
  6340. */
  6341. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  6342. {
  6343. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  6344. $byId = [];
  6345. foreach ($pool as $r) {
  6346. if (!is_array($r)) {
  6347. continue;
  6348. }
  6349. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  6350. if ($this->isValidScydgyRowId($sid)) {
  6351. $byId[$sid] = $r;
  6352. }
  6353. }
  6354. $out = [];
  6355. foreach ($purchaseOrders as $po) {
  6356. if (!is_array($po)) {
  6357. continue;
  6358. }
  6359. $sid = (int)($po['scydgy_id'] ?? 0);
  6360. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  6361. $out[] = $byId[$sid];
  6362. }
  6363. }
  6364. return $out;
  6365. }
  6366. /**
  6367. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  6368. *
  6369. * @return array<int, array<string, mixed>>
  6370. */
  6371. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  6372. {
  6373. $scydgyId = trim($scydgyId);
  6374. if ($scydgyId === '') {
  6375. return [];
  6376. }
  6377. try {
  6378. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6379. } catch (\Throwable $e) {
  6380. $anchor = null;
  6381. }
  6382. if (!is_array($anchor)) {
  6383. return [];
  6384. }
  6385. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  6386. return [];
  6387. }
  6388. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6389. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  6390. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  6391. try {
  6392. $q = Db::table('purchase_order');
  6393. if ($ccydh !== '') {
  6394. $q->where('CCYDH', $ccydh);
  6395. } else {
  6396. $q->where('scydgy_id', $scydgyId);
  6397. }
  6398. if ($isValidPick) {
  6399. $q->where('pick_time', $pickTime);
  6400. }
  6401. $pos = $q->order('scydgy_id', 'asc')->select();
  6402. } catch (\Throwable $e) {
  6403. $pos = [$anchor];
  6404. }
  6405. if (!is_array($pos) || $pos === []) {
  6406. $pos = [$anchor];
  6407. }
  6408. $pos = array_values(array_filter($pos, function ($po) {
  6409. if (!is_array($po)) {
  6410. return false;
  6411. }
  6412. $mr = $po['mod_rq'] ?? null;
  6413. if ($mr === null || $mr === '') {
  6414. return true;
  6415. }
  6416. $mrs = trim((string)$mr);
  6417. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  6418. }));
  6419. if ($pos === []) {
  6420. $pos = [$anchor];
  6421. }
  6422. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  6423. if ($rows === []) {
  6424. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  6425. }
  6426. return $rows;
  6427. }
  6428. /**
  6429. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  6430. *
  6431. * @param array<int, array<string, mixed>> $mergeRows
  6432. * @return array<int, array<string, mixed>>
  6433. */
  6434. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  6435. {
  6436. $list = array_values($mergeRows);
  6437. $n = count($list);
  6438. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  6439. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  6440. $mergeSame = $n > 1 && $orderKey0 !== '';
  6441. if ($mergeSame) {
  6442. foreach ($list as $rr) {
  6443. if (!is_array($rr)) {
  6444. $mergeSame = false;
  6445. break;
  6446. }
  6447. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  6448. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  6449. $mergeSame = false;
  6450. break;
  6451. }
  6452. }
  6453. }
  6454. $out = [];
  6455. foreach ($list as $idx => $r) {
  6456. if (!is_array($r)) {
  6457. continue;
  6458. }
  6459. $qty = $this->resolveProcuremenThisQuantity($r);
  6460. $price = $this->resolveProcuremenCeilingPrice($r);
  6461. $sid = $this->extractScydgyRowId($r);
  6462. $out[] = [
  6463. 'seq' => $idx + 1,
  6464. 'scydgy_id' => $sid,
  6465. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6466. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6467. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6468. 'CDW' => trim((string)($r['CDW'] ?? '')),
  6469. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  6470. 'NGZL' => $r['NGZL'] ?? '',
  6471. 'This_quantity' => $qty,
  6472. 'ceilingPrice' => $price,
  6473. 'CDF' => trim((string)($r['CDF'] ?? '')),
  6474. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  6475. 'show_order_cells' => !$mergeSame || $idx === 0,
  6476. 'order_rowspan' => $mergeSame ? $n : 1,
  6477. ];
  6478. }
  6479. return $out;
  6480. }
  6481. /**
  6482. * 解析金额/数量(去千分位等非数字字符)
  6483. */
  6484. protected function parseProcuremenMoneyNumber($value): ?float
  6485. {
  6486. if ($value === null || $value === '') {
  6487. return null;
  6488. }
  6489. if (is_numeric($value)) {
  6490. return (float)$value;
  6491. }
  6492. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  6493. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  6494. }
  6495. protected function formatProcuremenMoneyDisplay(?float $amount): string
  6496. {
  6497. if ($amount === null) {
  6498. return '';
  6499. }
  6500. // 保留小数(最多 5 位),去掉末尾无意义的 0,避免 0.25 被显示成 0
  6501. $s = rtrim(rtrim(sprintf('%.5F', (float)$amount), '0'), '.');
  6502. return $s === '' ? '0' : $s;
  6503. }
  6504. /**
  6505. * 列表/详情展示:工作量为 0 时显示空
  6506. */
  6507. protected function formatProcuremenWorkloadDisplay($value): string
  6508. {
  6509. if ($value === null || $value === '') {
  6510. return '';
  6511. }
  6512. $s = trim((string)$value);
  6513. if ($s === '') {
  6514. return '';
  6515. }
  6516. if (is_numeric($s) && (float)$s == 0) {
  6517. return '';
  6518. }
  6519. return $s;
  6520. }
  6521. /**
  6522. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  6523. */
  6524. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  6525. {
  6526. foreach ($details as $d) {
  6527. if (!is_array($d)) {
  6528. continue;
  6529. }
  6530. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  6531. $cn = trim((string)($d['company_name'] ?? ''));
  6532. if ($cn !== '') {
  6533. return $cn;
  6534. }
  6535. }
  6536. }
  6537. return trim((string)($main['pick_company_name'] ?? ''));
  6538. }
  6539. /**
  6540. * 详情报价小计:单价 × 本工序本次数量
  6541. */
  6542. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  6543. {
  6544. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  6545. if ($unit === null) {
  6546. return null;
  6547. }
  6548. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  6549. if ($qty === null || $qty <= 0) {
  6550. return null;
  6551. }
  6552. return $unit * $qty;
  6553. }
  6554. /**
  6555. * 详情页:工序小计 + 供应商分组报价与总计
  6556. *
  6557. * @param array<int, array<string, mixed>> $mergeRows
  6558. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  6559. * @return array{
  6560. * process_rows: array,
  6561. * supplier_groups: array,
  6562. * order_total_text: string,
  6563. * order_total_has: bool,
  6564. * selected_company: string
  6565. * }
  6566. */
  6567. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  6568. {
  6569. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  6570. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  6571. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
  6572. || ((int)($main['manual_pick'] ?? 0) === 1);
  6573. $qtyBySid = [];
  6574. $gymcBySid = [];
  6575. $orderedSids = [];
  6576. foreach ($mergeRows as $mr) {
  6577. if (!is_array($mr)) {
  6578. continue;
  6579. }
  6580. $sid = $this->extractScydgyRowId($mr);
  6581. if ($this->isValidScydgyRowId($sid)) {
  6582. $orderedSids[] = $sid;
  6583. }
  6584. $qty = trim((string)($mr['This_quantity'] ?? ''));
  6585. if ($qty === '') {
  6586. $qty = trim((string)($mr['NGZL'] ?? ''));
  6587. }
  6588. $qtyBySid[$sid] = $qty;
  6589. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  6590. }
  6591. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  6592. $detailByCompanySid = [];
  6593. foreach ($details as $d) {
  6594. if (!is_array($d)) {
  6595. continue;
  6596. }
  6597. $cn = trim((string)($d['company_name'] ?? ''));
  6598. $sid = (int)($d['scydgy_id'] ?? 0);
  6599. if ($cn === '' || $sid === 0) {
  6600. continue;
  6601. }
  6602. if (!isset($detailByCompanySid[$cn])) {
  6603. $detailByCompanySid[$cn] = [];
  6604. }
  6605. $detailByCompanySid[$cn][$sid] = $d;
  6606. }
  6607. $supplierGroups = [];
  6608. foreach ($detailByCompanySid as $cn => $bySid) {
  6609. $lines = [];
  6610. $groupTotal = 0.0;
  6611. $groupHas = false;
  6612. $groupVoid = true;
  6613. $usedSids = [];
  6614. $appendLine = function (int $sid, array $d) use (
  6615. &$lines,
  6616. &$groupTotal,
  6617. &$groupHas,
  6618. &$groupVoid,
  6619. $qtyBySid,
  6620. $gymcBySid,
  6621. $quoteVisible
  6622. ) {
  6623. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  6624. if (!$isVoid) {
  6625. $groupVoid = false;
  6626. }
  6627. $qtyStr = $qtyBySid[$sid] ?? '';
  6628. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  6629. $am = trim((string)($d['amount'] ?? ''));
  6630. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  6631. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  6632. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  6633. $sub = null;
  6634. if (!$isVoid && $amountNum !== null) {
  6635. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  6636. }
  6637. $ct = $this->resolveDetailSupplierOperTime($d);
  6638. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  6639. $leadFilled = ($leadDays !== null);
  6640. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  6641. $line = [
  6642. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  6643. 'amount' => $am,
  6644. 'unit_price_text' => $amountFilled
  6645. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  6646. : '未填写',
  6647. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  6648. 'delivery_ymd' => $deliveryYmd,
  6649. 'amount_filled' => $amountFilled,
  6650. 'delivery_filled' => $deliveryFilled,
  6651. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  6652. 'lead_days' => $leadFilled ? $leadDays : '',
  6653. 'lead_days_filled'=> $leadFilled,
  6654. 'lead_days_show' => $leadText,
  6655. 'lead_days_text' => $leadText,
  6656. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  6657. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  6658. 'is_void' => $isVoid,
  6659. 'oper_time_text' => $ct,
  6660. ];
  6661. if (!$quoteVisible && !$isVoid) {
  6662. $this->maskSupplierQuoteLineBeforeDeadline($line);
  6663. } elseif ($sub !== null) {
  6664. $groupTotal += $sub;
  6665. $groupHas = true;
  6666. }
  6667. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  6668. };
  6669. foreach ($orderedSids as $sid) {
  6670. if (!isset($bySid[$sid])) {
  6671. continue;
  6672. }
  6673. $usedSids[$sid] = true;
  6674. $appendLine($sid, $bySid[$sid]);
  6675. }
  6676. foreach ($bySid as $sid => $d) {
  6677. if (isset($usedSids[$sid])) {
  6678. continue;
  6679. }
  6680. $appendLine((int)$sid, $d);
  6681. }
  6682. $firstDetail = null;
  6683. foreach ($bySid as $d) {
  6684. if (is_array($d)) {
  6685. $firstDetail = $d;
  6686. break;
  6687. }
  6688. }
  6689. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  6690. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  6691. if ($username === '' && $ph !== '') {
  6692. $username = $this->resolveCustomerContactName($ph, $cn);
  6693. }
  6694. $remark = '';
  6695. foreach ($bySid as $d) {
  6696. if (!is_array($d)) {
  6697. continue;
  6698. }
  6699. $rm = '';
  6700. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  6701. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  6702. $rm = trim((string)$d[$rk]);
  6703. break;
  6704. }
  6705. }
  6706. if ($rm !== '') {
  6707. $remark = $rm;
  6708. break;
  6709. }
  6710. }
  6711. $lineCount = count($lines);
  6712. $hasRemark = $lineCount > 0;
  6713. $supplierGroup = [
  6714. 'company_name' => $cn,
  6715. 'username' => $username,
  6716. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  6717. 'phone' => $ph,
  6718. 'remark' => $remark,
  6719. 'has_remark' => $hasRemark,
  6720. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  6721. 'is_void' => $groupVoid,
  6722. 'lines' => $lines,
  6723. 'line_count' => $lineCount,
  6724. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  6725. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  6726. 'has_total' => $lineCount > 0,
  6727. ];
  6728. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  6729. $supplierGroups[] = $supplierGroup;
  6730. }
  6731. usort($supplierGroups, function ($a, $b) {
  6732. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  6733. return ($a['is_void'] ?? false) ? 1 : -1;
  6734. }
  6735. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  6736. return ($a['is_selected'] ?? false) ? -1 : 1;
  6737. }
  6738. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  6739. });
  6740. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  6741. return [
  6742. 'process_rows' => $processRows,
  6743. 'supplier_groups' => $supplierGroups,
  6744. 'order_total_text' => '',
  6745. 'order_total_has' => false,
  6746. 'selected_company' => $selectedCompany,
  6747. ];
  6748. }
  6749. /**
  6750. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  6751. */
  6752. protected function buildProcessLinesPlain(array $mergeRows): string
  6753. {
  6754. $lines = [];
  6755. $i = 1;
  6756. foreach ($mergeRows as $r) {
  6757. if (!is_array($r)) {
  6758. continue;
  6759. }
  6760. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6761. $dw = trim((string)($r['CDW'] ?? ''));
  6762. $gzl = trim((string)($r['NGZL'] ?? ''));
  6763. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  6764. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  6765. if ($dw !== '') {
  6766. $parts[] = '单位:' . $dw;
  6767. }
  6768. if ($gzl !== '') {
  6769. $parts[] = '工作量:' . $gzl;
  6770. }
  6771. if ($qty !== '') {
  6772. $parts[] = '本次数量:' . $qty;
  6773. }
  6774. $lines[] = implode(' ', $parts);
  6775. $i++;
  6776. }
  6777. return implode("\n", $lines);
  6778. }
  6779. /**
  6780. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  6781. *
  6782. * @return array<string, string>
  6783. */
  6784. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  6785. {
  6786. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  6787. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  6788. }
  6789. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  6790. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  6791. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6792. $cyjmc = '';
  6793. foreach ($mergeRows as $mr) {
  6794. if (!is_array($mr)) {
  6795. continue;
  6796. }
  6797. if ($ccydh === '') {
  6798. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  6799. }
  6800. if ($cyjmc === '') {
  6801. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  6802. }
  6803. }
  6804. if ($pos !== []) {
  6805. $firstPo = $pos[0];
  6806. if (is_array($firstPo)) {
  6807. if ($ccydh === '') {
  6808. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  6809. }
  6810. if ($cyjmc === '') {
  6811. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  6812. }
  6813. }
  6814. }
  6815. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  6816. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  6817. if (is_array($any)) {
  6818. if ($ccydh === '') {
  6819. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  6820. }
  6821. if ($cyjmc === '') {
  6822. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  6823. }
  6824. }
  6825. }
  6826. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  6827. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  6828. $cgymc = '';
  6829. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  6830. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  6831. }
  6832. return [
  6833. 'ccydh' => $ccydh,
  6834. 'cyjmc' => $cyjmc,
  6835. 'cgymc' => $cgymc,
  6836. 'process_lines' => $processLines,
  6837. 'process_lines_html' => '',
  6838. ];
  6839. }
  6840. /**
  6841. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  6842. */
  6843. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  6844. {
  6845. $lines = [];
  6846. if ($ccydh !== '') {
  6847. $lines[] = '订单号:' . $ccydh;
  6848. }
  6849. if ($cyjmc !== '') {
  6850. $lines[] = '印件名称:' . $cyjmc;
  6851. }
  6852. if ($processPlain !== '') {
  6853. $lines[] = $processPlain;
  6854. }
  6855. return implode("\n", $lines);
  6856. }
  6857. /**
  6858. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  6859. *
  6860. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6861. */
  6862. protected function buildPlatformLinksPlain(array $detailLinks): string
  6863. {
  6864. $lines = [];
  6865. $i = 1;
  6866. foreach ($detailLinks as $lk) {
  6867. if (!is_array($lk)) {
  6868. continue;
  6869. }
  6870. $url = trim((string)($lk['url'] ?? ''));
  6871. if ($url === '') {
  6872. continue;
  6873. }
  6874. $label = trim((string)($lk['cgymc'] ?? ''));
  6875. if ($label === '') {
  6876. $label = '工序' . $i;
  6877. }
  6878. $lines[] = $label . ':' . $url;
  6879. $i++;
  6880. }
  6881. return implode("\n", $lines);
  6882. }
  6883. /**
  6884. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  6885. *
  6886. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6887. */
  6888. protected function buildPlatformLinksHtml(array $detailLinks): string
  6889. {
  6890. $parts = [];
  6891. $i = 1;
  6892. foreach ($detailLinks as $lk) {
  6893. if (!is_array($lk)) {
  6894. continue;
  6895. }
  6896. $url = trim((string)($lk['url'] ?? ''));
  6897. if ($url === '') {
  6898. continue;
  6899. }
  6900. $label = trim((string)($lk['cgymc'] ?? ''));
  6901. if ($label === '') {
  6902. $label = '工序' . $i;
  6903. }
  6904. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  6905. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  6906. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  6907. $i++;
  6908. }
  6909. return implode("<br>\n", $parts);
  6910. }
  6911. /**
  6912. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  6913. *
  6914. * @return array<string, mixed>
  6915. */
  6916. protected function loadMailerConfig(): array
  6917. {
  6918. try {
  6919. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  6920. } catch (\Throwable $e) {
  6921. $cfg = [];
  6922. }
  6923. return is_array($cfg) ? $cfg : [];
  6924. }
  6925. protected function loadNotifyTemplateRow(string $scene): ?array
  6926. {
  6927. try {
  6928. $row = Db::table('purchase_sms_template')
  6929. ->where('scene', $scene)
  6930. ->where(function ($q) {
  6931. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  6932. })
  6933. ->order('id', 'asc')
  6934. ->find();
  6935. } catch (\Throwable $e) {
  6936. return null;
  6937. }
  6938. if (!is_array($row) || $row === []) {
  6939. return null;
  6940. }
  6941. return [
  6942. 'title' => trim((string)($row['title'] ?? '')),
  6943. 'content' => trim((string)($row['content'] ?? '')),
  6944. ];
  6945. }
  6946. /**
  6947. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  6948. */
  6949. protected function buildProcessLinesHtml(array $mergeRows): string
  6950. {
  6951. if (count($mergeRows) <= 1) {
  6952. $r = $mergeRows[0] ?? [];
  6953. if (!is_array($r)) {
  6954. return '';
  6955. }
  6956. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6957. $dw = trim((string)($r['CDW'] ?? ''));
  6958. $gzl = trim((string)($r['NGZL'] ?? ''));
  6959. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  6960. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  6961. if ($dw !== '') {
  6962. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  6963. }
  6964. if ($gzl !== '') {
  6965. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  6966. }
  6967. if ($qty !== '') {
  6968. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  6969. }
  6970. return $html;
  6971. }
  6972. $rows = '';
  6973. $i = 1;
  6974. foreach ($mergeRows as $r) {
  6975. if (!is_array($r)) {
  6976. continue;
  6977. }
  6978. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  6979. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  6980. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  6981. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  6982. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  6983. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  6984. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  6985. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  6986. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  6987. $i++;
  6988. }
  6989. if ($rows === '') {
  6990. return '';
  6991. }
  6992. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  6993. . '<thead><tr style="background:#f5f5f5;">'
  6994. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  6995. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  6996. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  6997. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  6998. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  6999. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  7000. }
  7001. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  7002. {
  7003. $sysRq = trim($sysRq);
  7004. if ($sysRq === '') {
  7005. if ($required) {
  7006. $this->error('请选择招标截止日期');
  7007. }
  7008. return '';
  7009. }
  7010. $ts = strtotime($sysRq);
  7011. if ($ts === false || $ts <= 0) {
  7012. $this->error('招标截止日期格式无效');
  7013. }
  7014. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  7015. if (!$allowPast) {
  7016. $ymd = date('Y-m-d', $ts);
  7017. if ($ymd < date('Y-m-d')) {
  7018. $this->error('招标截止日期不能早于今天');
  7019. }
  7020. if ($ts <= time()) {
  7021. $this->error('招标截止时间不能早于当前时间');
  7022. }
  7023. }
  7024. return date('Y-m-d H:i:s', $ts);
  7025. }
  7026. /**
  7027. * 确保 purchase_order.czlyq(类型)存在
  7028. */
  7029. protected function ensurePurchaseOrderCzlyqColumn(): void
  7030. {
  7031. static $done = false;
  7032. if ($done) {
  7033. return;
  7034. }
  7035. $done = true;
  7036. try {
  7037. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  7038. if (empty($cols)) {
  7039. Db::execute(
  7040. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  7041. );
  7042. }
  7043. } catch (\Throwable $e) {
  7044. // ignore
  7045. }
  7046. }
  7047. /**
  7048. * 确保 purchase_order.delivery_deadline 存在
  7049. */
  7050. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  7051. {
  7052. static $done = false;
  7053. if ($done) {
  7054. return;
  7055. }
  7056. $done = true;
  7057. try {
  7058. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  7059. if (empty($cols)) {
  7060. Db::execute(
  7061. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  7062. );
  7063. }
  7064. } catch (\Throwable $e) {
  7065. // ignore
  7066. }
  7067. }
  7068. /**
  7069. * 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
  7070. */
  7071. protected function ensurePurchaseOrderScoreRuleIdColumn(): void
  7072. {
  7073. static $done = false;
  7074. if ($done) {
  7075. return;
  7076. }
  7077. $done = true;
  7078. // 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
  7079. $adds = [
  7080. 'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
  7081. 'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
  7082. 'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
  7083. 'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
  7084. 'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
  7085. ];
  7086. $changed = false;
  7087. foreach ($adds as $col => $ddl) {
  7088. try {
  7089. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  7090. if (!is_array($cols) || $cols === []) {
  7091. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  7092. $changed = true;
  7093. }
  7094. } catch (\Throwable $e) {
  7095. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  7096. }
  7097. }
  7098. if ($changed) {
  7099. $this->clearPurchaseOrderTableFieldsCache();
  7100. }
  7101. }
  7102. /**
  7103. * ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
  7104. */
  7105. protected function clearPurchaseOrderTableFieldsCache(): void
  7106. {
  7107. try {
  7108. $db = (string)Config::get('database.database');
  7109. $key = $db . '.purchase_order';
  7110. $ref = new \ReflectionProperty(\think\db\Query::class, 'info');
  7111. $ref->setAccessible(true);
  7112. $info = $ref->getValue();
  7113. if (is_array($info) && isset($info[$key])) {
  7114. unset($info[$key]);
  7115. $ref->setValue(null, $info);
  7116. }
  7117. } catch (\Throwable $e) {
  7118. }
  7119. try {
  7120. $db = (string)Config::get('database.database');
  7121. $schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
  7122. if (is_file($schemaFile)) {
  7123. @unlink($schemaFile);
  7124. }
  7125. } catch (\Throwable $e) {
  7126. }
  7127. }
  7128. /**
  7129. * @return array<string, bool>
  7130. */
  7131. protected function loadPurchaseOrderColumnSet(): array
  7132. {
  7133. static $set = null;
  7134. if (is_array($set)) {
  7135. return $set;
  7136. }
  7137. $set = [];
  7138. try {
  7139. $cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
  7140. } catch (\Throwable $e) {
  7141. return $set;
  7142. }
  7143. if (!is_array($cols)) {
  7144. return $set;
  7145. }
  7146. foreach ($cols as $c) {
  7147. if (!is_array($c)) {
  7148. continue;
  7149. }
  7150. $f = (string)($c['Field'] ?? $c['field'] ?? '');
  7151. if ($f !== '') {
  7152. $set[$f] = true;
  7153. }
  7154. }
  7155. return $set;
  7156. }
  7157. /**
  7158. * 解析交货截止日期(仅年月日)
  7159. */
  7160. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  7161. {
  7162. $raw = trim($raw);
  7163. if ($raw === '') {
  7164. if ($required) {
  7165. $this->error('请选择交货截止日期');
  7166. }
  7167. return '';
  7168. }
  7169. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  7170. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  7171. } else {
  7172. $ts = strtotime(str_replace('/', '-', $raw));
  7173. if ($ts === false || $ts <= 0) {
  7174. $this->error('交货截止日期格式无效');
  7175. }
  7176. $ymd = date('Y-m-d', $ts);
  7177. }
  7178. if ($ymd < date('Y-m-d')) {
  7179. $this->error('交货截止日期不能早于今天');
  7180. }
  7181. return $ymd;
  7182. }
  7183. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  7184. {
  7185. $s = trim((string)$value);
  7186. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  7187. return '';
  7188. }
  7189. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  7190. return $m[1];
  7191. }
  7192. $ts = strtotime(str_replace('/', '-', $s));
  7193. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  7194. }
  7195. /**
  7196. * @param array{pos?:array} $bundle
  7197. */
  7198. protected function resolveBundleDeliveryDeadline(array $bundle): string
  7199. {
  7200. foreach ($bundle['pos'] ?? [] as $po) {
  7201. if (!is_array($po)) {
  7202. continue;
  7203. }
  7204. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7205. if ($d !== '') {
  7206. return $d;
  7207. }
  7208. }
  7209. return '';
  7210. }
  7211. protected function formatProcuremenSysRqForInput($sysRq): string
  7212. {
  7213. $sr = trim((string)$sysRq);
  7214. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  7215. return '';
  7216. }
  7217. $ts = strtotime($sr);
  7218. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  7219. }
  7220. protected function formatProcuremenSysRqForDisplay($sysRq): string
  7221. {
  7222. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  7223. if ($sr === '') {
  7224. return '—';
  7225. }
  7226. $ts = strtotime($sr);
  7227. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  7228. }
  7229. /**
  7230. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  7231. *
  7232. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  7233. * @return array{ccydh?:string,pos:array,merge_rows:array}
  7234. */
  7235. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  7236. {
  7237. return $bundle;
  7238. }
  7239. /**
  7240. * 写入/更新 purchase_order(单道工序行)
  7241. *
  7242. * @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
  7243. */
  7244. protected function upsertPurchaseOrderFromRow(
  7245. array $row,
  7246. string $sysRqDb,
  7247. $wflowStatus = null,
  7248. ?string $pickTime = null,
  7249. ?array $exists = null,
  7250. ?string $deliveryDeadline = null,
  7251. $scoreRuleId = null
  7252. ): void {
  7253. $ids = $this->extractScydgyRowId($row);
  7254. if (!$this->isValidScydgyRowId($ids)) {
  7255. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  7256. }
  7257. if ($exists === null) {
  7258. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7259. }
  7260. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  7261. $this->ensurePurchaseOrderScoreRuleIdColumn();
  7262. $this->ensurePurchaseOrderCzlyqColumn();
  7263. $data = [
  7264. 'scydgy_id' => $ids,
  7265. 'CCYDH' => $row['CCYDH'] ?? null,
  7266. 'CYJMC' => $row['CYJMC'] ?? null,
  7267. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  7268. 'CDXMC' => $row['CDXMC'] ?? null,
  7269. 'CGYBH' => $row['CGYBH'] ?? null,
  7270. 'CGYMC' => $row['CGYMC'] ?? null,
  7271. 'CDW' => $row['CDW'] ?? null,
  7272. 'czlyq' => $row['czlyq'] ?? null,
  7273. 'NGZL' => $row['NGZL'] ?? null,
  7274. 'CDF' => $row['CDF'] ?? null,
  7275. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  7276. 'MBZ' => $row['MBZ'] ?? null,
  7277. 'bwjg' => $row['bwjg'] ?? null,
  7278. 'iStatus' => $row['iStatus'] ?? null,
  7279. 'dStamp' => $row['dStamp'] ?? null,
  7280. 'dputrecord' => $row['dputrecord'] ?? null,
  7281. 'cywyxm' => $row['cywyxm'] ?? null,
  7282. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  7283. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  7284. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7285. 'sys_rq' => $sysRqDb,
  7286. ];
  7287. // 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
  7288. $qtyUp = trim((string)($data['This_quantity'] ?? ''));
  7289. if ($qtyUp === '') {
  7290. $qtyFallback = $this->resolveProcuremenThisQuantity([
  7291. 'This_quantity' => '',
  7292. 'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
  7293. ]);
  7294. if ($qtyFallback !== '') {
  7295. $data['This_quantity'] = $qtyFallback;
  7296. }
  7297. }
  7298. if ($deliveryDeadline !== null) {
  7299. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  7300. }
  7301. // 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
  7302. $scoreRule = null;
  7303. if (is_array($scoreRuleId)) {
  7304. $scoreRule = $scoreRuleId;
  7305. $scoreRuleId = (int)($scoreRule['id'] ?? 0);
  7306. } else {
  7307. $scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
  7308. }
  7309. if ($scoreRuleId !== null && $scoreRuleId > 0) {
  7310. $poCols = $this->loadPurchaseOrderColumnSet();
  7311. if (!empty($poCols['score_rule_id'])) {
  7312. $data['score_rule_id'] = $scoreRuleId;
  7313. if (is_array($scoreRule)) {
  7314. if (!empty($poCols['score_rule_name'])) {
  7315. $data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
  7316. }
  7317. if (!empty($poCols['score_quality_weight'])) {
  7318. $data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
  7319. }
  7320. if (!empty($poCols['score_price_weight'])) {
  7321. $data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
  7322. }
  7323. if (!empty($poCols['score_lead_weight'])) {
  7324. $data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
  7325. }
  7326. }
  7327. }
  7328. }
  7329. if ($wflowStatus !== null && $wflowStatus !== '') {
  7330. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  7331. }
  7332. if ($pickTime !== null && $pickTime !== '') {
  7333. $data['pick_time'] = $pickTime;
  7334. $data['pick_company_name'] = '';
  7335. }
  7336. if ($exists) {
  7337. $upd = $data;
  7338. unset($upd['scydgy_id']);
  7339. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  7340. } else {
  7341. $data['createtime'] = date('Y-m-d H:i:s');
  7342. Db::table('purchase_order')->insert($data);
  7343. }
  7344. }
  7345. /**
  7346. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  7347. *
  7348. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  7349. */
  7350. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
  7351. {
  7352. $toDb = function ($value) {
  7353. if ($value === null) {
  7354. return null;
  7355. }
  7356. if (is_scalar($value)) {
  7357. return $value;
  7358. }
  7359. return json_encode($value, JSON_UNESCAPED_UNICODE);
  7360. };
  7361. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7362. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7363. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7364. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  7365. if ($username === '') {
  7366. $username = $this->resolveCustomerContactName($phone, $companyName);
  7367. }
  7368. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  7369. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  7370. }
  7371. if ($requirePhone && $phone === '') {
  7372. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  7373. }
  7374. $detailLinks = [];
  7375. foreach ($mergeRows as $row) {
  7376. if (!is_array($row)) {
  7377. continue;
  7378. }
  7379. $sid = $this->extractScydgyRowId($row);
  7380. $detailId = 0;
  7381. if ($skipExisting) {
  7382. try {
  7383. $existsQuery = Db::table('purchase_order_detail')
  7384. ->where('scydgy_id', $sid)
  7385. ->where('company_name', $companyName);
  7386. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  7387. $exists = $existsQuery->find();
  7388. } catch (\Throwable $e) {
  7389. $exists = null;
  7390. }
  7391. if (is_array($exists)) {
  7392. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  7393. }
  7394. }
  7395. if ($detailId <= 0) {
  7396. $one = [
  7397. 'scydgy_id' => $toDb($sid),
  7398. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  7399. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  7400. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  7401. 'username' => $username !== '' ? $username : null,
  7402. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  7403. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  7404. 'createtime' => date('Y-m-d H:i:s'),
  7405. 'status' => ProcuremenStatus::POD_UNPICKED,
  7406. 'status_name' => '未提交',
  7407. ];
  7408. Db::table('purchase_order_detail')->insert($one);
  7409. $detailId = (int)Db::getLastInsID();
  7410. }
  7411. $mprocUrl = '';
  7412. if ($buildMobileLinks && $detailId > 0) {
  7413. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  7414. }
  7415. $detailLinks[] = [
  7416. 'detail_id' => $detailId,
  7417. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  7418. 'url' => $mprocUrl,
  7419. ];
  7420. }
  7421. $this->invalidatePickHiddenScydgyCache();
  7422. return $detailLinks;
  7423. }
  7424. /**
  7425. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  7426. * @return array<string, mixed>
  7427. */
  7428. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks): array
  7429. {
  7430. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7431. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7432. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7433. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  7434. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  7435. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  7436. $isMerge = !empty($ctx['is_merge']);
  7437. $contactName = trim((string)($c['username'] ?? ''));
  7438. if ($contactName === '') {
  7439. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  7440. }
  7441. $notifyVars = [
  7442. 'company_name' => $companyName,
  7443. 'contact_name' => $contactName,
  7444. 'phone' => $phone,
  7445. 'email' => $toEmail,
  7446. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  7447. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  7448. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  7449. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  7450. 'deadline' => (string)($ctx['deadline'] ?? ''),
  7451. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  7452. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  7453. 'platform_url' => $platformUrl,
  7454. 'platform_links' => $platformLinksPlain,
  7455. 'platform_links_html' => $platformLinksHtml,
  7456. ];
  7457. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  7458. $mailPlain = $this->renderNotifyTemplate('review_email', $notifyVars);
  7459. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  7460. return [
  7461. 'company_name' => $companyName,
  7462. 'phone' => $phone,
  7463. 'email' => $toEmail,
  7464. 'sms_content' => $smsContent,
  7465. 'mail_plain' => $mailPlain,
  7466. 'mail_body' => $mailBody,
  7467. 'notify_vars' => $notifyVars,
  7468. 'detail_links' => $detailLinks,
  7469. ];
  7470. }
  7471. /**
  7472. * @param array<string, mixed> $chosen
  7473. * @param array<int, array<string, mixed>> $mergeRows
  7474. * @param array{ccydh:string, pos:array} $bundle
  7475. */
  7476. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue'): void
  7477. {
  7478. if (!$sendSms && !$sendEmail) {
  7479. return;
  7480. }
  7481. $companyName = trim((string)($chosen['name'] ?? ''));
  7482. $phone = trim((string)($chosen['phone'] ?? ''));
  7483. $toEmail = trim((string)($chosen['email'] ?? ''));
  7484. if ($companyName === '') {
  7485. throw new \Exception('供应商名称无效');
  7486. }
  7487. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  7488. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  7489. }
  7490. if ($sendSms && $phone === '') {
  7491. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  7492. }
  7493. $sids = [];
  7494. foreach ($mergeRows as $mr) {
  7495. if (!is_array($mr)) {
  7496. continue;
  7497. }
  7498. $sid = $this->extractScydgyRowId($mr);
  7499. if ($this->isValidScydgyRowId($sid)) {
  7500. $sids[$sid] = true;
  7501. }
  7502. }
  7503. if ($sids === []) {
  7504. throw new \Exception('未找到工序行,无法发送通知');
  7505. }
  7506. $sysRqNotify = '';
  7507. $pos = $bundle['pos'] ?? [];
  7508. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7509. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  7510. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  7511. $ts = strtotime($sr);
  7512. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  7513. }
  7514. }
  7515. try {
  7516. $detailsQuery = Db::table('purchase_order_detail')
  7517. ->where('scydgy_id', 'in', array_keys($sids))
  7518. ->where('company_name', $companyName);
  7519. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7520. $details = $detailsQuery->order('id', 'asc')->select();
  7521. } catch (\Throwable $e) {
  7522. $details = [];
  7523. }
  7524. if (!is_array($details) || $details === []) {
  7525. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  7526. try {
  7527. $detailsQuery = Db::table('purchase_order_detail')
  7528. ->where('scydgy_id', 'in', array_keys($sids))
  7529. ->where('company_name', $companyName);
  7530. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7531. $details = $detailsQuery->order('id', 'asc')->select();
  7532. } catch (\Throwable $e) {
  7533. $details = [];
  7534. }
  7535. }
  7536. if (!is_array($details) || $details === []) {
  7537. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  7538. }
  7539. $detailLinks = [];
  7540. foreach ($details as $d) {
  7541. if (!is_array($d)) {
  7542. continue;
  7543. }
  7544. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  7545. if ($detailId <= 0) {
  7546. continue;
  7547. }
  7548. $sid = (int)($d['scydgy_id'] ?? 0);
  7549. $gymc = '';
  7550. foreach ($mergeRows as $mr) {
  7551. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  7552. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  7553. break;
  7554. }
  7555. }
  7556. $detailLinks[] = [
  7557. 'detail_id' => $detailId,
  7558. 'cgymc' => $gymc,
  7559. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  7560. ];
  7561. }
  7562. if ($detailLinks === []) {
  7563. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  7564. }
  7565. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  7566. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks);
  7567. $notifyBundle['email_log_scene'] = $emailLogScene;
  7568. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  7569. $poIdLog = 0;
  7570. $pos = $bundle['pos'] ?? [];
  7571. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7572. $poIdLog = (int)($pos[0]['id'] ?? 0);
  7573. }
  7574. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  7575. if ($sendEmail) {
  7576. $mailTplRow = $this->loadNotifyTemplateRow('review_email');
  7577. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  7578. throw new \Exception($this->notifyTemplateMissingMessage('review_email'));
  7579. }
  7580. $mailSubject = $this->resolveProcuremenEmailSubject('review_email');
  7581. $mailConfig = $this->loadMailerConfig();
  7582. if (!$this->isProcuremenNotifyDryRun()) {
  7583. if (empty($mailConfig['host'])) {
  7584. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  7585. }
  7586. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  7587. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  7588. }
  7589. }
  7590. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  7591. }
  7592. if ($sendSms) {
  7593. $this->issueSendSupplierSms($notifyBundle);
  7594. }
  7595. }
  7596. /**
  7597. * @param array<int, array<string, mixed>> $quoteGroups
  7598. * @return array<int, array<string, mixed>>
  7599. */
  7600. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  7601. {
  7602. $names = [];
  7603. if (is_string($companiesJson) && $companiesJson !== '') {
  7604. $decoded = json_decode($companiesJson, true);
  7605. if (is_array($decoded)) {
  7606. foreach ($decoded as $nm) {
  7607. $nm = trim((string)$nm);
  7608. if ($nm !== '') {
  7609. $names[] = $nm;
  7610. }
  7611. }
  7612. }
  7613. }
  7614. $names = array_values(array_unique($names));
  7615. if ($names === [] && $selectedCompany !== '') {
  7616. $names = [$selectedCompany];
  7617. }
  7618. if ($names === []) {
  7619. return $quoteGroups;
  7620. }
  7621. $targets = [];
  7622. foreach ($quoteGroups as $g) {
  7623. if (!is_array($g)) {
  7624. continue;
  7625. }
  7626. $cn = trim((string)($g['name'] ?? ''));
  7627. if ($cn !== '' && in_array($cn, $names, true)) {
  7628. $targets[] = $g;
  7629. }
  7630. }
  7631. return $targets;
  7632. }
  7633. /**
  7634. * @return array{pos:array, merge_rows:array, bundle:array}
  7635. */
  7636. protected function loadAuditResendBundle(string $scydgyId): array
  7637. {
  7638. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7639. $pos = $bundle['pos'];
  7640. $mergeRows = $bundle['merge_rows'];
  7641. if ($pos === [] || $mergeRows === []) {
  7642. $this->error('该订单不在待确认供应商状态');
  7643. }
  7644. $sysRqDb = '';
  7645. if (isset($pos[0]) && is_array($pos[0])) {
  7646. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  7647. }
  7648. foreach ($pos as $i => $poRow) {
  7649. if (is_array($pos[$i]) && $sysRqDb !== '') {
  7650. $pos[$i]['sys_rq'] = $sysRqDb;
  7651. }
  7652. }
  7653. $bundle['pos'] = $pos;
  7654. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  7655. }
  7656. /**
  7657. * @param array<int, array<string, mixed>> $targets
  7658. */
  7659. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  7660. {
  7661. if ($targets === []) {
  7662. $this->error('未找到可通知的供应商');
  7663. }
  7664. $notifyErrors = [];
  7665. try {
  7666. $this->notifyDryRunPreview = [];
  7667. foreach ($targets as $g) {
  7668. if (!is_array($g)) {
  7669. continue;
  7670. }
  7671. $cname = trim((string)($g['name'] ?? ''));
  7672. if ($cname === '') {
  7673. continue;
  7674. }
  7675. $chosen = [
  7676. 'name' => $cname,
  7677. 'company_name' => $cname,
  7678. 'email' => trim((string)($g['email'] ?? '')),
  7679. 'phone' => trim((string)($g['phone'] ?? '')),
  7680. 'username' => trim((string)($g['username'] ?? '')),
  7681. ];
  7682. try {
  7683. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  7684. } catch (\Throwable $e) {
  7685. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7686. }
  7687. }
  7688. } catch (\Throwable $e) {
  7689. $this->error('通知发送失败:' . $e->getMessage());
  7690. }
  7691. if ($notifyErrors !== []) {
  7692. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  7693. }
  7694. if ($this->isProcuremenNotifyDryRun()) {
  7695. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  7696. 'notify_dry_run' => true,
  7697. 'notify_preview' => $this->notifyDryRunPreview,
  7698. ]);
  7699. }
  7700. $nameLabels = [];
  7701. foreach ($targets as $g) {
  7702. if (!is_array($g)) {
  7703. continue;
  7704. }
  7705. $n = trim((string)($g['name'] ?? ''));
  7706. if ($n !== '') {
  7707. $nameLabels[] = $n;
  7708. }
  7709. }
  7710. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  7711. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  7712. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  7713. $seenLogSid = [];
  7714. foreach ($bundle['pos'] ?? [] as $poRow) {
  7715. if (!is_array($poRow)) {
  7716. continue;
  7717. }
  7718. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7719. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  7720. continue;
  7721. }
  7722. $seenLogSid[$sid] = true;
  7723. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7724. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7725. }
  7726. if ($seenLogSid === []) {
  7727. foreach ($mergeRows as $mr) {
  7728. if (!is_array($mr)) {
  7729. continue;
  7730. }
  7731. $sid = $this->extractScydgyRowId($mr);
  7732. if ($this->isValidScydgyRowId($sid)) {
  7733. $this->addOrderLog($sid, $logAction, $logMsg, null);
  7734. break;
  7735. }
  7736. }
  7737. }
  7738. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  7739. }
  7740. /**
  7741. * 协助下发 — 发送短信(一家供应商)
  7742. *
  7743. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  7744. */
  7745. protected function issueSendSupplierSms(array $bundle): void
  7746. {
  7747. $companyName = (string)($bundle['company_name'] ?? '');
  7748. $phone = (string)($bundle['phone'] ?? '');
  7749. $smsContent = (string)($bundle['sms_content'] ?? '');
  7750. $this->logIssueNotifyDebug('短信', [
  7751. 'company' => $companyName,
  7752. 'phone' => $phone,
  7753. 'sms_content' => $smsContent,
  7754. ]);
  7755. if ($this->isProcuremenNotifyDryRun()) {
  7756. $this->recordNotifyDryRunPreview([
  7757. 'scene' => 'issue_sms',
  7758. 'company_name' => $companyName,
  7759. 'phone' => $phone,
  7760. 'sms_content' => $smsContent,
  7761. ]);
  7762. return;
  7763. }
  7764. $this->smsbao($phone, $smsContent);
  7765. }
  7766. /**
  7767. * 协助下发 — 发送邮件(一家供应商)
  7768. *
  7769. * @param array<string, mixed> $bundle
  7770. * @param array<string, mixed> $mailConfig
  7771. */
  7772. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  7773. {
  7774. $companyName = (string)($bundle['company_name'] ?? '');
  7775. $toEmail = (string)($bundle['email'] ?? '');
  7776. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  7777. $mailBody = (string)($bundle['mail_body'] ?? '');
  7778. $this->logIssueNotifyDebug('邮件', [
  7779. 'company' => $companyName,
  7780. 'email' => $toEmail,
  7781. 'mail_subject' => $mailSubject,
  7782. 'mail_body' => $mailPlain,
  7783. ]);
  7784. if ($this->isProcuremenNotifyDryRun()) {
  7785. $this->recordNotifyDryRunPreview([
  7786. 'scene' => 'issue_email',
  7787. 'company_name' => $companyName,
  7788. 'email' => $toEmail,
  7789. 'mail_subject' => $mailSubject,
  7790. 'mail_body' => $mailPlain,
  7791. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  7792. 'notify_vars' => $bundle['notify_vars'] ?? [],
  7793. 'detail_links' => $bundle['detail_links'] ?? [],
  7794. ]);
  7795. return;
  7796. }
  7797. $mail = new PHPMailer(true);
  7798. $mail->isSMTP();
  7799. $mail->Host = $mailConfig['host'];
  7800. $mail->SMTPAuth = true;
  7801. $mail->Username = $mailConfig['addr'];
  7802. $mail->Password = $mailConfig['pass'];
  7803. $mail->SMTPSecure = $mailConfig['security'];
  7804. $mail->Port = $mailConfig['port'];
  7805. $mail->CharSet = $mailConfig['charset'];
  7806. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  7807. $mail->addAddress($toEmail, $companyName);
  7808. $mail->isHTML(true);
  7809. $mail->Subject = $mailSubject;
  7810. $mail->Body = $mailBody;
  7811. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  7812. $sendOk = true;
  7813. $failReason = '';
  7814. try {
  7815. $mail->send();
  7816. } catch (\Throwable $e) {
  7817. $sendOk = false;
  7818. $failReason = $e->getMessage();
  7819. $this->persistEmailSendLog([
  7820. 'from_email' => $fromEmail,
  7821. 'to_email' => $toEmail,
  7822. 'send_time' => date('Y-m-d H:i:s'),
  7823. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7824. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7825. 'company_name' => $companyName,
  7826. 'mail_subject' => $mailSubject,
  7827. 'status' => 0,
  7828. 'fail_reason' => $failReason,
  7829. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7830. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7831. ]);
  7832. throw $e;
  7833. }
  7834. $this->persistEmailSendLog([
  7835. 'from_email' => $fromEmail,
  7836. 'to_email' => $toEmail,
  7837. 'send_time' => date('Y-m-d H:i:s'),
  7838. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7839. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7840. 'company_name' => $companyName,
  7841. 'mail_subject' => $mailSubject,
  7842. 'status' => 1,
  7843. 'fail_reason' => '',
  7844. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7845. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7846. ]);
  7847. }
  7848. /**
  7849. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  7850. *
  7851. * @param array<int, array<string, mixed>> $mergeRows
  7852. * @return array<string, mixed>
  7853. */
  7854. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  7855. {
  7856. $head = $mergeRows[0] ?? [];
  7857. $isMerge = count($mergeRows) > 1;
  7858. return [
  7859. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  7860. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  7861. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  7862. 'is_merge' => $isMerge,
  7863. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  7864. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  7865. 'deadline' => $sysRqNotify,
  7866. ];
  7867. }
  7868. /**
  7869. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  7870. *
  7871. * @param array<string, mixed> $data
  7872. */
  7873. protected function logIssueNotifyDebug(string $type, array $data): void
  7874. {
  7875. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  7876. return;
  7877. }
  7878. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  7879. }
  7880. protected function ensurePurchaseEmailSendLogTableOnce(): void
  7881. {
  7882. try {
  7883. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  7884. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  7885. return;
  7886. } catch (\Throwable $e) {
  7887. }
  7888. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  7889. if (is_file($sqlFile)) {
  7890. $sql = file_get_contents($sqlFile);
  7891. if (is_string($sql) && $sql !== '') {
  7892. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  7893. $stmt = trim($stmt);
  7894. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  7895. continue;
  7896. }
  7897. try {
  7898. Db::execute($stmt);
  7899. } catch (\Throwable $ignore) {
  7900. }
  7901. }
  7902. }
  7903. }
  7904. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  7905. }
  7906. /**
  7907. * @param array<string, mixed> $row
  7908. */
  7909. protected function persistEmailSendLog(array $row): void
  7910. {
  7911. try {
  7912. $this->ensurePurchaseEmailSendLogTableOnce();
  7913. } catch (\Throwable $e) {
  7914. return;
  7915. }
  7916. list($adminId, $adminName) = $this->GetUseName();
  7917. $cut = function ($s, $max) {
  7918. $s = (string)$s;
  7919. if (function_exists('mb_substr')) {
  7920. return mb_substr($s, 0, $max, 'UTF-8');
  7921. }
  7922. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  7923. };
  7924. $data = [
  7925. 'from_email' => $cut($row['from_email'] ?? '', 128),
  7926. 'to_email' => $cut($row['to_email'] ?? '', 128),
  7927. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  7928. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  7929. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  7930. 'company_name' => $cut($row['company_name'] ?? '', 128),
  7931. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  7932. 'status' => !empty($row['status']) ? 1 : 0,
  7933. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  7934. 'admin_id' => (int)$adminId,
  7935. 'admin_name' => $cut($adminName, 64),
  7936. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  7937. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  7938. 'createtime' => date('Y-m-d H:i:s'),
  7939. ];
  7940. try {
  7941. Db::table('purchase_email_send_log')->insert($data);
  7942. } catch (\Throwable $e) {
  7943. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  7944. }
  7945. }
  7946. protected function formatEmailLogSceneText(string $scene): string
  7947. {
  7948. $map = [
  7949. 'pick_issue' => '初选下发',
  7950. 'audit_resend' => '确认页重发',
  7951. 'rfq_salesman' => '询价通知业务员',
  7952. ];
  7953. return $map[$scene] ?? $scene;
  7954. }
  7955. /**
  7956. * 邮件发送日志列表
  7957. */
  7958. public function emailLog()
  7959. {
  7960. $this->relationSearch = false;
  7961. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  7962. $this->request->filter(['strip_tags', 'trim']);
  7963. $bakModel = $this->model;
  7964. $this->model = new \app\admin\model\Purchaseemailsendlog;
  7965. if ($this->request->isAjax()) {
  7966. $this->ensurePurchaseEmailSendLogTableOnce();
  7967. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  7968. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  7969. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  7970. $list = $this->model
  7971. ->where($where)
  7972. ->order($sortField, $orderDir)
  7973. ->paginate($limit);
  7974. $rows = [];
  7975. foreach ($list->items() as $item) {
  7976. $row = is_array($item) ? $item : $item->toArray();
  7977. $scene = trim((string)($row['scene'] ?? ''));
  7978. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  7979. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  7980. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  7981. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  7982. $rows[] = $row;
  7983. }
  7984. $this->model = $bakModel;
  7985. return json(['total' => $list->total(), 'rows' => $rows]);
  7986. }
  7987. $this->model = $bakModel;
  7988. return $this->view->fetch('procuremen/emaillog');
  7989. }
  7990. /**
  7991. * 协助下发弹窗(选多家供应商并通知)
  7992. */
  7993. public function pickReview()
  7994. {
  7995. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  7996. $this->error(__('You have no permission'));
  7997. }
  7998. if ($this->request->isPost()) {
  7999. $this->error('请使用弹窗内「确认下发」提交');
  8000. }
  8001. $this->view->assign('pickMode', 1);
  8002. $this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
  8003. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  8004. }
  8005. /**
  8006. * 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
  8007. */
  8008. protected function ensurePurchaseOrderNotifySalesmanColumn(): 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 'notify_salesman'");
  8017. if (empty($cols)) {
  8018. Db::execute(
  8019. "ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
  8020. );
  8021. } else {
  8022. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  8023. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
  8024. Db::execute(
  8025. "ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
  8026. );
  8027. }
  8028. }
  8029. } catch (\Throwable $e) {
  8030. // ignore
  8031. }
  8032. }
  8033. /**
  8034. * 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
  8035. */
  8036. protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
  8037. {
  8038. static $done = false;
  8039. if ($done) {
  8040. return;
  8041. }
  8042. $done = true;
  8043. try {
  8044. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
  8045. if (empty($cols)) {
  8046. Db::execute(
  8047. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
  8048. );
  8049. }
  8050. } catch (\Throwable $e) {
  8051. // ignore
  8052. }
  8053. try {
  8054. $cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
  8055. if (empty($cols2)) {
  8056. Db::execute(
  8057. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
  8058. );
  8059. }
  8060. } catch (\Throwable $e) {
  8061. // ignore
  8062. }
  8063. }
  8064. /**
  8065. * 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
  8066. */
  8067. protected function ensureRfqSalesmanEmailTemplate(): void
  8068. {
  8069. static $done = false;
  8070. if ($done) {
  8071. return;
  8072. }
  8073. $done = true;
  8074. $content = "您好,{contact_name}:\n\n"
  8075. . "有新的协助采购询价需求,请知悉。\n"
  8076. . "印件名称:{cyjmc}\n"
  8077. . "工序名称:{cgymc}\n"
  8078. . "本次数量:{this_quantity}\n"
  8079. . "供应商:{supplier_name}\n"
  8080. . "需求发起人:{cywyxm}\n";
  8081. try {
  8082. $row = Db::table('purchase_sms_template')
  8083. ->where('scene', 'rfq_salesman_email')
  8084. ->find();
  8085. } catch (\Throwable $e) {
  8086. return;
  8087. }
  8088. $now = date('Y-m-d H:i:s');
  8089. if (is_array($row) && $row !== []) {
  8090. $old = (string)($row['content'] ?? '');
  8091. $needMigrate = (strpos($old, '需求编号:{ccydh}') !== false)
  8092. || (strpos($old, '{supplier_name}') === false && strpos($old, '供应商:') === false);
  8093. if ($needMigrate) {
  8094. $data = ['content' => $content];
  8095. try {
  8096. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
  8097. if (!empty($cols)) {
  8098. $data['updatetime'] = $now;
  8099. }
  8100. } catch (\Throwable $e) {
  8101. }
  8102. try {
  8103. Db::table('purchase_sms_template')
  8104. ->where('id', (int)($row['id'] ?? 0))
  8105. ->update($data);
  8106. } catch (\Throwable $e) {
  8107. }
  8108. }
  8109. return;
  8110. }
  8111. try {
  8112. $data = [
  8113. 'scene' => 'rfq_salesman_email',
  8114. 'title' => '询价邮箱通知',
  8115. 'content' => $content,
  8116. 'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
  8117. 'status' => 1,
  8118. ];
  8119. try {
  8120. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8121. } catch (\Throwable $e) {
  8122. $cols = [];
  8123. }
  8124. $colNames = [];
  8125. foreach ($cols as $c) {
  8126. if (!is_array($c)) {
  8127. continue;
  8128. }
  8129. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8130. if ($n !== '') {
  8131. $colNames[$n] = true;
  8132. }
  8133. }
  8134. if (isset($colNames['updatetime'])) {
  8135. $data['updatetime'] = $now;
  8136. }
  8137. if (isset($colNames['createtime'])) {
  8138. $data['createtime'] = $now;
  8139. }
  8140. Db::table('purchase_sms_template')->insert($data);
  8141. } catch (\Throwable $e) {
  8142. // ignore
  8143. }
  8144. }
  8145. /**
  8146. * 询价多选字段:数组或字符串统一为顿号拼接
  8147. *
  8148. * @param mixed $raw
  8149. */
  8150. protected function joinRfqMultiSelectValues($raw): string
  8151. {
  8152. $parts = [];
  8153. if (is_array($raw)) {
  8154. foreach ($raw as $item) {
  8155. if (is_array($item)) {
  8156. continue;
  8157. }
  8158. $v = trim((string)$item);
  8159. if ($v !== '') {
  8160. $parts[] = $v;
  8161. }
  8162. }
  8163. } else {
  8164. $s = trim((string)$raw);
  8165. if ($s !== '') {
  8166. foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
  8167. $v = trim((string)$piece);
  8168. if ($v !== '') {
  8169. $parts[] = $v;
  8170. }
  8171. }
  8172. }
  8173. }
  8174. $parts = array_values(array_unique($parts));
  8175. return implode('、', $parts);
  8176. }
  8177. /**
  8178. * 新增询价:可选供应商名称(仅落库记录,不发通知)
  8179. *
  8180. * @return string[]
  8181. */
  8182. protected function loadRfqSupplierNameOptions(): array
  8183. {
  8184. $out = [];
  8185. try {
  8186. $rows = Db::table('customer')
  8187. ->where(function ($q) {
  8188. $q->where('status', 1)
  8189. ->whereOr('status', '1')
  8190. ->whereOr('status', '')
  8191. ->whereNull('status');
  8192. })
  8193. ->order('id', 'desc')
  8194. ->column('company_name');
  8195. } catch (\Throwable $e) {
  8196. return [];
  8197. }
  8198. if (!is_array($rows)) {
  8199. return [];
  8200. }
  8201. foreach ($rows as $name) {
  8202. $name = trim((string)$name);
  8203. if ($name === '' || isset($out[$name])) {
  8204. continue;
  8205. }
  8206. $out[$name] = $name;
  8207. }
  8208. return array_values($out);
  8209. }
  8210. /**
  8211. * 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
  8212. */
  8213. protected function rfqNotifySalesmanAuthGroupId(): int
  8214. {
  8215. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  8216. if ($id > 0) {
  8217. return $id;
  8218. }
  8219. try {
  8220. $found = Db::name('auth_group')
  8221. ->where('name', '业务员')
  8222. ->where('status', 'normal')
  8223. ->order('id', 'asc')
  8224. ->value('id');
  8225. $id = (int)$found;
  8226. } catch (\Throwable $e) {
  8227. $id = 0;
  8228. }
  8229. return $id > 0 ? $id : 12;
  8230. }
  8231. /**
  8232. * 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
  8233. *
  8234. * @return string[]
  8235. */
  8236. protected function loadRfqSalesmanNameOptions(): array
  8237. {
  8238. $out = [];
  8239. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8240. $name = trim((string)($row['name'] ?? ''));
  8241. if ($name !== '') {
  8242. $out[] = $name;
  8243. }
  8244. }
  8245. return $out;
  8246. }
  8247. /**
  8248. * 业务员角色组下管理员:姓名、邮箱、手机
  8249. *
  8250. * @return array<int, array{name:string,email:string,mobile:string}>
  8251. */
  8252. protected function loadRfqSalesmanContactOptions(): array
  8253. {
  8254. $out = [];
  8255. $seen = [];
  8256. $groupId = $this->rfqNotifySalesmanAuthGroupId();
  8257. if ($groupId <= 0) {
  8258. return [];
  8259. }
  8260. try {
  8261. $adminIds = Db::name('auth_group_access')
  8262. ->where('group_id', $groupId)
  8263. ->column('uid');
  8264. } catch (\Throwable $e) {
  8265. return [];
  8266. }
  8267. $adminIds = is_array($adminIds)
  8268. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  8269. : [];
  8270. if ($adminIds === []) {
  8271. return [];
  8272. }
  8273. try {
  8274. $rows = Db::name('admin')
  8275. ->where('status', 'normal')
  8276. ->where('id', 'in', $adminIds)
  8277. ->order('id', 'asc')
  8278. ->field('id,nickname,username,email,mobile')
  8279. ->select();
  8280. } catch (\Throwable $e) {
  8281. return [];
  8282. }
  8283. if (!is_array($rows)) {
  8284. return [];
  8285. }
  8286. foreach ($rows as $row) {
  8287. if (!is_array($row)) {
  8288. continue;
  8289. }
  8290. $name = trim((string)($row['nickname'] ?? ''));
  8291. if ($name === '') {
  8292. $name = trim((string)($row['username'] ?? ''));
  8293. }
  8294. if ($name === '' || isset($seen[$name])) {
  8295. continue;
  8296. }
  8297. $seen[$name] = true;
  8298. $out[] = [
  8299. 'name' => $name,
  8300. 'email' => trim((string)($row['email'] ?? '')),
  8301. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  8302. ];
  8303. }
  8304. return $out;
  8305. }
  8306. /**
  8307. * 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
  8308. *
  8309. * @return string[]
  8310. */
  8311. protected function loadRfqDeptNameOptions(): array
  8312. {
  8313. $out = [];
  8314. // ERP 承揽部门(主来源)
  8315. try {
  8316. $vals = Db::table('mcyd')
  8317. ->where('CCLBMMC', '<>', '')
  8318. ->whereNotNull('CCLBMMC')
  8319. ->distinct(true)
  8320. ->limit(300)
  8321. ->column('CCLBMMC');
  8322. } catch (\Throwable $e) {
  8323. $vals = [];
  8324. }
  8325. if (is_array($vals)) {
  8326. foreach ($vals as $v) {
  8327. $v = trim((string)$v);
  8328. if ($v === '' || isset($out[$v])) {
  8329. continue;
  8330. }
  8331. $out[$v] = $v;
  8332. }
  8333. }
  8334. // 手工询价历史部门补全
  8335. try {
  8336. $poVals = Db::table('purchase_order')
  8337. ->where('CCLBMMC', '<>', '')
  8338. ->whereNotNull('CCLBMMC')
  8339. ->distinct(true)
  8340. ->limit(200)
  8341. ->column('CCLBMMC');
  8342. } catch (\Throwable $e) {
  8343. $poVals = [];
  8344. }
  8345. if (is_array($poVals)) {
  8346. foreach ($poVals as $v) {
  8347. $v = trim((string)$v);
  8348. if ($v === '' || isset($out[$v])) {
  8349. continue;
  8350. }
  8351. $out[$v] = $v;
  8352. }
  8353. }
  8354. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  8355. if (!isset($out[$preset])) {
  8356. $out[$preset] = $preset;
  8357. }
  8358. }
  8359. $list = array_values($out);
  8360. // 常用部门靠前
  8361. usort($list, static function ($a, $b) {
  8362. $weight = [
  8363. '营销中心' => 1,
  8364. '业务部' => 2,
  8365. '市场部' => 3,
  8366. '外贸部' => 4,
  8367. '新华技术业务部' => 5,
  8368. ];
  8369. $wa = $weight[$a] ?? 100;
  8370. $wb = $weight[$b] ?? 100;
  8371. if ($wa !== $wb) {
  8372. return $wa <=> $wb;
  8373. }
  8374. return strcmp((string)$a, (string)$b);
  8375. });
  8376. return $list;
  8377. }
  8378. /**
  8379. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  8380. */
  8381. public function add()
  8382. {
  8383. if ($this->request->isPost()) {
  8384. $params = $this->request->post('row/a');
  8385. if (!is_array($params)) {
  8386. $this->error(__('Parameter %s can not be empty', ''));
  8387. }
  8388. [, $adminName] = $this->GetUseName();
  8389. $params['cywyxm'] = $adminName;
  8390. try {
  8391. $sid = $this->saveManualPickOrder($params);
  8392. } catch (\InvalidArgumentException $e) {
  8393. $this->error($e->getMessage());
  8394. } catch (\Throwable $e) {
  8395. $this->error($e->getMessage());
  8396. }
  8397. $this->success('新增成功', '', [
  8398. 'scydgy_id' => $sid,
  8399. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  8400. ]);
  8401. }
  8402. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8403. [, $adminName] = $this->GetUseName();
  8404. $this->view->assign('adminNickname', $adminName);
  8405. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  8406. $this->view->assign('defaultCclbmmc', '营销中心');
  8407. $this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
  8408. $this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
  8409. $this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
  8410. return $this->view->fetch();
  8411. }
  8412. /**
  8413. * 业务员新增进度查询(手工询价;发起人 / 通知业务员可见,超管看全部)
  8414. */
  8415. public function rfqlist()
  8416. {
  8417. $this->relationSearch = false;
  8418. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ';
  8419. $this->request->filter(['strip_tags', 'trim']);
  8420. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8421. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8422. $this->ensureRfqSalesmanEmailTemplate();
  8423. if ($this->request->isAjax()) {
  8424. try {
  8425. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  8426. $limit = max(10, min(500, (int)$limit));
  8427. $filterYm = trim((string)$this->request->param('filter_ym', ''));
  8428. if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
  8429. $filterYm = date('Y-m');
  8430. }
  8431. $applyFilters = function ($query) use ($where, $filterYm) {
  8432. $query->where('scydgy_id', '<', 0);
  8433. $this->applyPurchaseOrderNotDeletedWhere($query);
  8434. $this->applyManualRfqViewerWhere($query);
  8435. $this->applyRfqListMonthFilter($query, $filterYm);
  8436. if (!empty($where)) {
  8437. // 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
  8438. $safeWhere = [];
  8439. $skipFields = [
  8440. 'supplier_name' => true,
  8441. 'progress_text' => true,
  8442. 'createtime_text' => true,
  8443. 'notify_time_text' => true,
  8444. 'can_notify_salesman' => true,
  8445. 'has_issued' => true,
  8446. 'has_quoted' => true,
  8447. ];
  8448. foreach ((array)$where as $cond) {
  8449. if (!is_array($cond) || !isset($cond[0])) {
  8450. continue;
  8451. }
  8452. $field = (string)$cond[0];
  8453. $fieldBase = (string)preg_replace('/\|.*$/', '', $field);
  8454. $fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
  8455. if (isset($skipFields[$fieldBase])) {
  8456. continue;
  8457. }
  8458. if ($fieldBase === 'supplier_name') {
  8459. continue;
  8460. }
  8461. $safeWhere[] = $cond;
  8462. }
  8463. if ($safeWhere !== []) {
  8464. $query->where($safeWhere);
  8465. }
  8466. }
  8467. };
  8468. $countQuery = Db::table('purchase_order');
  8469. $applyFilters($countQuery);
  8470. $total = (int)$countQuery->count();
  8471. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  8472. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  8473. $listQuery = Db::table('purchase_order');
  8474. $applyFilters($listQuery);
  8475. $rows = $listQuery
  8476. ->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')
  8477. ->order($sortField, $orderDir)
  8478. ->limit($offset, $limit)
  8479. ->select();
  8480. if (!is_array($rows)) {
  8481. $rows = [];
  8482. }
  8483. $sidList = [];
  8484. foreach ($rows as $r) {
  8485. if (!is_array($r)) {
  8486. continue;
  8487. }
  8488. $sid = (int)($r['scydgy_id'] ?? 0);
  8489. if ($sid < 0) {
  8490. $sidList[$sid] = true;
  8491. }
  8492. }
  8493. $issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
  8494. $quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
  8495. $out = [];
  8496. foreach ($rows as $r) {
  8497. if (!is_array($r)) {
  8498. continue;
  8499. }
  8500. $sid = (int)($r['scydgy_id'] ?? 0);
  8501. if ($sid >= 0) {
  8502. continue;
  8503. }
  8504. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  8505. if ($createdText === '') {
  8506. $createdText = trim((string)($r['dStamp'] ?? ''));
  8507. }
  8508. $notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
  8509. $supplier = trim((string)($r['cGzzxMc'] ?? ''));
  8510. if ($supplier === '') {
  8511. $supplier = trim((string)($r['pick_company_name'] ?? ''));
  8512. }
  8513. $hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
  8514. || isset($issuedSidSet[$sid]);
  8515. $hasQuoted = isset($quotedSidSet[$sid]);
  8516. $salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
  8517. $canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
  8518. $out[] = [
  8519. 'id' => (int)($r['id'] ?? 0),
  8520. 'scydgy_id' => $sid,
  8521. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  8522. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  8523. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  8524. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  8525. 'CDW' => trim((string)($r['CDW'] ?? '')),
  8526. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  8527. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  8528. 'CDF' => trim((string)($r['CDF'] ?? '')),
  8529. 'supplier_name' => $supplier,
  8530. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  8531. 'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
  8532. 'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
  8533. 'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
  8534. 'notify_time_text' => $notifyTimeText,
  8535. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  8536. 'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
  8537. 'has_issued' => $hasIssued ? 1 : 0,
  8538. 'has_quoted' => $hasQuoted ? 1 : 0,
  8539. 'can_notify_salesman' => $canNotifySalesman,
  8540. 'createtime' => $r['createtime'] ?? null,
  8541. 'createtime_text' => $createdText,
  8542. ];
  8543. }
  8544. return json(['total' => $total, 'rows' => $out]);
  8545. } catch (\Throwable $e) {
  8546. Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
  8547. return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
  8548. }
  8549. }
  8550. $sidebar = $this->loadRfqSidebarYearMonths();
  8551. $defaultYm = $this->resolveRfqListDefaultYm($sidebar);
  8552. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  8553. [, $adminName] = $this->GetUseName();
  8554. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  8555. $this->view->assign('adminNickname', $adminName);
  8556. $this->view->assign('defaultYm', $defaultYm);
  8557. $this->view->assign('sidebarYearMonths', $sidebar);
  8558. return $this->view->fetch('procuremen/rfqlist');
  8559. }
  8560. /**
  8561. * 列表默认月份:当月有数据用当月,否则取最近有数据的月份
  8562. *
  8563. * @param array<int, array{year:string, months:array}> $sidebar
  8564. */
  8565. protected function resolveRfqListDefaultYm(array $sidebar): string
  8566. {
  8567. $current = date('Y-m');
  8568. $yms = $this->flattenProcuremenSidebarYms($sidebar);
  8569. if (in_array($current, $yms, true)) {
  8570. return $current;
  8571. }
  8572. if ($yms !== []) {
  8573. rsort($yms, SORT_STRING);
  8574. return (string)$yms[0];
  8575. }
  8576. return $current;
  8577. }
  8578. /**
  8579. * 手工询价列表左侧月份(按 createtime / dStamp)
  8580. *
  8581. * @return array<int, array{year:string, months:array}>
  8582. */
  8583. protected function loadRfqSidebarYearMonths(): array
  8584. {
  8585. $ymSet = [];
  8586. try {
  8587. $q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
  8588. $this->applyPurchaseOrderNotDeletedWhere($q);
  8589. $this->applyManualRfqViewerWhere($q);
  8590. $rows = $q->field('createtime,dStamp')->limit(5000)->select();
  8591. } catch (\Throwable $e) {
  8592. $rows = [];
  8593. }
  8594. if (!is_array($rows)) {
  8595. $rows = [];
  8596. }
  8597. foreach ($rows as $r) {
  8598. if (!is_array($r)) {
  8599. continue;
  8600. }
  8601. $t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  8602. if ($t === '') {
  8603. $t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
  8604. }
  8605. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  8606. $ymSet[$m[1] . '-' . $m[2]] = true;
  8607. }
  8608. }
  8609. return $this->buildYearMonthSidebar(array_keys($ymSet));
  8610. }
  8611. /**
  8612. * 手工询价可见范围:仅「需求发起人」或「通知业务员」与当前登录账号一致(超管看全部)
  8613. */
  8614. protected function applyManualRfqViewerWhere($query): void
  8615. {
  8616. if ($this->auth->isSuperAdmin()) {
  8617. return;
  8618. }
  8619. [, $adminName] = $this->GetUseName();
  8620. $adminName = trim((string)$adminName);
  8621. if ($adminName === '') {
  8622. $query->whereRaw('1 = 0');
  8623. return;
  8624. }
  8625. // 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
  8626. $query->where(function ($q) use ($adminName) {
  8627. $q->where('cywyxm', $adminName)
  8628. ->whereOr('notify_salesman', $adminName)
  8629. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  8630. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  8631. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  8632. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  8633. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  8634. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  8635. });
  8636. }
  8637. /**
  8638. * 当前用户是否可查看/操作该手工询价单(需求发起人或通知业务员;超管全部)
  8639. */
  8640. protected function canViewManualRfqOrder(array $po): bool
  8641. {
  8642. if ($this->auth->isSuperAdmin()) {
  8643. return true;
  8644. }
  8645. [, $adminName] = $this->GetUseName();
  8646. $adminName = trim((string)$adminName);
  8647. if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
  8648. return true;
  8649. }
  8650. if ($adminName !== '') {
  8651. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  8652. if ($n === $adminName) {
  8653. return true;
  8654. }
  8655. }
  8656. }
  8657. return false;
  8658. }
  8659. /**
  8660. * 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
  8661. */
  8662. protected function applyRfqListMonthFilter($query, string $ym): void
  8663. {
  8664. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  8665. $ym = date('Y-m');
  8666. }
  8667. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  8668. // 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
  8669. $query->whereRaw(
  8670. "("
  8671. . "CASE "
  8672. . "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  8673. . "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
  8674. . "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
  8675. . "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  8676. . "THEN TRIM(CAST(createtime AS CHAR(32))) "
  8677. . "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
  8678. . "END"
  8679. . ") LIKE '{$ymEsc}-%'"
  8680. );
  8681. }
  8682. /**
  8683. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  8684. */
  8685. public function rfqlistDetails()
  8686. {
  8687. return $this->details();
  8688. }
  8689. /**
  8690. * 查询询价 — 弹窗:可选通知业务员名单(勾选后确认通知)
  8691. */
  8692. public function rfqnotifysalesmen()
  8693. {
  8694. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen'])) {
  8695. $this->error(__('You have no permission'));
  8696. }
  8697. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8698. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8699. $sid = (int)$this->request->param('scydgy_id', 0);
  8700. if ($sid >= 0) {
  8701. $this->error('仅支持手工新增询价单');
  8702. }
  8703. $po = $this->loadManualRfqOrderForNotify($sid);
  8704. $selectedMap = [];
  8705. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  8706. $selectedMap[$n] = true;
  8707. }
  8708. $list = [];
  8709. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8710. $name = trim((string)($row['name'] ?? ''));
  8711. if ($name === '') {
  8712. continue;
  8713. }
  8714. $email = trim((string)($row['email'] ?? ''));
  8715. $mobile = trim((string)($row['mobile'] ?? ''));
  8716. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  8717. $list[] = [
  8718. 'name' => $name,
  8719. 'email' => $email,
  8720. 'mobile' => $mobile,
  8721. 'can_select' => $hasEmail ? 1 : 0,
  8722. 'checked' => (!empty($selectedMap[$name]) && $hasEmail) ? 1 : 0,
  8723. ];
  8724. }
  8725. $canNotify = $this->canRfqNotifySalesman($po);
  8726. $this->success('', null, [
  8727. 'scydgy_id' => $sid,
  8728. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  8729. 'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
  8730. 'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
  8731. 'can_notify_salesman' => $canNotify ? 1 : 0,
  8732. 'list' => $list,
  8733. ]);
  8734. }
  8735. /**
  8736. * 查询询价 — 补加通知业务员可选名单
  8737. */
  8738. public function rfqsalesmanoptions()
  8739. {
  8740. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen', 'rfqsalesmanoptions', 'rfqappendsalesmen'])) {
  8741. $this->error(__('You have no permission'));
  8742. }
  8743. $out = [];
  8744. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8745. $email = trim((string)($row['email'] ?? ''));
  8746. $mobile = trim((string)($row['mobile'] ?? ''));
  8747. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  8748. $out[] = [
  8749. 'name' => (string)($row['name'] ?? ''),
  8750. 'email' => $email,
  8751. 'mobile' => $mobile,
  8752. 'can_select' => $hasEmail ? 1 : 0,
  8753. ];
  8754. }
  8755. $this->success('', null, ['list' => $out]);
  8756. }
  8757. /**
  8758. * 查询询价 — 补加通知业务员(合并更新 notify_salesman)
  8759. */
  8760. public function rfqappendsalesmen()
  8761. {
  8762. if (!$this->request->isPost()) {
  8763. $this->error(__('Invalid parameters'));
  8764. }
  8765. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesmen', 'rfqappendsalesmen'])) {
  8766. $this->error(__('You have no permission'));
  8767. }
  8768. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8769. $sid = (int)$this->request->post('scydgy_id', 0);
  8770. if ($sid >= 0) {
  8771. $this->error('仅支持手工新增询价单');
  8772. }
  8773. $po = $this->loadManualRfqOrderForNotify($sid);
  8774. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  8775. $this->error('订单已完结,无法添加业务员');
  8776. }
  8777. $raw = $this->request->post('salesmen/a', []);
  8778. if (!is_array($raw) || $raw === []) {
  8779. $salesmenJson = $this->request->post('salesmen_json', '');
  8780. if (is_string($salesmenJson) && $salesmenJson !== '') {
  8781. $decoded = json_decode($salesmenJson, true);
  8782. $raw = is_array($decoded) ? $decoded : [];
  8783. }
  8784. }
  8785. $addNames = [];
  8786. foreach ((array)$raw as $item) {
  8787. if (is_array($item)) {
  8788. $n = trim((string)($item['name'] ?? ''));
  8789. } else {
  8790. $n = trim((string)$item);
  8791. }
  8792. if ($n !== '') {
  8793. $addNames[] = $n;
  8794. }
  8795. }
  8796. $addNames = array_values(array_unique($addNames));
  8797. if ($addNames === []) {
  8798. $this->error('请选择要添加的业务员');
  8799. }
  8800. $allowedOptions = $this->loadRfqSalesmanContactOptions();
  8801. $allowedMap = [];
  8802. foreach ($allowedOptions as $opt) {
  8803. $n = trim((string)($opt['name'] ?? ''));
  8804. if ($n === '') {
  8805. continue;
  8806. }
  8807. $email = trim((string)($opt['email'] ?? ''));
  8808. $allowedMap[$n] = ($email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL));
  8809. }
  8810. foreach ($addNames as $n) {
  8811. if (!array_key_exists($n, $allowedMap)) {
  8812. $this->error('业务员不在可选名单中:' . $n);
  8813. }
  8814. if (!$allowedMap[$n]) {
  8815. $this->error('业务员未填写有效邮箱,无法添加:' . $n);
  8816. }
  8817. }
  8818. $existingRaw = trim((string)($po['notify_salesman'] ?? ''));
  8819. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  8820. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  8821. try {
  8822. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['notify_salesman' => $mergedStr]);
  8823. } catch (\Throwable $e) {
  8824. $this->error('保存失败:' . $e->getMessage());
  8825. }
  8826. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  8827. $this->addOrderLog($sid, 'rfq_append_salesman', '添加通知业务员:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  8828. $this->success('已添加业务员', null, [
  8829. 'scydgy_id' => $sid,
  8830. 'notify_salesman' => $mergedStr,
  8831. 'added_count' => count($addNames),
  8832. ]);
  8833. }
  8834. /**
  8835. * 查询询价 — 勾选业务员后邮箱通知(salesmen_json)
  8836. */
  8837. public function rfqnotifysalesman()
  8838. {
  8839. if (!$this->request->isPost()) {
  8840. $this->error(__('Invalid parameters'));
  8841. }
  8842. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqnotifysalesman'])) {
  8843. $this->error(__('You have no permission'));
  8844. }
  8845. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8846. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8847. $sid = (int)$this->request->post('scydgy_id', 0);
  8848. if ($sid >= 0) {
  8849. $this->error('仅支持手工新增询价单');
  8850. }
  8851. $po = $this->loadManualRfqOrderForNotify($sid);
  8852. $this->assertRfqCanNotifySalesman($po);
  8853. $raw = $this->request->post('salesmen/a', []);
  8854. if (!is_array($raw) || $raw === []) {
  8855. $salesmenJson = $this->request->post('salesmen_json', '');
  8856. if (is_string($salesmenJson) && $salesmenJson !== '') {
  8857. $decoded = json_decode($salesmenJson, true);
  8858. $raw = is_array($decoded) ? $decoded : [];
  8859. }
  8860. }
  8861. // 兼容旧参数:notify_all / 单人 name
  8862. if ((!is_array($raw) || $raw === []) && (int)$this->request->post('notify_all', 0) === 1) {
  8863. $raw = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  8864. }
  8865. if ((!is_array($raw) || $raw === [])) {
  8866. $oneName = trim((string)$this->request->post('name', ''));
  8867. if ($oneName !== '') {
  8868. $raw = [$oneName];
  8869. }
  8870. }
  8871. $selectedNames = [];
  8872. foreach ((array)$raw as $item) {
  8873. if (is_array($item)) {
  8874. $n = trim((string)($item['name'] ?? ''));
  8875. } else {
  8876. $n = trim((string)$item);
  8877. }
  8878. if ($n !== '') {
  8879. $selectedNames[] = $n;
  8880. }
  8881. }
  8882. $selectedNames = array_values(array_unique($selectedNames));
  8883. if ($selectedNames === []) {
  8884. $this->error('请选择要通知的业务员');
  8885. }
  8886. $optionMap = [];
  8887. foreach ($this->loadRfqSalesmanContactOptions() as $opt) {
  8888. $n = trim((string)($opt['name'] ?? ''));
  8889. if ($n === '') {
  8890. continue;
  8891. }
  8892. $optionMap[$n] = $opt;
  8893. }
  8894. $targets = [];
  8895. foreach ($selectedNames as $n) {
  8896. if (!isset($optionMap[$n])) {
  8897. $this->error('业务员不在可选名单中:' . $n);
  8898. }
  8899. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  8900. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  8901. $this->error('业务员未填写有效邮箱,无法通知:' . $n);
  8902. }
  8903. $resolved = $this->resolveRfqSalesmanContactRows([$n]);
  8904. $targets[] = $resolved[0] ?? [
  8905. 'admin_id' => 0,
  8906. 'name' => $n,
  8907. 'email' => $email,
  8908. ];
  8909. }
  8910. $mergedStr = $this->joinRfqMultiSelectValues($selectedNames);
  8911. try {
  8912. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  8913. 'notify_salesman' => $mergedStr,
  8914. ]);
  8915. } catch (\Throwable $e) {
  8916. $this->error('保存通知业务员失败:' . $e->getMessage());
  8917. }
  8918. $po['notify_salesman'] = $mergedStr;
  8919. $mailConfig = $this->loadMailerConfig();
  8920. if (empty($mailConfig['host'])) {
  8921. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  8922. }
  8923. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  8924. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  8925. }
  8926. $this->ensureRfqSalesmanEmailTemplate();
  8927. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  8928. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  8929. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  8930. $qty = trim((string)($po['This_quantity'] ?? ''));
  8931. $cywyxm = trim((string)($po['cywyxm'] ?? ''));
  8932. $supplier = trim((string)($po['cGzzxMc'] ?? ''));
  8933. if ($supplier === '') {
  8934. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  8935. }
  8936. try {
  8937. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
  8938. } catch (\Throwable $e) {
  8939. $this->error($e->getMessage());
  8940. }
  8941. $okNames = [];
  8942. $failMsgs = [];
  8943. foreach ($targets as $contact) {
  8944. $toEmail = trim((string)($contact['email'] ?? ''));
  8945. $toName = trim((string)($contact['name'] ?? ''));
  8946. $notifyVars = [
  8947. 'contact_name' => $toName,
  8948. 'salesman_name' => $toName,
  8949. 'company_name' => $toName,
  8950. 'email' => $toEmail,
  8951. 'ccydh' => $ccydh,
  8952. 'cyjmc' => $cyjmc,
  8953. 'cgymc' => $cgymc,
  8954. 'this_quantity' => $qty,
  8955. 'supplier_name' => $supplier,
  8956. 'cywyxm' => $cywyxm,
  8957. ];
  8958. try {
  8959. $mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
  8960. $mailSubject = $mailSubjectTpl;
  8961. foreach ($notifyVars as $k => $v) {
  8962. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  8963. }
  8964. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  8965. $mailSubject = trim((string)$mailSubject);
  8966. if ($mailSubject === '') {
  8967. $mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  8968. }
  8969. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  8970. $bundle = [
  8971. 'company_name' => $toName,
  8972. 'email' => $toEmail,
  8973. 'mail_plain' => $mailPlain,
  8974. 'mail_body' => $mailBody,
  8975. 'ccydh' => $ccydh,
  8976. 'email_log_scene' => 'rfq_salesman',
  8977. 'email_log_scydgy_id' => $sid,
  8978. 'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
  8979. 'notify_vars' => $notifyVars,
  8980. ];
  8981. $this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
  8982. $okNames[] = $toName . '(' . $toEmail . ')';
  8983. } catch (\Throwable $e) {
  8984. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  8985. }
  8986. }
  8987. if ($okNames === []) {
  8988. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  8989. }
  8990. $now = date('Y-m-d H:i:s');
  8991. try {
  8992. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  8993. 'rfq_salesman_notified' => 1,
  8994. 'rfq_salesman_notify_time' => $now,
  8995. ]);
  8996. } catch (\Throwable $e) {
  8997. // ignore
  8998. }
  8999. $this->addOrderLog(
  9000. $sid,
  9001. 'rfq_notify_salesman',
  9002. '邮箱通知业务员:' . implode('、', $okNames),
  9003. (int)($po['id'] ?? 0)
  9004. );
  9005. $msg = '已通知 ' . count($okNames) . ' 人';
  9006. if ($failMsgs !== []) {
  9007. $msg .= ';部分失败:' . implode(';', $failMsgs);
  9008. }
  9009. $this->success($msg, null, [
  9010. 'scydgy_id' => $sid,
  9011. 'notify_salesman' => $mergedStr,
  9012. 'rfq_salesman_notified' => 1,
  9013. 'rfq_salesman_notify_time' => $now,
  9014. 'notify_time_text' => $now,
  9015. 'ok_count' => count($okNames),
  9016. 'fail_count' => count($failMsgs),
  9017. ]);
  9018. }
  9019. /**
  9020. * 查询询价 — 下发前:返回将通知的供应商表格数据
  9021. */
  9022. public function rfqissuesuppliers()
  9023. {
  9024. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqissuesuppliers'])) {
  9025. $this->error(__('You have no permission'));
  9026. }
  9027. $sid = (int)$this->request->param('scydgy_id', 0);
  9028. if ($sid >= 0) {
  9029. $this->error('仅支持手工新增询价单');
  9030. }
  9031. $po = $this->loadManualRfqOrderForNotify($sid);
  9032. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9033. if ($supplierRaw === '') {
  9034. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9035. }
  9036. $names = $this->splitRfqSalesmanNames($supplierRaw);
  9037. $list = [];
  9038. foreach ($names as $name) {
  9039. // 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
  9040. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9041. $email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
  9042. $phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
  9043. $username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
  9044. $okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
  9045. $list[] = [
  9046. 'name' => $name,
  9047. 'username' => $username,
  9048. 'email' => $email,
  9049. 'phone' => $phone,
  9050. 'can_notify' => $okEmail ? 1 : 0,
  9051. 'found' => is_array($contact) ? 1 : 0,
  9052. ];
  9053. }
  9054. $this->success('', null, [
  9055. 'scydgy_id' => $sid,
  9056. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9057. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9058. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9059. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9060. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9061. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9062. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9063. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9064. 'list' => $list,
  9065. ]);
  9066. }
  9067. /**
  9068. * 查询询价 — 补加供应商可选名单
  9069. */
  9070. public function rfqsupplieroptions()
  9071. {
  9072. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
  9073. $this->error(__('You have no permission'));
  9074. }
  9075. $names = array_values($this->loadRfqSupplierNameOptions());
  9076. $out = [];
  9077. foreach ($names as $name) {
  9078. $out[] = ['name' => $name];
  9079. }
  9080. $this->success('', null, ['list' => $out]);
  9081. }
  9082. /**
  9083. * 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
  9084. */
  9085. public function rfqappendsuppliers()
  9086. {
  9087. if (!$this->request->isPost()) {
  9088. $this->error(__('Invalid parameters'));
  9089. }
  9090. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqappendsuppliers'])) {
  9091. $this->error(__('You have no permission'));
  9092. }
  9093. $sid = (int)$this->request->post('scydgy_id', 0);
  9094. if ($sid >= 0) {
  9095. $this->error('仅支持手工新增询价单');
  9096. }
  9097. $po = $this->loadManualRfqOrderForNotify($sid);
  9098. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9099. $this->error('订单已完结,无法补加供应商');
  9100. }
  9101. $raw = $this->request->post('suppliers/a', []);
  9102. if (!is_array($raw) || $raw === []) {
  9103. $suppliersJson = $this->request->post('suppliers_json', '');
  9104. if (is_string($suppliersJson) && $suppliersJson !== '') {
  9105. $decoded = json_decode($suppliersJson, true);
  9106. $raw = is_array($decoded) ? $decoded : [];
  9107. }
  9108. }
  9109. $addNames = [];
  9110. foreach ((array)$raw as $item) {
  9111. if (is_array($item)) {
  9112. $n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
  9113. } else {
  9114. $n = trim((string)$item);
  9115. }
  9116. if ($n !== '') {
  9117. $addNames[] = $n;
  9118. }
  9119. }
  9120. $addNames = array_values(array_unique($addNames));
  9121. if ($addNames === []) {
  9122. $this->error('请选择要补加的供应商');
  9123. }
  9124. $existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9125. if ($existingRaw === '') {
  9126. $existingRaw = trim((string)($po['pick_company_name'] ?? ''));
  9127. }
  9128. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9129. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9130. try {
  9131. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
  9132. } catch (\Throwable $e) {
  9133. $this->error('保存失败:' . $e->getMessage());
  9134. }
  9135. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9136. $this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9137. $this->success('已补加供应商', null, [
  9138. 'scydgy_id' => $sid,
  9139. 'cGzzxMc' => $mergedStr,
  9140. 'added_count' => count($addNames),
  9141. ]);
  9142. }
  9143. /**
  9144. * 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
  9145. */
  9146. public function rfqissue()
  9147. {
  9148. if (!$this->request->isPost()) {
  9149. $this->error(__('Invalid parameters'));
  9150. }
  9151. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue'])) {
  9152. $this->error(__('You have no permission'));
  9153. }
  9154. $sid = (int)$this->request->post('scydgy_id', 0);
  9155. if ($sid >= 0) {
  9156. $this->error('仅支持手工新增询价单');
  9157. }
  9158. $po = $this->loadManualRfqOrderForNotify($sid);
  9159. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9160. $this->error('订单已完结,无法下发');
  9161. }
  9162. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9163. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9164. $this->error('订单已进入后续流程,无法再下发');
  9165. }
  9166. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9167. if ($supplierRaw === '') {
  9168. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9169. }
  9170. $supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
  9171. if ($supplierNames === []) {
  9172. $this->error('请先在新增询价时选择供应商');
  9173. }
  9174. $companies = [];
  9175. $missing = [];
  9176. $noEmail = [];
  9177. foreach ($supplierNames as $name) {
  9178. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9179. if ($contact === null) {
  9180. $missing[] = $name;
  9181. continue;
  9182. }
  9183. $em = trim((string)($contact['email'] ?? ''));
  9184. if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
  9185. $noEmail[] = $name;
  9186. continue;
  9187. }
  9188. $companies[] = $contact;
  9189. }
  9190. if ($missing !== []) {
  9191. $this->error('未找到供应商档案:' . implode('、', $missing));
  9192. }
  9193. if ($noEmail !== []) {
  9194. $this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
  9195. }
  9196. if ($companies === []) {
  9197. $this->error('没有可通知的供应商');
  9198. }
  9199. $mailConfig = $this->loadMailerConfig();
  9200. if (empty($mailConfig['host'])) {
  9201. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9202. }
  9203. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9204. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9205. }
  9206. $mergeRow = $po;
  9207. $mergeRow['ID'] = $sid;
  9208. $mergeRow['id'] = $sid;
  9209. $mergeRows = [$mergeRow];
  9210. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9211. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9212. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9213. }
  9214. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9215. $issueTime = date('Y-m-d H:i:s');
  9216. $nameLabels = [];
  9217. foreach ($companies as $c) {
  9218. $nameLabels[] = trim((string)($c['name'] ?? ''));
  9219. }
  9220. $logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
  9221. Db::startTrans();
  9222. try {
  9223. $this->upsertPurchaseOrderFromRow(
  9224. $mergeRow,
  9225. $sysRqDb,
  9226. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9227. $issueTime,
  9228. $po,
  9229. null,
  9230. $scoreRule
  9231. );
  9232. foreach ($companies as $c) {
  9233. $this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
  9234. }
  9235. Db::commit();
  9236. } catch (\Throwable $e) {
  9237. Db::rollback();
  9238. $this->error($e->getMessage());
  9239. }
  9240. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9241. if ($poId <= 0) {
  9242. try {
  9243. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9244. } catch (\Throwable $e) {
  9245. $poId = 0;
  9246. }
  9247. }
  9248. $this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
  9249. $posNotify = [];
  9250. try {
  9251. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9252. if (is_array($fresh)) {
  9253. $fresh['sys_rq'] = $sysRqDb;
  9254. $posNotify = [$fresh];
  9255. }
  9256. } catch (\Throwable $e) {
  9257. $posNotify = [$po];
  9258. $posNotify[0]['sys_rq'] = $sysRqDb;
  9259. }
  9260. $notifyBundle = [
  9261. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9262. 'pos' => $posNotify,
  9263. 'merge_rows' => $mergeRows,
  9264. ];
  9265. $notifyErrors = [];
  9266. foreach ($companies as $c) {
  9267. $cname = trim((string)($c['name'] ?? ''));
  9268. try {
  9269. // 询价下发:仅邮箱通知供应商
  9270. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'pick_issue');
  9271. } catch (\Throwable $e) {
  9272. $notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
  9273. }
  9274. }
  9275. if ($notifyErrors !== []) {
  9276. $this->error('下发已保存,但邮件通知失败:' . implode(';', $notifyErrors));
  9277. }
  9278. $this->success('已询价并邮件通知供应商', null, [
  9279. 'scydgy_id' => $sid,
  9280. 'progress_text' => '待报价',
  9281. 'supplier_count' => count($companies),
  9282. ]);
  9283. }
  9284. /**
  9285. * 查询询价 — 弹窗内向单个供应商发送询价邮件
  9286. */
  9287. public function rfqissuesendmail()
  9288. {
  9289. if (!$this->request->isPost()) {
  9290. $this->error(__('Invalid parameters'));
  9291. }
  9292. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqissue', 'rfqissuesendmail'])) {
  9293. $this->error(__('You have no permission'));
  9294. }
  9295. $sid = (int)$this->request->post('scydgy_id', 0);
  9296. $companyName = trim((string)$this->request->post('company_name', ''));
  9297. if ($sid >= 0) {
  9298. $this->error('仅支持手工新增询价单');
  9299. }
  9300. if ($companyName === '') {
  9301. $this->error('请选择供应商');
  9302. }
  9303. $po = $this->loadManualRfqOrderForNotify($sid);
  9304. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9305. $this->error('订单已完结,无法发送');
  9306. }
  9307. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9308. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9309. $this->error('订单已进入后续流程,无法再发送');
  9310. }
  9311. $contact = $this->resolveCustomerContactByCompanyName($companyName, false);
  9312. if ($contact === null) {
  9313. $this->error('未找到供应商档案:' . $companyName);
  9314. }
  9315. $email = trim((string)($contact['email'] ?? ''));
  9316. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9317. $this->error('该供应商未填写有效邮箱');
  9318. }
  9319. $mailConfig = $this->loadMailerConfig();
  9320. if (empty($mailConfig['host'])) {
  9321. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9322. }
  9323. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9324. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9325. }
  9326. $mergeRow = $po;
  9327. $mergeRow['ID'] = $sid;
  9328. $mergeRow['id'] = $sid;
  9329. $mergeRows = [$mergeRow];
  9330. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9331. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9332. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9333. }
  9334. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9335. $issueTime = date('Y-m-d H:i:s');
  9336. Db::startTrans();
  9337. try {
  9338. $this->upsertPurchaseOrderFromRow(
  9339. $mergeRow,
  9340. $sysRqDb,
  9341. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9342. $issueTime,
  9343. $po,
  9344. null,
  9345. $scoreRule
  9346. );
  9347. $this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
  9348. Db::commit();
  9349. } catch (\Throwable $e) {
  9350. Db::rollback();
  9351. $this->error($e->getMessage());
  9352. }
  9353. $posNotify = [];
  9354. try {
  9355. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9356. if (is_array($fresh)) {
  9357. $fresh['sys_rq'] = $sysRqDb;
  9358. $posNotify = [$fresh];
  9359. }
  9360. } catch (\Throwable $e) {
  9361. $posNotify = [$po];
  9362. $posNotify[0]['sys_rq'] = $sysRqDb;
  9363. }
  9364. $notifyBundle = [
  9365. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9366. 'pos' => $posNotify,
  9367. 'merge_rows' => $mergeRows,
  9368. ];
  9369. try {
  9370. $this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'pick_issue');
  9371. } catch (\Throwable $e) {
  9372. $this->error('明细已保存,但邮件发送失败:' . $e->getMessage());
  9373. }
  9374. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9375. if ($poId <= 0) {
  9376. try {
  9377. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9378. } catch (\Throwable $e) {
  9379. $poId = 0;
  9380. }
  9381. }
  9382. $this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
  9383. $this->success('已向「' . $companyName . '」发送询价邮件', null, [
  9384. 'scydgy_id' => $sid,
  9385. 'company_name' => $companyName,
  9386. ]);
  9387. }
  9388. /**
  9389. * 查询询价 — 查看各供应商报价(单价)
  9390. */
  9391. public function rfqquotes()
  9392. {
  9393. if (!$this->hasProcuremenPerm(['rfqlist', 'rfqquotes', 'rfqissue'])) {
  9394. $this->error(__('You have no permission'));
  9395. }
  9396. $sid = (int)$this->request->param('scydgy_id', 0);
  9397. if ($sid >= 0) {
  9398. $this->error('仅支持手工新增询价单');
  9399. }
  9400. $po = $this->loadManualRfqOrderForNotify($sid);
  9401. $rows = [];
  9402. try {
  9403. // 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
  9404. $q = Db::table('purchase_order_detail')
  9405. ->where('scydgy_id', $sid)
  9406. ->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
  9407. ->order('id', 'asc');
  9408. $this->applyActivePurchaseOrderDetailWhere($q);
  9409. $rows = $q->select();
  9410. } catch (\Throwable $e) {
  9411. try {
  9412. $q = Db::table('purchase_order_detail')
  9413. ->where('scydgy_id', $sid)
  9414. ->order('id', 'asc');
  9415. $this->applyActivePurchaseOrderDetailWhere($q);
  9416. $rows = $q->select();
  9417. } catch (\Throwable $e2) {
  9418. $rows = [];
  9419. }
  9420. }
  9421. if (!is_array($rows)) {
  9422. $rows = [];
  9423. }
  9424. $list = [];
  9425. foreach ($rows as $row) {
  9426. if (!is_array($row)) {
  9427. continue;
  9428. }
  9429. $amount = trim((string)($row['amount'] ?? ''));
  9430. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  9431. // 未报价不显示时间(createtime 是下发时间,不是报价时间)
  9432. $oper = '';
  9433. if ($isQuoted) {
  9434. $oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
  9435. if ($oper === '') {
  9436. $oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  9437. }
  9438. }
  9439. $list[] = [
  9440. 'id' => (int)($row['id'] ?? 0),
  9441. 'company_name' => trim((string)($row['company_name'] ?? '')),
  9442. 'amount' => $amount,
  9443. 'amount_text' => $isQuoted ? $amount : '',
  9444. 'is_quoted' => $isQuoted,
  9445. 'quote_label' => $isQuoted ? '已报价' : '未报价',
  9446. 'status_name' => trim((string)($row['status_name'] ?? '')),
  9447. 'oper_time' => $oper,
  9448. ];
  9449. }
  9450. $this->success('', null, [
  9451. 'scydgy_id' => $sid,
  9452. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9453. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9454. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9455. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9456. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9457. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9458. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9459. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9460. 'list' => $list,
  9461. ]);
  9462. }
  9463. /**
  9464. * 手工询价是否已下发(有下发明细或已进入待确认及之后)
  9465. */
  9466. protected function isRfqOrderIssued(array $po): bool
  9467. {
  9468. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  9469. return true;
  9470. }
  9471. $sid = (int)($po['scydgy_id'] ?? 0);
  9472. if ($sid >= 0) {
  9473. return false;
  9474. }
  9475. try {
  9476. $q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  9477. $this->applyActivePurchaseOrderDetailWhere($q);
  9478. return (int)$q->count() > 0;
  9479. } catch (\Throwable $e) {
  9480. return false;
  9481. }
  9482. }
  9483. /**
  9484. * 批量:已有下发明细的手工询价 scydgy_id
  9485. *
  9486. * @param int[] $scydgyIds
  9487. * @return array<int, bool>
  9488. */
  9489. protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
  9490. {
  9491. $set = [];
  9492. $ids = [];
  9493. foreach ($scydgyIds as $sid) {
  9494. $sid = (int)$sid;
  9495. if ($sid < 0) {
  9496. $ids[$sid] = true;
  9497. }
  9498. }
  9499. if ($ids === []) {
  9500. return $set;
  9501. }
  9502. try {
  9503. $q = Db::table('purchase_order_detail')
  9504. ->where('scydgy_id', 'in', array_keys($ids))
  9505. ->field('scydgy_id');
  9506. $this->applyActivePurchaseOrderDetailWhere($q);
  9507. $rows = $q->select();
  9508. } catch (\Throwable $e) {
  9509. return $set;
  9510. }
  9511. if (!is_array($rows)) {
  9512. return $set;
  9513. }
  9514. foreach ($rows as $row) {
  9515. if (!is_array($row)) {
  9516. continue;
  9517. }
  9518. $sid = (int)($row['scydgy_id'] ?? 0);
  9519. if ($sid < 0) {
  9520. $set[$sid] = true;
  9521. }
  9522. }
  9523. return $set;
  9524. }
  9525. /**
  9526. * 批量:已填单价(已报价)的手工询价 scydgy_id
  9527. *
  9528. * @param int[] $scydgyIds
  9529. * @return array<int, bool>
  9530. */
  9531. protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
  9532. {
  9533. $set = [];
  9534. $ids = [];
  9535. foreach ($scydgyIds as $sid) {
  9536. $sid = (int)$sid;
  9537. if ($sid < 0) {
  9538. $ids[$sid] = true;
  9539. }
  9540. }
  9541. if ($ids === []) {
  9542. return $set;
  9543. }
  9544. try {
  9545. $q = Db::table('purchase_order_detail')
  9546. ->where('scydgy_id', 'in', array_keys($ids))
  9547. ->field('scydgy_id,amount');
  9548. $this->applyActivePurchaseOrderDetailWhere($q);
  9549. $rows = $q->select();
  9550. } catch (\Throwable $e) {
  9551. return $set;
  9552. }
  9553. if (!is_array($rows)) {
  9554. return $set;
  9555. }
  9556. foreach ($rows as $row) {
  9557. if (!is_array($row)) {
  9558. continue;
  9559. }
  9560. $amount = trim((string)($row['amount'] ?? ''));
  9561. if ($amount === '' || $amount === '0' || $amount === '0.00') {
  9562. continue;
  9563. }
  9564. $sid = (int)($row['scydgy_id'] ?? 0);
  9565. if ($sid < 0) {
  9566. $set[$sid] = true;
  9567. }
  9568. }
  9569. return $set;
  9570. }
  9571. /**
  9572. * 已下发且至少一家供应商已报价,才允许通知业务员
  9573. */
  9574. protected function canRfqNotifySalesman(array $po): bool
  9575. {
  9576. if (!$this->isRfqOrderIssued($po)) {
  9577. return false;
  9578. }
  9579. $sid = (int)($po['scydgy_id'] ?? 0);
  9580. if ($sid >= 0) {
  9581. return false;
  9582. }
  9583. $quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
  9584. return isset($quoted[$sid]);
  9585. }
  9586. protected function assertRfqCanNotifySalesman(array $po): void
  9587. {
  9588. if (!$this->isRfqOrderIssued($po)) {
  9589. $this->error('请先询价并等待供应商报价后再通知业务员');
  9590. }
  9591. if (!$this->canRfqNotifySalesman($po)) {
  9592. $this->error('供应商尚未报价,暂不能通知业务员');
  9593. }
  9594. }
  9595. /**
  9596. * 加载手工询价单(含可见性校验)
  9597. *
  9598. * @return array<string, mixed>
  9599. */
  9600. protected function loadManualRfqOrderForNotify(int $scydgyId): array
  9601. {
  9602. try {
  9603. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  9604. } catch (\Throwable $e) {
  9605. $po = null;
  9606. }
  9607. if (!is_array($po)) {
  9608. $this->error('订单不存在');
  9609. }
  9610. $modRq = trim((string)($po['mod_rq'] ?? ''));
  9611. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  9612. $this->error('订单不存在');
  9613. }
  9614. if ($this->auth->isSuperAdmin()) {
  9615. return $po;
  9616. }
  9617. if ($this->canViewManualRfqOrder($po)) {
  9618. return $po;
  9619. }
  9620. $this->error('无权操作该订单');
  9621. }
  9622. /**
  9623. * @return string[]
  9624. */
  9625. protected function splitRfqSalesmanNames(string $raw): array
  9626. {
  9627. $parts = [];
  9628. $raw = trim($raw);
  9629. if ($raw === '') {
  9630. return [];
  9631. }
  9632. foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
  9633. $v = trim((string)$piece);
  9634. if ($v !== '' && !in_array($v, $parts, true)) {
  9635. $parts[] = $v;
  9636. }
  9637. }
  9638. return $parts;
  9639. }
  9640. /**
  9641. * 按姓名匹配 fa_admin 邮箱
  9642. *
  9643. * @param string[] $names
  9644. * @return array<int, array{admin_id:int,name:string,email:string}>
  9645. */
  9646. protected function resolveRfqSalesmanContactRows(array $names): array
  9647. {
  9648. $out = [];
  9649. foreach ($names as $name) {
  9650. $name = trim((string)$name);
  9651. if ($name === '') {
  9652. continue;
  9653. }
  9654. $adminId = 0;
  9655. $email = '';
  9656. try {
  9657. $row = Db::name('admin')
  9658. ->where(function ($q) use ($name) {
  9659. $q->where('nickname', $name)->whereOr('username', $name);
  9660. })
  9661. ->where('status', 'normal')
  9662. ->order('id', 'asc')
  9663. ->field('id,nickname,username,email')
  9664. ->find();
  9665. } catch (\Throwable $e) {
  9666. $row = null;
  9667. }
  9668. if (is_array($row)) {
  9669. $adminId = (int)($row['id'] ?? 0);
  9670. $email = trim((string)($row['email'] ?? ''));
  9671. $disp = trim((string)($row['nickname'] ?? ''));
  9672. if ($disp === '') {
  9673. $disp = trim((string)($row['username'] ?? ''));
  9674. }
  9675. if ($disp !== '') {
  9676. $name = $disp;
  9677. }
  9678. }
  9679. $out[] = [
  9680. 'admin_id' => $adminId,
  9681. 'name' => $name,
  9682. 'email' => $email,
  9683. ];
  9684. }
  9685. return $out;
  9686. }
  9687. /**
  9688. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  9689. */
  9690. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  9691. {
  9692. if ($scydgyId >= 0) {
  9693. return;
  9694. }
  9695. try {
  9696. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  9697. } catch (\Throwable $e) {
  9698. $po = null;
  9699. }
  9700. if (!is_array($po)) {
  9701. $this->error('订单不存在');
  9702. }
  9703. $modRq = trim((string)($po['mod_rq'] ?? ''));
  9704. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  9705. $this->error('订单不存在');
  9706. }
  9707. if ($this->auth->isSuperAdmin()) {
  9708. return;
  9709. }
  9710. [, $adminName] = $this->GetUseName();
  9711. $cywy = trim((string)($po['cywyxm'] ?? ''));
  9712. if ($cywy !== '' && $cywy === $adminName) {
  9713. return;
  9714. }
  9715. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  9716. try {
  9717. if ($this->auth->check($rule)) {
  9718. return;
  9719. }
  9720. } catch (\Throwable $e) {
  9721. }
  9722. }
  9723. $this->error('无权查看该订单');
  9724. }
  9725. /**
  9726. * 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
  9727. */
  9728. protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
  9729. {
  9730. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  9731. return ProcuremenStatus::PO_COMPLETED;
  9732. }
  9733. $sid = (int)($row['scydgy_id'] ?? 0);
  9734. if ($sid < 0) {
  9735. if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
  9736. return '已通知业务员';
  9737. }
  9738. if ($hasQuoted) {
  9739. return '供应商已报价';
  9740. }
  9741. if ($hasIssued
  9742. || ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
  9743. || ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
  9744. return '待报价';
  9745. }
  9746. try {
  9747. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  9748. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  9749. if ((int)$detCntQuery->count() > 0) {
  9750. return '待报价';
  9751. }
  9752. } catch (\Throwable $e) {
  9753. }
  9754. return '待询价';
  9755. }
  9756. if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
  9757. return '待入库评分';
  9758. }
  9759. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  9760. return '待采购确认';
  9761. }
  9762. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  9763. return '待确认供应商';
  9764. }
  9765. return '待协助下发';
  9766. }
  9767. /**
  9768. * 协助初选列表 — 批量软删除
  9769. */
  9770. public function pickDelete()
  9771. {
  9772. if (!$this->request->isPost() || !$this->request->isAjax()) {
  9773. $this->error(__('Invalid parameters'));
  9774. }
  9775. if (!$this->procuremenCanPickDelete()) {
  9776. $this->error(__('You have no permission'));
  9777. }
  9778. $rowsRaw = $this->request->post('rows_json', '[]');
  9779. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  9780. if (!is_array($rows) || $rows === []) {
  9781. $this->error('请至少勾选一条工序');
  9782. }
  9783. $done = 0;
  9784. Db::startTrans();
  9785. try {
  9786. foreach ($rows as $row) {
  9787. if (!is_array($row)) {
  9788. continue;
  9789. }
  9790. $this->softDeleteProcuremenPickRow($row);
  9791. $done++;
  9792. }
  9793. if ($done < 1) {
  9794. throw new \Exception('没有可删除的工序');
  9795. }
  9796. Db::commit();
  9797. } catch (\InvalidArgumentException $e) {
  9798. Db::rollback();
  9799. $this->error($e->getMessage());
  9800. } catch (\Throwable $e) {
  9801. Db::rollback();
  9802. $this->error($e->getMessage());
  9803. }
  9804. $this->pickHiddenScydgySetCache = null;
  9805. $this->success('已删除 ' . $done . ' 条工序');
  9806. }
  9807. /**
  9808. * 下发 — 手工新增工序(弹窗)
  9809. */
  9810. public function pickAdd()
  9811. {
  9812. if ($this->request->isPost()) {
  9813. $params = $this->request->post('row/a');
  9814. if (!is_array($params)) {
  9815. $this->error(__('Parameter %s can not be empty', ''));
  9816. }
  9817. try {
  9818. $sid = $this->saveManualPickOrder($params);
  9819. } catch (\InvalidArgumentException $e) {
  9820. $this->error($e->getMessage());
  9821. } catch (\Throwable $e) {
  9822. $this->error($e->getMessage());
  9823. }
  9824. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  9825. }
  9826. return $this->view->fetch('procuremen/pick_add');
  9827. }
  9828. /**
  9829. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  9830. */
  9831. public function pickSubmit()
  9832. {
  9833. if (!$this->request->isPost()) {
  9834. $this->error(__('Invalid parameters'));
  9835. }
  9836. // ---------- 接口订单数据 ----------
  9837. $rowJson = $this->request->post('row_json', '');
  9838. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  9839. $companiesJson = $this->request->post('companies_json', '[]');
  9840. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  9841. $companies = json_decode($companiesJson, true);
  9842. if (!is_array($companies)) {
  9843. $this->error('供应商数据无效');
  9844. }
  9845. $issueCompanies = $this->normalizePickCompanies($companies);
  9846. if ($issueCompanies === []) {
  9847. $this->error('请至少选择一家合作供应商');
  9848. }
  9849. $issueNameLabels = [];
  9850. foreach ($issueCompanies as $pc) {
  9851. $issueNameLabels[] = $pc['name'];
  9852. }
  9853. $issueNamesSummary = implode('、', $issueNameLabels);
  9854. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  9855. if ($sysRq === '') {
  9856. $this->error('请选择招标截止日期');
  9857. }
  9858. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  9859. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  9860. (string)$this->request->post('delivery_deadline', ''),
  9861. true
  9862. );
  9863. $scoreRuleId = (int)$this->request->post('score_rule_id', 0);
  9864. if ($scoreRuleId <= 0) {
  9865. $this->error('请选择订单类型');
  9866. }
  9867. $scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
  9868. if ((int)($scoreRule['id'] ?? 0) <= 0) {
  9869. $this->error('订单类型无效,请刷新后重选');
  9870. }
  9871. $scoreRuleId = (int)$scoreRule['id'];
  9872. $this->ensurePurchaseOrderScoreRuleIdColumn();
  9873. $isMerge = count($mergeRows) > 1;
  9874. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  9875. $logMsg = '下发' . $procPart
  9876. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  9877. $issueTime = date('Y-m-d H:i:s');
  9878. $logSidList = [];
  9879. foreach ($mergeRows as $row) {
  9880. if (!is_array($row)) {
  9881. continue;
  9882. }
  9883. $sid = $this->extractScydgyRowId($row);
  9884. if ($this->isValidScydgyRowId($sid)) {
  9885. $logSidList[$sid] = true;
  9886. }
  9887. }
  9888. $existingBySid = [];
  9889. if ($logSidList !== []) {
  9890. try {
  9891. $existingRows = Db::table('purchase_order')
  9892. ->where('scydgy_id', 'in', array_keys($logSidList))
  9893. ->select();
  9894. if (is_array($existingRows)) {
  9895. foreach ($existingRows as $poRow) {
  9896. if (!is_array($poRow)) {
  9897. continue;
  9898. }
  9899. $sid = (int)($poRow['scydgy_id'] ?? 0);
  9900. if ($this->isValidScydgyRowId($sid)) {
  9901. $existingBySid[$sid] = $poRow;
  9902. }
  9903. }
  9904. }
  9905. } catch (\Throwable $e) {
  9906. $existingBySid = [];
  9907. }
  9908. }
  9909. Db::startTrans();
  9910. try {
  9911. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  9912. foreach ($mergeRows as $row) {
  9913. if (!is_array($row)) {
  9914. continue;
  9915. }
  9916. $sid = $this->extractScydgyRowId($row);
  9917. $this->upsertPurchaseOrderFromRow(
  9918. $row,
  9919. $sysRqDb,
  9920. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9921. $issueTime,
  9922. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  9923. $deliveryDeadlineDb,
  9924. $scoreRule
  9925. );
  9926. }
  9927. foreach ($issueCompanies as $c) {
  9928. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  9929. }
  9930. Db::commit();
  9931. } catch (\Throwable $e) {
  9932. Db::rollback();
  9933. $this->error($e->getMessage());
  9934. }
  9935. $poIdBySid = [];
  9936. if ($logSidList !== []) {
  9937. try {
  9938. $poIdBySid = Db::table('purchase_order')
  9939. ->where('scydgy_id', 'in', array_keys($logSidList))
  9940. ->column('id', 'scydgy_id');
  9941. } catch (\Throwable $e) {
  9942. $poIdBySid = [];
  9943. }
  9944. }
  9945. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  9946. if ($logSidList !== []) {
  9947. list($adminId, $adminName) = $this->GetUseName();
  9948. $logRows = [];
  9949. $seenLogSid = [];
  9950. foreach ($mergeRows as $row) {
  9951. if (!is_array($row)) {
  9952. continue;
  9953. }
  9954. $ids = $this->extractScydgyRowId($row);
  9955. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  9956. continue;
  9957. }
  9958. $seenLogSid[$ids] = true;
  9959. $poIdLog = null;
  9960. if (isset($poIdBySid[$ids])) {
  9961. $tid = (int)$poIdBySid[$ids];
  9962. $poIdLog = $tid > 0 ? $tid : null;
  9963. }
  9964. $logRows[] = ProcuremenOperLog::buildInsertRow(
  9965. $ids,
  9966. 'issue_submit',
  9967. $logMsg,
  9968. $poIdLog,
  9969. (int)$adminId,
  9970. (string)$adminName
  9971. );
  9972. }
  9973. if ($logRows !== []) {
  9974. try {
  9975. Db::table('purchase_order_oper_log')->insertAll($logRows);
  9976. } catch (\Throwable $e) {
  9977. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  9978. }
  9979. }
  9980. }
  9981. $notifyErrors = [];
  9982. $posNotify = [];
  9983. if ($logSidList !== []) {
  9984. try {
  9985. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  9986. } catch (\Throwable $e) {
  9987. $posNotify = [];
  9988. }
  9989. }
  9990. if (!is_array($posNotify)) {
  9991. $posNotify = [];
  9992. }
  9993. foreach ($posNotify as $i => $prow) {
  9994. if (is_array($posNotify[$i])) {
  9995. $posNotify[$i]['sys_rq'] = $sysRqDb;
  9996. }
  9997. }
  9998. $ccydhPick = '';
  9999. foreach ($mergeRows as $row) {
  10000. if (!is_array($row)) {
  10001. continue;
  10002. }
  10003. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  10004. if ($ccydhPick !== '') {
  10005. break;
  10006. }
  10007. }
  10008. $notifyBundleBase = [
  10009. 'ccydh' => $ccydhPick,
  10010. 'pos' => $posNotify,
  10011. 'merge_rows' => $mergeRows,
  10012. ];
  10013. try {
  10014. $this->notifyDryRunPreview = [];
  10015. foreach ($issueCompanies as $c) {
  10016. if (!is_array($c)) {
  10017. continue;
  10018. }
  10019. $cname = trim((string)($c['name'] ?? ''));
  10020. if ($cname === '') {
  10021. continue;
  10022. }
  10023. try {
  10024. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  10025. } catch (\Throwable $e) {
  10026. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10027. }
  10028. }
  10029. } catch (\Throwable $e) {
  10030. $this->error('通知发送失败:' . $e->getMessage());
  10031. }
  10032. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10033. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  10034. }
  10035. if ($this->isProcuremenNotifyDryRun()) {
  10036. $this->success('【演练模式】已保存并生成通知预览', '', [
  10037. 'notify_dry_run' => true,
  10038. 'notify_preview' => $this->notifyDryRunPreview,
  10039. ]);
  10040. }
  10041. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  10042. }
  10043. /**
  10044. * 确认供应商弹窗
  10045. */
  10046. public function auditIssue()
  10047. {
  10048. $ids = $this->request->param('ids', $this->request->param('id', ''));
  10049. if (is_array($ids)) {
  10050. $ids = isset($ids[0]) ? $ids[0] : '';
  10051. }
  10052. $ids = trim((string)$ids);
  10053. if ($ids === '') {
  10054. $this->error(__('Invalid parameters'));
  10055. }
  10056. if ($this->request->isPost()) {
  10057. $this->error('请使用弹窗内「确认」提交');
  10058. }
  10059. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10060. $pos = $bundle['pos'];
  10061. if ($pos === []) {
  10062. $this->error('该订单不在待确认供应商状态');
  10063. }
  10064. $po = $pos[0];
  10065. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10066. if ($quoteGroups === []) {
  10067. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  10068. }
  10069. $pickedName = '';
  10070. foreach ($pos as $poRow) {
  10071. if (!is_array($poRow)) {
  10072. continue;
  10073. }
  10074. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  10075. if ($pn !== '') {
  10076. $pickedName = $pn;
  10077. break;
  10078. }
  10079. }
  10080. $this->view->assign('po', $po);
  10081. $this->view->assign('scydgyId', $ids);
  10082. $this->view->assign('orderCcydh', $bundle['ccydh']);
  10083. $mergeRows = $bundle['merge_rows'];
  10084. $this->view->assign('processRows', $mergeRows);
  10085. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  10086. $this->view->assign('processCount', count($mergeRows));
  10087. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  10088. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  10089. $this->view->assign('pickedCompanyName', $pickedName);
  10090. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10091. if ($sysRqForView === '') {
  10092. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10093. }
  10094. $this->view->assign('sysRq', $sysRqForView);
  10095. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  10096. if ($deliveryDeadlineForView === '') {
  10097. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10098. }
  10099. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10100. $this->ensurePurchaseOrderManualPickColumns();
  10101. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
  10102. $manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
  10103. $manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
  10104. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  10105. if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
  10106. $pickedName = $manualPickInfo['company'];
  10107. $this->view->assign('pickedCompanyName', $pickedName);
  10108. }
  10109. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  10110. $this->view->assign('manualPicked', $manualPicked);
  10111. $this->view->assign('manualPickReason', $manualPickInfo['reason']);
  10112. $this->view->assign('quoteVisible', $quoteVisible);
  10113. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
  10114. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  10115. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
  10116. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
  10117. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  10118. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  10119. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  10120. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  10121. return $this->view->fetch('procuremen/audit_issue');
  10122. }
  10123. /**
  10124. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  10125. *
  10126. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10127. */
  10128. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  10129. {
  10130. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10131. return false;
  10132. }
  10133. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10134. return false;
  10135. }
  10136. return true;
  10137. }
  10138. /**
  10139. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  10140. *
  10141. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10142. */
  10143. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  10144. {
  10145. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10146. return false;
  10147. }
  10148. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10149. return false;
  10150. }
  10151. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  10152. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  10153. return true;
  10154. }
  10155. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  10156. }
  10157. /**
  10158. * 确认页 — 补加供应商弹窗
  10159. */
  10160. public function auditAppend()
  10161. {
  10162. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  10163. $this->error(__('You have no permission'));
  10164. }
  10165. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  10166. if (is_array($ids)) {
  10167. $ids = isset($ids[0]) ? $ids[0] : '';
  10168. }
  10169. $ids = trim((string)$ids);
  10170. if ($ids === '') {
  10171. $this->error(__('Invalid parameters'));
  10172. }
  10173. if ($this->request->isPost()) {
  10174. $this->error('请使用弹窗内「确认」提交');
  10175. }
  10176. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10177. if (($bundle['pos'] ?? []) === []) {
  10178. $this->error('该订单不在待确认供应商状态');
  10179. }
  10180. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10181. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10182. $this->error('已开标验证,不能再补加供应商');
  10183. }
  10184. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10185. $this->error('已指定供应商,不能再补加供应商');
  10186. }
  10187. $this->error('已经超过了招标截止日期,不可操作');
  10188. }
  10189. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10190. $existingNames = [];
  10191. foreach ($quoteGroups as $g) {
  10192. if (!is_array($g)) {
  10193. continue;
  10194. }
  10195. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  10196. if ($n !== '') {
  10197. $existingNames[$n] = true;
  10198. }
  10199. }
  10200. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  10201. $mergeRows = $bundle['merge_rows'] ?? [];
  10202. $this->view->assign('scydgyId', $ids);
  10203. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  10204. $this->view->assign('po', $po);
  10205. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  10206. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  10207. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  10208. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10209. if ($sysRqForView === '') {
  10210. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10211. }
  10212. $this->view->assign('sysRq', $sysRqForView);
  10213. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  10214. if ($deliveryDeadlineForView === '') {
  10215. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10216. }
  10217. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10218. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  10219. }
  10220. /**
  10221. * 确认页 — 补加供应商提交
  10222. */
  10223. public function auditAppendSubmit()
  10224. {
  10225. if (!$this->request->isPost()) {
  10226. $this->error(__('Invalid parameters'));
  10227. }
  10228. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  10229. $this->error(__('You have no permission'));
  10230. }
  10231. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  10232. if ($ids === '') {
  10233. $this->error(__('Invalid parameters'));
  10234. }
  10235. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10236. if (($bundle['pos'] ?? []) === []) {
  10237. $this->error('该订单不在待确认供应商状态');
  10238. }
  10239. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10240. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10241. $this->error('已开标验证,不能再补加供应商');
  10242. }
  10243. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10244. $this->error('已指定供应商,不能再补加供应商');
  10245. }
  10246. $this->error('已经超过了招标截止日期,不可操作');
  10247. }
  10248. $companiesJson = $this->request->post('companies_json', '[]');
  10249. $companies = json_decode((string)$companiesJson, true);
  10250. if (!is_array($companies)) {
  10251. $this->error('供应商数据无效');
  10252. }
  10253. $issueCompanies = $this->normalizePickCompanies($companies);
  10254. if ($issueCompanies === []) {
  10255. $this->error('请至少选择一家合作供应商');
  10256. }
  10257. $mergeRows = $bundle['merge_rows'] ?? [];
  10258. if (!is_array($mergeRows) || $mergeRows === []) {
  10259. $this->error('未找到工序行,无法补加');
  10260. }
  10261. $existingNames = [];
  10262. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  10263. if (!is_array($g)) {
  10264. continue;
  10265. }
  10266. $n = trim((string)($g['company_name'] ?? ''));
  10267. if ($n !== '') {
  10268. $existingNames[$n] = true;
  10269. }
  10270. }
  10271. $toAdd = [];
  10272. foreach ($issueCompanies as $c) {
  10273. if (!is_array($c)) {
  10274. continue;
  10275. }
  10276. $n = trim((string)($c['name'] ?? ''));
  10277. if ($n === '' || isset($existingNames[$n])) {
  10278. continue;
  10279. }
  10280. $toAdd[] = $c;
  10281. }
  10282. if ($toAdd === []) {
  10283. $this->error('所选供应商均已在本单中,请选择新的供应商');
  10284. }
  10285. $addedNames = [];
  10286. Db::startTrans();
  10287. try {
  10288. foreach ($toAdd as $c) {
  10289. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10290. $addedNames[] = trim((string)($c['name'] ?? ''));
  10291. }
  10292. Db::commit();
  10293. } catch (\Throwable $e) {
  10294. Db::rollback();
  10295. $this->error($e->getMessage());
  10296. }
  10297. $notifyErrors = [];
  10298. $notifyBundleBase = [
  10299. 'ccydh' => $bundle['ccydh'] ?? '',
  10300. 'pos' => $bundle['pos'] ?? [],
  10301. 'merge_rows' => $mergeRows,
  10302. ];
  10303. foreach ($toAdd as $c) {
  10304. if (!is_array($c)) {
  10305. continue;
  10306. }
  10307. $cname = trim((string)($c['name'] ?? ''));
  10308. if ($cname === '') {
  10309. continue;
  10310. }
  10311. try {
  10312. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  10313. } catch (\Throwable $e) {
  10314. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10315. }
  10316. }
  10317. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  10318. $seenLogSid = [];
  10319. foreach ($bundle['pos'] ?? [] as $poRow) {
  10320. if (!is_array($poRow)) {
  10321. continue;
  10322. }
  10323. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10324. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  10325. continue;
  10326. }
  10327. $seenLogSid[$sid] = true;
  10328. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10329. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10330. }
  10331. if ($seenLogSid === []) {
  10332. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  10333. if ($this->isValidScydgyRowId($logSid)) {
  10334. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  10335. }
  10336. }
  10337. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10338. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  10339. }
  10340. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  10341. }
  10342. /**
  10343. * 开标双重验证 — 可选验证人列表
  10344. */
  10345. public function bidOpenUsers()
  10346. {
  10347. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10348. $this->error('无权限');
  10349. }
  10350. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  10351. if ($scydgyId !== '') {
  10352. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10353. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10354. $this->success('已完成开标验证', null, [
  10355. 'verified' => 1,
  10356. 'users' => [],
  10357. ]);
  10358. }
  10359. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10360. $this->error('本单已指定供应商,无需再开标');
  10361. }
  10362. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10363. }
  10364. $this->success('', null, [
  10365. 'verified' => 0,
  10366. 'users' => $this->listBidOpenVerifierCandidates(),
  10367. ]);
  10368. }
  10369. /**
  10370. * 开标双重验证 — 向指定管理员发送短信验证码
  10371. */
  10372. public function bidOpenSendCode()
  10373. {
  10374. if (!$this->request->isPost()) {
  10375. $this->error(__('Invalid parameters'));
  10376. }
  10377. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10378. $this->error('无权限');
  10379. }
  10380. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10381. $adminId = (int)$this->request->post('admin_id', 0);
  10382. if ($scydgyId === '' || $adminId <= 0) {
  10383. $this->error('参数无效');
  10384. }
  10385. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10386. if ($bundle['pos'] === []) {
  10387. $this->error('该订单不在待确认供应商状态');
  10388. }
  10389. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10390. $this->success('已完成开标验证,无需重复发送');
  10391. }
  10392. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10393. $this->error('本单已指定供应商,无需再开标');
  10394. }
  10395. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10396. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10397. if ($ccydh === '') {
  10398. $this->error('订单号无效');
  10399. }
  10400. $admin = $this->loadBidOpenAdminUser($adminId);
  10401. if ($admin === null) {
  10402. $this->error('验证人无效或未绑定手机号');
  10403. }
  10404. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  10405. $cd = max(30, min(120, $cd));
  10406. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  10407. $this->error('发送过于频繁,请稍后再试');
  10408. }
  10409. $code = (string)random_int(100000, 999999);
  10410. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  10411. $ttl = max(60, min(600, $ttl));
  10412. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  10413. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  10414. try {
  10415. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  10416. } catch (\Throwable $e) {
  10417. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  10418. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  10419. $this->error($e->getMessage());
  10420. }
  10421. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  10422. }
  10423. /**
  10424. * 开标双重验证 — 两人验证码校验并记录
  10425. */
  10426. public function bidOpenVerify()
  10427. {
  10428. if (!$this->request->isPost()) {
  10429. $this->error(__('Invalid parameters'));
  10430. }
  10431. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10432. $this->error('无权限');
  10433. }
  10434. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10435. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  10436. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  10437. $code1 = trim((string)$this->request->post('code1', ''));
  10438. $code2 = trim((string)$this->request->post('code2', ''));
  10439. if ($scydgyId === '') {
  10440. $this->error('参数无效');
  10441. }
  10442. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  10443. $this->error('请选择两位验证人');
  10444. }
  10445. if ($verifier1Id === $verifier2Id) {
  10446. $this->error('两位验证人不能相同');
  10447. }
  10448. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  10449. $this->error('请输入6位短信验证码');
  10450. }
  10451. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10452. if ($bundle['pos'] === []) {
  10453. $this->error('该订单不在待确认供应商状态');
  10454. }
  10455. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10456. if ($ccydh === '') {
  10457. $this->error('订单号无效');
  10458. }
  10459. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10460. $this->success('已完成开标验证');
  10461. }
  10462. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10463. $this->error('本单已指定供应商,无需再开标');
  10464. }
  10465. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10466. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  10467. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  10468. if ($verifier1 === null || $verifier2 === null) {
  10469. $this->error('验证人无效或未绑定手机号');
  10470. }
  10471. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  10472. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  10473. }
  10474. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  10475. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  10476. }
  10477. try {
  10478. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  10479. } catch (\Throwable $e) {
  10480. $this->error($e->getMessage());
  10481. }
  10482. $this->success('开标验证成功,可查看供应商报价与交货日期');
  10483. }
  10484. /**
  10485. * 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
  10486. */
  10487. public function auditManualPick()
  10488. {
  10489. if (!$this->request->isPost()) {
  10490. $this->error(__('Invalid parameters'));
  10491. }
  10492. if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
  10493. $this->error('无权限');
  10494. }
  10495. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10496. if ($scydgyId === '') {
  10497. $this->error('参数无效');
  10498. }
  10499. $companyName = trim((string)$this->request->post('selected_company', ''));
  10500. $reason = trim((string)$this->request->post('pick_reason', ''));
  10501. if ($companyName === '') {
  10502. $this->error('请选择一家供应商');
  10503. }
  10504. if ($reason === '') {
  10505. $this->error('请填写选择说明');
  10506. }
  10507. if (mb_strlen($reason) > 500) {
  10508. $this->error('选择说明不能超过500字');
  10509. }
  10510. $this->ensurePurchaseOrderManualPickColumns();
  10511. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10512. $pos = $bundle['pos'];
  10513. if ($pos === []) {
  10514. $this->error('该订单不在待确认供应商状态');
  10515. }
  10516. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10517. $this->error('本单已开标验证,请直接在列表中选定供应商后确认');
  10518. }
  10519. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10520. if ($quoteGroups === []) {
  10521. $this->error('暂无供应商,请确认已完成协助初选通知');
  10522. }
  10523. $matched = null;
  10524. foreach ($quoteGroups as $g) {
  10525. if (!is_array($g)) {
  10526. continue;
  10527. }
  10528. if (trim((string)($g['name'] ?? '')) === $companyName) {
  10529. $matched = $g;
  10530. break;
  10531. }
  10532. }
  10533. if ($matched === null) {
  10534. $this->error('所选供应商不在本单报价列表中');
  10535. }
  10536. $logMsg = '指定供应商:已选定「' . $companyName . '」;说明:' . $reason;
  10537. Db::startTrans();
  10538. try {
  10539. foreach ($pos as $poRow) {
  10540. if (!is_array($poRow)) {
  10541. continue;
  10542. }
  10543. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10544. if (!$this->isValidScydgyRowId($sid)) {
  10545. continue;
  10546. }
  10547. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10548. 'pick_company_name' => $companyName,
  10549. 'manual_pick' => 1,
  10550. 'manual_pick_reason' => $reason,
  10551. ]);
  10552. }
  10553. Db::commit();
  10554. } catch (\Throwable $e) {
  10555. Db::rollback();
  10556. $this->error($e->getMessage());
  10557. }
  10558. foreach ($pos as $poRow) {
  10559. if (!is_array($poRow)) {
  10560. continue;
  10561. }
  10562. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10563. if (!$this->isValidScydgyRowId($sid)) {
  10564. continue;
  10565. }
  10566. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10567. $this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10568. }
  10569. // 自选后可见报价:按本单规则计算评分(与开标后一致)
  10570. try {
  10571. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10572. if ($ccydh !== '') {
  10573. // 重新加载以拿到未掩码报价参与计分
  10574. $bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10575. $groupsFresh = $this->loadAuditSupplierQuoteGroups($bundleFresh);
  10576. ProcuremenSupplierScore::saveForOrder($ccydh, $groupsFresh, date('Y-m'));
  10577. }
  10578. } catch (\Throwable $e) {
  10579. Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
  10580. }
  10581. $this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
  10582. }
  10583. /**
  10584. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  10585. */
  10586. public function auditSubmit()
  10587. {
  10588. if (!$this->request->isPost()) {
  10589. $this->error(__('Invalid parameters'));
  10590. }
  10591. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10592. if ($scydgyId === '') {
  10593. $this->error('参数无效');
  10594. }
  10595. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10596. $pos = $bundle['pos'];
  10597. $mergeRows = $bundle['merge_rows'];
  10598. if ($pos === [] || $mergeRows === []) {
  10599. $this->error('该订单不在待确认供应商状态');
  10600. }
  10601. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10602. if ($quoteGroups === []) {
  10603. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  10604. }
  10605. $companyName = trim((string)$this->request->post('selected_company', ''));
  10606. if ($companyName === '') {
  10607. $this->error('请选择一家供应商');
  10608. }
  10609. $matched = null;
  10610. foreach ($quoteGroups as $g) {
  10611. if (!is_array($g)) {
  10612. continue;
  10613. }
  10614. if (trim((string)($g['name'] ?? '')) === $companyName) {
  10615. $matched = $g;
  10616. break;
  10617. }
  10618. }
  10619. if ($matched === null) {
  10620. $this->error('所选供应商不在本单报价列表中');
  10621. }
  10622. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10623. if ($sysRqDb === '') {
  10624. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  10625. } else {
  10626. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  10627. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  10628. }
  10629. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  10630. $this->error('未到招标截止日期,暂不可确认');
  10631. }
  10632. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
  10633. && !$this->isProcuremenManualPickedForBundle($bundle)
  10634. ) {
  10635. $this->error('请先完成开标双重验证或指定供应商后再确认');
  10636. }
  10637. $procCnt = count($mergeRows);
  10638. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  10639. $logMsg = '确认供应商' . $procPart . ':已选定「' . $companyName . '」';
  10640. Db::startTrans();
  10641. try {
  10642. foreach ($pos as $poRow) {
  10643. if (!is_array($poRow)) {
  10644. continue;
  10645. }
  10646. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10647. if (!$this->isValidScydgyRowId($sid)) {
  10648. continue;
  10649. }
  10650. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  10651. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  10652. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  10653. 'pick_company_name' => $companyName,
  10654. 'sys_rq' => $sysRqDb,
  10655. ]);
  10656. }
  10657. Db::commit();
  10658. } catch (\Throwable $e) {
  10659. Db::rollback();
  10660. $this->error($e->getMessage());
  10661. }
  10662. foreach ($pos as $poRow) {
  10663. if (!is_array($poRow)) {
  10664. continue;
  10665. }
  10666. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10667. if (!$this->isValidScydgyRowId($sid)) {
  10668. continue;
  10669. }
  10670. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10671. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10672. }
  10673. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  10674. }
  10675. /**
  10676. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  10677. */
  10678. public function auditResendSms()
  10679. {
  10680. if (!$this->request->isPost()) {
  10681. $this->error(__('Invalid parameters'));
  10682. }
  10683. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10684. if ($scydgyId === '') {
  10685. $this->error('参数无效');
  10686. }
  10687. $loaded = $this->loadAuditResendBundle($scydgyId);
  10688. $mergeRows = $loaded['merge_rows'];
  10689. $bundle = $loaded['bundle'];
  10690. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  10691. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10692. if ($quoteGroups === []) {
  10693. $this->error('暂无可通知的供应商');
  10694. }
  10695. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  10696. $companiesJson = (string)$this->request->post('companies_json', '');
  10697. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  10698. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  10699. }
  10700. /**
  10701. * 确认供应商 — 二次发送邮件(可选单家/批量)
  10702. */
  10703. public function auditResendEmail()
  10704. {
  10705. if (!$this->request->isPost()) {
  10706. $this->error(__('Invalid parameters'));
  10707. }
  10708. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10709. if ($scydgyId === '') {
  10710. $this->error('参数无效');
  10711. }
  10712. $loaded = $this->loadAuditResendBundle($scydgyId);
  10713. $mergeRows = $loaded['merge_rows'];
  10714. $bundle = $loaded['bundle'];
  10715. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  10716. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10717. if ($quoteGroups === []) {
  10718. $this->error('暂无可通知的供应商');
  10719. }
  10720. $companiesJson = (string)$this->request->post('companies_json', '');
  10721. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  10722. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  10723. if ($companiesJson === '' && $selectedCompany === '') {
  10724. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  10725. }
  10726. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  10727. }
  10728. /**
  10729. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  10730. *
  10731. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  10732. * @return array<int, true> 已处理的 scydgy_id 集合
  10733. */
  10734. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  10735. {
  10736. $pos = $bundle['pos'] ?? [];
  10737. if (!is_array($pos) || $pos === []) {
  10738. return [];
  10739. }
  10740. $sids = [];
  10741. $poIdBySid = [];
  10742. foreach ($pos as $poRow) {
  10743. if (!is_array($poRow)) {
  10744. continue;
  10745. }
  10746. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10747. if ($this->isValidScydgyRowId($sid)) {
  10748. $sids[$sid] = true;
  10749. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10750. if ($poId > 0) {
  10751. $poIdBySid[$sid] = $poId;
  10752. }
  10753. }
  10754. }
  10755. if ($sids === []) {
  10756. return [];
  10757. }
  10758. $logMsg = '重新下发';
  10759. $suffix = trim((string)$logSuffix, ',, ');
  10760. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  10761. $logMsg .= ':从历史存证退回协助初选';
  10762. } else {
  10763. $logMsg .= ':退回协助初选';
  10764. }
  10765. Db::table('purchase_order')
  10766. ->where('scydgy_id', 'in', array_keys($sids))
  10767. ->update([
  10768. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  10769. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  10770. 'pick_company_name' => '',
  10771. 'pick_time' => null,
  10772. 'sys_rq' => null,
  10773. 'mod_rq' => null,
  10774. ]);
  10775. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  10776. foreach (array_keys($sids) as $sid) {
  10777. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  10778. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10779. }
  10780. return $sids;
  10781. }
  10782. /**
  10783. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  10784. *
  10785. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  10786. */
  10787. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  10788. {
  10789. $scydgyId = trim($scydgyId);
  10790. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  10791. if ($scydgyId === '') {
  10792. return $empty;
  10793. }
  10794. try {
  10795. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10796. } catch (\Throwable $e) {
  10797. $anchor = null;
  10798. }
  10799. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  10800. return $empty;
  10801. }
  10802. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  10803. if ($ccydh === '') {
  10804. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  10805. }
  10806. try {
  10807. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  10808. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  10809. $pos = $query->order('scydgy_id', 'asc')->select();
  10810. } catch (\Throwable $e) {
  10811. $pos = [$anchor];
  10812. }
  10813. if (!is_array($pos) || $pos === []) {
  10814. $pos = [$anchor];
  10815. }
  10816. return [
  10817. 'ccydh' => $ccydh,
  10818. 'pos' => $pos,
  10819. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  10820. ];
  10821. }
  10822. protected function purchaseOrderRowIsCompleted(array $po): bool
  10823. {
  10824. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  10825. }
  10826. /**
  10827. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  10828. *
  10829. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  10830. */
  10831. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  10832. {
  10833. $scydgyId = trim($scydgyId);
  10834. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  10835. if ($scydgyId === '') {
  10836. return $empty;
  10837. }
  10838. try {
  10839. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10840. } catch (\Throwable $e) {
  10841. $anchor = null;
  10842. }
  10843. if (!is_array($anchor)) {
  10844. return $empty;
  10845. }
  10846. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  10847. if ($ccydh === '') {
  10848. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  10849. }
  10850. try {
  10851. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  10852. } catch (\Throwable $e) {
  10853. $pos = [$anchor];
  10854. }
  10855. if (!is_array($pos) || $pos === []) {
  10856. $pos = [$anchor];
  10857. }
  10858. return [
  10859. 'ccydh' => $ccydh,
  10860. 'pos' => $pos,
  10861. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  10862. ];
  10863. }
  10864. /**
  10865. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  10866. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  10867. */
  10868. public function auditAbandon()
  10869. {
  10870. if (!$this->request->isPost()) {
  10871. $this->error(__('Invalid parameters'));
  10872. }
  10873. $anchorIds = [];
  10874. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  10875. if ($batchRaw !== '') {
  10876. $decoded = json_decode($batchRaw, true);
  10877. if (is_array($decoded)) {
  10878. foreach ($decoded as $id) {
  10879. $s = trim((string)$id);
  10880. if ($s !== '') {
  10881. $anchorIds[] = $s;
  10882. }
  10883. }
  10884. }
  10885. }
  10886. if ($anchorIds === []) {
  10887. $single = trim((string)$this->request->post('scydgy_id', ''));
  10888. if ($single !== '') {
  10889. $anchorIds[] = $single;
  10890. }
  10891. }
  10892. if ($anchorIds === []) {
  10893. $this->error('请至少选择一条订单');
  10894. }
  10895. $processedCcydh = [];
  10896. $doneOrders = 0;
  10897. $allSids = [];
  10898. Db::startTrans();
  10899. try {
  10900. foreach ($anchorIds as $anchorId) {
  10901. $fromArchive = false;
  10902. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  10903. if (($bundle['pos'] ?? []) === []) {
  10904. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  10905. $fromArchive = ($bundle['pos'] ?? []) !== [];
  10906. }
  10907. if (($bundle['pos'] ?? []) === []) {
  10908. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  10909. $fromArchive = ($bundle['pos'] ?? []) !== [];
  10910. }
  10911. if (($bundle['pos'] ?? []) === []) {
  10912. continue;
  10913. }
  10914. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10915. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  10916. if (isset($processedCcydh[$dedupeKey])) {
  10917. continue;
  10918. }
  10919. $processedCcydh[$dedupeKey] = true;
  10920. $sids = $fromArchive
  10921. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回协助初选')
  10922. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  10923. if ($sids === []) {
  10924. continue;
  10925. }
  10926. $doneOrders++;
  10927. foreach (array_keys($sids) as $sid) {
  10928. $allSids[(int)$sid] = true;
  10929. }
  10930. }
  10931. if ($doneOrders < 1) {
  10932. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  10933. }
  10934. Db::commit();
  10935. } catch (\Throwable $e) {
  10936. Db::rollback();
  10937. $this->error($e->getMessage());
  10938. }
  10939. $this->pickHiddenScydgySetCache = null;
  10940. $msg = $doneOrders > 1
  10941. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  10942. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  10943. $this->success($msg);
  10944. }
  10945. /**
  10946. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  10947. */
  10948. public function archiveAbandon()
  10949. {
  10950. return $this->auditAbandon();
  10951. }
  10952. /**
  10953. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  10954. */
  10955. public function purchaseApprovalReject()
  10956. {
  10957. if (!$this->request->isPost() || !$this->request->isAjax()) {
  10958. $this->error(__('Invalid parameters'));
  10959. }
  10960. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  10961. $this->error(__('You have no permission'));
  10962. }
  10963. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  10964. $decoded = json_decode($batchRaw, true);
  10965. if (!is_array($decoded) || $decoded === []) {
  10966. $this->error('提交数据无效');
  10967. }
  10968. $done = 0;
  10969. Db::startTrans();
  10970. try {
  10971. foreach ($decoded as $item) {
  10972. if (!is_array($item)) {
  10973. continue;
  10974. }
  10975. $sid = (int)($item['scydgy_id'] ?? 0);
  10976. if (!$this->isValidScydgyRowId($sid)) {
  10977. continue;
  10978. }
  10979. $this->runPurchaseApprovalRejectForSid($sid);
  10980. $done++;
  10981. }
  10982. if ($done < 1) {
  10983. throw new \Exception('所选订单均不在待审批状态');
  10984. }
  10985. Db::commit();
  10986. } catch (\Throwable $e) {
  10987. Db::rollback();
  10988. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  10989. }
  10990. $this->pickHiddenScydgySetCache = null;
  10991. $this->success('已驳回并退回「协助审批下发」');
  10992. }
  10993. /**
  10994. * @throws \Exception
  10995. */
  10996. protected function runPurchaseApprovalRejectForSid(int $sid): void
  10997. {
  10998. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  10999. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  11000. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  11001. $allIds = $this->purchaseOrderDetail($sid);
  11002. if ($allIds === []) {
  11003. throw new \Exception('未找到下发明细');
  11004. }
  11005. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11006. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  11007. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11008. 'pick_company_name' => '',
  11009. ]);
  11010. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  11011. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  11012. $poId = 0;
  11013. try {
  11014. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  11015. if (is_array($po)) {
  11016. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11017. }
  11018. } catch (\Throwable $e) {
  11019. }
  11020. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  11021. }
  11022. /**
  11023. * 审核弹窗(旧入口,POST 已关闭)
  11024. */
  11025. public function review()
  11026. {
  11027. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  11028. $this->error(__('You have no permission'));
  11029. }
  11030. if ($this->request->isPost()) {
  11031. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  11032. }
  11033. $this->view->assign('pickMode', 0);
  11034. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  11035. }
  11036. /**
  11037. * 审核弹窗获取公司列表
  11038. */
  11039. public function reviewCompanies()
  11040. {
  11041. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  11042. $this->error(__('You have no permission'));
  11043. }
  11044. if (!$this->request->isAjax()) {
  11045. $this->error(__('Invalid parameters'));
  11046. }
  11047. $list = [];
  11048. try {
  11049. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  11050. $rows = Db::table('customer')
  11051. ->where(function ($q) {
  11052. $q->where('status', 1)
  11053. ->whereOr('status', '1')
  11054. ->whereOr('status', '')
  11055. ->whereNull('status');
  11056. })
  11057. ->order('id', 'desc')
  11058. ->select();
  11059. } catch (\Throwable $e) {
  11060. $this->success('', '', []);
  11061. return;
  11062. }
  11063. if (!is_array($rows)) {
  11064. $this->success('', '', []);
  11065. return;
  11066. }
  11067. $detailColCandidates = [
  11068. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  11069. 'company_detail', 'company_desc', 'address',
  11070. ];
  11071. foreach ($rows as $row) {
  11072. if (!is_array($row)) {
  11073. continue;
  11074. }
  11075. $norm = [];
  11076. foreach ($row as $k => $v) {
  11077. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  11078. }
  11079. $row = $norm;
  11080. $st = $row['status'] ?? '';
  11081. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  11082. continue;
  11083. }
  11084. $payload = $this->buildCustomerContactPayloadFromRow($row);
  11085. if ($payload === null) {
  11086. continue;
  11087. }
  11088. $detail = '';
  11089. foreach ($detailColCandidates as $dk) {
  11090. if (!isset($row[$dk])) {
  11091. continue;
  11092. }
  11093. $dv = trim((string)$row[$dk]);
  11094. if ($dv !== '') {
  11095. $detail = $dv;
  11096. break;
  11097. }
  11098. }
  11099. $payload['detail'] = $detail;
  11100. $list[] = $this->maskSupplierContactFields($payload);
  11101. }
  11102. $this->success('', '', $list);
  11103. }
  11104. /**
  11105. * 采购确认-下发明细弹窗:
  11106. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  11107. */
  11108. public function outward_detail()
  11109. {
  11110. $ids = $this->request->param('ids', $this->request->param('id', ''));
  11111. if (is_array($ids)) {
  11112. $ids = isset($ids[0]) ? $ids[0] : '';
  11113. }
  11114. $ids = trim((string)$ids);
  11115. if ($ids === '') {
  11116. $this->error(__('Invalid parameters'));
  11117. }
  11118. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  11119. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  11120. $wffTab = 'all';
  11121. }
  11122. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  11123. $purchaseOrderId = 0;
  11124. $po = null;
  11125. try {
  11126. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  11127. if (is_array($po)) {
  11128. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11129. }
  11130. } catch (\Throwable $e) {
  11131. $purchaseOrderId = 0;
  11132. $po = null;
  11133. }
  11134. if (!$isPurchaseConfirm && is_array($po)) {
  11135. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11136. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  11137. $isPurchaseConfirm = true;
  11138. }
  11139. }
  11140. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  11141. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11142. $confirmProcessCount = 1;
  11143. $confirmPickGroups = [];
  11144. $processDisplayRows = [];
  11145. $allDetailsBySid = [];
  11146. $requiredSidList = [];
  11147. $sidList = [$ids];
  11148. if ($isPurchaseConfirm) {
  11149. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  11150. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  11151. if ($mergeRows !== []) {
  11152. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  11153. }
  11154. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  11155. if ($confirmBundle['pos'] !== []) {
  11156. $sidList = [];
  11157. foreach ($confirmBundle['pos'] as $poRow) {
  11158. if (!is_array($poRow)) {
  11159. continue;
  11160. }
  11161. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11162. if (!$this->isValidScydgyRowId($sid)) {
  11163. continue;
  11164. }
  11165. $sidList[] = (string)$sid;
  11166. $requiredSidList[] = $sid;
  11167. }
  11168. }
  11169. if ($sidList === []) {
  11170. $sidList = [$ids];
  11171. $requiredSidList = [(int)$ids];
  11172. }
  11173. $confirmProcessCount = max(1, count($requiredSidList));
  11174. if (is_array($po) && $purchaseOrderId <= 0) {
  11175. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11176. }
  11177. }
  11178. $rows = [];
  11179. try {
  11180. if (count($sidList) === 1) {
  11181. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  11182. } else {
  11183. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  11184. }
  11185. } catch (\Throwable $e) {
  11186. $rows = [];
  11187. }
  11188. if ($isPurchaseConfirm) {
  11189. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  11190. }
  11191. foreach ($rows as &$r) {
  11192. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  11193. $r['id'] = $r['ID'];
  11194. }
  11195. if (isset($r['createtime'])) {
  11196. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  11197. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  11198. } else {
  11199. $r['createtime_text'] = (string)$r['createtime'];
  11200. }
  11201. } else {
  11202. $r['createtime_text'] = '';
  11203. }
  11204. if (is_array($r)) {
  11205. $r = $this->maskSupplierContactFields($r);
  11206. }
  11207. }
  11208. unset($r);
  11209. $pickedCompanyName = '';
  11210. $manualPicked = 0;
  11211. $manualPickReason = '';
  11212. $quoteVisible = 0;
  11213. $bidOpenVerified = 0;
  11214. if ($isPurchaseConfirm) {
  11215. // 确认包为空时,用当前主单兜底,避免指定说明读不到
  11216. if (($confirmBundle['ccydh'] ?? '') === '' && is_array($po)) {
  11217. $confirmBundle['ccydh'] = trim((string)($po['CCYDH'] ?? ''));
  11218. }
  11219. if (($confirmBundle['pos'] ?? []) === [] && is_array($po)) {
  11220. $confirmBundle['pos'] = [$po];
  11221. }
  11222. $manualPickInfo = $this->resolveProcuremenManualPickInfo($confirmBundle);
  11223. $manualPicked = $this->isProcuremenManualPickedForBundle($confirmBundle) ? 1 : 0;
  11224. $manualPickReason = (string)($manualPickInfo['reason'] ?? '');
  11225. if ($manualPickInfo['company'] !== '') {
  11226. $pickedCompanyName = $manualPickInfo['company'];
  11227. }
  11228. if ($pickedCompanyName === '') {
  11229. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  11230. if (!is_array($poRow)) {
  11231. continue;
  11232. }
  11233. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  11234. if ($pn !== '') {
  11235. $pickedCompanyName = $pn;
  11236. break;
  11237. }
  11238. }
  11239. }
  11240. // 再兜底:直接读当前主单字段
  11241. if (is_array($po) && (int)($po['manual_pick'] ?? 0) === 1) {
  11242. $manualPicked = 1;
  11243. if ($manualPickReason === '') {
  11244. $manualPickReason = trim((string)($po['manual_pick_reason'] ?? ''));
  11245. }
  11246. if ($pickedCompanyName === '') {
  11247. $pickedCompanyName = trim((string)($po['pick_company_name'] ?? ''));
  11248. }
  11249. }
  11250. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle) ? 1 : 0;
  11251. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  11252. }
  11253. $this->view->assign('rows', $rows ?: []);
  11254. $this->view->assign('rowCount', count($rows ?: []));
  11255. $this->view->assign('scydgyId', $ids);
  11256. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  11257. $this->view->assign('headTitle', $headTitle);
  11258. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  11259. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  11260. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  11261. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  11262. $this->view->assign('processDisplayRows', $processDisplayRows);
  11263. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  11264. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  11265. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  11266. $this->view->assign('manualPicked', $manualPicked);
  11267. $this->view->assign('manualPickReason', $manualPickReason);
  11268. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  11269. $this->view->assign('quoteVisible', $quoteVisible);
  11270. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
  11271. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  11272. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
  11273. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
  11274. $sysRqDisplay = '—';
  11275. if ($isPurchaseConfirm) {
  11276. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  11277. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  11278. );
  11279. }
  11280. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  11281. $this->view->assign('sysRq', $isPurchaseConfirm
  11282. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  11283. : '');
  11284. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  11285. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  11286. : '');
  11287. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  11288. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  11289. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  11290. if ($isPurchaseConfirm) {
  11291. return $this->view->fetch();
  11292. }
  11293. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  11294. $this->view->engine->layout(false);
  11295. try {
  11296. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  11297. $this->view->assign('dialogBody', $bodyHtml);
  11298. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  11299. } finally {
  11300. if ($restoreLayout) {
  11301. $this->view->engine->layout($restoreLayout);
  11302. }
  11303. }
  11304. }
  11305. /**
  11306. * 月度导出记录表(不存在时自动创建)
  11307. */
  11308. protected function ensurePurchaseMonthExportLogTable(): void
  11309. {
  11310. try {
  11311. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  11312. } catch (\Throwable $e) {
  11313. Db::execute(
  11314. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  11315. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  11316. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  11317. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  11318. `admin_name` varchar(64) NOT NULL DEFAULT '',
  11319. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  11320. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  11321. `createtime` int(10) unsigned DEFAULT NULL,
  11322. PRIMARY KEY (`id`),
  11323. KEY `idx_ym` (`ym`),
  11324. KEY `idx_ct` (`createtime`)
  11325. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  11326. );
  11327. }
  11328. }
  11329. /**
  11330. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  11331. *
  11332. * @param array<int, mixed> $dbRows
  11333. * @return array<int, array<string, mixed>>
  11334. */
  11335. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  11336. {
  11337. $keyword = trim((string)$this->request->get('search', ''));
  11338. if ($keyword === '') {
  11339. $keyword = trim((string)$this->request->request('search', ''));
  11340. }
  11341. $filter = $this->request->get('filter', '');
  11342. $op = $this->request->get('op', '');
  11343. if (is_string($filter) && $filter !== '') {
  11344. $filterArr = (array)json_decode($filter, true);
  11345. } else {
  11346. $filterArr = is_array($filter) ? $filter : [];
  11347. }
  11348. if (is_string($op) && $op !== '') {
  11349. $opArr = (array)json_decode($op, true);
  11350. } else {
  11351. $opArr = is_array($op) ? $op : [];
  11352. }
  11353. if ($keyword === '' && $filterArr === []) {
  11354. return array_values(array_filter($dbRows, 'is_array'));
  11355. }
  11356. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  11357. $out = [];
  11358. foreach ($dbRows as $row) {
  11359. if (!is_array($row)) {
  11360. continue;
  11361. }
  11362. if ($keyword !== '') {
  11363. $hit = false;
  11364. foreach ($searchFields as $f) {
  11365. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  11366. $hit = true;
  11367. break;
  11368. }
  11369. }
  11370. if (!$hit) {
  11371. continue;
  11372. }
  11373. }
  11374. $passFilter = true;
  11375. foreach ($filterArr as $field => $val) {
  11376. $field = (string)$field;
  11377. $val = trim((string)$val);
  11378. if ($field === '' || $val === '') {
  11379. continue;
  11380. }
  11381. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  11382. continue;
  11383. }
  11384. $cell = (string)($row[$field] ?? '');
  11385. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  11386. if ($mode === '=' || $mode === 'EQUAL') {
  11387. if (strcasecmp($cell, $val) !== 0) {
  11388. $passFilter = false;
  11389. break;
  11390. }
  11391. } elseif (mb_stripos($cell, $val) === false) {
  11392. $passFilter = false;
  11393. break;
  11394. }
  11395. }
  11396. if (!$passFilter) {
  11397. continue;
  11398. }
  11399. $out[] = $row;
  11400. }
  11401. return $out;
  11402. }
  11403. /**
  11404. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  11405. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  11406. */
  11407. public function export_month_outward()
  11408. {
  11409. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  11410. $this->error(__('You have no permission'));
  11411. }
  11412. $bundle = $this->prepareMonthOutwardExportBundle();
  11413. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  11414. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  11415. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  11416. $spreadsheet = new Spreadsheet();
  11417. $sheet = $spreadsheet->getActiveSheet();
  11418. $sheet->setTitle('外协加工明细');
  11419. $mon = (int)substr($ym, 5, 2);
  11420. $sheet->mergeCells('A1:H1');
  11421. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  11422. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  11423. $sheet->getStyle('A1')->getAlignment()
  11424. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11425. ->setVertical(Alignment::VERTICAL_CENTER);
  11426. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  11427. $col = 'A';
  11428. foreach ($headers as $h) {
  11429. $sheet->setCellValue($col . '2', $h);
  11430. $col++;
  11431. }
  11432. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  11433. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11434. $rowNum = 3;
  11435. $sumSubtotalCounts = 0;
  11436. $grandAmount = 0.0;
  11437. $globalSeq = 0;
  11438. if ($groups === []) {
  11439. $sheet->mergeCells('A3:H3');
  11440. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  11441. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11442. $rowNum = 4;
  11443. } else {
  11444. foreach ($groups as $items) {
  11445. if ($items === []) {
  11446. continue;
  11447. }
  11448. $groupLineCount = count($items);
  11449. $subAmount = 0.0;
  11450. foreach ($items as $line) {
  11451. $globalSeq++;
  11452. $dr = $line['detail'];
  11453. $amt = $this->procuremenExportAmount($dr);
  11454. $subAmount += $amt;
  11455. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  11456. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  11457. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  11458. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  11459. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  11460. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  11461. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  11462. $sheet->setCellValue('H' . $rowNum, $amt);
  11463. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  11464. $rowNum++;
  11465. }
  11466. $sumSubtotalCounts += $groupLineCount;
  11467. $grandAmount += $subAmount;
  11468. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11469. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  11470. $sheet->getStyle('G' . $rowNum)->getAlignment()
  11471. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  11472. ->setVertical(Alignment::VERTICAL_CENTER);
  11473. $rowNum++;
  11474. }
  11475. }
  11476. $sheet->setCellValue('A' . $rowNum, '总计');
  11477. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  11478. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11479. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  11480. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  11481. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  11482. $lastRow = $rowNum;
  11483. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  11484. 'borders' => [
  11485. 'allBorders' => [
  11486. 'borderStyle' => Border::BORDER_THIN,
  11487. 'color' => ['rgb' => '000000'],
  11488. ],
  11489. ],
  11490. ]);
  11491. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  11492. if ($lastRow >= 3) {
  11493. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11494. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11495. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11496. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11497. }
  11498. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  11499. $sheet->getColumnDimension('A')->setWidth(7);
  11500. $sheet->getColumnDimension('B')->setWidth(16);
  11501. $sheet->getColumnDimension('C')->setWidth(52);
  11502. $sheet->getColumnDimension('D')->setWidth(32);
  11503. $sheet->getColumnDimension('E')->setWidth(12);
  11504. $sheet->getColumnDimension('F')->setWidth(44);
  11505. $sheet->getColumnDimension('G')->setWidth(26);
  11506. $sheet->getColumnDimension('H')->setWidth(13);
  11507. $sheet->getRowDimension(1)->setRowHeight(28);
  11508. $ymCompact = str_replace('-', '', $ym);
  11509. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  11510. $filename = $fileBase . '.xlsx';
  11511. try {
  11512. $this->ensurePurchaseMonthExportLogTable();
  11513. list($adminId, $adminName) = $this->GetUseName();
  11514. Db::table('purchase_month_export_log')->insert([
  11515. 'ym' => $ym,
  11516. 'admin_id' => (int)$adminId,
  11517. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  11518. 'row_count' => count($exportLines),
  11519. 'total_amount' => round($grandAmount, 2),
  11520. 'createtime' => time(),
  11521. ]);
  11522. } catch (\Throwable $e) {
  11523. Log::write('month export log: ' . $e->getMessage(), 'error');
  11524. }
  11525. if (ob_get_length()) {
  11526. ob_end_clean();
  11527. }
  11528. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  11529. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  11530. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  11531. header('Cache-Control: max-age=0');
  11532. $writer = new Xlsx($spreadsheet);
  11533. $writer->save('php://output');
  11534. $spreadsheet->disconnectWorksheets();
  11535. unset($spreadsheet);
  11536. exit;
  11537. }
  11538. /**
  11539. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  11540. */
  11541. public function export_month_quote()
  11542. {
  11543. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  11544. $this->error(__('You have no permission'));
  11545. }
  11546. $bundle = $this->prepareMonthOutwardExportBundle();
  11547. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  11548. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  11549. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  11550. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  11551. $spreadsheet = new Spreadsheet();
  11552. $sheet = $spreadsheet->getActiveSheet();
  11553. $sheet->setTitle('供应商报价明细');
  11554. $mon = (int)substr($ym, 5, 2);
  11555. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  11556. $sheet->getColumnDimension('A')->setWidth(7);
  11557. $sheet->getColumnDimension('B')->setWidth(16);
  11558. $sheet->getColumnDimension('C')->setWidth(52);
  11559. $sheet->getColumnDimension('D')->setWidth(26);
  11560. $sheet->getColumnDimension('E')->setWidth(32);
  11561. $sheet->getColumnDimension('F')->setWidth(12);
  11562. $sheet->getColumnDimension('G')->setWidth(14);
  11563. $sheet->getColumnDimension('H')->setWidth(12);
  11564. if ($quoteLastRow < 1) {
  11565. $quoteLastRow = 3;
  11566. }
  11567. $ymCompact = str_replace('-', '', $ym);
  11568. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  11569. if (ob_get_length()) {
  11570. ob_end_clean();
  11571. }
  11572. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  11573. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  11574. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  11575. header('Cache-Control: max-age=0');
  11576. $writer = new Xlsx($spreadsheet);
  11577. $writer->save('php://output');
  11578. $spreadsheet->disconnectWorksheets();
  11579. unset($spreadsheet);
  11580. exit;
  11581. }
  11582. /**
  11583. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  11584. *
  11585. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  11586. */
  11587. protected function prepareMonthOutwardExportBundle(): array
  11588. {
  11589. $this->request->filter(['strip_tags', 'trim']);
  11590. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  11591. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  11592. $ym = date('Y-m');
  11593. }
  11594. $dbRows = [];
  11595. try {
  11596. $query = Db::table('purchase_order');
  11597. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  11598. $dbRows = $query->select();
  11599. } catch (\Throwable $e) {
  11600. $dbRows = [];
  11601. }
  11602. if (!is_array($dbRows)) {
  11603. $dbRows = [];
  11604. }
  11605. $completeTsMap = [];
  11606. $sidList = [];
  11607. foreach ($dbRows as $dbRow) {
  11608. if (!is_array($dbRow)) {
  11609. continue;
  11610. }
  11611. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  11612. if ($sid > 0) {
  11613. $sidList[$sid] = true;
  11614. }
  11615. }
  11616. if ($sidList !== []) {
  11617. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  11618. }
  11619. $searchKw = trim((string)$this->request->get('search', ''));
  11620. if ($searchKw === '') {
  11621. $searchKw = trim((string)$this->request->request('search', ''));
  11622. }
  11623. $filterRaw = $this->request->get('filter', '');
  11624. $filterArrTmp = [];
  11625. if (is_string($filterRaw) && $filterRaw !== '') {
  11626. $filterArrTmp = (array)json_decode($filterRaw, true);
  11627. } elseif (is_array($filterRaw)) {
  11628. $filterArrTmp = $filterRaw;
  11629. }
  11630. $hasSearch = ($searchKw !== '');
  11631. if (!$hasSearch) {
  11632. foreach ($filterArrTmp as $fv) {
  11633. if (trim((string)$fv) !== '') {
  11634. $hasSearch = true;
  11635. break;
  11636. }
  11637. }
  11638. }
  11639. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap, $hasSearch) {
  11640. if (!is_array($dbRow)) {
  11641. return false;
  11642. }
  11643. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  11644. if ($done['ts'] <= 0) {
  11645. return false;
  11646. }
  11647. if ($hasSearch) {
  11648. return true;
  11649. }
  11650. return date('Y-m', $done['ts']) === $ym;
  11651. }));
  11652. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  11653. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  11654. $mainBySid = [];
  11655. foreach ($pool as $rw) {
  11656. if (!is_array($rw)) {
  11657. continue;
  11658. }
  11659. $rid = (int)($rw['ID'] ?? 0);
  11660. if ($rid > 0) {
  11661. $mainBySid[$rid] = $rw;
  11662. }
  11663. }
  11664. if ($mainBySid === []) {
  11665. $detailRows = [];
  11666. } else {
  11667. try {
  11668. $detailRows = Db::table('purchase_order_detail')
  11669. ->where('scydgy_id', 'in', array_keys($mainBySid))
  11670. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  11671. ->order('status', 'desc')
  11672. ->order('CCYDH', 'asc')
  11673. ->order('company_name', 'asc')
  11674. ->order('id', 'asc')
  11675. ->select();
  11676. } catch (\Throwable $e) {
  11677. try {
  11678. $detailRows = Db::table('purchase_order_detail')
  11679. ->where('scydgy_id', 'in', array_keys($mainBySid))
  11680. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  11681. ->order('status', 'desc')
  11682. ->order('CCYDH', 'asc')
  11683. ->order('company_name', 'asc')
  11684. ->order('ID', 'asc')
  11685. ->select();
  11686. } catch (\Throwable $e2) {
  11687. $detailRows = [];
  11688. }
  11689. }
  11690. }
  11691. if (!is_array($detailRows)) {
  11692. $detailRows = [];
  11693. }
  11694. $exportLines = [];
  11695. $detailSidSeen = [];
  11696. foreach ($detailRows as $dr) {
  11697. if (!is_array($dr)) {
  11698. continue;
  11699. }
  11700. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11701. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  11702. continue;
  11703. }
  11704. if (isset($detailSidSeen[$sid])) {
  11705. continue;
  11706. }
  11707. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  11708. continue;
  11709. }
  11710. $detailSidSeen[$sid] = true;
  11711. $m = $mainBySid[$sid];
  11712. $exportLines[] = [
  11713. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11714. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11715. 'company_name' => (string)($dr['company_name'] ?? ''),
  11716. 'CDF' => (string)($m['CDF'] ?? ''),
  11717. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11718. 'gx' => $this->procuremenExportGxText($m),
  11719. 'detail' => $dr,
  11720. ];
  11721. }
  11722. foreach ($detailRows as $dr) {
  11723. if (!is_array($dr)) {
  11724. continue;
  11725. }
  11726. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11727. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  11728. continue;
  11729. }
  11730. $detailSidSeen[$sid] = true;
  11731. $m = $mainBySid[$sid];
  11732. $exportLines[] = [
  11733. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11734. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11735. 'company_name' => (string)($dr['company_name'] ?? ''),
  11736. 'CDF' => (string)($m['CDF'] ?? ''),
  11737. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11738. 'gx' => $this->procuremenExportGxText($m),
  11739. 'detail' => $dr,
  11740. ];
  11741. }
  11742. foreach ($mainBySid as $sid => $m) {
  11743. if (isset($detailSidSeen[$sid])) {
  11744. continue;
  11745. }
  11746. $company = trim((string)($m['pick_company_name'] ?? ''));
  11747. $exportLines[] = [
  11748. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  11749. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  11750. 'company_name' => $company,
  11751. 'CDF' => (string)($m['CDF'] ?? ''),
  11752. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  11753. 'gx' => $this->procuremenExportGxText($m),
  11754. 'detail' => [],
  11755. ];
  11756. }
  11757. $groups = [];
  11758. foreach ($exportLines as $line) {
  11759. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  11760. if (!isset($groups[$k])) {
  11761. $groups[$k] = [];
  11762. }
  11763. $groups[$k][] = $line;
  11764. }
  11765. ksort($groups, SORT_STRING);
  11766. return [
  11767. 'ym' => $ym,
  11768. 'mainBySid' => $mainBySid,
  11769. 'detailRows' => $detailRows,
  11770. 'exportLines' => $exportLines,
  11771. 'groups' => $groups,
  11772. ];
  11773. }
  11774. /**
  11775. * 导出用:工序列文案
  11776. */
  11777. protected function procuremenExportGxText(array $r)
  11778. {
  11779. $a = trim((string)($r['CDXMC'] ?? ''));
  11780. $b = trim((string)($r['CGYMC'] ?? ''));
  11781. if ($a !== '' && $b !== '') {
  11782. return $a . ':' . $b;
  11783. }
  11784. return $a !== '' ? $a : $b;
  11785. }
  11786. /**
  11787. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  11788. */
  11789. protected function procuremenExportAmount(array $r)
  11790. {
  11791. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  11792. if (!array_key_exists($k, $r)) {
  11793. continue;
  11794. }
  11795. $v = $r[$k];
  11796. if ($v === null || $v === '') {
  11797. continue;
  11798. }
  11799. if (is_numeric($v)) {
  11800. return (float)$v;
  11801. }
  11802. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  11803. if ($v !== '' && is_numeric($v)) {
  11804. return (float)$v;
  11805. }
  11806. }
  11807. return 0.0;
  11808. }
  11809. /**
  11810. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  11811. *
  11812. * @param array<int, array<string, mixed>> $detailRows
  11813. * @param array<int, array<string, mixed>> $mainBySid
  11814. * @return array<int, array<string, mixed>>
  11815. */
  11816. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  11817. {
  11818. $lines = [];
  11819. foreach ($detailRows as $dr) {
  11820. if (!is_array($dr)) {
  11821. continue;
  11822. }
  11823. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  11824. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  11825. continue;
  11826. }
  11827. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  11828. continue;
  11829. }
  11830. $cn = trim((string)($dr['company_name'] ?? ''));
  11831. if ($cn === '') {
  11832. continue;
  11833. }
  11834. $m = $mainBySid[$sid];
  11835. $am = trim((string)($dr['amount'] ?? ''));
  11836. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  11837. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  11838. $amountText = $amountFilled
  11839. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  11840. : '未填写';
  11841. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  11842. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  11843. if ($deliveryShow === '' && $deliveryRaw !== '') {
  11844. $deliveryShow = $deliveryRaw;
  11845. }
  11846. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  11847. ? $deliveryShow
  11848. : '未填写';
  11849. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  11850. $lines[] = [
  11851. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  11852. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  11853. 'gx' => $this->procuremenExportGxText($m),
  11854. 'company_name' => $cn,
  11855. 'amount_text' => $amountText,
  11856. 'amount_num' => $amountFilled ? $amountNum : null,
  11857. 'delivery_text' => $deliveryText,
  11858. 'picked_text' => $picked ? '中标' : '未中标',
  11859. 'picked' => $picked,
  11860. ];
  11861. }
  11862. $winnerSupplierByOrder = [];
  11863. foreach ($lines as $line) {
  11864. $dh = trim((string)($line['CCYDH'] ?? ''));
  11865. $cn = trim((string)($line['company_name'] ?? ''));
  11866. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  11867. $winnerSupplierByOrder[$dh][$cn] = true;
  11868. }
  11869. }
  11870. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  11871. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  11872. if ($c !== 0) {
  11873. return $c;
  11874. }
  11875. $dh = trim((string)($a['CCYDH'] ?? ''));
  11876. $aCn = trim((string)($a['company_name'] ?? ''));
  11877. $bCn = trim((string)($b['company_name'] ?? ''));
  11878. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  11879. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  11880. if ($aSupplierWin !== $bSupplierWin) {
  11881. return $aSupplierWin ? -1 : 1;
  11882. }
  11883. $c = strcmp($aCn, $bCn);
  11884. if ($c !== 0) {
  11885. return $c;
  11886. }
  11887. if (!empty($a['picked']) !== !empty($b['picked'])) {
  11888. return !empty($a['picked']) ? -1 : 1;
  11889. }
  11890. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  11891. if ($c !== 0) {
  11892. return $c;
  11893. }
  11894. return 0;
  11895. });
  11896. return $lines;
  11897. }
  11898. /**
  11899. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  11900. *
  11901. * @param array<int, array<string, mixed>> $quoteLines
  11902. */
  11903. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  11904. {
  11905. $mon = (int)substr($ym, 5, 2);
  11906. $titleRow = $startRow;
  11907. $headerRow = $startRow + 1;
  11908. $dataStartRow = $startRow + 2;
  11909. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  11910. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  11911. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  11912. $sheet->getStyle('A' . $titleRow)->getAlignment()
  11913. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11914. ->setVertical(Alignment::VERTICAL_CENTER);
  11915. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  11916. $col = 'A';
  11917. foreach ($headers as $h) {
  11918. $sheet->setCellValue($col . $headerRow, $h);
  11919. $col++;
  11920. }
  11921. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  11922. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11923. $rowNum = $dataStartRow;
  11924. if ($quoteLines === []) {
  11925. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  11926. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  11927. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11928. $rowNum = $dataStartRow + 1;
  11929. } else {
  11930. $i = 0;
  11931. foreach ($quoteLines as $line) {
  11932. $i++;
  11933. $sheet->setCellValue('A' . $rowNum, $i);
  11934. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  11935. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  11936. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  11937. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  11938. if ($line['amount_num'] !== null) {
  11939. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  11940. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  11941. } else {
  11942. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  11943. }
  11944. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  11945. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  11946. if (!empty($line['picked'])) {
  11947. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  11948. }
  11949. $rowNum++;
  11950. }
  11951. }
  11952. $lastRow = $rowNum - 1;
  11953. if ($lastRow >= $headerRow) {
  11954. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  11955. 'borders' => [
  11956. 'allBorders' => [
  11957. 'borderStyle' => Border::BORDER_THIN,
  11958. 'color' => ['rgb' => '000000'],
  11959. ],
  11960. ],
  11961. ]);
  11962. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  11963. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11964. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11965. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11966. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  11967. if ($lastRow >= $dataStartRow) {
  11968. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  11969. }
  11970. }
  11971. return $lastRow;
  11972. }
  11973. /**
  11974. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  11975. */
  11976. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  11977. {
  11978. if ($lastRow < $dataStartRow || $headerRow < 1) {
  11979. return;
  11980. }
  11981. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  11982. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11983. ->setVertical(Alignment::VERTICAL_CENTER);
  11984. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  11985. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11986. ->setVertical(Alignment::VERTICAL_CENTER);
  11987. if ($lastCol > 'B') {
  11988. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  11989. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  11990. ->setVertical(Alignment::VERTICAL_CENTER);
  11991. }
  11992. }
  11993. /**
  11994. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  11995. */
  11996. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  11997. {
  11998. $s = trim($ccydh);
  11999. if ($s === '') {
  12000. return 'ORDER';
  12001. }
  12002. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  12003. $s = trim($s, '._-');
  12004. if ($s === '') {
  12005. return 'ORDER';
  12006. }
  12007. if (function_exists('mb_substr')) {
  12008. return mb_substr($s, 0, 80, 'UTF-8');
  12009. }
  12010. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  12011. }
  12012. /**
  12013. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  12014. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  12015. *
  12016. * @return array{objectKey: string, webPath: string}
  12017. */
  12018. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  12019. {
  12020. $sid = (int)$scydgyId;
  12021. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  12022. $y = date('Y');
  12023. $m = date('m');
  12024. $d = date('d');
  12025. $basename = $safeOrder . '_' . $sid . '.pdf';
  12026. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  12027. return [
  12028. 'objectKey' => $objectKey,
  12029. 'webPath' => '/' . $objectKey,
  12030. ];
  12031. }
  12032. /**
  12033. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  12034. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  12035. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  12036. *
  12037. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  12038. */
  12039. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  12040. {
  12041. if (!$this->isValidScydgyRowId($scydgyId)) {
  12042. return '';
  12043. }
  12044. $ids = trim((string)$scydgyId);
  12045. $prep = $this->prepareProcuremenDetailsView($ids);
  12046. if (!$prep['ok']) {
  12047. return '';
  12048. }
  12049. $ccydh = $prep['ccydh'];
  12050. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  12051. $objectKey = $paths['objectKey'];
  12052. $webPath = $paths['webPath'];
  12053. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  12054. $this->view->assign([
  12055. 'pdf_export' => 1,
  12056. 'pdfMetaLine' => $meta,
  12057. ]);
  12058. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  12059. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  12060. $this->view->engine->layout(false);
  12061. try {
  12062. $html = $this->view->fetch('procuremen/details_pdf_shell');
  12063. } catch (\Throwable $e) {
  12064. if ($restoreLayout) {
  12065. $this->view->engine->layout($restoreLayout);
  12066. }
  12067. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  12068. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12069. return '';
  12070. }
  12071. if ($restoreLayout) {
  12072. $this->view->engine->layout($restoreLayout);
  12073. }
  12074. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12075. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  12076. if (!is_dir($tempDir)) {
  12077. @mkdir($tempDir, 0755, true);
  12078. }
  12079. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  12080. try {
  12081. $mpdf = new \Mpdf\Mpdf([
  12082. 'mode' => 'utf-8',
  12083. 'format' => 'A4',
  12084. 'margin_left' => 12,
  12085. 'margin_right' => 12,
  12086. 'margin_top' => 14,
  12087. 'margin_bottom' => 14,
  12088. 'tempDir' => $tempDir,
  12089. 'autoScriptToLang' => true,
  12090. 'autoLangToFont' => true,
  12091. ]);
  12092. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  12093. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  12094. $mpdf->SetBasePath('http://127.0.0.1/');
  12095. $mpdf->WriteHTML($html);
  12096. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  12097. } catch (\Throwable $e) {
  12098. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  12099. if (is_file($tempPdf)) {
  12100. @unlink($tempPdf);
  12101. }
  12102. return '';
  12103. }
  12104. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  12105. if ($ossUrl !== '') {
  12106. @unlink($tempPdf);
  12107. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12108. return $ossUrl;
  12109. }
  12110. $pi = pathinfo($objectKey);
  12111. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  12112. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  12113. if ($baseFile === '') {
  12114. @unlink($tempPdf);
  12115. return '';
  12116. }
  12117. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  12118. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  12119. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  12120. @unlink($tempPdf);
  12121. return '';
  12122. }
  12123. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  12124. if (!@copy($tempPdf, $fullPath)) {
  12125. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  12126. @unlink($tempPdf);
  12127. return '';
  12128. }
  12129. @unlink($tempPdf);
  12130. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12131. return $webPath;
  12132. }
  12133. /**
  12134. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  12135. */
  12136. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  12137. {
  12138. if ($scydgyId <= 0 || $webPath === '') {
  12139. return;
  12140. }
  12141. try {
  12142. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  12143. } catch (\Throwable $e) {
  12144. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  12145. }
  12146. }
  12147. /**
  12148. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  12149. *
  12150. * @param array<string, string> $vars
  12151. * @return array<string, string>
  12152. */
  12153. protected function normalizeSmsTemplateVars(array $vars): array
  12154. {
  12155. $out = [];
  12156. foreach ($vars as $k => $v) {
  12157. $out[(string)$k] = trim((string)$v);
  12158. }
  12159. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  12160. $out['contact_name'] = $out['company_name'];
  12161. }
  12162. return $out;
  12163. }
  12164. /**
  12165. * 按手机号或公司名称查 customer 表联系人姓名
  12166. */
  12167. protected function resolveCustomerContactName(string $phone, string $companyName): string
  12168. {
  12169. $phone = trim($phone);
  12170. $companyName = trim($companyName);
  12171. try {
  12172. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  12173. $row = Db::table('customer')
  12174. ->where(function ($q) use ($phone) {
  12175. $q->where('phone', $phone)->whereOr('account', $phone);
  12176. })
  12177. ->order('id', 'asc')
  12178. ->find();
  12179. if (is_array($row)) {
  12180. $nm = trim((string)($row['username'] ?? ''));
  12181. if ($nm !== '') {
  12182. return $nm;
  12183. }
  12184. }
  12185. }
  12186. if ($companyName !== '') {
  12187. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  12188. if (is_array($row)) {
  12189. return trim((string)($row['username'] ?? ''));
  12190. }
  12191. }
  12192. } catch (\Throwable $e) {
  12193. }
  12194. return '';
  12195. }
  12196. /**
  12197. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  12198. */
  12199. protected function plainTextToHtmlEmailBody(string $text): string
  12200. {
  12201. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  12202. $parts = explode("\n", $text);
  12203. $out = [];
  12204. foreach ($parts as $line) {
  12205. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  12206. $out[] = $line;
  12207. } else {
  12208. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  12209. }
  12210. }
  12211. return implode("<br>\n", $out);
  12212. }
  12213. /**
  12214. * 短信场景:去掉链接类变量,避免误填 URL
  12215. *
  12216. * @param array<string, string> $vars
  12217. * @return array<string, string>
  12218. */
  12219. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  12220. {
  12221. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  12222. return $vars;
  12223. }
  12224. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  12225. $vars[$k] = '';
  12226. }
  12227. return $vars;
  12228. }
  12229. /**
  12230. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  12231. *
  12232. * @param array<string, string> $vars
  12233. */
  12234. protected function renderNotifyTemplate(string $scene, array $vars): string
  12235. {
  12236. $vars = $this->normalizeSmsTemplateVars($vars);
  12237. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  12238. $row = $this->loadNotifyTemplateRow($scene);
  12239. if ($row === null) {
  12240. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12241. }
  12242. $tpl = trim((string)($row['content'] ?? ''));
  12243. if ($tpl === '') {
  12244. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12245. }
  12246. foreach ($vars as $k => $v) {
  12247. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  12248. }
  12249. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  12250. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  12251. return $tpl;
  12252. }
  12253. protected function resolveProcuremenEmailSubject(string $scene): string
  12254. {
  12255. // 询价通知业务员:模版名称即邮件主题(可含 {ccydh})
  12256. if ($scene === 'rfq_salesman_email') {
  12257. $row = $this->loadNotifyTemplateRow($scene);
  12258. $title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
  12259. if ($title !== '') {
  12260. return $title;
  12261. }
  12262. return '协助采购询价通知';
  12263. }
  12264. $map = [
  12265. 'review_email' => '您有新的协助加工订单',
  12266. ];
  12267. $subject = trim((string)($map[$scene] ?? ''));
  12268. if ($subject === '') {
  12269. $this->error('未配置邮件主题:' . $scene);
  12270. }
  12271. return $subject;
  12272. }
  12273. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  12274. {
  12275. $map = [
  12276. 'review_email' => '协助下发-邮箱',
  12277. 'review_sms' => '协助下发-短信',
  12278. 'confirm_ok' => '采购确认-通过',
  12279. 'confirm_fail' => '采购确认-未通过',
  12280. 'bid_open' => '开标双重验证',
  12281. 'rfq_salesman_email' => '询价通知业务员-邮箱',
  12282. ];
  12283. $label = $map[$scene] ?? $scene;
  12284. if ($titleRequired) {
  12285. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  12286. }
  12287. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  12288. }
  12289. /**
  12290. * 是否开启协助通知演练(不发真实短信/邮件)
  12291. */
  12292. protected function isProcuremenNotifyDryRun(): bool
  12293. {
  12294. return (bool)Config::get('procuremen_notify_dry_run');
  12295. }
  12296. /**
  12297. * @param array<string, mixed> $payload
  12298. */
  12299. protected function recordNotifyDryRunPreview(array $payload): void
  12300. {
  12301. $this->notifyDryRunPreview[] = $payload;
  12302. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  12303. }
  12304. /**
  12305. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  12306. * @throws \Exception
  12307. */
  12308. protected function smsbao($phone, $content)
  12309. {
  12310. if ($this->isProcuremenNotifyDryRun()) {
  12311. $this->recordNotifyDryRunPreview([
  12312. 'scene' => 'sms_only',
  12313. 'phone' => $phone,
  12314. 'sms_content' => $content,
  12315. ]);
  12316. return;
  12317. }
  12318. $statusStr = [
  12319. '0' => '短信发送成功',
  12320. '-1' => '参数不全',
  12321. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  12322. '30' => '密码错误',
  12323. '40' => '账号不存在',
  12324. '41' => '余额不足',
  12325. '42' => '帐户已过期',
  12326. '43' => 'IP地址限制',
  12327. '50' => '内容含有敏感词',
  12328. ];
  12329. $smsapi = 'http://api.smsbao.com/';
  12330. $user = 'zhuwei123';
  12331. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  12332. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  12333. $result = @file_get_contents($sendurl);
  12334. if ($result === false) {
  12335. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  12336. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  12337. }
  12338. $result = trim((string)$result);
  12339. if ($result !== '0') {
  12340. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  12341. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  12342. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  12343. }
  12344. }
  12345. }