Procuremen.php 517 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenGuard;
  6. use app\common\library\ProcuremenOperLog;
  7. use app\common\library\ProcuremenSchema;
  8. use app\common\library\ProcuremenStatus;
  9. use app\common\library\ProcuremenSupplierScore;
  10. use app\common\library\ProcuremenTime;
  11. use PHPMailer\PHPMailer\PHPMailer;
  12. use think\Config;
  13. use think\Cache;
  14. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  15. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  16. use PhpOffice\PhpSpreadsheet\Style\Border;
  17. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  18. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  19. use think\Db;
  20. use think\Log;
  21. class Procuremen extends Backend
  22. {
  23. /**
  24. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  25. */
  26. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,b.czlyq,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  27. /**
  28. * Procuremen模型对象
  29. * @var \app\admin\model\Procuremen
  30. */
  31. protected $model = null;
  32. /**
  33. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  34. */
  35. protected $notifyDryRunPreview = [];
  36. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  37. protected $procuremenRedisCache = null;
  38. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  39. protected $pickHiddenScydgySetCache = null;
  40. /** 邮件发送日志表结构已就绪缓存键 */
  41. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  42. /**
  43. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  44. * @var array
  45. */
  46. protected $noNeedRight = [
  47. 'pickreview', 'review', 'reviewcompanies',
  48. // 方法内用 hasProcuremenPerm 校验(兼容 auditsubmit / auditissue)
  49. 'auditmanualpick',
  50. // 与 rfqlist 同权,方法内校验
  51. 'rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqissuesuppliers', 'rfqissue', 'rfqissuesendmail', 'rfqquotes',
  52. 'rfqappendsuppliers', 'rfqsupplieroptions', 'rfqsalesmanoptions', 'rfqappendsalesmen',
  53. ];
  54. public function _initialize()
  55. {
  56. parent::_initialize();
  57. $this->model = new \app\admin\model\Procuremen;
  58. $this->maybeMigrateLegacyWflowStatusText();
  59. $this->assignProcuremenAuthConfig();
  60. try {
  61. ProcuremenSchema::ensureAll();
  62. } catch (\Throwable $e) {
  63. }
  64. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  65. $this->ensurePurchaseEmailSendLogTableOnce();
  66. }
  67. }
  68. /**
  69. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  70. */
  71. protected function maybeMigrateLegacyWflowStatusText(): void
  72. {
  73. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  74. if (is_file($flagFile)) {
  75. return;
  76. }
  77. $map = [
  78. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  79. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  80. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  81. '3' => ProcuremenStatus::WFLOW_APPROVED,
  82. ];
  83. try {
  84. foreach ($map as $num => $text) {
  85. Db::table('purchase_order')
  86. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  87. ->update(['wflow_status' => $text]);
  88. }
  89. @file_put_contents($flagFile, date('c'));
  90. } catch (\Throwable $e) {
  91. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  92. }
  93. }
  94. /**
  95. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  96. *
  97. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  98. */
  99. protected function hasProcuremenPerm(array $actions): bool
  100. {
  101. foreach ($actions as $action) {
  102. $action = strtolower(trim((string)$action));
  103. if ($action === '') {
  104. continue;
  105. }
  106. if (strpos($action, 'procuremen/') !== 0) {
  107. $action = 'procuremen/' . $action;
  108. }
  109. if ($this->auth->check($action)) {
  110. return true;
  111. }
  112. }
  113. $suffixes = [];
  114. foreach ($actions as $action) {
  115. $action = strtolower(trim((string)$action));
  116. $action = preg_replace('#^procuremen/#', '', $action);
  117. if ($action !== '') {
  118. $suffixes[$action] = true;
  119. }
  120. }
  121. if ($suffixes === []) {
  122. return false;
  123. }
  124. try {
  125. foreach ($this->auth->getRuleList() as $rule) {
  126. $rule = strtolower((string)$rule);
  127. if (strpos($rule, 'procuremen/') !== 0) {
  128. continue;
  129. }
  130. foreach (array_keys($suffixes) as $suffix) {
  131. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  132. return true;
  133. }
  134. }
  135. }
  136. } catch (\Throwable $e) {
  137. }
  138. return false;
  139. }
  140. /**
  141. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  142. *
  143. * @param string[] $actions
  144. */
  145. protected function hasProcuremenPermStrict(array $actions): bool
  146. {
  147. foreach ($actions as $action) {
  148. $action = strtolower(trim((string)$action));
  149. if ($action === '') {
  150. continue;
  151. }
  152. if (strpos($action, 'procuremen/') !== 0) {
  153. $action = 'procuremen/' . $action;
  154. }
  155. if ($this->auth->check($action)) {
  156. return true;
  157. }
  158. }
  159. return false;
  160. }
  161. /**
  162. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  163. *
  164. * @param string[] $titles
  165. */
  166. protected function authHasAssignedRuleTitle(array $titles): bool
  167. {
  168. $titles = array_values(array_filter(array_map('trim', $titles)));
  169. if ($titles === []) {
  170. return false;
  171. }
  172. try {
  173. $ids = $this->auth->getRuleIds();
  174. if (in_array('*', $ids, true)) {
  175. return true;
  176. }
  177. if ($ids === []) {
  178. return false;
  179. }
  180. $rows = Db::name('auth_rule')
  181. ->where('status', 'normal')
  182. ->whereIn('id', $ids)
  183. ->column('title');
  184. foreach ($rows as $title) {
  185. $t = trim((string)$title);
  186. if ($t !== '' && in_array($t, $titles, true)) {
  187. return true;
  188. }
  189. }
  190. } catch (\Throwable $e) {
  191. }
  192. return false;
  193. }
  194. protected function procuremenCanPickDelete(): bool
  195. {
  196. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  197. return true;
  198. }
  199. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  200. }
  201. protected function procuremenCanComplete(): bool
  202. {
  203. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  204. return true;
  205. }
  206. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  207. }
  208. protected function procuremenCanDispatch(): bool
  209. {
  210. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  211. }
  212. /**
  213. * 前端按钮显隐(Config.procuremenAuth)
  214. */
  215. protected function assignProcuremenAuthConfig(): void
  216. {
  217. $authMap = [
  218. 'pickreview' => $this->procuremenCanDispatch(),
  219. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  220. 'pickdelete' => $this->procuremenCanPickDelete(),
  221. 'completedirectly' => $this->procuremenCanComplete(),
  222. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  223. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  224. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  225. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  226. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  227. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  228. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  229. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  230. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  231. 'details' => $this->hasProcuremenPerm(['details']),
  232. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  233. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  234. 'export_month_quote' => $this->hasProcuremenPerm(['export_month_quote', 'exportMonthQuote', 'export_month_outward', 'exportMonthOutward']),
  235. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  236. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  237. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  238. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  239. 'auditmanualpick' => $this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue']),
  240. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  241. 'add' => $this->hasProcuremenPerm(['add']),
  242. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  243. // 查询询价三个操作按钮:各自独立,不再因有 rfqlist 就全部放开
  244. 'rfqissue' => $this->hasProcuremenPerm(['rfqissue']),
  245. 'rfqquotes' => $this->hasProcuremenPerm(['rfqquotes']),
  246. 'rfqnotifysalesman' => $this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen']),
  247. 'rfqnotifysalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman']),
  248. // 询价附属接口:有「询价」按钮权限即可(无需再单独勾选)
  249. 'rfqissuesuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers']),
  250. 'rfqissuesendmail' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail']),
  251. 'rfqappendsuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers']),
  252. 'rfqsupplieroptions' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions']),
  253. 'rfqsalesmanoptions' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen']),
  254. 'rfqappendsalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen']),
  255. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  256. ];
  257. $this->assignconfig('procuremenAuth', $authMap);
  258. }
  259. /**
  260. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  261. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  262. *
  263. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  264. */
  265. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  266. {
  267. static $mprocCfgLoaded = false;
  268. if (!$mprocCfgLoaded) {
  269. $mprocCfgLoaded = true;
  270. if (is_file(APP_PATH . 'extra/mproc.php')) {
  271. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  272. }
  273. }
  274. $eid = (int)$purchaseOrderDetailId;
  275. $base = $this->resolveMprocMobilePublicBaseUrl();
  276. if ($base === '') {
  277. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  278. }
  279. $path = trim((string)Config::get('mproc.mobile_index_path'));
  280. if ($path === '') {
  281. $path = '/index.php/index/index/index';
  282. } else {
  283. $path = '/' . ltrim($path, '/');
  284. }
  285. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  286. if ($eid > 0) {
  287. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  288. }
  289. return $base . $path . '?main_tab=orders';
  290. }
  291. /**
  292. * 邮件/短信外链:须为带点的公网域名
  293. */
  294. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  295. {
  296. $u = trim((string)$baseUrl);
  297. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  298. return false;
  299. }
  300. $host = parse_url($u, PHP_URL_HOST);
  301. if (!is_string($host) || $host === '') {
  302. return false;
  303. }
  304. if (strcasecmp($host, 'localhost') === 0) {
  305. return false;
  306. }
  307. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  308. return false;
  309. }
  310. if (strpos($host, '.') === false) {
  311. return false;
  312. }
  313. return true;
  314. }
  315. /**
  316. * 解析用于协助邮件/短信的手机端站点根
  317. */
  318. protected function resolveMprocMobilePublicBaseUrl()
  319. {
  320. $candidates = [];
  321. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  322. $candidates[] = trim((string)Config::get('site.indexurl'));
  323. $cdn = trim((string)Config::get('site.cdnurl'));
  324. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  325. $candidates[] = rtrim($cdn, '/');
  326. }
  327. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  328. $candidates[] = $reqBase;
  329. foreach ($candidates as $c) {
  330. if ($c === '') {
  331. continue;
  332. }
  333. $c = rtrim($c, '/');
  334. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  335. return $c;
  336. }
  337. }
  338. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  339. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  340. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  341. return $reqBase;
  342. }
  343. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  344. return '';
  345. }
  346. /**
  347. * 获取 Redis 中 procuremen_redis
  348. */
  349. protected function ProcuremenRedis(): array
  350. {
  351. if ($this->procuremenRedisCache !== null) {
  352. return $this->procuremenRedisCache;
  353. }
  354. try {
  355. $redis = redis();
  356. $raw = $redis->get('procuremen_redis');
  357. if ($raw === false || $raw === '') {
  358. $this->procuremenRedisCache = [];
  359. return $this->procuremenRedisCache;
  360. }
  361. $decoded = json_decode($raw, true);
  362. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  363. $this->procuremenRedisCache = [];
  364. return $this->procuremenRedisCache;
  365. }
  366. $this->procuremenRedisCache = $decoded['data'];
  367. // 整包已解码时顺带补齐侧栏小键,避免下次首屏再扫库
  368. if ($this->loadProcuremenSidebarYmList() === []) {
  369. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($this->procuremenRedisCache));
  370. }
  371. return $this->procuremenRedisCache;
  372. } catch (\Throwable $e) {
  373. $this->procuremenRedisCache = [];
  374. return $this->procuremenRedisCache;
  375. }
  376. }
  377. /**
  378. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  379. *
  380. * @return array<int, array<string, mixed>>
  381. */
  382. protected function procuremenFetchErpPoolFromDb(): array
  383. {
  384. try {
  385. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  386. $endTime = date('Y-m-d 23:59:59');
  387. $list = Db::table('scydgy')
  388. ->alias('a')
  389. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  390. ->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, b.czlyq, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  391. ->where([
  392. 'a.bwjg' => 1,
  393. 'a.iEndBz' => 0,
  394. 'a.iType' => 0,
  395. 'a.iStatus' => 10,
  396. ])
  397. ->where('a.dStamp', '>=', $startTime)
  398. ->where('a.dStamp', '<=', $endTime)
  399. ->order('a.dStamp', 'desc')
  400. ->select();
  401. if (!is_array($list)) {
  402. return [];
  403. }
  404. try {
  405. $redis = redis();
  406. $payload = [
  407. 'code' => 200,
  408. 'msg' => 'success',
  409. 'data' => $list,
  410. ];
  411. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  412. $this->procuremenRedisCache = $list;
  413. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($list));
  414. $this->clearPickMonthPoolCaches();
  415. $this->warmPickMonthPoolCachesFromPool($list);
  416. } catch (\Throwable $e) {
  417. }
  418. return $list;
  419. } catch (\Throwable $e) {
  420. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  421. return [];
  422. }
  423. }
  424. /**
  425. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  426. *
  427. * @return array<int, array<string, mixed>>
  428. */
  429. protected function procuremenEnsureRedisPool(): array
  430. {
  431. $pool = $this->ProcuremenRedis();
  432. if (is_array($pool) && $pool !== []) {
  433. return $pool;
  434. }
  435. static $warmed = false;
  436. if ($warmed) {
  437. return is_array($pool) ? $pool : [];
  438. }
  439. $warmed = true;
  440. return $this->procuremenFetchErpPoolFromDb();
  441. }
  442. /**
  443. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  444. *
  445. * @param array<string, mixed> $row
  446. */
  447. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  448. {
  449. $t = $this->procuremenRowListSortTime($row, $primary);
  450. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  451. return null;
  452. }
  453. $mo = (int)$m[2];
  454. if ($mo < 1 || $mo > 12) {
  455. return null;
  456. }
  457. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  458. }
  459. /**
  460. * @param array<int, array{year:string, months:array}> $sidebar
  461. * @return array<int, array{year:string, months:array}>
  462. */
  463. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  464. {
  465. $ym = trim($ym);
  466. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  467. return $sidebar;
  468. }
  469. foreach ($sidebar as $block) {
  470. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  471. continue;
  472. }
  473. foreach ($block['months'] as $item) {
  474. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  475. return $sidebar;
  476. }
  477. }
  478. }
  479. $y = substr($ym, 0, 4);
  480. $mo = (int)substr($ym, 5, 2);
  481. $sidebar[] = [
  482. 'year' => $y,
  483. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  484. ];
  485. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  486. }
  487. /**
  488. * @param array<int, array{year:string, months:array}> $sidebar
  489. * @return string[]
  490. */
  491. protected function flattenProcuremenSidebarYms(array $sidebar): array
  492. {
  493. $yms = [];
  494. foreach ($sidebar as $block) {
  495. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  496. continue;
  497. }
  498. foreach ($block['months'] as $item) {
  499. if (!is_array($item)) {
  500. continue;
  501. }
  502. $ym = trim((string)($item['ym'] ?? ''));
  503. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  504. $yms[$ym] = true;
  505. }
  506. }
  507. }
  508. return array_keys($yms);
  509. }
  510. /**
  511. * 左侧菜单(协助初选)
  512. * 优先 Redis 月份小键;为空时用轻量 DISTINCT 查库补齐(避免只显示空当月、漏掉有数据的月份)。
  513. */
  514. protected function GetIndexYearMonths()
  515. {
  516. $ymList = $this->ensureProcuremenPickSidebarYmList();
  517. if ($ymList === []) {
  518. $def = date('Y-m');
  519. $ymList = [preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m')];
  520. }
  521. return $this->buildYearMonthSidebar($ymList);
  522. }
  523. /**
  524. * 初选侧栏月份:以轻量 DISTINCT 查库为准(有数据才显示),并写回 Redis 小键。
  525. *
  526. * @return string[]
  527. */
  528. protected function ensureProcuremenPickSidebarYmList(bool $forceRefresh = false): array
  529. {
  530. static $memo = null;
  531. if (!$forceRefresh && is_array($memo)) {
  532. return $memo;
  533. }
  534. $fromDb = $this->queryProcuremenPickSidebarYmListLight();
  535. if ($fromDb !== []) {
  536. $this->saveProcuremenSidebarYmList($fromDb);
  537. $memo = $fromDb;
  538. return $memo;
  539. }
  540. // 库侧暂无初选数据时,再回退 Redis / 当月,避免侧栏空白
  541. $cached = $this->loadProcuremenSidebarYmList();
  542. if ($cached !== []) {
  543. $memo = $cached;
  544. return $memo;
  545. }
  546. $memo = [date('Y-m')];
  547. return $memo;
  548. }
  549. /**
  550. * @return string[] 形如 2026-07
  551. */
  552. protected function loadProcuremenSidebarYmList(): array
  553. {
  554. try {
  555. $raw = redis()->get('procuremen_redis_yms');
  556. if ($raw === false || $raw === null || $raw === '') {
  557. return [];
  558. }
  559. $decoded = json_decode((string)$raw, true);
  560. if (!is_array($decoded)) {
  561. return [];
  562. }
  563. $out = [];
  564. foreach ($decoded as $ym) {
  565. $ym = trim((string)$ym);
  566. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  567. $out[$ym] = true;
  568. }
  569. }
  570. return array_keys($out);
  571. } catch (\Throwable $e) {
  572. return [];
  573. }
  574. }
  575. /**
  576. * @param string[] $ymList
  577. */
  578. protected function saveProcuremenSidebarYmList(array $ymList): void
  579. {
  580. $out = [];
  581. foreach ($ymList as $ym) {
  582. $ym = trim((string)$ym);
  583. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  584. $out[$ym] = true;
  585. }
  586. }
  587. if ($out === []) {
  588. return;
  589. }
  590. try {
  591. redis()->set('procuremen_redis_yms', json_encode(array_keys($out), JSON_UNESCAPED_UNICODE));
  592. } catch (\Throwable $e) {
  593. }
  594. }
  595. /**
  596. * @param array<int, array<string, mixed>> $pool
  597. * @return string[]
  598. */
  599. protected function extractYearMonthsFromPoolRows(array $pool): array
  600. {
  601. $ymSet = [];
  602. foreach ($pool as $r) {
  603. if (!is_array($r)) {
  604. continue;
  605. }
  606. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  607. continue;
  608. }
  609. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  610. if ($ym !== null) {
  611. $ymSet[$ym] = true;
  612. }
  613. }
  614. return array_keys($ymSet);
  615. }
  616. /**
  617. * 轻量查询初选侧栏月份(只取 DISTINCT 年月,不拉整包工序)
  618. *
  619. * @return string[]
  620. */
  621. protected function queryProcuremenPickSidebarYmListLight(): array
  622. {
  623. try {
  624. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  625. $endTime = date('Y-m-d 23:59:59');
  626. $sql = 'SELECT DISTINCT DATE_FORMAT('
  627. . 'IF(b.dputrecord IS NOT NULL AND TRIM(CAST(b.dputrecord AS CHAR(32))) <> \'\''
  628. . ' AND TRIM(CAST(b.dputrecord AS CHAR(32))) NOT LIKE \'0000-00-00%\','
  629. . ' b.dputrecord, a.dStamp), \'%Y-%m\') AS ym'
  630. . ' FROM scydgy a'
  631. . ' INNER JOIN mcyd b ON b.ICYDID = a.ICYDID AND b.iStatus >= 10'
  632. . ' WHERE a.bwjg = 1 AND a.iEndBz = 0 AND a.iType = 0 AND a.iStatus = 10'
  633. . ' AND a.dStamp >= ? AND a.dStamp <= ?';
  634. $rows = Db::query($sql, [$startTime, $endTime]);
  635. if (!is_array($rows)) {
  636. return [];
  637. }
  638. $out = [];
  639. foreach ($rows as $r) {
  640. $ym = trim((string)($r['ym'] ?? ''));
  641. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  642. $out[$ym] = true;
  643. }
  644. }
  645. return array_keys($out);
  646. } catch (\Throwable $e) {
  647. Log::write('初选侧栏月份轻量查询失败:' . $e->getMessage(), 'warning');
  648. return [];
  649. }
  650. }
  651. /**
  652. * @return string[] 含当月在内的近 N 个自然月
  653. */
  654. protected function buildRecentCalendarYmList(int $months = 12): array
  655. {
  656. $months = max(1, min(24, $months));
  657. $out = [];
  658. $base = strtotime(date('Y-m-01'));
  659. for ($i = 0; $i < $months; $i++) {
  660. $out[] = date('Y-m', strtotime('-' . $i . ' month', $base));
  661. }
  662. return $out;
  663. }
  664. /**
  665. * 初选按月工序池:优先月缓存;未命中则直接按月查 ERP。
  666. * 禁止为列表去解近一年整包 Redis(解包/连接异常会造成长时间转圈)。
  667. *
  668. * @return array<int, array<string, mixed>>
  669. */
  670. protected function loadPickPoolForYm(string $ym): array
  671. {
  672. $ym = trim($ym);
  673. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  674. return [];
  675. }
  676. $hit = $this->readPickMonthPoolCache($ym);
  677. if ($hit !== null) {
  678. return $hit;
  679. }
  680. return $this->queryPickPoolForYmFromDb($ym);
  681. }
  682. /**
  683. * @return array<int, array<string, mixed>>|null null=无有效缓存(含旧版空数组误缓存)
  684. */
  685. protected function readPickMonthPoolCache(string $ym): ?array
  686. {
  687. try {
  688. $raw = redis()->get('procuremen_pick_pool:' . $ym);
  689. if ($raw === false || $raw === null || $raw === '') {
  690. return null;
  691. }
  692. $decoded = json_decode((string)$raw, true);
  693. if (!is_array($decoded)) {
  694. return null;
  695. }
  696. // 新格式:{ok:1, rows:[...]},空月也算有效(已从整包确认)
  697. if (isset($decoded['ok']) && (int)$decoded['ok'] === 1 && isset($decoded['rows']) && is_array($decoded['rows'])) {
  698. return $decoded['rows'];
  699. }
  700. // 旧格式:仅非空行列表可命中;[] 多半是错误 SQL 写入,视为未命中
  701. if ($decoded === []) {
  702. try {
  703. redis()->del('procuremen_pick_pool:' . $ym);
  704. } catch (\Throwable $e) {
  705. }
  706. return null;
  707. }
  708. if (isset($decoded[0]) && is_array($decoded[0])) {
  709. return $decoded;
  710. }
  711. return null;
  712. } catch (\Throwable $e) {
  713. return null;
  714. }
  715. }
  716. /**
  717. * @param array<int, array<string, mixed>> $rows
  718. */
  719. protected function writePickMonthPoolCache(string $ym, array $rows): void
  720. {
  721. try {
  722. redis()->setex(
  723. 'procuremen_pick_pool:' . $ym,
  724. 600,
  725. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  726. );
  727. } catch (\Throwable $e) {
  728. }
  729. }
  730. /**
  731. * @param array<int, array<string, mixed>> $pool
  732. * @return array<int, array<string, mixed>>
  733. */
  734. protected function filterPoolRowsByYm(array $pool, string $ym): array
  735. {
  736. $out = [];
  737. foreach ($pool as $r) {
  738. if (!is_array($r)) {
  739. continue;
  740. }
  741. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  742. continue;
  743. }
  744. if ($this->procuremenRowYearMonth($r, 'dputrecord') === $ym) {
  745. $out[] = $r;
  746. }
  747. }
  748. return $out;
  749. }
  750. /**
  751. * 按 dStamp 取当月附近数据,再用列表规则(dputrecord 优先)精确到 ym
  752. *
  753. * @return array<int, array<string, mixed>>
  754. */
  755. protected function queryPickPoolForYmFromDb(string $ym): array
  756. {
  757. $monthStart = $ym . '-01 00:00:00';
  758. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  759. // 略放大窗口,避免 dStamp 与 dputrecord 跨月导致漏数;最终仍按 ym 精确过滤
  760. $queryStart = date('Y-m-d 00:00:00', strtotime($monthStart . ' -7 days'));
  761. $queryEnd = date('Y-m-d 23:59:59', strtotime($monthEnd . ' +7 days'));
  762. try {
  763. $list = Db::table('scydgy')
  764. ->alias('a')
  765. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  766. ->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, b.czlyq, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  767. ->where([
  768. 'a.bwjg' => 1,
  769. 'a.iEndBz' => 0,
  770. 'a.iType' => 0,
  771. 'a.iStatus' => 10,
  772. ])
  773. ->where('a.dStamp', '>=', $queryStart)
  774. ->where('a.dStamp', '<=', $queryEnd)
  775. ->order('a.dStamp', 'desc')
  776. ->select();
  777. } catch (\Throwable $e) {
  778. Log::write('初选按月取数失败 ym=' . $ym . ':' . $e->getMessage(), 'error');
  779. return [];
  780. }
  781. if (!is_array($list)) {
  782. $list = [];
  783. }
  784. $out = $this->filterPoolRowsByYm($list, $ym);
  785. // 新格式缓存(含空月),避免重复打库;读侧只认 ok=1
  786. $this->writePickMonthPoolCache($ym, $out);
  787. try {
  788. $yms = $this->loadProcuremenSidebarYmList();
  789. if ($out !== [] && ($yms === [] || !in_array($ym, $yms, true))) {
  790. $yms[] = $ym;
  791. $this->saveProcuremenSidebarYmList($yms);
  792. }
  793. } catch (\Throwable $e) {
  794. }
  795. return $out;
  796. }
  797. /**
  798. * 整包写入后拆成按月小缓存,供初选列表秒开
  799. *
  800. * @param array<int, array<string, mixed>> $pool
  801. */
  802. protected function warmPickMonthPoolCachesFromPool(array $pool): void
  803. {
  804. if ($pool === []) {
  805. return;
  806. }
  807. $byYm = [];
  808. foreach ($pool as $r) {
  809. if (!is_array($r)) {
  810. continue;
  811. }
  812. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  813. continue;
  814. }
  815. $rowYm = $this->procuremenRowYearMonth($r, 'dputrecord');
  816. if ($rowYm === null) {
  817. continue;
  818. }
  819. $byYm[$rowYm][] = $r;
  820. }
  821. if ($byYm === []) {
  822. return;
  823. }
  824. try {
  825. $redis = redis();
  826. foreach ($byYm as $rowYm => $rows) {
  827. $redis->setex(
  828. 'procuremen_pick_pool:' . $rowYm,
  829. 600,
  830. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  831. );
  832. }
  833. try {
  834. $redis->del('procuremen_pick_hidden_scydgy_v1');
  835. } catch (\Throwable $e) {
  836. }
  837. } catch (\Throwable $e) {
  838. }
  839. }
  840. /**
  841. * 刷新整包后清理近月缓存,避免脏读
  842. */
  843. protected function clearPickMonthPoolCaches(int $months = 24): void
  844. {
  845. try {
  846. $redis = redis();
  847. foreach ($this->buildRecentCalendarYmList($months) as $ym) {
  848. try {
  849. $redis->del('procuremen_pick_pool:' . $ym);
  850. } catch (\Throwable $e) {
  851. }
  852. }
  853. } catch (\Throwable $e) {
  854. }
  855. $this->invalidatePickHiddenScydgyCache();
  856. }
  857. /**
  858. * 下发/完结后清隐藏集缓存,避免初选列表最多 90 秒仍显示已下发行
  859. */
  860. protected function invalidatePickHiddenScydgyCache(): void
  861. {
  862. $this->pickHiddenScydgySetCache = null;
  863. try {
  864. redis()->del('procuremen_pick_hidden_scydgy_v1');
  865. } catch (\Throwable $e) {
  866. }
  867. }
  868. /** 列表/首屏读完鉴权后尽早释放 session,避免多 iframe 串行卡死 */
  869. protected function procuremenReleaseSessionLock(): void
  870. {
  871. if (session_status() === PHP_SESSION_ACTIVE) {
  872. @session_write_close();
  873. }
  874. }
  875. /**
  876. * @param string[] $ymList 形如 2026-06
  877. * @return array<int, array{year:string, months:array}>
  878. */
  879. protected function buildYearMonthSidebar(array $ymList): array
  880. {
  881. rsort($ymList, SORT_STRING);
  882. $byYear = [];
  883. foreach ($ymList as $ym) {
  884. $y = substr($ym, 0, 4);
  885. $mo = (int)substr($ym, 5, 2);
  886. if (!isset($byYear[$y])) {
  887. $byYear[$y] = [];
  888. }
  889. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  890. }
  891. krsort($byYear, SORT_NUMERIC);
  892. foreach ($byYear as $y => $items) {
  893. usort($byYear[$y], function ($a, $b) {
  894. return strcmp($b['ym'], $a['ym']);
  895. });
  896. }
  897. $sidebar = [];
  898. foreach ($byYear as $y => $months) {
  899. $sidebar[] = ['year' => $y, 'months' => $months];
  900. }
  901. return $sidebar;
  902. }
  903. /**
  904. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  905. */
  906. protected function GetIssuedOrderYearMonths(string $stage): array
  907. {
  908. $ymSet = [];
  909. try {
  910. $query = Db::table('purchase_order');
  911. $this->applyPurchaseOrderNotDeletedWhere($query);
  912. if ($stage === 'audit') {
  913. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  914. } elseif ($stage === 'confirm') {
  915. $this->applyPurchaseOrderConfirmStageWhere($query);
  916. } else {
  917. return $this->GetIndexYearMonths();
  918. }
  919. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  920. if (is_array($rows)) {
  921. foreach ($rows as $r) {
  922. if (!is_array($r)) {
  923. continue;
  924. }
  925. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  926. if ($ym !== null) {
  927. $ymSet[$ym] = true;
  928. }
  929. }
  930. }
  931. } catch (\Throwable $e) {
  932. $ymSet = [];
  933. }
  934. $ymList = array_keys($ymSet);
  935. if ($ymList === []) {
  936. $def = $this->resolveProcuremenDefaultYm($stage);
  937. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  938. }
  939. return $this->buildYearMonthSidebar($ymList);
  940. }
  941. /**
  942. * 列表默认月份:已下发类取最近有数据的月份;初选也取最近有数据月份(避免跨月后落到空当月)
  943. */
  944. protected function resolveProcuremenDefaultYm(string $stage): string
  945. {
  946. if ($stage === 'pick') {
  947. $yms = $this->ensureProcuremenPickSidebarYmList();
  948. if ($yms !== []) {
  949. rsort($yms, SORT_STRING);
  950. return $yms[0];
  951. }
  952. return date('Y-m');
  953. }
  954. try {
  955. $query = Db::table('purchase_order');
  956. $this->applyPurchaseOrderNotDeletedWhere($query);
  957. if ($stage === 'audit') {
  958. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  959. } elseif ($stage === 'confirm') {
  960. $this->applyPurchaseOrderConfirmStageWhere($query);
  961. } else {
  962. return date('Y-m');
  963. }
  964. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  965. if ($latest === null || $latest === '') {
  966. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  967. }
  968. $t = $this->formatProcuremenDetailTime($latest);
  969. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  970. return $m[1] . '-' . $m[2];
  971. }
  972. } catch (\Throwable $e) {
  973. }
  974. return date('Y-m');
  975. }
  976. protected function applyPurchaseOrderNotDeletedWhere($query): void
  977. {
  978. $query->whereRaw(
  979. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  980. );
  981. }
  982. /**
  983. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  984. */
  985. protected function applyPurchaseOrderConfirmStageWhere($query): void
  986. {
  987. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  988. $quoted = [];
  989. foreach ($vals as $v) {
  990. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  991. }
  992. if ($quoted === []) {
  993. $query->whereRaw('1 = 0');
  994. return;
  995. }
  996. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  997. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  998. }
  999. /**
  1000. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  1001. *
  1002. * @param array<string, mixed> $row
  1003. * @return array<string, mixed>
  1004. */
  1005. protected function normalizePurchaseOrderListTimeRow(array $row): array
  1006. {
  1007. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  1008. $pick = trim((string)($row['pick_time'] ?? ''));
  1009. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  1010. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  1011. $t = trim((string)($row[$key] ?? ''));
  1012. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1013. $row['pick_time'] = $t;
  1014. break;
  1015. }
  1016. }
  1017. }
  1018. return $row;
  1019. }
  1020. /**
  1021. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  1022. */
  1023. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  1024. {
  1025. if (!in_array($stage, ['audit', 'confirm'], true)) {
  1026. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1027. }
  1028. if ($pool === []) {
  1029. $def = $this->resolveProcuremenDefaultYm($stage);
  1030. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  1031. }
  1032. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  1033. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1034. return false;
  1035. }
  1036. $monthStart = $ym . '-01 00:00:00';
  1037. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1038. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  1039. return $probe !== [];
  1040. };
  1041. if ($tryYm($requestedYm)) {
  1042. return $requestedYm;
  1043. }
  1044. $fallback = $this->resolveProcuremenDefaultYm($stage);
  1045. if ($tryYm($fallback)) {
  1046. return $fallback;
  1047. }
  1048. $bestYm = '';
  1049. $bestTime = '';
  1050. foreach ($pool as $row) {
  1051. if (!is_array($row)) {
  1052. continue;
  1053. }
  1054. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  1055. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  1056. continue;
  1057. }
  1058. $ymRow = $m[1];
  1059. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  1060. $bestTime = $t;
  1061. $bestYm = $ymRow;
  1062. }
  1063. }
  1064. if ($bestYm !== '') {
  1065. return $bestYm;
  1066. }
  1067. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1068. }
  1069. protected function isPurchaseOrderDetailVoid(array $row): bool
  1070. {
  1071. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  1072. return true;
  1073. }
  1074. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  1075. }
  1076. /**
  1077. * 仅当前有效下发明细(排除废弃归档)
  1078. */
  1079. protected function applyActivePurchaseOrderDetailWhere($query): void
  1080. {
  1081. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1082. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  1083. }
  1084. /**
  1085. * @param array<string, mixed> $detailRow
  1086. */
  1087. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  1088. {
  1089. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  1090. return false;
  1091. }
  1092. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  1093. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  1094. }
  1095. /**
  1096. * 废弃退回初选:下发明细标记归档,不物理删除
  1097. *
  1098. * @param array<int, int|string> $scydgyIds
  1099. */
  1100. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  1101. {
  1102. $ids = [];
  1103. foreach ($scydgyIds as $sid) {
  1104. $n = (int)$sid;
  1105. if ($this->isValidScydgyRowId($n) || $n < 0) {
  1106. $ids[$n] = true;
  1107. }
  1108. }
  1109. if ($ids === []) {
  1110. return;
  1111. }
  1112. $void = ProcuremenStatus::POD_VOID;
  1113. Db::table('purchase_order_detail')
  1114. ->where('scydgy_id', 'in', array_keys($ids))
  1115. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1116. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  1117. ->update([
  1118. 'status' => $void,
  1119. 'status_name' => $void,
  1120. ]);
  1121. }
  1122. /**
  1123. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  1124. */
  1125. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  1126. {
  1127. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  1128. $norm = function (string $col) use ($p): string {
  1129. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  1130. };
  1131. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  1132. $parts = [];
  1133. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  1134. if ($key === 'createtime') {
  1135. $parts[] = $createtime;
  1136. } else {
  1137. $parts[] = $norm($key);
  1138. }
  1139. }
  1140. return 'COALESCE(' . implode(', ', $parts) . ')';
  1141. }
  1142. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  1143. {
  1144. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  1145. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  1146. }
  1147. /**
  1148. * @return array<int, array<string, mixed>>
  1149. */
  1150. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  1151. {
  1152. $this->ensurePurchaseOrderCzlyqColumn();
  1153. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1154. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  1155. try {
  1156. $query = Db::table('purchase_order')->field($fields);
  1157. $this->applyPurchaseOrderNotDeletedWhere($query);
  1158. if ($stage === 'audit') {
  1159. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1160. } elseif ($stage === 'confirm') {
  1161. $this->applyPurchaseOrderConfirmStageWhere($query);
  1162. } else {
  1163. return [];
  1164. }
  1165. $query->order('pick_time', 'desc')->order('id', 'desc');
  1166. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  1167. $monthStart = $ym . '-01 00:00:00';
  1168. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1169. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  1170. }
  1171. $rows = $query->select();
  1172. } catch (\Throwable $e) {
  1173. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  1174. $rows = [];
  1175. }
  1176. return is_array($rows) ? $rows : [];
  1177. }
  1178. /**
  1179. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  1180. */
  1181. protected function resolveProcuremenListStage(): string
  1182. {
  1183. $tab = trim((string)$this->request->request('wff_tab', ''));
  1184. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  1185. return $tab;
  1186. }
  1187. $action = strtolower((string)$this->request->action());
  1188. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  1189. return $action;
  1190. }
  1191. return 'pick';
  1192. }
  1193. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  1194. {
  1195. $this->procuremenReleaseSessionLock();
  1196. $rootTrue = rtrim((string)$this->request->root(true), '/');
  1197. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  1198. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  1199. $indexPhpRoot = $rootTrue . '/index.php';
  1200. }
  1201. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  1202. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  1203. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  1204. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  1205. $this->view->assign('defaultYm', $defaultYm);
  1206. $this->view->assign('sidebarYearMonths', $sidebar);
  1207. $this->view->assign('procuremenStage', $stage);
  1208. $this->view->assign('procuremenPageTitle', $pageTitle);
  1209. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  1210. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  1211. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  1212. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  1213. $this->assignconfig('procuremenFilterOptions', $this->buildProcuremenFilterOptions($stage));
  1214. }
  1215. /**
  1216. * 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
  1217. *
  1218. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1219. */
  1220. protected function buildProcuremenFilterOptions(string $stage): array
  1221. {
  1222. $buckets = [
  1223. 'czlyq' => [],
  1224. 'CCLBMMC' => [],
  1225. 'cywyxm' => [],
  1226. 'CGYMC' => [],
  1227. ];
  1228. $maxPerField = 300;
  1229. try {
  1230. if ($stage === 'pick') {
  1231. // 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
  1232. return $buckets;
  1233. }
  1234. if (in_array($stage, ['audit', 'confirm'], true)) {
  1235. $this->ensurePurchaseOrderCzlyqColumn();
  1236. foreach (array_keys($buckets) as $field) {
  1237. try {
  1238. $query = Db::table('purchase_order')->field($field);
  1239. $this->applyPurchaseOrderNotDeletedWhere($query);
  1240. if ($stage === 'audit') {
  1241. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1242. } else {
  1243. $this->applyPurchaseOrderConfirmStageWhere($query);
  1244. }
  1245. $query->where($field, '<>', '')->whereNotNull($field);
  1246. $vals = $query->distinct(true)->limit($maxPerField)->column($field);
  1247. if (!is_array($vals)) {
  1248. continue;
  1249. }
  1250. foreach ($vals as $v) {
  1251. $v = trim((string)$v);
  1252. if ($v !== '') {
  1253. $buckets[$field][$v] = $v;
  1254. }
  1255. }
  1256. } catch (\Throwable $e) {
  1257. // 单字段失败不影响其它
  1258. }
  1259. }
  1260. }
  1261. } catch (\Throwable $e) {
  1262. Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
  1263. }
  1264. foreach ($buckets as &$set) {
  1265. if ($set !== []) {
  1266. ksort($set, SORT_STRING);
  1267. }
  1268. }
  1269. unset($set);
  1270. return $buckets;
  1271. }
  1272. /**
  1273. * filter JSON 是否含有效条件
  1274. *
  1275. * @param array<string, mixed> $filterArr
  1276. */
  1277. protected function procuremenFilterArrHasValue(array $filterArr): bool
  1278. {
  1279. foreach ($filterArr as $v) {
  1280. if (is_array($v)) {
  1281. if (array_filter($v, function ($x) {
  1282. return $x !== '' && $x !== null;
  1283. })) {
  1284. return true;
  1285. }
  1286. } elseif ($v !== '' && $v !== null) {
  1287. return true;
  1288. }
  1289. }
  1290. return false;
  1291. }
  1292. /**
  1293. * 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
  1294. *
  1295. * @param array<string, mixed> $filterArr
  1296. * @param array<string, mixed> $opArr
  1297. */
  1298. protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
  1299. {
  1300. if ($search !== '') {
  1301. return false;
  1302. }
  1303. foreach ($filterArr as $fk => $fv) {
  1304. if (is_array($fv)) {
  1305. continue;
  1306. }
  1307. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  1308. continue;
  1309. }
  1310. if ($fv === null) {
  1311. continue;
  1312. }
  1313. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  1314. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  1315. if ($sym === '' || $sym === '=') {
  1316. continue;
  1317. }
  1318. return false;
  1319. }
  1320. return true;
  1321. }
  1322. /**
  1323. * 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
  1324. *
  1325. * @param array<int, mixed> $rows
  1326. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1327. */
  1328. protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
  1329. {
  1330. $buckets = [
  1331. 'czlyq' => [],
  1332. 'CCLBMMC' => [],
  1333. 'cywyxm' => [],
  1334. 'CGYMC' => [],
  1335. ];
  1336. foreach ($rows as $r) {
  1337. if (!is_array($r)) {
  1338. continue;
  1339. }
  1340. foreach ($buckets as $field => &$set) {
  1341. if (count($set) >= $maxPerField) {
  1342. continue;
  1343. }
  1344. $v = trim((string)($r[$field] ?? ''));
  1345. if ($v !== '') {
  1346. $set[$v] = $v;
  1347. }
  1348. }
  1349. unset($set);
  1350. $full = true;
  1351. foreach ($buckets as $set) {
  1352. if (count($set) < $maxPerField) {
  1353. $full = false;
  1354. break;
  1355. }
  1356. }
  1357. if ($full) {
  1358. break;
  1359. }
  1360. }
  1361. foreach ($buckets as &$set) {
  1362. if ($set !== []) {
  1363. // 保证 json 编码为对象(避免 list 下标 0,1,2… 被前端当选项)
  1364. $normalized = [];
  1365. foreach ($set as $k => $v) {
  1366. $s = trim((string)(is_scalar($v) ? $v : $k));
  1367. if ($s === '') {
  1368. continue;
  1369. }
  1370. $normalized[$s] = $s;
  1371. }
  1372. ksort($normalized, SORT_STRING);
  1373. $set = $normalized;
  1374. }
  1375. }
  1376. unset($set);
  1377. return $buckets;
  1378. }
  1379. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  1380. public function pick()
  1381. {
  1382. $this->request->filter(['strip_tags', 'trim']);
  1383. if (!$this->request->isAjax()) {
  1384. $this->assignProcuremenListPage('pick', '协助下发');
  1385. return $this->view->fetch('procuremen/index');
  1386. }
  1387. return $this->index();
  1388. }
  1389. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  1390. public function audit()
  1391. {
  1392. $this->request->filter(['strip_tags', 'trim']);
  1393. if (!$this->request->isAjax()) {
  1394. $this->assignProcuremenListPage('audit', '确认供应商');
  1395. return $this->view->fetch('procuremen/index');
  1396. }
  1397. return $this->index();
  1398. }
  1399. /** 采购确认(定标) */
  1400. public function confirm()
  1401. {
  1402. $this->request->filter(['strip_tags', 'trim']);
  1403. if (!$this->request->isAjax()) {
  1404. $this->assignProcuremenListPage('confirm', '采购确认');
  1405. return $this->view->fetch('procuremen/index');
  1406. }
  1407. return $this->index();
  1408. }
  1409. /**
  1410. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  1411. */
  1412. public function index()
  1413. {
  1414. $this->request->filter(['strip_tags', 'trim']);
  1415. if (!$this->request->isAjax()) {
  1416. $this->assignProcuremenListPage('pick', '协助下发');
  1417. return $this->view->fetch('procuremen/index');
  1418. }
  1419. if ($this->request->request('keyField')) {
  1420. return $this->selectpage();
  1421. }
  1422. $this->procuremenReleaseSessionLock();
  1423. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  1424. $limit = max(10, min(500, (int)$limit));
  1425. $ym = $this->request->request('ym', '');
  1426. $ym = is_string($ym) ? trim($ym) : '';
  1427. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  1428. $wffTab = $this->resolveProcuremenListStage();
  1429. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1430. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  1431. ? $this->resolveProcuremenDefaultYm($wffTab)
  1432. : date('Y-m');
  1433. }
  1434. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1435. $ym = date('Y-m');
  1436. }
  1437. $monthStart = $ym . '-01 00:00:00';
  1438. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1439. $search = trim((string)$this->request->get('search', ''));
  1440. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  1441. $opArr = (array)json_decode($this->request->get('op', ''), true);
  1442. if (!is_array($filterArr)) {
  1443. $filterArr = [];
  1444. }
  1445. if (!is_array($opArr)) {
  1446. $opArr = [];
  1447. }
  1448. // 开标状态为计算字段,不能进池内等值筛选;单独抽出后在合并后再滤
  1449. $bidOpenStatusFilter = '';
  1450. foreach (['bid_open_status_text', 'a.bid_open_status_text'] as $bidFk) {
  1451. if (!array_key_exists($bidFk, $filterArr)) {
  1452. continue;
  1453. }
  1454. $bidOpenStatusFilter = trim((string)$filterArr[$bidFk]);
  1455. unset($filterArr[$bidFk], $opArr[$bidFk]);
  1456. }
  1457. // 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
  1458. $applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
  1459. $hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
  1460. try {
  1461. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  1462. if ($wffTab === 'audit') {
  1463. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  1464. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  1465. );
  1466. } elseif ($wffTab === 'confirm') {
  1467. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  1468. if ($dbRows === []) {
  1469. try {
  1470. $dbRows = Db::table('purchase_order')
  1471. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1472. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  1473. ->whereRaw('(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')')
  1474. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  1475. ->order('pick_time', 'desc')->order('id', 'desc')
  1476. ->select();
  1477. } catch (\Throwable $e) {
  1478. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  1479. $dbRows = [];
  1480. }
  1481. }
  1482. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  1483. if ($pool === []) {
  1484. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1485. }
  1486. } else {
  1487. // 初选:按月直查 ERP(不解整包 Redis,避免长时间转圈)
  1488. if ($applyMonthRange) {
  1489. $pool = $this->loadPickPoolForYm($ym);
  1490. } else {
  1491. $pool = $this->procuremenEnsureRedisPool();
  1492. }
  1493. if (!is_array($pool)) {
  1494. $pool = [];
  1495. }
  1496. // 只针对本页候选 ID 查隐藏集,避免全表扫 purchase_order_detail
  1497. $hideSet = $this->loadPickHiddenScydgySetForIds($this->extractScydgyIdsFromPool($pool));
  1498. if ($pool !== [] && $hideSet !== []) {
  1499. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1500. if (!is_array($r)) {
  1501. return false;
  1502. }
  1503. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1504. return $id <= 0 || !isset($hideSet[$id]);
  1505. }));
  1506. }
  1507. // 手工新增(YW / scydgy_id<0)只走「新增询价/查询询价」,不进初选表格
  1508. if ($pool === []) {
  1509. return json([
  1510. 'total' => 0,
  1511. 'rows' => [],
  1512. 'activeYm' => $ym,
  1513. 'filterOptions' => (
  1514. (int)$offset === 0
  1515. && !$hasActiveSearch
  1516. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1517. )
  1518. ? $this->extractProcuremenFilterOptionsFromRows([])
  1519. : new \stdClass(),
  1520. ]);
  1521. }
  1522. }
  1523. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  1524. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  1525. $monthStart = $ym . '-01 00:00:00';
  1526. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1527. }
  1528. $filtered = $this->filterProcuremenIndexPool(
  1529. $pool,
  1530. $monthStart,
  1531. $monthEnd,
  1532. $applyMonthRange,
  1533. $search,
  1534. $filterArr,
  1535. $opArr,
  1536. $listTimePrimary
  1537. );
  1538. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1539. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1540. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1541. }
  1542. if ($wffTab === 'audit' && $bidOpenStatusFilter !== '') {
  1543. $filtered = $this->filterProcuremenPoolByBidOpenStatus($filtered, $bidOpenStatusFilter);
  1544. }
  1545. $sortField = 'ID';
  1546. if (is_string($sort) && $sort !== '') {
  1547. $parts = explode(',', $sort);
  1548. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1549. if ($sortField === '') {
  1550. $sortField = 'ID';
  1551. }
  1552. }
  1553. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1554. $nFiltered = count($filtered);
  1555. if ($nFiltered > 1) {
  1556. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1557. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1558. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1559. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1560. if ($ta === $tb) {
  1561. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1562. }
  1563. if ($ta === '') {
  1564. return 1;
  1565. }
  1566. if ($tb === '') {
  1567. return -1;
  1568. }
  1569. return strcmp($ta, $tb) * $ord;
  1570. });
  1571. } elseif ($sortField === 'ID') {
  1572. $sortKeys = [];
  1573. foreach ($filtered as $i => $row) {
  1574. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1575. }
  1576. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1577. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1578. } elseif ($sortField === 'CCYDH') {
  1579. usort($filtered, function ($a, $b) use ($ord) {
  1580. $sa = trim((string)($a['CCYDH'] ?? ''));
  1581. $sb = trim((string)($b['CCYDH'] ?? ''));
  1582. if ($sa === $sb) {
  1583. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1584. }
  1585. if ($sa === '') {
  1586. return 1;
  1587. }
  1588. if ($sb === '') {
  1589. return -1;
  1590. }
  1591. return strcmp($sa, $sb) * $ord;
  1592. });
  1593. } else {
  1594. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1595. $va = $a[$sortField] ?? null;
  1596. $vb = $b[$sortField] ?? null;
  1597. $sa = (string)$va;
  1598. $sb = (string)$vb;
  1599. if ($sa === $sb) {
  1600. return 0;
  1601. }
  1602. return strcmp($sa, $sb) * $ord;
  1603. });
  1604. }
  1605. }
  1606. $offset = max(0, (int)$offset);
  1607. $limit = max(1, (int)$limit);
  1608. $rows = array_slice($filtered, $offset, $limit);
  1609. foreach ($rows as &$rw) {
  1610. if (!is_array($rw)) {
  1611. continue;
  1612. }
  1613. $rid = (int)($rw['ID'] ?? 0);
  1614. $rw['_iss_out'] = ($wffTab !== 'pick');
  1615. }
  1616. unset($rw);
  1617. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1618. $idList = [];
  1619. foreach ($rows as $rw) {
  1620. if (!is_array($rw)) {
  1621. continue;
  1622. }
  1623. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1624. foreach ($rw['_order_merge_rows'] as $mr) {
  1625. $mid = (int)($mr['ID'] ?? 0);
  1626. if ($this->isValidScydgyRowId($mid)) {
  1627. $idList[$mid] = true;
  1628. }
  1629. }
  1630. }
  1631. $id = (int)($rw['ID'] ?? 0);
  1632. if ($this->isValidScydgyRowId($id)) {
  1633. $idList[$id] = true;
  1634. }
  1635. }
  1636. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1637. foreach ($rows as &$rw) {
  1638. if (!is_array($rw)) {
  1639. continue;
  1640. }
  1641. $mergeIds = [];
  1642. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1643. foreach ($rw['_order_merge_rows'] as $mr) {
  1644. $mid = (int)($mr['ID'] ?? 0);
  1645. if ($this->isValidScydgyRowId($mid)) {
  1646. $mergeIds[$mid] = true;
  1647. }
  1648. }
  1649. }
  1650. $rid = (int)($rw['ID'] ?? 0);
  1651. if ($this->isValidScydgyRowId($rid)) {
  1652. $mergeIds[$rid] = true;
  1653. }
  1654. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1655. $rw['po_detail_count'] = $s['cnt'];
  1656. $rw['po_amount_fill_cnt'] = $s['amt'];
  1657. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1658. }
  1659. unset($rw);
  1660. }
  1661. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1662. $idList = [];
  1663. foreach ($rows as $rw) {
  1664. if (!is_array($rw)) {
  1665. continue;
  1666. }
  1667. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1668. foreach ($rw['_order_merge_rows'] as $mr) {
  1669. $mid = (int)($mr['ID'] ?? 0);
  1670. if ($this->isValidScydgyRowId($mid)) {
  1671. $idList[$mid] = true;
  1672. }
  1673. }
  1674. }
  1675. $id = (int)($rw['ID'] ?? 0);
  1676. if ($this->isValidScydgyRowId($id)) {
  1677. $idList[$id] = true;
  1678. }
  1679. }
  1680. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1681. $bidOpenSet = [];
  1682. $manualPickSet = [];
  1683. if ($wffTab === 'audit') {
  1684. $ccydhList = [];
  1685. foreach ($rows as $rw0) {
  1686. if (!is_array($rw0)) {
  1687. continue;
  1688. }
  1689. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1690. if ($c0 !== '') {
  1691. $ccydhList[] = $c0;
  1692. }
  1693. }
  1694. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1695. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  1696. }
  1697. foreach ($rows as &$rw) {
  1698. if (!is_array($rw)) {
  1699. continue;
  1700. }
  1701. $mergeIds = [];
  1702. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1703. foreach ($rw['_order_merge_rows'] as $mr) {
  1704. $mid = (int)($mr['ID'] ?? 0);
  1705. if ($this->isValidScydgyRowId($mid)) {
  1706. $mergeIds[$mid] = true;
  1707. }
  1708. }
  1709. }
  1710. $rid = (int)($rw['ID'] ?? 0);
  1711. if ($this->isValidScydgyRowId($rid)) {
  1712. $mergeIds[$rid] = true;
  1713. }
  1714. $buckets = [];
  1715. foreach (array_keys($mergeIds) as $mid) {
  1716. if (isset($quoteBucket[$mid])) {
  1717. $buckets[] = $quoteBucket[$mid];
  1718. }
  1719. }
  1720. $supplierText = $buckets !== []
  1721. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1722. : '';
  1723. if ($wffTab === 'confirm') {
  1724. $picked = trim((string)($rw['pick_company_name'] ?? $rw['picked_supplier_name'] ?? ''));
  1725. if ($picked === '') {
  1726. // 兜底:从合并工序行取
  1727. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1728. foreach ($rw['_order_merge_rows'] as $mr) {
  1729. if (!is_array($mr)) {
  1730. continue;
  1731. }
  1732. $pn = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  1733. if ($pn !== '') {
  1734. $picked = $pn;
  1735. break;
  1736. }
  1737. }
  1738. }
  1739. }
  1740. $rw['picked_supplier_name'] = $picked;
  1741. } else {
  1742. $rw['notify_supplier_text'] = $supplierText;
  1743. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1744. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1745. $manualPicked = ($ccydh !== '' && isset($manualPickSet[$ccydh]));
  1746. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1747. $rw['manual_picked'] = $manualPicked ? 1 : 0;
  1748. if ($verified) {
  1749. $rw['bid_open_status_text'] = '已开标';
  1750. } elseif ($manualPicked) {
  1751. $rw['bid_open_status_text'] = '已指定供应商';
  1752. } else {
  1753. $rw['bid_open_status_text'] = '待开标';
  1754. }
  1755. }
  1756. }
  1757. unset($rw);
  1758. }
  1759. if (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
  1760. $this->enrichProcuremenListMilestoneTimes($rows);
  1761. $this->syncCollapsedOrderQtyPriceForList($rows);
  1762. }
  1763. if ($wffTab === 'all' && count($rows) > 0) {
  1764. $this->mergePurchaseOrder($rows);
  1765. }
  1766. if ($wffTab === 'pick' && count($rows) > 0) {
  1767. $this->mergePurchaseOrder($rows);
  1768. }
  1769. foreach ($rows as &$rwClean) {
  1770. if (is_array($rwClean)) {
  1771. unset($rwClean['_order_merge_rows']);
  1772. if (array_key_exists('NGZL', $rwClean)) {
  1773. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1774. }
  1775. }
  1776. }
  1777. unset($rwClean);
  1778. return json([
  1779. 'total' => count($filtered),
  1780. 'rows' => $rows,
  1781. 'activeYm' => $ym,
  1782. // 初选:把有数据的月份带回,替换「空月份日历」侧栏
  1783. 'sidebarYms' => ($wffTab === 'pick' && (int)$offset === 0)
  1784. ? $this->ensureProcuremenPickSidebarYmList()
  1785. : [],
  1786. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1787. 'filterOptions' => (
  1788. (int)$offset === 0
  1789. && !$hasActiveSearch
  1790. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1791. )
  1792. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1793. : new \stdClass(),
  1794. ]);
  1795. } catch (\Throwable $e) {
  1796. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1797. return json([
  1798. 'total' => 0,
  1799. 'rows' => [],
  1800. ]);
  1801. }
  1802. }
  1803. /**
  1804. * @param array<int, array<string, mixed>> $pool
  1805. * @return int[]
  1806. */
  1807. protected function extractScydgyIdsFromPool(array $pool): array
  1808. {
  1809. $ids = [];
  1810. foreach ($pool as $r) {
  1811. if (!is_array($r)) {
  1812. continue;
  1813. }
  1814. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1815. if ($id > 0) {
  1816. $ids[$id] = $id;
  1817. }
  1818. }
  1819. return array_values($ids);
  1820. }
  1821. /**
  1822. * 仅查询指定工序 ID 是否已下发/进入后续流程(初选列表加速)
  1823. *
  1824. * @param int[] $scydgyIds
  1825. * @return array<int, true>
  1826. */
  1827. protected function loadPickHiddenScydgySetForIds(array $scydgyIds): array
  1828. {
  1829. $hideSet = [];
  1830. $scydgyIds = array_values(array_filter(array_map('intval', $scydgyIds), function ($id) {
  1831. return $id > 0;
  1832. }));
  1833. if ($scydgyIds === []) {
  1834. return $hideSet;
  1835. }
  1836. // 分批,避免 whereIn 过长
  1837. foreach (array_chunk($scydgyIds, 500) as $chunk) {
  1838. try {
  1839. $poIds = Db::table('purchase_order')
  1840. ->where('scydgy_id', 'in', $chunk)
  1841. ->where(function ($q) {
  1842. $q->whereIn('wflow_status', array_merge(
  1843. ProcuremenStatus::wflowPendingConfirmValues(),
  1844. ProcuremenStatus::wflowPendingApprovalValues()
  1845. ))
  1846. ->whereOr(function ($q1) {
  1847. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1848. })
  1849. ->whereOr(function ($q2) {
  1850. $q2->whereNotNull('pick_time')
  1851. ->where('pick_time', '<>', '')
  1852. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1853. })
  1854. ->whereOr(function ($q3) {
  1855. $q3->whereNotNull('mod_rq')
  1856. ->where('mod_rq', '<>', '')
  1857. ->where('mod_rq', 'not like', '0000-00-00%');
  1858. });
  1859. })
  1860. ->column('scydgy_id');
  1861. if (is_array($poIds)) {
  1862. foreach ($poIds as $pid) {
  1863. $k = (int)$pid;
  1864. if ($k !== 0) {
  1865. $hideSet[$k] = true;
  1866. }
  1867. }
  1868. }
  1869. } catch (\Throwable $e) {
  1870. }
  1871. try {
  1872. $detIdsQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $chunk);
  1873. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1874. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1875. if (is_array($detIds)) {
  1876. foreach ($detIds as $pid) {
  1877. $k = (int)$pid;
  1878. if ($this->isValidScydgyRowId($k)) {
  1879. $hideSet[$k] = true;
  1880. }
  1881. }
  1882. }
  1883. } catch (\Throwable $e) {
  1884. }
  1885. }
  1886. return $hideSet;
  1887. }
  1888. /**
  1889. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1890. *
  1891. * @return array<int, true>
  1892. */
  1893. protected function loadPickHiddenScydgySet(): array
  1894. {
  1895. if ($this->pickHiddenScydgySetCache !== null) {
  1896. return $this->pickHiddenScydgySetCache;
  1897. }
  1898. $cacheKey = 'procuremen_pick_hidden_scydgy_v1';
  1899. try {
  1900. $raw = redis()->get($cacheKey);
  1901. if ($raw !== false && $raw !== null && $raw !== '') {
  1902. $ids = json_decode((string)$raw, true);
  1903. if (is_array($ids)) {
  1904. $hideSet = [];
  1905. foreach ($ids as $pid) {
  1906. $k = (int)$pid;
  1907. if ($k !== 0) {
  1908. $hideSet[$k] = true;
  1909. }
  1910. }
  1911. $this->pickHiddenScydgySetCache = $hideSet;
  1912. return $hideSet;
  1913. }
  1914. }
  1915. } catch (\Throwable $e) {
  1916. }
  1917. $hideSet = [];
  1918. try {
  1919. $poIds = Db::table('purchase_order')
  1920. ->where(function ($q) {
  1921. $q->whereIn('wflow_status', array_merge(
  1922. ProcuremenStatus::wflowPendingConfirmValues(),
  1923. ProcuremenStatus::wflowPendingApprovalValues()
  1924. ))
  1925. ->whereOr(function ($q1) {
  1926. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1927. })
  1928. ->whereOr(function ($q2) {
  1929. $q2->whereNotNull('pick_time')
  1930. ->where('pick_time', '<>', '')
  1931. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1932. })
  1933. ->whereOr(function ($q3) {
  1934. $q3->whereNotNull('mod_rq')
  1935. ->where('mod_rq', '<>', '')
  1936. ->where('mod_rq', 'not like', '0000-00-00%');
  1937. });
  1938. })
  1939. ->column('scydgy_id');
  1940. if (is_array($poIds)) {
  1941. foreach ($poIds as $pid) {
  1942. $k = (int)$pid;
  1943. if ($k !== 0) {
  1944. $hideSet[$k] = true;
  1945. }
  1946. }
  1947. }
  1948. } catch (\Throwable $e) {
  1949. }
  1950. try {
  1951. $detIdsQuery = Db::table('purchase_order_detail');
  1952. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1953. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1954. if (is_array($detIds)) {
  1955. foreach ($detIds as $pid) {
  1956. $k = (int)$pid;
  1957. if ($this->isValidScydgyRowId($k)) {
  1958. $hideSet[$k] = true;
  1959. }
  1960. }
  1961. }
  1962. } catch (\Throwable $e) {
  1963. }
  1964. $this->pickHiddenScydgySetCache = $hideSet;
  1965. try {
  1966. redis()->setex($cacheKey, 90, json_encode(array_map('intval', array_keys($hideSet))));
  1967. } catch (\Throwable $e) {
  1968. }
  1969. return $hideSet;
  1970. }
  1971. /**
  1972. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1973. *
  1974. * @return array<int, array<string, mixed>>
  1975. */
  1976. protected function loadPickManualOrderRows(): array
  1977. {
  1978. try {
  1979. $dbRows = Db::table('purchase_order')
  1980. ->where('scydgy_id', '<', 0)
  1981. ->whereRaw('(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')')
  1982. ->order('scydgy_id', 'asc')
  1983. ->select();
  1984. } catch (\Throwable $e) {
  1985. try {
  1986. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1987. } catch (\Throwable $e2) {
  1988. return [];
  1989. }
  1990. }
  1991. if (!is_array($dbRows) || $dbRows === []) {
  1992. return [];
  1993. }
  1994. $detailSidSet = [];
  1995. try {
  1996. $negIds = [];
  1997. foreach ($dbRows as $dbRow) {
  1998. if (!is_array($dbRow)) {
  1999. continue;
  2000. }
  2001. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2002. if ($sid < 0) {
  2003. $negIds[$sid] = true;
  2004. }
  2005. }
  2006. if ($negIds !== []) {
  2007. $detQuery = Db::table('purchase_order_detail')
  2008. ->where('scydgy_id', 'in', array_keys($negIds));
  2009. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  2010. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  2011. if (is_array($detRows)) {
  2012. foreach ($detRows as $did) {
  2013. $detailSidSet[(int)$did] = true;
  2014. }
  2015. }
  2016. }
  2017. } catch (\Throwable $e) {
  2018. }
  2019. $pool = [];
  2020. foreach ($dbRows as $dbRow) {
  2021. if (!is_array($dbRow)) {
  2022. continue;
  2023. }
  2024. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2025. if ($sid >= 0) {
  2026. continue;
  2027. }
  2028. // 已进入确认/审批的不进初选;仅废弃明细残留的仍算可下发
  2029. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  2030. continue;
  2031. }
  2032. // 仅排除已完结;空 status / 「进行中」/ 0 均保留(新建手工单)
  2033. if (ProcuremenStatus::isPoCompleted($dbRow['status'] ?? '')) {
  2034. continue;
  2035. }
  2036. if (isset($detailSidSet[$sid])) {
  2037. continue;
  2038. }
  2039. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  2040. $r['_is_manual'] = 1;
  2041. $pool[] = $r;
  2042. }
  2043. return $pool;
  2044. }
  2045. /**
  2046. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  2047. */
  2048. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  2049. {
  2050. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  2051. foreach ($keys as $k) {
  2052. $t = trim((string)($row[$k] ?? ''));
  2053. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2054. return $t;
  2055. }
  2056. }
  2057. return '';
  2058. }
  2059. /**
  2060. * 分配手工新增工序行 ID(负数递减)
  2061. * 调用方须在命名锁内执行,避免并发重复
  2062. */
  2063. protected function allocateManualScydgyId(): int
  2064. {
  2065. try {
  2066. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  2067. $min = (int)$min;
  2068. return $min < 0 ? $min - 1 : -1;
  2069. } catch (\Throwable $e) {
  2070. return -1;
  2071. }
  2072. }
  2073. /**
  2074. * 手工新增订单号:YW + 年月日 + 当日序号(如 YW20260618001)
  2075. * 调用方须在命名锁内执行,避免并发重复
  2076. */
  2077. protected function allocateManualOrderCcydh(): string
  2078. {
  2079. $prefix = 'YW' . date('Ymd');
  2080. $maxSeq = 0;
  2081. try {
  2082. $rows = Db::table('purchase_order')
  2083. ->where('CCYDH', 'like', $prefix . '%')
  2084. ->column('CCYDH');
  2085. if (is_array($rows)) {
  2086. foreach ($rows as $ccydh) {
  2087. $ccydh = trim((string)$ccydh);
  2088. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3,})$/', $ccydh, $m)) {
  2089. $maxSeq = max($maxSeq, (int)$m[1]);
  2090. }
  2091. }
  2092. }
  2093. } catch (\Throwable $e) {
  2094. }
  2095. $next = $maxSeq + 1;
  2096. $width = $next > 999 ? strlen((string)$next) : 3;
  2097. return $prefix . str_pad((string)$next, $width, '0', STR_PAD_LEFT);
  2098. }
  2099. /**
  2100. * MySQL 命名锁(跨连接防并发撞号)
  2101. */
  2102. protected function acquireProcuremenNamedLock(string $name, int $timeoutSec = 10): bool
  2103. {
  2104. $name = trim($name);
  2105. if ($name === '') {
  2106. return false;
  2107. }
  2108. try {
  2109. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2110. $rows = Db::query('SELECT GET_LOCK(\'' . $nameSql . '\', ' . max(1, $timeoutSec) . ') AS locked');
  2111. if (!is_array($rows) || $rows === []) {
  2112. return false;
  2113. }
  2114. $v = $rows[0]['locked'] ?? $rows[0]['LOCKED'] ?? null;
  2115. return (int)$v === 1;
  2116. } catch (\Throwable $e) {
  2117. return false;
  2118. }
  2119. }
  2120. protected function releaseProcuremenNamedLock(string $name): void
  2121. {
  2122. $name = trim($name);
  2123. if ($name === '') {
  2124. return;
  2125. }
  2126. try {
  2127. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2128. Db::query('SELECT RELEASE_LOCK(\'' . $nameSql . '\')');
  2129. } catch (\Throwable $e) {
  2130. }
  2131. }
  2132. /**
  2133. * purchase_order.mod_rq 是否有有效软删除时间
  2134. */
  2135. protected function isPurchaseOrderSoftDeleted($modRq): bool
  2136. {
  2137. $t = trim((string)$modRq);
  2138. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  2139. }
  2140. /**
  2141. * 列表行 → purchase_order 写入字段
  2142. *
  2143. * @return array<string, mixed>
  2144. */
  2145. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  2146. {
  2147. return [
  2148. 'scydgy_id' => $scydgyId,
  2149. 'CCYDH' => $row['CCYDH'] ?? null,
  2150. 'CYJMC' => $row['CYJMC'] ?? null,
  2151. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2152. 'CDXMC' => $row['CDXMC'] ?? null,
  2153. 'CGYBH' => $row['CGYBH'] ?? null,
  2154. 'CGYMC' => $row['CGYMC'] ?? null,
  2155. 'CDW' => $row['CDW'] ?? null,
  2156. 'czlyq' => $row['czlyq'] ?? null,
  2157. 'NGZL' => $row['NGZL'] ?? null,
  2158. 'CDF' => $row['CDF'] ?? null,
  2159. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2160. 'MBZ' => $row['MBZ'] ?? null,
  2161. 'bwjg' => $row['bwjg'] ?? null,
  2162. 'iStatus' => $row['iStatus'] ?? null,
  2163. 'dStamp' => $row['dStamp'] ?? null,
  2164. 'dputrecord' => $row['dputrecord'] ?? null,
  2165. 'cywyxm' => $row['cywyxm'] ?? null,
  2166. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2167. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2168. ];
  2169. }
  2170. /**
  2171. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  2172. *
  2173. * @return array{po:?array<string,mixed>, hidden:bool}
  2174. */
  2175. protected function resolvePickRowPoContext(int $sid): array
  2176. {
  2177. $po = null;
  2178. try {
  2179. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2180. if (is_array($found)) {
  2181. $po = $found;
  2182. }
  2183. } catch (\Throwable $e) {
  2184. }
  2185. $hideSet = $this->loadPickHiddenScydgySet();
  2186. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  2187. }
  2188. /**
  2189. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  2190. */
  2191. protected function assertPickRowCanDelete(int $sid, array $row): void
  2192. {
  2193. $ctx = $this->resolvePickRowPoContext($sid);
  2194. $po = $ctx['po'];
  2195. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2196. return;
  2197. }
  2198. if (is_array($po)) {
  2199. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2200. throw new \InvalidArgumentException('该工序已完结,无法删除');
  2201. }
  2202. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2203. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  2204. }
  2205. }
  2206. if ($ctx['hidden']) {
  2207. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2208. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  2209. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  2210. }
  2211. }
  2212. /**
  2213. * 初选直接完结前校验
  2214. */
  2215. protected function assertPickRowCanComplete(int $sid, array $row): void
  2216. {
  2217. $ctx = $this->resolvePickRowPoContext($sid);
  2218. $po = $ctx['po'];
  2219. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2220. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  2221. }
  2222. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2223. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  2224. }
  2225. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  2226. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  2227. }
  2228. }
  2229. /**
  2230. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  2231. */
  2232. protected function softDeleteProcuremenPickRow(array $row): void
  2233. {
  2234. $sid = $this->extractScydgyRowId($row);
  2235. if (!$this->isValidScydgyRowId($sid)) {
  2236. throw new \InvalidArgumentException('无效的行主键');
  2237. }
  2238. $this->assertPickRowCanDelete($sid, $row);
  2239. $po = $this->resolvePickRowPoContext($sid)['po'];
  2240. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2241. return;
  2242. }
  2243. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2244. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  2245. }
  2246. $now = date('Y-m-d H:i:s');
  2247. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2248. if (is_array($exists)) {
  2249. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  2250. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  2251. } else {
  2252. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  2253. $data['mod_rq'] = $now;
  2254. $data['createtime'] = $now;
  2255. Db::table('purchase_order')->insert($data);
  2256. $poIdLog = (int)Db::getLastInsID();
  2257. }
  2258. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  2259. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  2260. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  2261. if ($gymcLog !== '') {
  2262. $logTail .= ' / ' . $gymcLog;
  2263. }
  2264. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  2265. }
  2266. /**
  2267. * 手工新增协助工序(写入 purchase_order)
  2268. *
  2269. * @param array<string, mixed> $params
  2270. * @return int scydgy_id
  2271. */
  2272. protected function saveManualPickOrder(array $params): int
  2273. {
  2274. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  2275. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  2276. $ccydhIn = trim((string)($params['CCYDH'] ?? ''));
  2277. $lockName = 'procuremen_manual_order_alloc';
  2278. if (!$this->acquireProcuremenNamedLock($lockName, 10)) {
  2279. throw new \RuntimeException('系统繁忙,请稍后重试');
  2280. }
  2281. try {
  2282. $ccydh = $ccydhIn !== '' ? $ccydhIn : $this->allocateManualOrderCcydh();
  2283. $now = date('Y-m-d H:i:s');
  2284. $sid = $this->allocateManualScydgyId();
  2285. $this->ensurePurchaseOrderNotifySalesmanColumn();
  2286. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  2287. // 选择供应商 / 通知业务员:支持多选,落库用顿号拼接
  2288. $supplierName = $this->joinRfqMultiSelectValues($params['cGzzxMc'] ?? ($params['pick_company_name'] ?? ''));
  2289. $notifySalesman = $this->joinRfqMultiSelectValues($params['notify_salesman'] ?? '');
  2290. $data = [
  2291. 'scydgy_id' => $sid,
  2292. 'CCYDH' => $ccydh,
  2293. 'CYJMC' => $cyjmc,
  2294. 'CGYMC' => $cgymc,
  2295. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  2296. 'CDW' => trim((string)($params['CDW'] ?? '')),
  2297. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  2298. 'CDF' => trim((string)($params['CDF'] ?? '')),
  2299. 'cGzzxMc' => $supplierName,
  2300. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  2301. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  2302. 'notify_salesman' => $notifySalesman,
  2303. 'rfq_salesman_notified' => 0,
  2304. 'rfq_salesman_notify_time' => null,
  2305. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  2306. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  2307. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  2308. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  2309. 'createtime' => $now,
  2310. 'dStamp' => $now,
  2311. 'dputrecord' => $now,
  2312. ];
  2313. Db::table('purchase_order')->insert($data);
  2314. $poId = (int)Db::getLastInsID();
  2315. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  2316. return $sid;
  2317. } finally {
  2318. $this->releaseProcuremenNamedLock($lockName);
  2319. }
  2320. }
  2321. protected function formatProcuremenRowLabel(array $row): string
  2322. {
  2323. $dh = trim((string)($row['CCYDH'] ?? ''));
  2324. $gymc = trim((string)($row['CGYMC'] ?? ''));
  2325. if ($dh !== '' && $gymc !== '') {
  2326. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  2327. }
  2328. if ($dh !== '') {
  2329. return '订单「' . $dh . '」';
  2330. }
  2331. if ($gymc !== '') {
  2332. return '工序「' . $gymc . '」';
  2333. }
  2334. $id = $this->extractScydgyRowId($row);
  2335. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  2336. }
  2337. /**
  2338. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  2339. */
  2340. protected function extractScydgyRowId(array $row): int
  2341. {
  2342. // 优先 scydgy_id,避免明细行 ID(自增主键)被误当成工序主键;手工单为负数
  2343. if (array_key_exists('scydgy_id', $row) && $row['scydgy_id'] !== null && $row['scydgy_id'] !== '') {
  2344. return (int)$row['scydgy_id'];
  2345. }
  2346. if (array_key_exists('SCYDGY_ID', $row) && $row['SCYDGY_ID'] !== null && $row['SCYDGY_ID'] !== '') {
  2347. return (int)$row['SCYDGY_ID'];
  2348. }
  2349. return (int)($row['ID'] ?? $row['id'] ?? 0);
  2350. }
  2351. protected function isValidScydgyRowId(int $id): bool
  2352. {
  2353. return ProcuremenGuard::isValidScydgyId($id);
  2354. }
  2355. protected function isManualScydgyRowId(int $id): bool
  2356. {
  2357. return $id < 0;
  2358. }
  2359. /**
  2360. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  2361. *
  2362. * @param int[] $scydgyIds
  2363. * @return array<int, string[]>
  2364. */
  2365. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  2366. {
  2367. $out = [];
  2368. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2369. if ($scydgyIds === []) {
  2370. return $out;
  2371. }
  2372. try {
  2373. $rows = Db::table('purchase_order_detail')
  2374. ->where('scydgy_id', 'in', $scydgyIds)
  2375. ->field('scydgy_id,company_name')
  2376. ->order('company_name', 'asc')
  2377. ->select();
  2378. } catch (\Throwable $e) {
  2379. $rows = [];
  2380. }
  2381. if (!is_array($rows)) {
  2382. return $out;
  2383. }
  2384. foreach ($rows as $r) {
  2385. if (!is_array($r)) {
  2386. continue;
  2387. }
  2388. $sid = (int)($r['scydgy_id'] ?? 0);
  2389. $cn = trim((string)($r['company_name'] ?? ''));
  2390. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2391. continue;
  2392. }
  2393. if (!isset($out[$sid])) {
  2394. $out[$sid] = [];
  2395. }
  2396. if (!in_array($cn, $out[$sid], true)) {
  2397. $out[$sid][] = $cn;
  2398. }
  2399. }
  2400. return $out;
  2401. }
  2402. /**
  2403. * 列表展示通知供应商(完整列表,前端单行省略展开)
  2404. *
  2405. * @param string[] $names
  2406. */
  2407. protected function formatNotifySupplierDisplay(array $names): string
  2408. {
  2409. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  2410. return trim((string)$n);
  2411. }, $names))));
  2412. if ($names === []) {
  2413. return '';
  2414. }
  2415. sort($names, SORT_STRING);
  2416. return implode("\n", $names);
  2417. }
  2418. /**
  2419. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  2420. *
  2421. * @param int[] $scydgyIds
  2422. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  2423. */
  2424. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  2425. {
  2426. $out = [];
  2427. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2428. if ($scydgyIds === []) {
  2429. return $out;
  2430. }
  2431. try {
  2432. $rows = Db::table('purchase_order_detail')
  2433. ->where('scydgy_id', 'in', $scydgyIds)
  2434. ->field('scydgy_id,company_name,amount')
  2435. ->select();
  2436. } catch (\Throwable $e) {
  2437. $rows = [];
  2438. }
  2439. if (!is_array($rows)) {
  2440. return $out;
  2441. }
  2442. foreach ($rows as $r) {
  2443. if (!is_array($r)) {
  2444. continue;
  2445. }
  2446. $sid = (int)($r['scydgy_id'] ?? 0);
  2447. $cn = trim((string)($r['company_name'] ?? ''));
  2448. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2449. continue;
  2450. }
  2451. if (!isset($out[$sid])) {
  2452. $out[$sid] = ['all' => [], 'quoted' => []];
  2453. }
  2454. $out[$sid]['all'][$cn] = true;
  2455. $am = trim((string)($r['amount'] ?? ''));
  2456. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2457. $out[$sid]['quoted'][$cn] = true;
  2458. }
  2459. }
  2460. return $out;
  2461. }
  2462. /**
  2463. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  2464. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  2465. */
  2466. protected function mergeQuotedSupplierBuckets(array $buckets): array
  2467. {
  2468. $merged = ['all' => [], 'quoted' => []];
  2469. foreach ($buckets as $b) {
  2470. if (!is_array($b)) {
  2471. continue;
  2472. }
  2473. foreach ($b['all'] ?? [] as $cn => $_) {
  2474. $merged['all'][$cn] = true;
  2475. }
  2476. foreach ($b['quoted'] ?? [] as $cn => $_) {
  2477. $merged['quoted'][$cn] = true;
  2478. }
  2479. }
  2480. return $merged;
  2481. }
  2482. /**
  2483. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  2484. */
  2485. protected function formatQuotedSupplierLines(array $bucket): string
  2486. {
  2487. $all = array_keys($bucket['all'] ?? []);
  2488. if ($all === []) {
  2489. return '';
  2490. }
  2491. sort($all, SORT_STRING);
  2492. $lines = [];
  2493. foreach ($all as $cn) {
  2494. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  2495. $lines[] = $cn . '(' . $status . ')';
  2496. }
  2497. return implode("\n", $lines);
  2498. }
  2499. /**
  2500. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  2501. */
  2502. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  2503. {
  2504. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2505. $this->view->engine->layout(false);
  2506. try {
  2507. $bodyHtml = $this->view->fetch($view);
  2508. $this->view->assign('dialogBody', $bodyHtml);
  2509. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  2510. return $this->view->fetch('procuremen/dialog_lite_shell');
  2511. } finally {
  2512. if ($restoreLayout) {
  2513. $this->view->engine->layout($restoreLayout);
  2514. }
  2515. }
  2516. }
  2517. /**
  2518. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  2519. */
  2520. protected function resolveBundleSysRq(array $bundle): string
  2521. {
  2522. foreach ($bundle['pos'] ?? [] as $po) {
  2523. if (!is_array($po)) {
  2524. continue;
  2525. }
  2526. $sr = trim((string)($po['sys_rq'] ?? ''));
  2527. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  2528. return $sr;
  2529. }
  2530. }
  2531. return '';
  2532. }
  2533. /**
  2534. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  2535. */
  2536. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  2537. {
  2538. $raw = trim((string)$sysRq);
  2539. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  2540. return true;
  2541. }
  2542. $ts = strtotime(str_replace('T', ' ', $raw));
  2543. if ($ts === false || $ts <= 0) {
  2544. return true;
  2545. }
  2546. return time() >= $ts;
  2547. }
  2548. /**
  2549. * 开标前校验:必须已过报价截止时间
  2550. *
  2551. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2552. */
  2553. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  2554. {
  2555. $sysRq = $this->resolveBundleSysRq($bundle);
  2556. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  2557. $this->error('未到招标截止日期');
  2558. }
  2559. }
  2560. /**
  2561. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  2562. *
  2563. * @param array<string, mixed> $d
  2564. * @param string $deliveryYmd
  2565. */
  2566. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  2567. {
  2568. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  2569. return max(0, (int)$d['lead_days']);
  2570. }
  2571. if ($deliveryYmd === '') {
  2572. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  2573. }
  2574. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  2575. return null;
  2576. }
  2577. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2578. $t2 = strtotime($m[1] . ' 00:00:00');
  2579. if ($t1 === false || $t2 === false) {
  2580. return null;
  2581. }
  2582. return max(0, (int)round(($t2 - $t1) / 86400));
  2583. }
  2584. /**
  2585. * @param int|null $days
  2586. */
  2587. protected function formatProcuremenLeadDaysText($days): string
  2588. {
  2589. if ($days === null || $days === '') {
  2590. return '未填写';
  2591. }
  2592. if (!is_numeric($days)) {
  2593. return '未填写';
  2594. }
  2595. return ((int)$days) . '天';
  2596. }
  2597. /**
  2598. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2599. *
  2600. * @param array<string, mixed> $line
  2601. */
  2602. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2603. {
  2604. $amountFilled = !empty($line['amount_filled']);
  2605. $deliveryFilled = !empty($line['delivery_filled']);
  2606. $leadFilled = !empty($line['lead_days_filled']);
  2607. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2608. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2609. $line['amount_show'] = '';
  2610. if (array_key_exists('amount_text', $line)) {
  2611. $line['amount_text'] = $line['unit_price_text'];
  2612. }
  2613. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2614. $line['delivery_show'] = $deliveryText;
  2615. if (array_key_exists('delivery_text', $line)) {
  2616. $line['delivery_text'] = $deliveryText;
  2617. }
  2618. $line['delivery_ymd'] = '';
  2619. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2620. $line['lead_days_show'] = $leadText;
  2621. $line['lead_days_text'] = $leadText;
  2622. $line['lead_days'] = '';
  2623. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2624. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2625. $line['subtotal_num'] = null;
  2626. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2627. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2628. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2629. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2630. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2631. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2632. $line['amount_filled'] = false;
  2633. $line['delivery_filled'] = false;
  2634. $line['lead_days_filled'] = false;
  2635. $line['is_quoted'] = false;
  2636. if (array_key_exists('quote_label', $line)) {
  2637. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2638. }
  2639. }
  2640. protected function ensurePurchaseOrderBidOpenTable(): void
  2641. {
  2642. static $ready = false;
  2643. if ($ready) {
  2644. return;
  2645. }
  2646. $cacheKey = 'procuremen_bid_open_table_ok_v1';
  2647. try {
  2648. if (Cache::get($cacheKey)) {
  2649. $ready = true;
  2650. return;
  2651. }
  2652. } catch (\Throwable $e) {
  2653. }
  2654. try {
  2655. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2656. $ready = true;
  2657. try {
  2658. Cache::set($cacheKey, 1, 86400);
  2659. } catch (\Throwable $e) {
  2660. }
  2661. } catch (\Throwable $e) {
  2662. Db::execute(
  2663. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2664. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2665. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2666. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2667. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2668. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2669. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2670. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2671. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2672. `createtime` datetime DEFAULT NULL,
  2673. PRIMARY KEY (`id`),
  2674. UNIQUE KEY `uk_ccydh` (`ccydh`)
  2675. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2676. );
  2677. $ready = true;
  2678. try {
  2679. Cache::set($cacheKey, 1, 86400);
  2680. } catch (\Throwable $e2) {
  2681. }
  2682. }
  2683. }
  2684. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  2685. {
  2686. $ccydh = trim($ccydh);
  2687. if ($ccydh === '') {
  2688. return false;
  2689. }
  2690. $this->ensurePurchaseOrderBidOpenTable();
  2691. try {
  2692. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2693. return is_array($row);
  2694. } catch (\Throwable $e) {
  2695. return false;
  2696. }
  2697. }
  2698. /**
  2699. * 批量查询订单是否已开标验证
  2700. *
  2701. * @param array<int, string> $ccydhs
  2702. * @return array<string, bool> ccydh => true
  2703. */
  2704. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  2705. {
  2706. $set = [];
  2707. $list = [];
  2708. foreach ($ccydhs as $c) {
  2709. $c = trim((string)$c);
  2710. if ($c !== '') {
  2711. $list[$c] = true;
  2712. }
  2713. }
  2714. if ($list === []) {
  2715. return $set;
  2716. }
  2717. $this->ensurePurchaseOrderBidOpenTable();
  2718. try {
  2719. $rows = Db::table('purchase_order_bid_open')
  2720. ->where('ccydh', 'in', array_keys($list))
  2721. ->field('ccydh')
  2722. ->select();
  2723. foreach ($rows as $row) {
  2724. if (!is_array($row)) {
  2725. continue;
  2726. }
  2727. $c = trim((string)($row['ccydh'] ?? ''));
  2728. if ($c !== '') {
  2729. $set[$c] = true;
  2730. }
  2731. }
  2732. } catch (\Throwable $e) {
  2733. return [];
  2734. }
  2735. return $set;
  2736. }
  2737. /**
  2738. * 批量查询订单是否已指定供应商(免开标)
  2739. *
  2740. * @param array<int, string> $ccydhs
  2741. * @return array<string, bool> ccydh => true
  2742. */
  2743. protected function loadProcuremenManualPickedCcydhSet(array $ccydhs): array
  2744. {
  2745. $set = [];
  2746. $list = [];
  2747. foreach ($ccydhs as $c) {
  2748. $c = trim((string)$c);
  2749. if ($c !== '') {
  2750. $list[$c] = true;
  2751. }
  2752. }
  2753. if ($list === []) {
  2754. return $set;
  2755. }
  2756. $this->ensurePurchaseOrderManualPickColumns();
  2757. try {
  2758. $rows = Db::table('purchase_order')
  2759. ->where('CCYDH', 'in', array_keys($list))
  2760. ->where('manual_pick', 1)
  2761. ->field('CCYDH')
  2762. ->select();
  2763. foreach ($rows as $row) {
  2764. if (!is_array($row)) {
  2765. continue;
  2766. }
  2767. $c = trim((string)($row['CCYDH'] ?? ''));
  2768. if ($c !== '') {
  2769. $set[$c] = true;
  2770. }
  2771. }
  2772. } catch (\Throwable $e) {
  2773. return [];
  2774. }
  2775. return $set;
  2776. }
  2777. /**
  2778. * 确认供应商列表:按开标状态筛选(已开标 / 已指定供应商 / 待开标)
  2779. *
  2780. * @param array<int, array<string, mixed>> $pool
  2781. * @return array<int, array<string, mixed>>
  2782. */
  2783. protected function filterProcuremenPoolByBidOpenStatus(array $pool, string $status): array
  2784. {
  2785. $status = trim($status);
  2786. if ($status === '' || !in_array($status, ['待开标', '已开标', '已指定供应商'], true)) {
  2787. return $pool;
  2788. }
  2789. $ccydhList = [];
  2790. foreach ($pool as $rw) {
  2791. if (!is_array($rw)) {
  2792. continue;
  2793. }
  2794. $c = trim((string)($rw['CCYDH'] ?? ''));
  2795. if ($c !== '') {
  2796. $ccydhList[] = $c;
  2797. }
  2798. }
  2799. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  2800. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  2801. $out = [];
  2802. foreach ($pool as $rw) {
  2803. if (!is_array($rw)) {
  2804. continue;
  2805. }
  2806. $c = trim((string)($rw['CCYDH'] ?? ''));
  2807. if ($c !== '' && isset($bidOpenSet[$c])) {
  2808. $t = '已开标';
  2809. } elseif ($c !== '' && isset($manualPickSet[$c])) {
  2810. $t = '已指定供应商';
  2811. } else {
  2812. $t = '待开标';
  2813. }
  2814. if ($t === $status) {
  2815. $out[] = $rw;
  2816. }
  2817. }
  2818. return $out;
  2819. }
  2820. /**
  2821. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  2822. *
  2823. * @param array<string, mixed> $group
  2824. */
  2825. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  2826. {
  2827. if ($quoteVisible) {
  2828. $group['remark_quote_pending'] = 0;
  2829. return;
  2830. }
  2831. $group['remark'] = '';
  2832. $group['remark_quote_pending'] = 0;
  2833. }
  2834. /**
  2835. * @param array{ccydh?:string} $bundle
  2836. */
  2837. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  2838. {
  2839. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  2840. }
  2841. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  2842. {
  2843. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  2844. return true;
  2845. }
  2846. return $this->isProcuremenManualPickedForBundle($bundle);
  2847. }
  2848. /**
  2849. * 确保 purchase_order 自选供应商字段
  2850. */
  2851. protected function ensurePurchaseOrderManualPickColumns(): void
  2852. {
  2853. static $done = false;
  2854. if ($done) {
  2855. return;
  2856. }
  2857. $done = true;
  2858. $adds = [
  2859. 'manual_pick' => "ADD COLUMN `manual_pick` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=自选供应商(免开标)' AFTER `pick_company_name`",
  2860. 'manual_pick_reason' => "ADD COLUMN `manual_pick_reason` varchar(500) NOT NULL DEFAULT '' COMMENT '自选供应商选择说明' AFTER `manual_pick`",
  2861. ];
  2862. foreach ($adds as $col => $ddl) {
  2863. try {
  2864. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  2865. if (!is_array($cols) || $cols === []) {
  2866. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  2867. }
  2868. } catch (\Throwable $e) {
  2869. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  2870. }
  2871. }
  2872. }
  2873. /**
  2874. * 是否已自选供应商(免开标查看报价)
  2875. *
  2876. * @param array{pos?:array} $bundle
  2877. */
  2878. protected function isProcuremenManualPickedForBundle(array $bundle): bool
  2879. {
  2880. $this->ensurePurchaseOrderManualPickColumns();
  2881. foreach ($bundle['pos'] ?? [] as $poRow) {
  2882. if (!is_array($poRow)) {
  2883. continue;
  2884. }
  2885. if ((int)($poRow['manual_pick'] ?? 0) === 1) {
  2886. return true;
  2887. }
  2888. }
  2889. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2890. if ($ccydh === '') {
  2891. return false;
  2892. }
  2893. try {
  2894. $v = Db::table('purchase_order')->where('CCYDH', $ccydh)->where('manual_pick', 1)->value('id');
  2895. return $v !== null && $v !== false && (int)$v > 0;
  2896. } catch (\Throwable $e) {
  2897. return false;
  2898. }
  2899. }
  2900. /**
  2901. * @param array{pos?:array} $bundle
  2902. * @return array{company:string,reason:string}
  2903. */
  2904. protected function resolveProcuremenManualPickInfo(array $bundle): array
  2905. {
  2906. $this->ensurePurchaseOrderManualPickColumns();
  2907. foreach ($bundle['pos'] ?? [] as $poRow) {
  2908. if (!is_array($poRow)) {
  2909. continue;
  2910. }
  2911. if ((int)($poRow['manual_pick'] ?? 0) !== 1) {
  2912. continue;
  2913. }
  2914. $cn = trim((string)($poRow['pick_company_name'] ?? ''));
  2915. $reason = trim((string)($poRow['manual_pick_reason'] ?? ''));
  2916. return ['company' => $cn, 'reason' => $reason];
  2917. }
  2918. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2919. if ($ccydh === '') {
  2920. return ['company' => '', 'reason' => ''];
  2921. }
  2922. try {
  2923. $row = Db::table('purchase_order')
  2924. ->where('CCYDH', $ccydh)
  2925. ->where('manual_pick', 1)
  2926. ->field('pick_company_name,manual_pick_reason')
  2927. ->order('id', 'asc')
  2928. ->find();
  2929. } catch (\Throwable $e) {
  2930. $row = null;
  2931. }
  2932. if (!is_array($row)) {
  2933. return ['company' => '', 'reason' => ''];
  2934. }
  2935. return [
  2936. 'company' => trim((string)($row['pick_company_name'] ?? '')),
  2937. 'reason' => trim((string)($row['manual_pick_reason'] ?? '')),
  2938. ];
  2939. }
  2940. protected function loadBidOpenAdminUser(int $adminId): ?array
  2941. {
  2942. if ($adminId <= 0) {
  2943. return null;
  2944. }
  2945. try {
  2946. $row = Db::name('admin')->where('id', $adminId)->find();
  2947. } catch (\Throwable $e) {
  2948. return null;
  2949. }
  2950. if (!is_array($row)) {
  2951. return null;
  2952. }
  2953. $status = strtolower(trim((string)($row['status'] ?? '')));
  2954. if ($status !== '' && $status !== 'normal') {
  2955. return null;
  2956. }
  2957. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  2958. return null;
  2959. }
  2960. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  2961. if (!preg_match('/^1\d{10}$/', $phone)) {
  2962. return null;
  2963. }
  2964. $name = trim((string)($row['nickname'] ?? ''));
  2965. if ($name === '') {
  2966. $name = trim((string)($row['username'] ?? ''));
  2967. }
  2968. return [
  2969. 'id' => (int)$row['id'],
  2970. 'username' => trim((string)($row['username'] ?? '')),
  2971. 'nickname' => $name,
  2972. 'mobile' => $phone,
  2973. ];
  2974. }
  2975. /**
  2976. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  2977. */
  2978. protected function bidOpenVerifierAuthGroupRootId(): int
  2979. {
  2980. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  2981. return $id > 0 ? $id : 10;
  2982. }
  2983. /**
  2984. * @return int[]
  2985. */
  2986. protected function loadBidOpenVerifierAuthGroupIds(): array
  2987. {
  2988. static $memo = [];
  2989. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  2990. if (isset($memo[$rootId])) {
  2991. return $memo[$rootId];
  2992. }
  2993. try {
  2994. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  2995. } catch (\Throwable $e) {
  2996. $memo[$rootId] = [$rootId];
  2997. return $memo[$rootId];
  2998. }
  2999. if (!is_array($groups) || $groups === []) {
  3000. $memo[$rootId] = [$rootId];
  3001. return $memo[$rootId];
  3002. }
  3003. $groupList = [];
  3004. foreach ($groups as $g) {
  3005. if (is_array($g)) {
  3006. $groupList[] = $g;
  3007. }
  3008. }
  3009. if ($groupList === []) {
  3010. $memo[$rootId] = [$rootId];
  3011. return $memo[$rootId];
  3012. }
  3013. $tree = \fast\Tree::instance();
  3014. $tree->init($groupList);
  3015. $ids = $tree->getChildrenIds($rootId, true);
  3016. if (!is_array($ids) || $ids === []) {
  3017. $memo[$rootId] = [$rootId];
  3018. return $memo[$rootId];
  3019. }
  3020. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  3021. return $memo[$rootId];
  3022. }
  3023. protected function isBidOpenVerifierAdmin(int $adminId): bool
  3024. {
  3025. if ($adminId <= 0) {
  3026. return false;
  3027. }
  3028. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3029. if ($groupIds === []) {
  3030. return false;
  3031. }
  3032. try {
  3033. return (bool)Db::name('auth_group_access')
  3034. ->where('uid', $adminId)
  3035. ->where('group_id', 'in', $groupIds)
  3036. ->count();
  3037. } catch (\Throwable $e) {
  3038. return false;
  3039. }
  3040. }
  3041. /**
  3042. * @return array<int, array<string, mixed>>
  3043. */
  3044. protected function listBidOpenVerifierCandidates(): array
  3045. {
  3046. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3047. if ($groupIds === []) {
  3048. return [];
  3049. }
  3050. try {
  3051. $adminIds = Db::name('auth_group_access')
  3052. ->where('group_id', 'in', $groupIds)
  3053. ->column('uid');
  3054. } catch (\Throwable $e) {
  3055. $adminIds = [];
  3056. }
  3057. $adminIds = is_array($adminIds)
  3058. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  3059. : [];
  3060. if ($adminIds === []) {
  3061. return [];
  3062. }
  3063. try {
  3064. $rows = Db::name('admin')
  3065. ->where('status', 'normal')
  3066. ->where('id', 'in', $adminIds)
  3067. ->where('mobile', '<>', '')
  3068. ->order('id', 'asc')
  3069. ->select();
  3070. } catch (\Throwable $e) {
  3071. return [];
  3072. }
  3073. if (!is_array($rows)) {
  3074. return [];
  3075. }
  3076. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  3077. $out = [];
  3078. foreach ($rows as $row) {
  3079. if (!is_array($row)) {
  3080. continue;
  3081. }
  3082. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  3083. if ($one === null) {
  3084. continue;
  3085. }
  3086. $out[] = [
  3087. 'id' => $one['id'],
  3088. 'username' => $one['username'],
  3089. 'nickname' => $one['nickname'],
  3090. 'group_name' => $groupNameMap[$one['id']] ?? '',
  3091. 'mobile' => mask_phone($one['mobile']),
  3092. 'mobile_plain' => (string)$one['mobile'],
  3093. ];
  3094. }
  3095. return $out;
  3096. }
  3097. /**
  3098. * @param int[] $adminIds
  3099. * @return array<int, string>
  3100. */
  3101. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  3102. {
  3103. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  3104. if ($adminIds === []) {
  3105. return [];
  3106. }
  3107. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3108. try {
  3109. $rows = Db::name('auth_group_access')
  3110. ->alias('aga')
  3111. ->join('auth_group ag', 'aga.group_id = ag.id')
  3112. ->where('aga.uid', 'in', $adminIds)
  3113. ->where('aga.group_id', 'in', $groupIds)
  3114. ->field('aga.uid,ag.name')
  3115. ->order('aga.uid', 'asc')
  3116. ->order('aga.group_id', 'asc')
  3117. ->select();
  3118. } catch (\Throwable $e) {
  3119. return [];
  3120. }
  3121. if (!is_array($rows)) {
  3122. return [];
  3123. }
  3124. $out = [];
  3125. foreach ($rows as $row) {
  3126. if (!is_array($row)) {
  3127. continue;
  3128. }
  3129. $uid = (int)($row['uid'] ?? 0);
  3130. $name = trim((string)($row['name'] ?? ''));
  3131. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  3132. continue;
  3133. }
  3134. $out[$uid] = $name;
  3135. }
  3136. return $out;
  3137. }
  3138. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  3139. {
  3140. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  3141. }
  3142. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  3143. {
  3144. return 'procuremen_bidopen_wait_' . $adminId;
  3145. }
  3146. protected function renderBidOpenVerifySms(string $code): string
  3147. {
  3148. $tpl = '';
  3149. try {
  3150. $row = $this->loadNotifyTemplateRow('bid_open');
  3151. if (is_array($row)) {
  3152. $tpl = trim((string)($row['content'] ?? ''));
  3153. }
  3154. } catch (\Throwable $e) {
  3155. $tpl = '';
  3156. }
  3157. if ($tpl === '') {
  3158. $tpl = '【可集达】您的短信验证码是{code}';
  3159. }
  3160. return str_replace('{code}', $code, $tpl);
  3161. }
  3162. protected function sendBidOpenVerifySms(string $phone, string $code): void
  3163. {
  3164. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  3165. }
  3166. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  3167. {
  3168. $code = trim($code);
  3169. if (!preg_match('/^\d{6}$/', $code)) {
  3170. return false;
  3171. }
  3172. $mock = Config::get('mproc.mock_sms_code');
  3173. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3174. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3175. return true;
  3176. }
  3177. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3178. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3179. return false;
  3180. }
  3181. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3182. return true;
  3183. }
  3184. /**
  3185. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3186. */
  3187. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  3188. {
  3189. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3190. if ($ccydh === '') {
  3191. throw new \InvalidArgumentException('订单号无效');
  3192. }
  3193. $this->ensurePurchaseOrderBidOpenTable();
  3194. list($operatorId, $operatorName) = $this->GetUseName();
  3195. $now = date('Y-m-d H:i:s');
  3196. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3197. $payload = [
  3198. 'ccydh' => $ccydh,
  3199. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  3200. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  3201. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  3202. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  3203. 'operator_id' => (int)$operatorId,
  3204. 'operator_name' => trim((string)$operatorName),
  3205. 'createtime' => $now,
  3206. ];
  3207. if (is_array($exists)) {
  3208. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  3209. } else {
  3210. Db::table('purchase_order_bid_open')->insert($payload);
  3211. }
  3212. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  3213. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  3214. $labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
  3215. (int)$payload['verifier1_id'],
  3216. (int)$payload['verifier2_id'],
  3217. ]);
  3218. if (isset($labelMap[(int)$payload['verifier1_id']]) && (int)$payload['verifier1_id'] > 0) {
  3219. $name1 = $labelMap[(int)$payload['verifier1_id']];
  3220. }
  3221. if (isset($labelMap[(int)$payload['verifier2_id']]) && (int)$payload['verifier2_id'] > 0) {
  3222. $name2 = $labelMap[(int)$payload['verifier2_id']];
  3223. }
  3224. $logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
  3225. $seenSid = [];
  3226. foreach ($bundle['pos'] ?? [] as $poRow) {
  3227. if (!is_array($poRow)) {
  3228. continue;
  3229. }
  3230. $sid = (int)($poRow['scydgy_id'] ?? 0);
  3231. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  3232. continue;
  3233. }
  3234. $seenSid[$sid] = true;
  3235. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  3236. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  3237. }
  3238. if ($seenSid === []) {
  3239. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  3240. if ($this->isValidScydgyRowId($anchor)) {
  3241. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  3242. }
  3243. }
  3244. // 开标通过后计算并写入供应商服务评分
  3245. try {
  3246. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  3247. ProcuremenSupplierScore::saveForOrder($ccydh, $quoteGroups, date('Y-m', strtotime($now) ?: time()));
  3248. } catch (\Throwable $e) {
  3249. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  3250. }
  3251. }
  3252. /**
  3253. * 报价行展示字段默认值(模板安全访问)
  3254. *
  3255. * @param array<string, mixed> $line
  3256. * @return array<string, mixed>
  3257. */
  3258. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  3259. {
  3260. if (!array_key_exists('amount_quote_pending', $line)) {
  3261. $line['amount_quote_pending'] = 0;
  3262. }
  3263. if (!array_key_exists('delivery_quote_pending', $line)) {
  3264. $line['delivery_quote_pending'] = 0;
  3265. }
  3266. if (!array_key_exists('quote_before_deadline', $line)) {
  3267. $line['quote_before_deadline'] = 0;
  3268. }
  3269. if (!array_key_exists('amount_filled', $line)) {
  3270. $line['amount_filled'] = 0;
  3271. }
  3272. if (!array_key_exists('delivery_filled', $line)) {
  3273. $line['delivery_filled'] = 0;
  3274. }
  3275. if (!array_key_exists('lead_days_filled', $line)) {
  3276. $line['lead_days_filled'] = 0;
  3277. }
  3278. if (!array_key_exists('lead_days_quote_pending', $line)) {
  3279. $line['lead_days_quote_pending'] = 0;
  3280. }
  3281. if (!array_key_exists('lead_days_show', $line)) {
  3282. $line['lead_days_show'] = '未填写';
  3283. }
  3284. if (!array_key_exists('lead_days_text', $line)) {
  3285. $line['lead_days_text'] = $line['lead_days_show'];
  3286. }
  3287. return $line;
  3288. }
  3289. /**
  3290. * 审核弹窗:按供应商汇总报价明细
  3291. *
  3292. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3293. * @return array<int, array<string, mixed>>
  3294. */
  3295. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  3296. {
  3297. $sids = [];
  3298. foreach ($bundle['pos'] ?? [] as $po) {
  3299. if (!is_array($po)) {
  3300. continue;
  3301. }
  3302. $sid = (int)($po['scydgy_id'] ?? 0);
  3303. if ($this->isValidScydgyRowId($sid)) {
  3304. $sids[$sid] = true;
  3305. }
  3306. }
  3307. if ($sids === []) {
  3308. return [];
  3309. }
  3310. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3311. $gymcMap = [];
  3312. $qtyBySid = [];
  3313. $orderedSids = [];
  3314. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3315. if (!is_array($mr)) {
  3316. continue;
  3317. }
  3318. $gid = $this->extractScydgyRowId($mr);
  3319. if ($this->isValidScydgyRowId($gid)) {
  3320. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3321. $orderedSids[] = $gid;
  3322. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3323. if ($qty === '') {
  3324. $qty = trim((string)($mr['NGZL'] ?? ''));
  3325. }
  3326. $qtyBySid[$gid] = $qty;
  3327. }
  3328. }
  3329. foreach ($bundle['pos'] ?? [] as $po) {
  3330. if (!is_array($po)) {
  3331. continue;
  3332. }
  3333. $gid = (int)($po['scydgy_id'] ?? 0);
  3334. if ($this->isValidScydgyRowId($gid)) {
  3335. $nm = trim((string)($po['CGYMC'] ?? ''));
  3336. if ($nm !== '') {
  3337. $gymcMap[$gid] = $nm;
  3338. }
  3339. if (!in_array($gid, $orderedSids, true)) {
  3340. $orderedSids[] = $gid;
  3341. }
  3342. }
  3343. }
  3344. try {
  3345. $detailsQuery = Db::table('purchase_order_detail')
  3346. ->where('scydgy_id', 'in', array_keys($sids));
  3347. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3348. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  3349. } catch (\Throwable $e) {
  3350. try {
  3351. $detailsQuery = Db::table('purchase_order_detail')
  3352. ->where('scydgy_id', 'in', array_keys($sids));
  3353. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3354. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  3355. } catch (\Throwable $e2) {
  3356. $details = [];
  3357. }
  3358. }
  3359. if (!is_array($details)) {
  3360. $details = [];
  3361. }
  3362. $byCompany = [];
  3363. foreach ($details as $d) {
  3364. if (!is_array($d)) {
  3365. continue;
  3366. }
  3367. $cn = trim((string)($d['company_name'] ?? ''));
  3368. if ($cn === '') {
  3369. continue;
  3370. }
  3371. if (!isset($byCompany[$cn])) {
  3372. $ph = trim((string)($d['phone'] ?? ''));
  3373. $username = trim((string)($d['username'] ?? ''));
  3374. if ($username === '') {
  3375. $username = $this->resolveCustomerContactName($ph, $cn);
  3376. }
  3377. $byCompany[$cn] = [
  3378. 'name' => $cn,
  3379. 'email' => trim((string)($d['email'] ?? '')),
  3380. 'phone' => $ph,
  3381. 'username' => $username,
  3382. 'remark' => '',
  3383. 'has_quote' => false,
  3384. 'lines_map' => [],
  3385. ];
  3386. }
  3387. if ($byCompany[$cn]['remark'] === '') {
  3388. $rm = '';
  3389. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3390. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3391. $rm = trim((string)$d[$rk]);
  3392. break;
  3393. }
  3394. }
  3395. if ($rm !== '') {
  3396. $byCompany[$cn]['remark'] = $rm;
  3397. }
  3398. }
  3399. $sid = (int)($d['scydgy_id'] ?? 0);
  3400. $am = trim((string)($d['amount'] ?? ''));
  3401. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3402. if ($gymc === '') {
  3403. $gymc = '工序';
  3404. }
  3405. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3406. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3407. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3408. $deliveryShow = $deliveryRaw;
  3409. }
  3410. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3411. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3412. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3413. $subtotal = null;
  3414. if ($amountNum !== null) {
  3415. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3416. }
  3417. $unitPriceText = $amountFilled
  3418. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3419. : '未填写';
  3420. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3421. $leadFilled = ($leadDays !== null);
  3422. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3423. $lineRow = [
  3424. 'cgymc' => $gymc,
  3425. 'amount' => $am,
  3426. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  3427. 'amount_filled' => $amountFilled,
  3428. 'unit_price_text' => $unitPriceText,
  3429. 'delivery' => $deliveryRaw,
  3430. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  3431. 'delivery_filled' => $deliveryFilled,
  3432. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  3433. 'lead_days' => $leadFilled ? $leadDays : '',
  3434. 'lead_days_filled'=> $leadFilled,
  3435. 'lead_days_show' => $leadText,
  3436. 'lead_days_text' => $leadText,
  3437. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3438. 'subtotal_num' => $subtotal,
  3439. 'status_name' => trim((string)($d['status_name'] ?? '')),
  3440. 'is_quoted' => $amountFilled,
  3441. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  3442. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3443. ];
  3444. if (!$quoteVisible) {
  3445. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  3446. }
  3447. // 按工序 id 暂存,下面再按上方工序表顺序输出
  3448. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  3449. }
  3450. foreach ($byCompany as $cn => $g) {
  3451. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  3452. $lines = [];
  3453. $usedSids = [];
  3454. foreach ($orderedSids as $sid) {
  3455. if (!isset($linesMap[$sid])) {
  3456. continue;
  3457. }
  3458. $lines[] = $linesMap[$sid];
  3459. $usedSids[$sid] = true;
  3460. }
  3461. foreach ($linesMap as $sid => $ln) {
  3462. if (isset($usedSids[$sid])) {
  3463. continue;
  3464. }
  3465. $lines[] = $ln;
  3466. }
  3467. $total = count($lines);
  3468. $quoted = 0;
  3469. $groupTotal = 0.0;
  3470. $groupHasTotal = false;
  3471. if ($quoteVisible) {
  3472. foreach ($lines as $ln) {
  3473. $am = trim((string)($ln['amount'] ?? ''));
  3474. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  3475. $quoted++;
  3476. }
  3477. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3478. $groupTotal += (float)$ln['subtotal_num'];
  3479. $groupHasTotal = true;
  3480. }
  3481. }
  3482. }
  3483. unset($byCompany[$cn]['lines_map']);
  3484. $byCompany[$cn]['lines'] = $lines;
  3485. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  3486. $byCompany[$cn]['line_count'] = $total;
  3487. $byCompany[$cn]['has_total'] = $total > 0;
  3488. $byCompany[$cn]['has_remark'] = $total > 0;
  3489. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  3490. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3491. // 工序行 + 备注行 + 总计行
  3492. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  3493. }
  3494. $groups = array_values($byCompany);
  3495. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3496. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  3497. }
  3498. /**
  3499. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  3500. *
  3501. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3502. * @return array<int, array<string, mixed>>
  3503. */
  3504. protected function loadConfirmSupplierPickGroups(array $bundle): array
  3505. {
  3506. $sids = [];
  3507. $poIdMap = [];
  3508. foreach ($bundle['pos'] ?? [] as $po) {
  3509. if (!is_array($po)) {
  3510. continue;
  3511. }
  3512. $sid = (int)($po['scydgy_id'] ?? 0);
  3513. if ($this->isValidScydgyRowId($sid)) {
  3514. $sids[$sid] = true;
  3515. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  3516. }
  3517. }
  3518. if ($sids === []) {
  3519. return [];
  3520. }
  3521. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3522. $gymcMap = [];
  3523. $qtyBySid = [];
  3524. $orderedSids = [];
  3525. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3526. if (!is_array($mr)) {
  3527. continue;
  3528. }
  3529. $gid = $this->extractScydgyRowId($mr);
  3530. if ($this->isValidScydgyRowId($gid)) {
  3531. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3532. $orderedSids[] = $gid;
  3533. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3534. if ($qty === '') {
  3535. $qty = trim((string)($mr['NGZL'] ?? ''));
  3536. }
  3537. $qtyBySid[$gid] = $qty;
  3538. }
  3539. }
  3540. foreach ($bundle['pos'] ?? [] as $po) {
  3541. if (!is_array($po)) {
  3542. continue;
  3543. }
  3544. $gid = (int)($po['scydgy_id'] ?? 0);
  3545. if ($this->isValidScydgyRowId($gid)) {
  3546. $nm = trim((string)($po['CGYMC'] ?? ''));
  3547. if ($nm !== '') {
  3548. $gymcMap[$gid] = $nm;
  3549. }
  3550. }
  3551. }
  3552. try {
  3553. $details = Db::table('purchase_order_detail')
  3554. ->where('scydgy_id', 'in', array_keys($sids))
  3555. ->order('company_name', 'asc')
  3556. ->order('id', 'asc')
  3557. ->select();
  3558. } catch (\Throwable $e) {
  3559. try {
  3560. $details = Db::table('purchase_order_detail')
  3561. ->where('scydgy_id', 'in', array_keys($sids))
  3562. ->order('company_name', 'asc')
  3563. ->order('ID', 'asc')
  3564. ->select();
  3565. } catch (\Throwable $e2) {
  3566. $details = [];
  3567. }
  3568. }
  3569. if (!is_array($details)) {
  3570. $details = [];
  3571. }
  3572. $byCompany = [];
  3573. foreach ($details as $d) {
  3574. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3575. continue;
  3576. }
  3577. $cn = trim((string)($d['company_name'] ?? ''));
  3578. if ($cn === '') {
  3579. continue;
  3580. }
  3581. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  3582. $sid = (int)($d['scydgy_id'] ?? 0);
  3583. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  3584. continue;
  3585. }
  3586. if (!isset($byCompany[$cn])) {
  3587. $ph = trim((string)($d['phone'] ?? ''));
  3588. $username = trim((string)($d['username'] ?? ''));
  3589. if ($username === '') {
  3590. $username = $this->resolveCustomerContactName($ph, $cn);
  3591. }
  3592. $byCompany[$cn] = [
  3593. 'name' => $cn,
  3594. 'email' => trim((string)($d['email'] ?? '')),
  3595. 'phone' => $ph,
  3596. 'username' => $username,
  3597. 'remark' => '',
  3598. 'pick_lines' => [],
  3599. 'detail_picks' => [],
  3600. ];
  3601. }
  3602. if ($byCompany[$cn]['remark'] === '') {
  3603. $rm = '';
  3604. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3605. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3606. $rm = trim((string)$d[$rk]);
  3607. break;
  3608. }
  3609. }
  3610. if ($rm !== '') {
  3611. $byCompany[$cn]['remark'] = $rm;
  3612. }
  3613. }
  3614. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3615. if ($gymc === '') {
  3616. $gymc = '工序';
  3617. }
  3618. $am = trim((string)($d['amount'] ?? ''));
  3619. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3620. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3621. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3622. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3623. $deliveryShow = $deliveryRaw;
  3624. }
  3625. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3626. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3627. $subtotal = null;
  3628. if ($amountNum !== null) {
  3629. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3630. }
  3631. $unitPriceText = $amountFilled
  3632. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3633. : '未填写';
  3634. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3635. $leadFilled = ($leadDays !== null);
  3636. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3637. $pickLine = [
  3638. 'cgymc' => $gymc,
  3639. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  3640. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  3641. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  3642. 'amount_filled' => $amountFilled,
  3643. 'delivery_filled' => $deliveryFilled,
  3644. 'unit_price_text' => $unitPriceText,
  3645. 'lead_days' => $leadFilled ? $leadDays : '',
  3646. 'lead_days_filled'=> $leadFilled,
  3647. 'lead_days_show' => $leadText,
  3648. 'lead_days_text' => $leadText,
  3649. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3650. 'subtotal_num' => $subtotal,
  3651. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3652. 'is_quoted' => $amountFilled,
  3653. ];
  3654. if (!$quoteVisible) {
  3655. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  3656. }
  3657. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  3658. $byCompany[$cn]['detail_picks'][$sid] = [
  3659. 'scydgy_id' => $sid,
  3660. 'detail_id' => $detailId,
  3661. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  3662. 'cgymc' => $gymc,
  3663. ];
  3664. }
  3665. $out = [];
  3666. foreach ($byCompany as $g) {
  3667. $pickLinesMap = $g['pick_lines'] ?? [];
  3668. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  3669. continue;
  3670. }
  3671. $pickLines = [];
  3672. $usedLineSids = [];
  3673. foreach ($orderedSids as $sid) {
  3674. if (!isset($pickLinesMap[$sid])) {
  3675. continue;
  3676. }
  3677. $pickLines[] = $pickLinesMap[$sid];
  3678. $usedLineSids[$sid] = true;
  3679. }
  3680. foreach ($pickLinesMap as $sid => $ln) {
  3681. if (isset($usedLineSids[$sid])) {
  3682. continue;
  3683. }
  3684. $pickLines[] = $ln;
  3685. }
  3686. $groupTotal = 0.0;
  3687. $groupHasTotal = false;
  3688. if ($quoteVisible) {
  3689. foreach ($pickLines as $ln) {
  3690. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3691. $groupTotal += (float)$ln['subtotal_num'];
  3692. $groupHasTotal = true;
  3693. }
  3694. }
  3695. }
  3696. $lineCount = count($pickLines);
  3697. $g['pick_lines'] = $pickLines;
  3698. $g['line_count'] = $lineCount;
  3699. $g['has_total'] = $lineCount > 0;
  3700. $g['has_remark'] = $lineCount > 0;
  3701. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  3702. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3703. // 工序行 + 备注行 + 总计行
  3704. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  3705. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  3706. $detailPicks = [];
  3707. $usedPickSids = [];
  3708. foreach ($orderedSids as $sid) {
  3709. if (!isset($detailPicksMap[$sid])) {
  3710. continue;
  3711. }
  3712. $detailPicks[] = $detailPicksMap[$sid];
  3713. $usedPickSids[$sid] = true;
  3714. }
  3715. foreach ($detailPicksMap as $sid => $dp) {
  3716. if (isset($usedPickSids[$sid])) {
  3717. continue;
  3718. }
  3719. $detailPicks[] = $dp;
  3720. }
  3721. $g['detail_picks'] = $detailPicks;
  3722. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  3723. unset($g['detail_picks']);
  3724. $out[] = $g;
  3725. }
  3726. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3727. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  3728. }
  3729. /**
  3730. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  3731. * @return array<int, int[]> scydgy_id => detail_id[]
  3732. */
  3733. protected function mapDetailIdsByScydgyId(array $details): array
  3734. {
  3735. $out = [];
  3736. foreach ($details as $d) {
  3737. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3738. continue;
  3739. }
  3740. $sid = (int)($d['scydgy_id'] ?? 0);
  3741. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  3742. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  3743. continue;
  3744. }
  3745. if (!isset($out[$sid])) {
  3746. $out[$sid] = [];
  3747. }
  3748. $out[$sid][] = $pk;
  3749. }
  3750. foreach ($out as $sid => $ids) {
  3751. $out[$sid] = array_values(array_unique($ids));
  3752. }
  3753. return $out;
  3754. }
  3755. /**
  3756. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  3757. *
  3758. * @param array<string, mixed> $dbRow
  3759. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  3760. */
  3761. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  3762. {
  3763. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  3764. $r = [
  3765. 'ID' => $sid,
  3766. 'scydgy_id' => $sid,
  3767. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  3768. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  3769. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  3770. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  3771. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  3772. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  3773. 'CDW' => $dbRow['CDW'] ?? '',
  3774. 'czlyq' => $dbRow['czlyq'] ?? '',
  3775. 'NGZL' => $dbRow['NGZL'] ?? '',
  3776. 'CDF' => $dbRow['CDF'] ?? '',
  3777. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  3778. 'MBZ' => $dbRow['MBZ'] ?? '',
  3779. 'bwjg' => $dbRow['bwjg'] ?? '',
  3780. 'iStatus' => $dbRow['iStatus'] ?? '',
  3781. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  3782. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  3783. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  3784. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  3785. 'dStamp' => $dbRow['dStamp'] ?? '',
  3786. 'pick_time' => $dbRow['pick_time'] ?? '',
  3787. ];
  3788. $r['This_quantity'] = $this->resolveProcuremenThisQuantity($r);
  3789. $r['ceilingPrice'] = $this->resolveProcuremenCeilingPrice($r);
  3790. if ($sid > 0 && isset($dStampMap[$sid])) {
  3791. $t = trim((string)$dStampMap[$sid]);
  3792. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  3793. $r['dStamp'] = $dStampMap[$sid];
  3794. }
  3795. }
  3796. $dsOut = trim((string)($r['dStamp'] ?? ''));
  3797. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  3798. $ct = $dbRow['createtime'];
  3799. if (is_numeric($ct) && (int)$ct > 946684800) {
  3800. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  3801. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  3802. $r['dStamp'] = trim($ct);
  3803. }
  3804. }
  3805. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  3806. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  3807. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  3808. $fallback = trim((string)($r['dStamp'] ?? ''));
  3809. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  3810. $r['dputrecord'] = $fallback;
  3811. }
  3812. }
  3813. if (array_key_exists('id', $dbRow)) {
  3814. $r['purchase_order_id'] = (int)$dbRow['id'];
  3815. }
  3816. if ($sid < 0) {
  3817. $r['_is_manual'] = 1;
  3818. }
  3819. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  3820. $pickOut = trim((string)($r['pick_time'] ?? ''));
  3821. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  3822. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  3823. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  3824. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  3825. $r['pick_time'] = $pickFallback;
  3826. break;
  3827. }
  3828. }
  3829. }
  3830. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  3831. if ($pickNm !== '') {
  3832. $r['pick_company_name'] = $pickNm;
  3833. $r['picked_supplier_name'] = $pickNm;
  3834. }
  3835. return $r;
  3836. }
  3837. /**
  3838. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  3839. *
  3840. * @return array<int, array<string, mixed>>
  3841. */
  3842. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  3843. {
  3844. $pool = [];
  3845. if (!is_array($dbRows) || $dbRows === []) {
  3846. return $pool;
  3847. }
  3848. $dStampMap = [];
  3849. $sidList = [];
  3850. foreach ($dbRows as $tmpRow) {
  3851. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  3852. $sid = (int)$tmpRow['scydgy_id'];
  3853. if ($sid > 0) {
  3854. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  3855. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3856. $sidList[$sid] = true;
  3857. }
  3858. }
  3859. }
  3860. }
  3861. if ($sidList !== []) {
  3862. try {
  3863. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  3864. } catch (\Throwable $e) {
  3865. $dStampMap = [];
  3866. }
  3867. }
  3868. foreach ($dbRows as $dbRow) {
  3869. if (!is_array($dbRow)) {
  3870. continue;
  3871. }
  3872. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  3873. }
  3874. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  3875. $needCcydh = [];
  3876. foreach ($pool as $row) {
  3877. if (!is_array($row)) {
  3878. continue;
  3879. }
  3880. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3881. continue;
  3882. }
  3883. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3884. if ($ccydh !== '') {
  3885. $needCcydh[$ccydh] = true;
  3886. }
  3887. }
  3888. if ($needCcydh !== []) {
  3889. $czMap = [];
  3890. try {
  3891. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  3892. } catch (\Throwable $e) {
  3893. $czMap = [];
  3894. }
  3895. if (is_array($czMap) && $czMap !== []) {
  3896. foreach ($pool as &$row) {
  3897. if (!is_array($row)) {
  3898. continue;
  3899. }
  3900. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3901. continue;
  3902. }
  3903. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3904. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  3905. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  3906. }
  3907. }
  3908. unset($row);
  3909. }
  3910. }
  3911. return $pool;
  3912. }
  3913. /**
  3914. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  3915. *
  3916. * @param int[] $scydgyIds
  3917. * @return array<int, array<string, mixed>>
  3918. */
  3919. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  3920. {
  3921. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3922. if ($scydgyIds === []) {
  3923. return [];
  3924. }
  3925. try {
  3926. $list = Db::table('purchase_order_detail')
  3927. ->where('scydgy_id', 'in', $scydgyIds)
  3928. ->field('scydgy_id,company_name,amount,delivery')
  3929. ->select();
  3930. } catch (\Throwable $e) {
  3931. $list = [];
  3932. }
  3933. return is_array($list) ? $list : [];
  3934. }
  3935. /**
  3936. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  3937. *
  3938. * @param int[] $scydgyIds
  3939. * @param array<int, array<string, mixed>> $allRows
  3940. * @return array{cnt:int, amt:int, deliv:int}
  3941. */
  3942. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  3943. {
  3944. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3945. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3946. if ($scydgyIds === [] || $allRows === []) {
  3947. return $out;
  3948. }
  3949. $idSet = array_flip($scydgyIds);
  3950. $all = [];
  3951. $withAmt = [];
  3952. $withDeliv = [];
  3953. foreach ($allRows as $r) {
  3954. if (!is_array($r)) {
  3955. continue;
  3956. }
  3957. $sid = (int)($r['scydgy_id'] ?? 0);
  3958. if (!isset($idSet[$sid])) {
  3959. continue;
  3960. }
  3961. $cn = trim((string)($r['company_name'] ?? ''));
  3962. if ($cn === '') {
  3963. continue;
  3964. }
  3965. $all[$cn] = true;
  3966. $am = $r['amount'] ?? null;
  3967. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  3968. $withAmt[$cn] = true;
  3969. }
  3970. $dv = $r['delivery'] ?? null;
  3971. if ($dv !== null && trim((string)$dv) !== '') {
  3972. $withDeliv[$cn] = true;
  3973. }
  3974. }
  3975. return [
  3976. 'cnt' => count($all),
  3977. 'amt' => count($withAmt),
  3978. 'deliv' => count($withDeliv),
  3979. ];
  3980. }
  3981. /**
  3982. * 本次数量:优先 This_quantity,空则回退工作量 NGZL(与下发/确认/审批弹窗一致)
  3983. *
  3984. * @param array<string, mixed> $row
  3985. */
  3986. protected function resolveProcuremenThisQuantity(array $row): string
  3987. {
  3988. $q = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  3989. if ($q !== '') {
  3990. return $q;
  3991. }
  3992. $ngzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  3993. if (!is_scalar($ngzl)) {
  3994. return '';
  3995. }
  3996. $s = trim((string)$ngzl);
  3997. if ($s === '') {
  3998. return '';
  3999. }
  4000. if (is_numeric($s) && (float)$s === 0.0) {
  4001. return '';
  4002. }
  4003. return $s;
  4004. }
  4005. /**
  4006. * @param array<string, mixed> $row
  4007. */
  4008. protected function resolveProcuremenCeilingPrice(array $row): string
  4009. {
  4010. return trim((string)($row['ceilingPrice'] ?? $row['ceiling_price'] ?? ''));
  4011. }
  4012. /**
  4013. * 多工序数量/限价拼接:跳过空值,避免出现「、10」「304、」
  4014. *
  4015. * @param array<int, mixed> $parts
  4016. */
  4017. protected function joinProcuremenNonEmpty(array $parts, string $sep = '、'): string
  4018. {
  4019. $out = [];
  4020. foreach ($parts as $p) {
  4021. $s = trim((string)$p);
  4022. if ($s !== '') {
  4023. $out[] = $s;
  4024. }
  4025. }
  4026. return $out === [] ? '' : implode($sep, $out);
  4027. }
  4028. /**
  4029. * 确认/审批列表:合并行按各工序同步本次数量、最高限价(顿号间隔)
  4030. *
  4031. * @param array<int, array<string, mixed>> $rows
  4032. */
  4033. protected function syncCollapsedOrderQtyPriceForList(array &$rows): void
  4034. {
  4035. if ($rows === []) {
  4036. return;
  4037. }
  4038. $idList = [];
  4039. foreach ($rows as $rw) {
  4040. if (!is_array($rw)) {
  4041. continue;
  4042. }
  4043. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4044. foreach ($rw['_order_merge_rows'] as $mr) {
  4045. if (!is_array($mr)) {
  4046. continue;
  4047. }
  4048. $mid = (int)($mr['ID'] ?? 0);
  4049. if ($this->isValidScydgyRowId($mid)) {
  4050. $idList[$mid] = true;
  4051. }
  4052. }
  4053. }
  4054. $id = (int)($rw['ID'] ?? 0);
  4055. if ($this->isValidScydgyRowId($id)) {
  4056. $idList[$id] = true;
  4057. }
  4058. }
  4059. if ($idList === []) {
  4060. return;
  4061. }
  4062. try {
  4063. $list = Db::table('purchase_order')
  4064. ->where('scydgy_id', 'in', array_keys($idList))
  4065. ->field('scydgy_id,This_quantity,ceilingPrice,NGZL,pick_company_name')
  4066. ->select();
  4067. } catch (\Throwable $e) {
  4068. return;
  4069. }
  4070. if (!is_array($list)) {
  4071. return;
  4072. }
  4073. $byId = [];
  4074. foreach ($list as $dbRow) {
  4075. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4076. continue;
  4077. }
  4078. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4079. }
  4080. foreach ($rows as &$rw) {
  4081. if (!is_array($rw)) {
  4082. continue;
  4083. }
  4084. $mergeRows = [];
  4085. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4086. $mergeRows = $rw['_order_merge_rows'];
  4087. } else {
  4088. $mergeRows = [$rw];
  4089. }
  4090. $qtyList = [];
  4091. $priceList = [];
  4092. $picked = '';
  4093. foreach ($mergeRows as $mr) {
  4094. if (!is_array($mr)) {
  4095. continue;
  4096. }
  4097. $sid = (int)($mr['ID'] ?? 0);
  4098. $db = ($sid !== 0 && isset($byId[$sid])) ? $byId[$sid] : null;
  4099. $src = $mr;
  4100. if (is_array($db)) {
  4101. $qDb = trim((string)($db['This_quantity'] ?? $db['this_quantity'] ?? ''));
  4102. $pDb = trim((string)($db['ceilingPrice'] ?? $db['ceiling_price'] ?? ''));
  4103. $ngzlDb = $db['NGZL'] ?? $db['ngzl'] ?? null;
  4104. if ($qDb !== '') {
  4105. $src['This_quantity'] = $qDb;
  4106. }
  4107. if ($pDb !== '') {
  4108. $src['ceilingPrice'] = $pDb;
  4109. }
  4110. if ($ngzlDb !== null && trim((string)$ngzlDb) !== '') {
  4111. $src['NGZL'] = $ngzlDb;
  4112. }
  4113. if ($picked === '') {
  4114. $picked = trim((string)($db['pick_company_name'] ?? ''));
  4115. }
  4116. }
  4117. if ($picked === '') {
  4118. $picked = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  4119. }
  4120. $qtyList[] = $this->resolveProcuremenThisQuantity($src);
  4121. $priceList[] = $this->resolveProcuremenCeilingPrice($src);
  4122. }
  4123. $rw['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  4124. $rw['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  4125. if ($picked !== '') {
  4126. $rw['pick_company_name'] = $picked;
  4127. $rw['picked_supplier_name'] = $picked;
  4128. }
  4129. }
  4130. unset($rw);
  4131. }
  4132. /**
  4133. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  4134. *
  4135. * @param int[] $scydgyIds
  4136. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  4137. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  4138. */
  4139. protected function OrderDetailSummary(array $scydgyIds)
  4140. {
  4141. $out = [];
  4142. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4143. if ($scydgyIds === []) {
  4144. return $out;
  4145. }
  4146. $list = [];
  4147. try {
  4148. $list = Db::table('purchase_order_detail')
  4149. ->where('scydgy_id', 'in', $scydgyIds)
  4150. ->field('id,scydgy_id,amount,delivery')
  4151. ->select();
  4152. } catch (\Throwable $e) {
  4153. $list = [];
  4154. }
  4155. if (!is_array($list)) {
  4156. return $out;
  4157. }
  4158. foreach ($list as $r) {
  4159. if (!is_array($r)) {
  4160. continue;
  4161. }
  4162. $ids = (int)($r['scydgy_id'] ?? 0);
  4163. if (!$this->isValidScydgyRowId($ids)) {
  4164. continue;
  4165. }
  4166. if (!isset($out[$ids])) {
  4167. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4168. }
  4169. $out[$ids]['cnt']++;
  4170. $am = $r['amount'] ?? null;
  4171. if ($am !== null && $am !== '') {
  4172. if (!(is_string($am) && trim($am) === '')) {
  4173. $out[$ids]['amt']++;
  4174. }
  4175. }
  4176. $dv = $r['delivery'] ?? null;
  4177. if ($dv !== null && trim((string)$dv) !== '') {
  4178. $out[$ids]['deliv']++;
  4179. }
  4180. }
  4181. return $out;
  4182. }
  4183. /**
  4184. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  4185. *
  4186. * @return array
  4187. */
  4188. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  4189. {
  4190. $strContains = function ($haystack, $needle) {
  4191. if ($needle === '') {
  4192. return false;
  4193. }
  4194. $haystack = (string)$haystack;
  4195. if (function_exists('mb_stripos')) {
  4196. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  4197. }
  4198. return stripos($haystack, $needle) !== false;
  4199. };
  4200. $stripAlias = function ($f) {
  4201. return preg_replace('/^[ab]\./i', '', (string)$f);
  4202. };
  4203. $searchColNames = [];
  4204. foreach (explode(',', $this->searchFields) as $colRaw) {
  4205. $c = $stripAlias(trim($colRaw));
  4206. if ($c !== '') {
  4207. $searchColNames[] = $c;
  4208. }
  4209. }
  4210. // 等值条件先行(表头下拉),减少后续日期解析量
  4211. $eqFilters = [];
  4212. $otherFilters = [];
  4213. foreach ($filterArr as $fk => $fv) {
  4214. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  4215. continue;
  4216. }
  4217. if (is_array($fv)) {
  4218. continue;
  4219. }
  4220. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  4221. continue;
  4222. }
  4223. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  4224. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  4225. $field = $stripAlias($fk);
  4226. if ($sym === '=' || $sym === '') {
  4227. $eqFilters[$field] = trim((string)$fv);
  4228. } else {
  4229. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  4230. }
  4231. }
  4232. $ymTarget = '';
  4233. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  4234. $ymTarget = $ymM[1];
  4235. }
  4236. $filtered = [];
  4237. foreach ($pool as $r) {
  4238. if (!is_array($r)) {
  4239. continue;
  4240. }
  4241. foreach ($eqFilters as $field => $fv) {
  4242. if (trim((string)($r[$field] ?? '')) !== $fv) {
  4243. continue 2;
  4244. }
  4245. }
  4246. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  4247. // 初选池不应含手工单;若混入则直接剔除
  4248. if ($isManual) {
  4249. continue;
  4250. }
  4251. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  4252. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  4253. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  4254. continue;
  4255. }
  4256. if ($applyMonthRange) {
  4257. $mo = (int)$m[2];
  4258. if ($mo < 1 || $mo > 12) {
  4259. continue;
  4260. }
  4261. if ($ymTarget !== '') {
  4262. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4263. if ($ymRow !== $ymTarget) {
  4264. continue;
  4265. }
  4266. } else {
  4267. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4268. $rowMonthStart = $ymRow . '-01 00:00:00';
  4269. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  4270. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  4271. continue;
  4272. }
  4273. }
  4274. }
  4275. if ($search !== '') {
  4276. $hitSearch = false;
  4277. foreach ($searchColNames as $c) {
  4278. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  4279. if ($cell !== '' && $strContains($cell, $search)) {
  4280. $hitSearch = true;
  4281. break;
  4282. }
  4283. }
  4284. if (!$hitSearch) {
  4285. continue;
  4286. }
  4287. }
  4288. foreach ($otherFilters as $item) {
  4289. $fv = $item['fv'];
  4290. $sym = $item['sym'];
  4291. $field = $item['field'];
  4292. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  4293. $cellStr = trim((string)$cell);
  4294. switch ($sym) {
  4295. case '<>':
  4296. if ((string)$cell === (string)$fv) {
  4297. continue 3;
  4298. }
  4299. break;
  4300. case 'LIKE':
  4301. case 'NOT LIKE':
  4302. $needle = trim((string)$fv);
  4303. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  4304. if ($sym === 'LIKE' && !$hit) {
  4305. continue 3;
  4306. }
  4307. if ($sym === 'NOT LIKE' && $hit) {
  4308. continue 3;
  4309. }
  4310. break;
  4311. case 'BETWEEN':
  4312. case 'RANGE':
  4313. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  4314. if (count($parts) < 2) {
  4315. $parts = is_string($fv) ? explode(',', $fv) : [];
  4316. }
  4317. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  4318. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  4319. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  4320. continue 3;
  4321. }
  4322. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  4323. continue 3;
  4324. }
  4325. break;
  4326. case '>':
  4327. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  4328. continue 3;
  4329. }
  4330. break;
  4331. case '>=':
  4332. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  4333. continue 3;
  4334. }
  4335. break;
  4336. case '<':
  4337. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  4338. continue 3;
  4339. }
  4340. break;
  4341. case '<=':
  4342. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  4343. continue 3;
  4344. }
  4345. break;
  4346. default:
  4347. if ((string)$cell !== (string)$fv) {
  4348. continue 3;
  4349. }
  4350. break;
  4351. }
  4352. }
  4353. $filtered[] = $r;
  4354. }
  4355. return $filtered;
  4356. }
  4357. /**
  4358. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  4359. */
  4360. public function snapshotToProcure()
  4361. {
  4362. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4363. $this->error(__('Invalid parameters'));
  4364. }
  4365. $row = json_decode($this->request->post('row_json', ''), true);
  4366. if (!is_array($row)) {
  4367. $this->error(__('Invalid parameters'));
  4368. }
  4369. try {
  4370. $ids = $this->extractScydgyRowId($row);
  4371. if (!$this->isValidScydgyRowId($ids)) {
  4372. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4373. }
  4374. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4375. $data = [
  4376. 'scydgy_id' => $ids,
  4377. 'CCYDH' => $row['CCYDH'] ?? null,
  4378. 'CYJMC' => $row['CYJMC'] ?? null,
  4379. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4380. 'CDXMC' => $row['CDXMC'] ?? null,
  4381. 'CGYBH' => $row['CGYBH'] ?? null,
  4382. 'CGYMC' => $row['CGYMC'] ?? null,
  4383. 'CDW' => $row['CDW'] ?? null,
  4384. 'czlyq' => $row['czlyq'] ?? null,
  4385. 'NGZL' => $row['NGZL'] ?? null,
  4386. 'CDF' => $row['CDF'] ?? null,
  4387. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4388. 'MBZ' => $row['MBZ'] ?? null,
  4389. 'bwjg' => $row['bwjg'] ?? null,
  4390. 'iStatus' => $row['iStatus'] ?? null,
  4391. 'dStamp' => $row['dStamp'] ?? null,
  4392. 'dputrecord' => $row['dputrecord'] ?? null,
  4393. 'cywyxm' => $row['cywyxm'] ?? null,
  4394. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4395. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4396. ];
  4397. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  4398. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  4399. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  4400. $this->success('操作成功');
  4401. return;
  4402. }
  4403. if ($exists) {
  4404. $upd = $data;
  4405. unset($upd['scydgy_id'], $upd['status']);
  4406. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4407. } else {
  4408. // 新增:不写 status(空/走库默认);仅写创建时间
  4409. $data['createtime'] = date('Y-m-d H:i:s');
  4410. Db::table('purchase_order')->insert($data);
  4411. }
  4412. } catch (\Throwable $e) {
  4413. $this->error($e->getMessage());
  4414. }
  4415. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  4416. $this->success('操作成功');
  4417. }
  4418. /**
  4419. * 未发列表
  4420. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  4421. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  4422. */
  4423. public function completeDirectly()
  4424. {
  4425. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4426. $this->error(__('参数错误'));
  4427. }
  4428. if (!$this->procuremenCanComplete()) {
  4429. $this->error(__('You have no permission'));
  4430. }
  4431. $row = json_decode($this->request->post('row_json', ''), true);
  4432. if (!is_array($row)) {
  4433. $this->error(__('Invalid parameters'));
  4434. }
  4435. $finishRaw = $this->request->post('finish', '1');
  4436. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  4437. $poIdLog = null;
  4438. try {
  4439. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  4440. $ids = $this->extractScydgyRowId($row);
  4441. if (!$this->isValidScydgyRowId($ids)) {
  4442. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4443. }
  4444. if ($asComplete) {
  4445. $this->assertPickRowCanComplete($ids, $row);
  4446. }
  4447. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4448. $data = [
  4449. 'scydgy_id' => $ids,
  4450. 'CCYDH' => $row['CCYDH'] ?? null,
  4451. 'CYJMC' => $row['CYJMC'] ?? null,
  4452. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4453. 'CDXMC' => $row['CDXMC'] ?? null,
  4454. 'CGYBH' => $row['CGYBH'] ?? null,
  4455. 'CGYMC' => $row['CGYMC'] ?? null,
  4456. 'CDW' => $row['CDW'] ?? null,
  4457. 'czlyq' => $row['czlyq'] ?? null,
  4458. 'NGZL' => $row['NGZL'] ?? null,
  4459. 'CDF' => $row['CDF'] ?? null,
  4460. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4461. 'MBZ' => $row['MBZ'] ?? null,
  4462. 'bwjg' => $row['bwjg'] ?? null,
  4463. 'iStatus' => $row['iStatus'] ?? null,
  4464. 'dStamp' => $row['dStamp'] ?? null,
  4465. 'dputrecord' => $row['dputrecord'] ?? null,
  4466. 'cywyxm' => $row['cywyxm'] ?? null,
  4467. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4468. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4469. ];
  4470. if ($asComplete) {
  4471. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  4472. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  4473. }
  4474. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  4475. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  4476. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  4477. $this->success('操作成功');
  4478. return;
  4479. }
  4480. if ($exists) {
  4481. $upd = $data;
  4482. unset($upd['scydgy_id']);
  4483. if (!$asComplete) {
  4484. unset($upd['status']);
  4485. }
  4486. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4487. } else {
  4488. // 新增:不写 status;完结时 $data 已含 status=1
  4489. $data['createtime'] = date('Y-m-d H:i:s');
  4490. Db::table('purchase_order')->insert($data);
  4491. }
  4492. } catch (\Throwable $e) {
  4493. $this->error($e->getMessage());
  4494. }
  4495. try {
  4496. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4497. if (is_array($rpo)) {
  4498. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4499. $poIdLog = $tid > 0 ? $tid : null;
  4500. }
  4501. } catch (\Throwable $e) {
  4502. $poIdLog = null;
  4503. }
  4504. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  4505. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  4506. if ($asComplete) {
  4507. $this->addOrderLog(
  4508. $ids,
  4509. 'mark_complete',
  4510. '点击「完结」,已标记为已完结',
  4511. $poIdLog
  4512. );
  4513. try {
  4514. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  4515. if ($pdfPublicPath === '') {
  4516. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  4517. }
  4518. } catch (\Throwable $e) {
  4519. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  4520. }
  4521. } else {
  4522. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  4523. $qtyPart = '本次数量「' . ($q !== '' ? $q : '') . '」';
  4524. $pricePart = '最高限价「' . ($p !== '' ? $p : '') . '」';
  4525. $detail = ($gymc !== '' ? ($gymc . $qtyPart) : $qtyPart) . ',' . $pricePart;
  4526. $this->addOrderLog(
  4527. $ids,
  4528. 'save_qty_price',
  4529. '保存本次数量、最高限价:' . $detail,
  4530. $poIdLog
  4531. );
  4532. }
  4533. $this->pickHiddenScydgySetCache = null;
  4534. $this->success("操作成功");
  4535. }
  4536. /**
  4537. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  4538. *
  4539. * @param array<int, array> $rows 引用传递当前页行
  4540. */
  4541. protected function mergePurchaseOrder(array &$rows)
  4542. {
  4543. if ($rows === []) {
  4544. return;
  4545. }
  4546. $ids = [];
  4547. foreach ($rows as $rw) {
  4548. if (!is_array($rw)) {
  4549. continue;
  4550. }
  4551. $id = (int)($rw['ID'] ?? 0);
  4552. // 含手工新增负数 scydgy_id,避免限价/数量不同步
  4553. if ($this->isValidScydgyRowId($id)) {
  4554. $ids[$id] = true;
  4555. }
  4556. }
  4557. $idList = array_keys($ids);
  4558. if ($idList === []) {
  4559. return;
  4560. }
  4561. try {
  4562. $list = Db::table('purchase_order')
  4563. ->where('scydgy_id', 'in', $idList)
  4564. ->field('scydgy_id,This_quantity,ceilingPrice')
  4565. ->select();
  4566. } catch (\Throwable $e) {
  4567. return;
  4568. }
  4569. if (!is_array($list)) {
  4570. return;
  4571. }
  4572. $byId = [];
  4573. foreach ($list as $dbRow) {
  4574. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4575. continue;
  4576. }
  4577. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4578. }
  4579. foreach ($rows as &$rw) {
  4580. if (!is_array($rw)) {
  4581. continue;
  4582. }
  4583. $sid = (int)($rw['ID'] ?? 0);
  4584. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  4585. continue;
  4586. }
  4587. $db = $byId[$sid];
  4588. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  4589. if (array_key_exists('This_quantity', $db)) {
  4590. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  4591. }
  4592. if (array_key_exists('ceilingPrice', $db)) {
  4593. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  4594. } elseif (array_key_exists('ceiling_price', $db)) {
  4595. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  4596. }
  4597. }
  4598. unset($rw);
  4599. }
  4600. /**
  4601. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  4602. */
  4603. public function purchaseConfirmPick()
  4604. {
  4605. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4606. $this->error(__('Invalid parameters'));
  4607. }
  4608. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  4609. $this->error(__('You have no permission'));
  4610. }
  4611. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  4612. if ($batchRaw !== '') {
  4613. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  4614. return;
  4615. }
  4616. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  4617. $sid = (int)$scydgyId;
  4618. if (!$this->isValidScydgyRowId($sid)) {
  4619. $this->error('参数无效');
  4620. }
  4621. $parseIdList = function ($raw) {
  4622. if (is_array($raw)) {
  4623. $arr = $raw;
  4624. } else {
  4625. $decoded = json_decode((string)$raw, true);
  4626. $arr = is_array($decoded) ? $decoded : [];
  4627. }
  4628. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  4629. };
  4630. $selectedRaw = $this->request->post('selected_ids', null);
  4631. if ($selectedRaw === null || $selectedRaw === '') {
  4632. $legacy = (int)$this->request->post('selected_id', 0);
  4633. $selectedIds = $legacy > 0 ? [$legacy] : [];
  4634. } else {
  4635. $selectedIds = $parseIdList($selectedRaw);
  4636. }
  4637. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  4638. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  4639. try {
  4640. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  4641. } catch (\InvalidArgumentException $e) {
  4642. $this->error($e->getMessage());
  4643. } catch (\Throwable $e) {
  4644. $this->error($e->getMessage());
  4645. }
  4646. $this->pickHiddenScydgySetCache = null;
  4647. $this->success('操作成功', '', $result);
  4648. }
  4649. /**
  4650. * 整单采购确认(多道工序一次提交)
  4651. */
  4652. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  4653. {
  4654. $decoded = json_decode($batchRaw, true);
  4655. if (!is_array($decoded) || $decoded === []) {
  4656. $this->error('提交数据无效');
  4657. }
  4658. $picks = [];
  4659. foreach ($decoded as $item) {
  4660. if (!is_array($item)) {
  4661. continue;
  4662. }
  4663. $sid = (int)($item['scydgy_id'] ?? 0);
  4664. if (!$this->isValidScydgyRowId($sid)) {
  4665. continue;
  4666. }
  4667. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  4668. if (!is_array($sel)) {
  4669. $sel = [(int)$sel];
  4670. }
  4671. $unsel = $item['unselected_ids'] ?? [];
  4672. if (!is_array($unsel)) {
  4673. $unsel = json_decode((string)$unsel, true);
  4674. $unsel = is_array($unsel) ? $unsel : [];
  4675. }
  4676. $picks[] = [
  4677. 'scydgy_id' => $sid,
  4678. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  4679. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  4680. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  4681. ];
  4682. }
  4683. if ($picks === []) {
  4684. $this->error('提交数据无效');
  4685. }
  4686. Db::startTrans();
  4687. $results = [];
  4688. try {
  4689. foreach ($picks as $pick) {
  4690. $results[] = $this->runPurchaseConfirmPick(
  4691. (int)$pick['scydgy_id'],
  4692. $pick['selected_ids'],
  4693. $pick['unselected_ids'],
  4694. (int)$pick['purchase_order_id'],
  4695. false,
  4696. false
  4697. );
  4698. }
  4699. Db::commit();
  4700. } catch (\Throwable $e) {
  4701. Db::rollback();
  4702. $msg = $e->getMessage();
  4703. $this->error($msg !== '' ? $msg : '提交失败');
  4704. }
  4705. try {
  4706. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  4707. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  4708. } catch (\Throwable $e) {
  4709. Log::write('采购确认通知批量发送异常: ' . $e->getMessage(), 'error');
  4710. }
  4711. $this->pickHiddenScydgySetCache = null;
  4712. $this->success('操作成功', '', ['batch' => $results]);
  4713. }
  4714. /**
  4715. * @return array<string, mixed>
  4716. */
  4717. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  4718. {
  4719. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  4720. ProcuremenGuard::assertWflowPendingApproval($poRow);
  4721. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  4722. $scydgyId = (string)$sid;
  4723. if ($selectedIds === []) {
  4724. throw new \InvalidArgumentException('请至少勾选一条明细');
  4725. }
  4726. $inter = array_intersect($selectedIds, $unselectedIds);
  4727. if ($inter !== []) {
  4728. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  4729. }
  4730. $allIds = $this->purchaseOrderDetail($sid);
  4731. if ($allIds === []) {
  4732. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  4733. }
  4734. foreach ($selectedIds as $id) {
  4735. if (!in_array($id, $allIds, true)) {
  4736. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  4737. }
  4738. }
  4739. foreach ($unselectedIds as $id) {
  4740. if (!in_array($id, $allIds, true)) {
  4741. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  4742. }
  4743. }
  4744. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  4745. sort($union, SORT_NUMERIC);
  4746. $expect = $allIds;
  4747. sort($expect, SORT_NUMERIC);
  4748. if ($union !== $expect) {
  4749. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  4750. }
  4751. if ($manageTransaction) {
  4752. Db::startTrans();
  4753. }
  4754. try {
  4755. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  4756. $aff = 0;
  4757. try {
  4758. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4759. } catch (\Throwable $e) {
  4760. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4761. }
  4762. if ($aff < 1) {
  4763. throw new \Exception('更新选中状态失败');
  4764. }
  4765. $poPayload = [
  4766. // 审核通过后进入「待入库评分」;合格/不合格后才置已完结
  4767. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  4768. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  4769. ];
  4770. if ($purchaseOrderId > 0) {
  4771. $poAff = (int)Db::table('purchase_order')
  4772. ->where('id', $purchaseOrderId)
  4773. ->where('scydgy_id', $sid)
  4774. ->update($poPayload);
  4775. if ($poAff < 1) {
  4776. throw new \Exception('主表订单不存在或与工序行不匹配');
  4777. }
  4778. } else {
  4779. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  4780. if ($poAff < 1) {
  4781. throw new \Exception('未找到');
  4782. }
  4783. }
  4784. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  4785. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  4786. if ($manageTransaction) {
  4787. Db::commit();
  4788. }
  4789. } catch (\Throwable $e) {
  4790. if ($manageTransaction) {
  4791. Db::rollback();
  4792. }
  4793. throw $e;
  4794. }
  4795. $poIdFinal = $purchaseOrderId;
  4796. if ($poIdFinal <= 0) {
  4797. try {
  4798. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4799. if (is_array($rpo)) {
  4800. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4801. }
  4802. } catch (\Throwable $e) {
  4803. $poIdFinal = 0;
  4804. }
  4805. }
  4806. $pickNames = [];
  4807. foreach ($selectedIds as $pid) {
  4808. $dr = $this->purchaseOrderDetai($sid, $pid);
  4809. $nm = trim((string)($dr['company_name'] ?? ''));
  4810. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  4811. }
  4812. $this->addOrderLog(
  4813. $sid,
  4814. 'purchase_confirm',
  4815. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  4816. $poIdFinal > 0 ? $poIdFinal : null
  4817. );
  4818. if ($sendNotifications) {
  4819. try {
  4820. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  4821. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  4822. 'scydgy_id' => $sid,
  4823. 'selected_ids' => $selectedIds,
  4824. 'unselected_ids' => $unselectedIds,
  4825. 'purchase_order_id' => $purchaseOrderId,
  4826. ]]);
  4827. } catch (\Throwable $e) {
  4828. Log::write('采购确认通知发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  4829. }
  4830. }
  4831. Log::write(sprintf(
  4832. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  4833. $scydgyId,
  4834. $purchaseOrderId,
  4835. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  4836. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  4837. ), 'notice');
  4838. $pdfPublicPath = '';
  4839. try {
  4840. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  4841. } catch (\Throwable $e) {
  4842. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  4843. }
  4844. return [
  4845. 'scydgy_id' => $scydgyId,
  4846. 'purchase_order_id' => $purchaseOrderId,
  4847. 'selected_ids' => $selectedIds,
  4848. 'unselected_ids' => $unselectedIds,
  4849. 'purchase_confirm_pdf' => $pdfPublicPath,
  4850. ];
  4851. }
  4852. /**
  4853. * 审批通过短信:按本次涉及的工序汇总 process_lines
  4854. *
  4855. * @param int[]|string[] $scydgyIds
  4856. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4857. */
  4858. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  4859. {
  4860. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4861. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4862. if ($scydgyIds === []) {
  4863. return $empty;
  4864. }
  4865. $pos = [];
  4866. try {
  4867. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  4868. } catch (\Throwable $e) {
  4869. $rows = [];
  4870. }
  4871. if (is_array($rows)) {
  4872. foreach ($rows as $po) {
  4873. if (is_array($po)) {
  4874. $pos[] = $po;
  4875. }
  4876. }
  4877. }
  4878. if ($pos === []) {
  4879. return $empty;
  4880. }
  4881. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  4882. return [
  4883. 'ccydh' => $ccydh,
  4884. 'pos' => $pos,
  4885. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4886. ];
  4887. }
  4888. /**
  4889. * 审批通过/未通过:短信 + 邮件(同一供应商只发一条;邮件含平台链接)
  4890. *
  4891. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  4892. * @param array<int, array<string, mixed>> $picks
  4893. */
  4894. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  4895. {
  4896. if ($picks === []) {
  4897. return;
  4898. }
  4899. $this->ensureConfirmResultEmailTemplates();
  4900. $fallbackDetailId = 0;
  4901. $winners = [];
  4902. $losers = [];
  4903. foreach ($picks as $pick) {
  4904. if (!is_array($pick)) {
  4905. continue;
  4906. }
  4907. $sid = (int)($pick['scydgy_id'] ?? 0);
  4908. if (!$this->isValidScydgyRowId($sid)) {
  4909. continue;
  4910. }
  4911. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  4912. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  4913. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  4914. $fallbackDetailId = (int)$selectedIds[0];
  4915. }
  4916. foreach ($selectedIds as $pid) {
  4917. $dr = $this->purchaseOrderDetai($sid, $pid);
  4918. if (!is_array($dr)) {
  4919. continue;
  4920. }
  4921. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  4922. }
  4923. foreach ($unselectedIds as $pid) {
  4924. $dr = $this->purchaseOrderDetai($sid, $pid);
  4925. if (!is_array($dr)) {
  4926. continue;
  4927. }
  4928. $key = $this->notifySupplierDedupeKey($dr);
  4929. if (!isset($winners[$key])) {
  4930. $losers[$key] = $dr;
  4931. }
  4932. }
  4933. }
  4934. if ($winners === [] && $losers === []) {
  4935. return;
  4936. }
  4937. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  4938. $poIdLog = 0;
  4939. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  4940. if (isset($pos[0]) && is_array($pos[0])) {
  4941. $poIdLog = (int)($pos[0]['id'] ?? 0);
  4942. }
  4943. $sendSmsSafe = function ($phone, $content) {
  4944. $phone = trim((string)$phone);
  4945. if ($phone === '') {
  4946. return;
  4947. }
  4948. try {
  4949. $this->smsbao($phone, $content);
  4950. } catch (\Throwable $e) {
  4951. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  4952. }
  4953. };
  4954. $sendConfirmEmailSafe = function (array $dr, string $emailScene) use ($confirmNotifyVars, $poIdLog) {
  4955. $cname = trim((string)($dr['company_name'] ?? ''));
  4956. $ph = trim((string)($dr['phone'] ?? ''));
  4957. $toEmail = trim((string)($dr['email'] ?? ''));
  4958. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  4959. Log::write('采购确认邮件跳过:无有效邮箱 company=' . $cname, 'error');
  4960. return;
  4961. }
  4962. $detailId = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  4963. if ($detailId <= 0) {
  4964. $detailId = (int)($confirmNotifyVars['_fallback_detail_id'] ?? 0);
  4965. }
  4966. try {
  4967. $platformUrl = $this->buildMprocMobileOrderUrl($detailId);
  4968. } catch (\Throwable $e) {
  4969. Log::write('采购确认邮件链接失败: ' . $e->getMessage(), 'error');
  4970. $platformUrl = '';
  4971. }
  4972. $vars = array_merge($confirmNotifyVars, [
  4973. 'company_name' => $cname,
  4974. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4975. 'phone' => $ph,
  4976. 'email' => $toEmail,
  4977. 'platform_url' => $platformUrl,
  4978. ]);
  4979. unset($vars['_fallback_detail_id']);
  4980. try {
  4981. $mailPlain = $this->renderNotifyTemplate($emailScene, $vars);
  4982. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  4983. // 平台链接做成可点击
  4984. if ($platformUrl !== '') {
  4985. $esc = htmlspecialchars($platformUrl, ENT_QUOTES, 'UTF-8');
  4986. $mailBody = str_replace($esc, '<a href="' . $esc . '">' . $esc . '</a>', $mailBody);
  4987. }
  4988. $mailSubject = $this->resolveProcuremenEmailSubject($emailScene);
  4989. $mailConfig = $this->loadMailerConfig();
  4990. $this->issueSendSupplierEmail([
  4991. 'company_name' => $cname,
  4992. 'email' => $toEmail,
  4993. 'mail_plain' => $mailPlain,
  4994. 'mail_body' => $mailBody,
  4995. 'notify_vars' => $vars,
  4996. 'sms_content' => '',
  4997. 'detail_links' => $platformUrl !== '' ? [['url' => $platformUrl, 'cgymc' => '']] : [],
  4998. 'email_log_scene' => 'confirm_result',
  4999. 'email_log_scydgy_id' => (int)($dr['scydgy_id'] ?? 0),
  5000. 'email_log_purchase_order_id' => $poIdLog,
  5001. ], $mailConfig, $mailSubject);
  5002. } catch (\Throwable $e) {
  5003. Log::write('采购确认邮件失败 company=' . $cname . ' email=' . $toEmail . ' ' . $e->getMessage(), 'error');
  5004. }
  5005. };
  5006. $confirmNotifyVars['_fallback_detail_id'] = $fallbackDetailId;
  5007. foreach ($winners as $dr) {
  5008. $cname = trim((string)($dr['company_name'] ?? ''));
  5009. $ph = trim((string)($dr['phone'] ?? ''));
  5010. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  5011. 'company_name' => $cname,
  5012. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5013. 'phone' => $ph,
  5014. ]));
  5015. $sendSmsSafe($ph, $sms);
  5016. $sendConfirmEmailSafe($dr, 'confirm_ok_email');
  5017. }
  5018. foreach ($losers as $dr) {
  5019. $cname = trim((string)($dr['company_name'] ?? ''));
  5020. $ph = trim((string)($dr['phone'] ?? ''));
  5021. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  5022. 'company_name' => $cname,
  5023. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5024. 'phone' => $ph,
  5025. ]));
  5026. $sendSmsSafe($ph, $sms);
  5027. $sendConfirmEmailSafe($dr, 'confirm_fail_email');
  5028. }
  5029. }
  5030. /**
  5031. * 短信去重键:优先手机号,否则公司名
  5032. */
  5033. protected function notifySupplierDedupeKey(array $detailRow): string
  5034. {
  5035. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  5036. if ($ph !== '') {
  5037. return 'p:' . $ph;
  5038. }
  5039. $cn = trim((string)($detailRow['company_name'] ?? ''));
  5040. return 'c:' . $cn;
  5041. }
  5042. /**
  5043. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  5044. *
  5045. * @param int[] $detailIds
  5046. */
  5047. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  5048. {
  5049. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  5050. if ($detailIds === []) {
  5051. return;
  5052. }
  5053. $payload = ['status_name' => $statusName];
  5054. try {
  5055. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  5056. } catch (\Throwable $e) {
  5057. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  5058. }
  5059. }
  5060. /**
  5061. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  5062. */
  5063. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  5064. {
  5065. try {
  5066. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  5067. } catch (\Throwable $e) {
  5068. return;
  5069. }
  5070. if (!is_array($rows)) {
  5071. return;
  5072. }
  5073. foreach ($rows as $dr) {
  5074. if (!is_array($dr)) {
  5075. continue;
  5076. }
  5077. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5078. if ($id <= 0) {
  5079. continue;
  5080. }
  5081. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  5082. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  5083. try {
  5084. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  5085. } catch (\Throwable $e) {
  5086. }
  5087. }
  5088. }
  5089. /**
  5090. * @param array<string, mixed> $detailRow
  5091. */
  5092. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  5093. {
  5094. $am = $detailRow['amount'] ?? null;
  5095. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  5096. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  5097. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  5098. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  5099. }
  5100. /**
  5101. * @return int[]
  5102. */
  5103. protected function purchaseOrderDetail(int $scydgyId): array
  5104. {
  5105. if (!$this->isValidScydgyRowId($scydgyId)) {
  5106. return [];
  5107. }
  5108. try {
  5109. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  5110. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  5111. $list = $listQuery->select();
  5112. } catch (\Throwable $e) {
  5113. return [];
  5114. }
  5115. if (!is_array($list)) {
  5116. return [];
  5117. }
  5118. $ids = [];
  5119. foreach ($list as $r) {
  5120. if (!is_array($r)) {
  5121. continue;
  5122. }
  5123. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  5124. if ($pk > 0) {
  5125. $ids[] = $pk;
  5126. }
  5127. }
  5128. return array_values(array_unique($ids));
  5129. }
  5130. /**
  5131. * 获取当前登录用户信息 [id, 展示名]
  5132. */
  5133. protected function GetUseName(): array
  5134. {
  5135. $id = 0;
  5136. $name = '';
  5137. try {
  5138. if ($this->auth && $this->auth->isLogin()) {
  5139. $u = $this->auth->getUserInfo();
  5140. if (is_array($u)) {
  5141. $id = (int)($u['id'] ?? 0);
  5142. $name = trim((string)($u['nickname'] ?? ''));
  5143. if ($name === '') {
  5144. $name = trim((string)($u['username'] ?? ''));
  5145. }
  5146. }
  5147. }
  5148. } catch (\Throwable $e) {
  5149. }
  5150. if ($name === '') {
  5151. $name = '未知用户';
  5152. }
  5153. return [$id, $name];
  5154. }
  5155. /**
  5156. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  5157. */
  5158. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  5159. {
  5160. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  5161. }
  5162. /**
  5163. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  5164. *
  5165. * @param array<int, array<string, mixed>> $rows
  5166. */
  5167. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  5168. {
  5169. $sidList = [];
  5170. foreach ($rows as $rw) {
  5171. if (!is_array($rw)) {
  5172. continue;
  5173. }
  5174. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5175. foreach ($rw['_order_merge_rows'] as $mr) {
  5176. $mid = (int)($mr['ID'] ?? 0);
  5177. if ($this->isValidScydgyRowId($mid)) {
  5178. $sidList[$mid] = true;
  5179. }
  5180. }
  5181. }
  5182. $id = (int)($rw['ID'] ?? 0);
  5183. if ($this->isValidScydgyRowId($id)) {
  5184. $sidList[$id] = true;
  5185. }
  5186. }
  5187. $sids = array_keys($sidList);
  5188. $issueBySid = [];
  5189. $confirmBySid = [];
  5190. $approveBySid = [];
  5191. if ($sids !== []) {
  5192. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  5193. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  5194. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  5195. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  5196. try {
  5197. $logs = Db::table('purchase_order_oper_log')
  5198. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  5199. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  5200. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  5201. ->order('id', 'asc')
  5202. ->select();
  5203. } catch (\Throwable $e) {
  5204. $logs = [];
  5205. }
  5206. if (is_array($logs)) {
  5207. $issueSet = array_fill_keys($issueActs, true);
  5208. $confirmSet = array_fill_keys($confirmActs, true);
  5209. $approveSet = array_fill_keys($approveActs, true);
  5210. foreach ($logs as $lg) {
  5211. if (!is_array($lg)) {
  5212. continue;
  5213. }
  5214. $lg = ProcuremenOperLog::normalizeRow($lg);
  5215. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  5216. if ($sid === 0) {
  5217. continue;
  5218. }
  5219. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  5220. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  5221. if ($t === '') {
  5222. continue;
  5223. }
  5224. if (isset($issueSet[$action])) {
  5225. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  5226. $issueBySid[$sid] = $t;
  5227. }
  5228. }
  5229. if (isset($confirmSet[$action])) {
  5230. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  5231. $confirmBySid[$sid] = $t;
  5232. }
  5233. }
  5234. if (isset($approveSet[$action])) {
  5235. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  5236. $approveBySid[$sid] = $t;
  5237. }
  5238. }
  5239. }
  5240. }
  5241. }
  5242. foreach ($rows as &$rw) {
  5243. if (!is_array($rw)) {
  5244. continue;
  5245. }
  5246. $mergeSids = [];
  5247. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5248. foreach ($rw['_order_merge_rows'] as $mr) {
  5249. $mid = (int)($mr['ID'] ?? 0);
  5250. if ($this->isValidScydgyRowId($mid)) {
  5251. $mergeSids[] = $mid;
  5252. }
  5253. }
  5254. }
  5255. $rid = (int)($rw['ID'] ?? 0);
  5256. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  5257. $mergeSids[] = $rid;
  5258. }
  5259. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  5260. $issue = $pick;
  5261. $confirm = '';
  5262. $approve = '';
  5263. foreach ($mergeSids as $sid) {
  5264. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  5265. $issue = $issueBySid[$sid];
  5266. }
  5267. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  5268. $confirm = $confirmBySid[$sid];
  5269. }
  5270. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  5271. $approve = $approveBySid[$sid];
  5272. }
  5273. }
  5274. if ($issue === '' && $pick !== '') {
  5275. $issue = $pick;
  5276. }
  5277. $rw['issue_time'] = $issue;
  5278. $rw['confirm_time'] = $confirm;
  5279. $rw['approve_time'] = $approve;
  5280. }
  5281. unset($rw);
  5282. }
  5283. /**
  5284. * 按主键取一条
  5285. */
  5286. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  5287. {
  5288. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  5289. return [];
  5290. }
  5291. try {
  5292. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  5293. if (is_array($one)) {
  5294. return $one;
  5295. }
  5296. } catch (\Throwable $e) {
  5297. }
  5298. try {
  5299. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  5300. if (is_array($one)) {
  5301. return $one;
  5302. }
  5303. } catch (\Throwable $e) {
  5304. }
  5305. return [];
  5306. }
  5307. /**
  5308. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  5309. */
  5310. protected function formatProcuremenDetailTime($v): string
  5311. {
  5312. if ($v === null || $v === '') {
  5313. return '';
  5314. }
  5315. if (is_numeric($v) && (int)$v > 946684800) {
  5316. return date('Y-m-d H:i:s', (int)$v);
  5317. }
  5318. return ProcuremenTime::formatDisplayDateTime($v);
  5319. }
  5320. /**
  5321. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  5322. */
  5323. protected function formatDeliveryYmd($v): string
  5324. {
  5325. if ($v === null || $v === '') {
  5326. return '';
  5327. }
  5328. $s = trim((string)$v);
  5329. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  5330. return '';
  5331. }
  5332. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5333. return $m[1];
  5334. }
  5335. $ts = strtotime($s);
  5336. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  5337. }
  5338. /**
  5339. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  5340. */
  5341. protected function detailRowSupplierOperated(array $r): bool
  5342. {
  5343. $am = $r['amount'] ?? null;
  5344. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5345. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5346. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5347. return $okAmt || $okDel;
  5348. }
  5349. /**
  5350. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  5351. */
  5352. protected function resolveDetailSupplierOperTime(array $r): string
  5353. {
  5354. if (!$this->detailRowSupplierOperated($r)) {
  5355. return '';
  5356. }
  5357. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  5358. if ($t !== '') {
  5359. return $t;
  5360. }
  5361. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  5362. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  5363. continue;
  5364. }
  5365. $t = $this->formatProcuremenDetailTime($r[$col]);
  5366. if ($t !== '') {
  5367. return $t;
  5368. }
  5369. }
  5370. return '';
  5371. }
  5372. /**
  5373. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  5374. */
  5375. protected function detailRowSupplierAccepted(array $r): bool
  5376. {
  5377. $am = $r['amount'] ?? null;
  5378. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5379. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5380. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5381. return $okAmt && $okDel;
  5382. }
  5383. /**
  5384. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  5385. */
  5386. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  5387. {
  5388. if ($detailCount > 0) {
  5389. return true;
  5390. }
  5391. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  5392. return true;
  5393. }
  5394. $pickTime = trim((string)($main['pick_time'] ?? ''));
  5395. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  5396. return true;
  5397. }
  5398. return false;
  5399. }
  5400. /**
  5401. * 下发时间:优先 pick_time,其次首条下发明细时间
  5402. */
  5403. protected function resolveProcuremenIssueTime(array $main, array $details): string
  5404. {
  5405. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  5406. if ($issueTime !== '') {
  5407. return $issueTime;
  5408. }
  5409. foreach ($details as $dr) {
  5410. if (!is_array($dr)) {
  5411. continue;
  5412. }
  5413. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5414. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  5415. $issueTime = $t;
  5416. }
  5417. }
  5418. if ($issueTime !== '') {
  5419. return $issueTime;
  5420. }
  5421. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5422. }
  5423. /**
  5424. * 直接点「完结」时间:优先操作记录 mark_complete
  5425. */
  5426. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  5427. {
  5428. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  5429. }
  5430. /**
  5431. * 操作记录时间(取指定 action 最近一条)
  5432. *
  5433. * @param string|array<int, string> $actions
  5434. */
  5435. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  5436. {
  5437. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  5438. }
  5439. /**
  5440. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  5441. *
  5442. * @param array $main purchase_order 一行
  5443. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  5444. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  5445. */
  5446. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  5447. {
  5448. $issueCnt = count($details);
  5449. $acceptCnt = 0;
  5450. $pickedName = '';
  5451. $pickedTime = '';
  5452. foreach ($details as $dr) {
  5453. if (!is_array($dr)) {
  5454. continue;
  5455. }
  5456. if ($this->detailRowSupplierAccepted($dr)) {
  5457. $acceptCnt++;
  5458. }
  5459. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5460. if ($pickedName === '') {
  5461. $pickedName = trim((string)($dr['company_name'] ?? ''));
  5462. }
  5463. if ($pickedTime === '') {
  5464. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  5465. if ($pickedTime === '') {
  5466. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5467. }
  5468. }
  5469. }
  5470. }
  5471. $hasMain = $main !== [];
  5472. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  5473. if ($poTime === '') {
  5474. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  5475. }
  5476. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  5477. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  5478. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  5479. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  5480. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  5481. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  5482. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  5483. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  5484. $inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
  5485. $inboundResult = '';
  5486. if ($scydgyId > 0) {
  5487. try {
  5488. $inRow = Db::table('purchase_order_inbound_score')
  5489. ->where('scydgy_id', $scydgyId)
  5490. ->field('result,updatetime,createtime')
  5491. ->find();
  5492. } catch (\Throwable $e) {
  5493. $inRow = null;
  5494. }
  5495. if (is_array($inRow) && $inRow !== []) {
  5496. $inboundResult = trim((string)($inRow['result'] ?? ''));
  5497. if ($inboundScoreTime === '') {
  5498. $inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
  5499. }
  5500. }
  5501. }
  5502. $inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
  5503. $supplierTime = '';
  5504. if ($acceptCnt > 0) {
  5505. foreach ($details as $dr) {
  5506. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  5507. continue;
  5508. }
  5509. $t = $this->resolveDetailSupplierOperTime($dr);
  5510. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  5511. $supplierTime = $t;
  5512. }
  5513. }
  5514. }
  5515. $directComplete = ($mainCompleted && !$issued);
  5516. $doneTime = '';
  5517. if ($mainCompleted) {
  5518. if ($directComplete) {
  5519. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  5520. }
  5521. if ($doneTime === '' && $inboundScoreTime !== '') {
  5522. $doneTime = $inboundScoreTime;
  5523. }
  5524. if ($doneTime === '') {
  5525. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5526. }
  5527. if ($doneTime === '') {
  5528. foreach ($details as $dr) {
  5529. if (!is_array($dr)) {
  5530. continue;
  5531. }
  5532. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  5533. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  5534. $doneTime = $t;
  5535. }
  5536. }
  5537. }
  5538. if ($doneTime === '') {
  5539. $doneTime = $poTime;
  5540. }
  5541. // 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
  5542. if ($doneTime === '' && $confirmApproveTime !== '') {
  5543. $doneTime = $confirmApproveTime;
  5544. }
  5545. }
  5546. if ($directComplete) {
  5547. // 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
  5548. $step1Done = $hasMain;
  5549. $step2Done = false;
  5550. $step3Done = false;
  5551. $step4Done = false;
  5552. $step5Done = false;
  5553. $stepInboundDone = $inboundScored;
  5554. $step6Done = $mainCompleted && $inboundScored;
  5555. } else {
  5556. $step1Done = $issued;
  5557. $step2Done = $issued;
  5558. $step3Done = $acceptCnt > 0;
  5559. $step4Done = $wflowPendingApproval;
  5560. if (!$step4Done) {
  5561. foreach ($details as $dr) {
  5562. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5563. $step4Done = true;
  5564. break;
  5565. }
  5566. }
  5567. }
  5568. $step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
  5569. $stepInboundDone = $inboundScored;
  5570. // 未确认合格/不合格时,「已完结」保持未点亮(灰色)
  5571. $step6Done = $mainCompleted && $inboundScored;
  5572. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  5573. if ($mainCompleted && $issued) {
  5574. $step3Done = true;
  5575. $step4Done = true;
  5576. $step5Done = true;
  5577. // 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
  5578. if ($supplierTime === '') {
  5579. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5580. if ($fillT !== '') {
  5581. $supplierTime = $fillT;
  5582. }
  5583. }
  5584. if ($pickedTime === '') {
  5585. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5586. if ($fillT !== '') {
  5587. $pickedTime = $fillT;
  5588. }
  5589. }
  5590. if ($auditSelectTime === '') {
  5591. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5592. if ($fillT !== '') {
  5593. $auditSelectTime = $fillT;
  5594. }
  5595. }
  5596. if ($confirmApproveTime === '') {
  5597. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5598. if ($fillT !== '') {
  5599. $confirmApproveTime = $fillT;
  5600. }
  5601. }
  5602. }
  5603. }
  5604. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  5605. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  5606. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  5607. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  5608. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  5609. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  5610. $inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
  5611. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  5612. $deadlineLines = [];
  5613. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  5614. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  5615. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  5616. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  5617. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  5618. }
  5619. }
  5620. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  5621. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  5622. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  5623. if ($deliveryDisp === '') {
  5624. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  5625. }
  5626. if ($deliveryDisp !== '') {
  5627. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  5628. }
  5629. }
  5630. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  5631. $deadlineText = implode("\n", $deadlineLines);
  5632. $prefixOperTime = static function (string $t): string {
  5633. $t = trim($t);
  5634. if ($t === '' || $t === '—') {
  5635. return $t;
  5636. }
  5637. if (strpos($t, '操作时间') === 0) {
  5638. return $t;
  5639. }
  5640. return '操作时间:' . $t;
  5641. };
  5642. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  5643. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  5644. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
  5645. $stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5646. $step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5647. $steps = [
  5648. [
  5649. 'title' => '未发',
  5650. 'subtitle' => '',
  5651. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  5652. 'done' => $step1Done,
  5653. ],
  5654. [
  5655. 'title' => '下发',
  5656. 'subtitle' => $deadlineText,
  5657. 'time' => $prefixOperTime($step2Time),
  5658. 'done' => $step2Done,
  5659. ],
  5660. [
  5661. 'title' => '供应商接单',
  5662. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  5663. 'time' => '',
  5664. 'done' => $step3Done,
  5665. ],
  5666. [
  5667. 'title' => '待确认',
  5668. 'subtitle' => $step4Done
  5669. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  5670. : ($issued ? '待选供应商' : ''),
  5671. 'time' => $prefixOperTime($step4Time),
  5672. 'done' => $step4Done,
  5673. ],
  5674. [
  5675. 'title' => '待审批',
  5676. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  5677. 'time' => $prefixOperTime($step5Time),
  5678. 'done' => $step5Done,
  5679. ],
  5680. [
  5681. 'title' => '是否合格',
  5682. 'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
  5683. 'time' => $prefixOperTime($stepInboundTime),
  5684. 'done' => $stepInboundDone,
  5685. ],
  5686. [
  5687. 'title' => '已完结',
  5688. 'subtitle' => '',
  5689. 'time' => $prefixOperTime($step6Time),
  5690. 'done' => $step6Done,
  5691. ],
  5692. ];
  5693. $currentIdx = count($steps) - 1;
  5694. if ($directComplete) {
  5695. // 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
  5696. if (!$step6Done) {
  5697. foreach ($steps as $i => $s) {
  5698. if (($s['title'] ?? '') === '是否合格') {
  5699. $currentIdx = $i;
  5700. break;
  5701. }
  5702. }
  5703. }
  5704. } else {
  5705. foreach ($steps as $i => $s) {
  5706. if (!$s['done']) {
  5707. $currentIdx = $i;
  5708. break;
  5709. }
  5710. }
  5711. }
  5712. $nSteps = count($steps);
  5713. foreach ($steps as $idx => &$s) {
  5714. $s['current'] = ($idx === $currentIdx);
  5715. if ($idx === 0) {
  5716. $s['pdf_left_bg'] = '';
  5717. } else {
  5718. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  5719. }
  5720. if ($idx >= $nSteps - 1) {
  5721. $s['pdf_right_bg'] = '';
  5722. } else {
  5723. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  5724. }
  5725. }
  5726. unset($s);
  5727. $labelMap = [
  5728. 'CCYDH' => '订单号',
  5729. 'CYJMC' => '印件名称',
  5730. 'CCLBMMC' => '承揽部门',
  5731. 'CGYMC' => '工序名称',
  5732. 'CDW' => '单位',
  5733. 'czlyq' => '类型',
  5734. 'NGZL' => '工作量',
  5735. 'CDF' => '单价',
  5736. 'cGzzxMc' => '工作中心',
  5737. 'MBZ' => '备注',
  5738. 'This_quantity' => '本次数量',
  5739. 'ceilingPrice' => '最高限价',
  5740. ];
  5741. $orderSummary = [];
  5742. foreach ($labelMap as $key => $lab) {
  5743. if (!array_key_exists($key, $main)) {
  5744. continue;
  5745. }
  5746. $val = $main[$key];
  5747. if ($val === null) {
  5748. $val = '';
  5749. } elseif (!is_scalar($val)) {
  5750. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  5751. } else {
  5752. $val = (string)$val;
  5753. }
  5754. $orderSummary[] = ['label' => $lab, 'value' => $val];
  5755. }
  5756. $orderSummary[] = [
  5757. 'label' => '是否合格',
  5758. 'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
  5759. ];
  5760. $orderSummaryGrid = [];
  5761. $n = count($orderSummary);
  5762. for ($i = 0; $i < $n; $i += 2) {
  5763. $left = $orderSummary[$i];
  5764. $hasRight = ($i + 1) < $n;
  5765. $orderSummaryGrid[] = [
  5766. 'l1' => $left['label'],
  5767. 'v1' => $left['value'],
  5768. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  5769. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  5770. ];
  5771. }
  5772. return [
  5773. 'steps' => $steps,
  5774. 'orderSummary' => $orderSummary,
  5775. 'orderSummaryGrid' => $orderSummaryGrid,
  5776. 'inbound_result' => $inboundResult,
  5777. 'inbound_score_time'=> $inboundScoreTime,
  5778. 'detailRows' => $details,
  5779. ];
  5780. }
  5781. /**
  5782. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  5783. *
  5784. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  5785. */
  5786. protected function prepareProcuremenDetailsView(string $ids): array
  5787. {
  5788. $main = [];
  5789. try {
  5790. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5791. $main = is_array($one) ? $one : [];
  5792. } catch (\Throwable $e) {
  5793. $main = [];
  5794. }
  5795. $details = [];
  5796. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  5797. if ($mergeRows === []) {
  5798. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  5799. if ($mergeRows === [] && $main !== []) {
  5800. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  5801. }
  5802. }
  5803. $detailSidList = [];
  5804. $anchorSid = (int)$ids;
  5805. if ($anchorSid !== 0) {
  5806. $detailSidList[$anchorSid] = true;
  5807. }
  5808. foreach ($mergeRows as $mr) {
  5809. if (!is_array($mr)) {
  5810. continue;
  5811. }
  5812. $sid = $this->extractScydgyRowId($mr);
  5813. if ($sid !== 0) {
  5814. $detailSidList[$sid] = true;
  5815. }
  5816. }
  5817. try {
  5818. if ($detailSidList !== []) {
  5819. $details = Db::table('purchase_order_detail')
  5820. ->where('scydgy_id', 'in', array_keys($detailSidList))
  5821. ->order('id', 'asc')
  5822. ->select();
  5823. }
  5824. } catch (\Throwable $e) {
  5825. $details = [];
  5826. }
  5827. if (!is_array($details)) {
  5828. $details = [];
  5829. }
  5830. foreach ($details as &$r) {
  5831. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  5832. $r['id'] = $r['ID'];
  5833. }
  5834. if (isset($r['createtime'])) {
  5835. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  5836. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  5837. } else {
  5838. $r['createtime_text'] = (string)$r['createtime'];
  5839. }
  5840. } else {
  5841. $r['createtime_text'] = '';
  5842. }
  5843. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  5844. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  5845. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  5846. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  5847. if (is_array($r)) {
  5848. $r = $this->maskSupplierContactFields($r);
  5849. }
  5850. }
  5851. unset($r);
  5852. $activeDetails = [];
  5853. foreach ($details as $r) {
  5854. if (is_array($r) && empty($r['is_void'])) {
  5855. $activeDetails[] = $r;
  5856. }
  5857. }
  5858. $operLogs = [];
  5859. try {
  5860. $operSidList = array_keys($detailSidList);
  5861. if ($operSidList === [] && (int)$ids !== 0) {
  5862. $operSidList = [(int)$ids];
  5863. }
  5864. if ($operSidList !== []) {
  5865. $operLogs = Db::table('purchase_order_oper_log')
  5866. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  5867. ->order('id', 'asc')
  5868. ->select();
  5869. }
  5870. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  5871. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  5872. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  5873. if ($poId > 0) {
  5874. $operLogs = Db::table('purchase_order_oper_log')
  5875. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  5876. ->order('id', 'asc')
  5877. ->select();
  5878. }
  5879. }
  5880. } catch (\Throwable $e) {
  5881. $operLogs = [];
  5882. }
  5883. if (!is_array($operLogs)) {
  5884. $operLogs = [];
  5885. }
  5886. $operLogsRaw = $operLogs;
  5887. $processNameBySid = [];
  5888. foreach ($mergeRows as $mr) {
  5889. if (!is_array($mr)) {
  5890. continue;
  5891. }
  5892. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  5893. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5894. if ($psid !== 0 && $gymc !== '') {
  5895. $processNameBySid[$psid] = $gymc;
  5896. }
  5897. }
  5898. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  5899. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
  5900. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  5901. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  5902. if ($ccydh === '') {
  5903. foreach ($details as $r) {
  5904. if (!is_array($r)) {
  5905. continue;
  5906. }
  5907. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  5908. if ($ccydh !== '') {
  5909. break;
  5910. }
  5911. }
  5912. }
  5913. $this->view->assign('ccydh', $ccydh);
  5914. $this->view->assign('steps', $bundle['steps']);
  5915. $this->view->assign('orderSummary', $bundle['orderSummary']);
  5916. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  5917. $this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
  5918. $this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
  5919. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  5920. $this->view->assign('processCount', count($mergeRows));
  5921. $this->view->assign('detailRows', $details);
  5922. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  5923. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  5924. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  5925. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  5926. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  5927. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  5928. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  5929. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  5930. $this->view->assign('operLogs', $operLogs);
  5931. $sg = $quoteView['supplier_groups'] ?? [];
  5932. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
  5933. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  5934. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
  5935. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
  5936. return [
  5937. 'ok' => $main !== [] || $details !== [],
  5938. 'ccydh' => $ccydh,
  5939. ];
  5940. }
  5941. /**
  5942. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  5943. */
  5944. public function details()
  5945. {
  5946. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5947. if (is_array($ids)) {
  5948. $ids = isset($ids[0]) ? $ids[0] : '';
  5949. }
  5950. $ids = trim((string)$ids);
  5951. if ($ids === '') {
  5952. $this->error(__('Invalid parameters'));
  5953. }
  5954. $this->assertManualOrderDetailsViewable((int)$ids);
  5955. $this->prepareProcuremenDetailsView($ids);
  5956. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  5957. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  5958. $this->view->engine->layout(false);
  5959. try {
  5960. return $this->view->fetch('procuremen/details_dialog_shell');
  5961. } finally {
  5962. if ($restoreLayout) {
  5963. $this->view->engine->layout($restoreLayout);
  5964. }
  5965. }
  5966. }
  5967. /**
  5968. * 解析合并审核工序行(订单号须一致,且均未协助)
  5969. *
  5970. * @return array<int, array<string, mixed>>
  5971. */
  5972. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  5973. {
  5974. $primary = json_decode($rowJson, true);
  5975. if (!is_array($primary)) {
  5976. $this->error(__('Invalid parameters'));
  5977. }
  5978. $merge = json_decode($mergeRowsJson, true);
  5979. if (!is_array($merge) || $merge === []) {
  5980. $merge = [$primary];
  5981. }
  5982. $seen = [];
  5983. $out = [];
  5984. foreach ($merge as $r) {
  5985. if (!is_array($r)) {
  5986. continue;
  5987. }
  5988. $id = $this->extractScydgyRowId($r);
  5989. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  5990. continue;
  5991. }
  5992. $seen[$id] = true;
  5993. $out[] = $r;
  5994. }
  5995. if ($out === []) {
  5996. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  5997. }
  5998. $ccydh = null;
  5999. foreach ($out as $r) {
  6000. $dh = trim((string)($r['CCYDH'] ?? ''));
  6001. if ($ccydh === null) {
  6002. $ccydh = $dh;
  6003. } elseif ($dh !== $ccydh) {
  6004. $this->error('合并审核要求所选行的订单号一致');
  6005. }
  6006. }
  6007. $ids = [];
  6008. foreach ($out as $r) {
  6009. $id = $this->extractScydgyRowId($r);
  6010. if ($this->isValidScydgyRowId($id)) {
  6011. $ids[$id] = true;
  6012. }
  6013. }
  6014. $poBySid = [];
  6015. $detCntBySid = [];
  6016. if ($ids !== []) {
  6017. $idList = array_keys($ids);
  6018. try {
  6019. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  6020. if (is_array($poList)) {
  6021. foreach ($poList as $po) {
  6022. if (!is_array($po)) {
  6023. continue;
  6024. }
  6025. $sid = (int)($po['scydgy_id'] ?? 0);
  6026. if ($this->isValidScydgyRowId($sid)) {
  6027. $poBySid[$sid] = $po;
  6028. }
  6029. }
  6030. }
  6031. } catch (\Throwable $e) {
  6032. }
  6033. try {
  6034. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  6035. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  6036. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  6037. if (is_array($detRows)) {
  6038. foreach ($detRows as $dr) {
  6039. if (!is_array($dr)) {
  6040. continue;
  6041. }
  6042. $sid = (int)($dr['scydgy_id'] ?? 0);
  6043. if ($this->isValidScydgyRowId($sid)) {
  6044. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  6045. }
  6046. }
  6047. }
  6048. } catch (\Throwable $e) {
  6049. }
  6050. }
  6051. foreach ($out as $r) {
  6052. $id = $this->extractScydgyRowId($r);
  6053. if (!$this->isValidScydgyRowId($id)) {
  6054. continue;
  6055. }
  6056. $po = $poBySid[$id] ?? null;
  6057. if (!is_array($po)) {
  6058. continue;
  6059. }
  6060. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6061. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6062. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  6063. }
  6064. $detCnt = (int)($detCntBySid[$id] ?? 0);
  6065. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  6066. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6067. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  6068. }
  6069. }
  6070. return $out;
  6071. }
  6072. /**
  6073. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  6074. */
  6075. protected function maskSupplierContactFields(array $item): array
  6076. {
  6077. if (array_key_exists('email', $item)) {
  6078. $item['email'] = mask_email((string)$item['email']);
  6079. }
  6080. if (array_key_exists('phone', $item)) {
  6081. $item['phone'] = mask_phone((string)$item['phone']);
  6082. }
  6083. return $item;
  6084. }
  6085. /**
  6086. * @param array<int, array<string, mixed>> $list
  6087. * @return array<int, array<string, mixed>>
  6088. */
  6089. protected function maskSupplierContactList(array $list): array
  6090. {
  6091. $out = [];
  6092. foreach ($list as $item) {
  6093. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  6094. }
  6095. return $out;
  6096. }
  6097. /**
  6098. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  6099. *
  6100. * @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
  6101. * @return array<string, string>|null
  6102. */
  6103. protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
  6104. {
  6105. if (!is_array($row)) {
  6106. return null;
  6107. }
  6108. $norm = [];
  6109. foreach ($row as $k => $v) {
  6110. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  6111. }
  6112. $row = $norm;
  6113. $st = $row['status'] ?? '';
  6114. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  6115. return null;
  6116. }
  6117. $companyName = '';
  6118. foreach (['company_name', 'name'] as $nk) {
  6119. if (!empty($row[$nk])) {
  6120. $companyName = trim((string)$row[$nk]);
  6121. break;
  6122. }
  6123. }
  6124. if ($companyName === '') {
  6125. return null;
  6126. }
  6127. $username = '';
  6128. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  6129. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  6130. $username = trim((string)$row[$uk]);
  6131. break;
  6132. }
  6133. }
  6134. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  6135. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  6136. if ($phone === '' && isset($row['account'])) {
  6137. $phone = trim((string)$row['account']);
  6138. }
  6139. if ($phone === '' && isset($row['mobile'])) {
  6140. $phone = trim((string)$row['mobile']);
  6141. }
  6142. if ($requireContactChannels && $email === '' && $phone === '') {
  6143. return null;
  6144. }
  6145. $category = '';
  6146. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6147. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6148. $category = trim((string)$row[$ck]);
  6149. break;
  6150. }
  6151. }
  6152. return [
  6153. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  6154. 'name' => $companyName,
  6155. 'company_name' => $companyName,
  6156. 'username' => $username,
  6157. 'email' => $email,
  6158. 'phone' => $phone,
  6159. 'category' => $category,
  6160. 'company_type' => $category,
  6161. ];
  6162. }
  6163. /**
  6164. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  6165. */
  6166. protected function resolveCustomerContactById(string $id): ?array
  6167. {
  6168. $id = trim($id);
  6169. if ($id === '' || !ctype_digit($id)) {
  6170. return null;
  6171. }
  6172. try {
  6173. $row = Db::table('customer')->where('id', (int)$id)->find();
  6174. } catch (\Throwable $e) {
  6175. return null;
  6176. }
  6177. return $this->buildCustomerContactPayloadFromRow($row);
  6178. }
  6179. /**
  6180. * 按供应商名称解析联系信息(兼容旧提交数据)
  6181. *
  6182. * @param bool $requireContactChannels true 时须有邮箱或手机
  6183. */
  6184. protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
  6185. {
  6186. $name = trim($name);
  6187. if ($name === '') {
  6188. return null;
  6189. }
  6190. try {
  6191. // customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
  6192. $row = Db::table('customer')
  6193. ->where('company_name', $name)
  6194. ->order('id', 'desc')
  6195. ->find();
  6196. } catch (\Throwable $e) {
  6197. return null;
  6198. }
  6199. return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
  6200. }
  6201. /**
  6202. * 规范化下发/确认时勾选的供应商
  6203. *
  6204. * @param array<int, mixed> $companies
  6205. * @return array<int, array<string, string>>
  6206. */
  6207. protected function normalizePickCompanies(array $companies): array
  6208. {
  6209. $out = [];
  6210. foreach ($companies as $c) {
  6211. if (!is_array($c)) {
  6212. continue;
  6213. }
  6214. $resolved = null;
  6215. $cid = trim((string)($c['id'] ?? ''));
  6216. if ($cid !== '') {
  6217. $resolved = $this->resolveCustomerContactById($cid);
  6218. }
  6219. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  6220. if ($resolved === null && $name !== '') {
  6221. $resolved = $this->resolveCustomerContactByCompanyName($name);
  6222. }
  6223. if ($resolved === null) {
  6224. continue;
  6225. }
  6226. $out[] = $resolved;
  6227. }
  6228. return $out;
  6229. }
  6230. /**
  6231. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  6232. *
  6233. * @param array<int, array<string, mixed>> $pool
  6234. * @return array<int, array<string, mixed>>
  6235. */
  6236. protected function collapseProcuremenPoolByOrder(array $pool): array
  6237. {
  6238. if ($pool === []) {
  6239. return [];
  6240. }
  6241. $groups = [];
  6242. foreach ($pool as $row) {
  6243. if (!is_array($row)) {
  6244. continue;
  6245. }
  6246. $dh = trim((string)($row['CCYDH'] ?? ''));
  6247. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  6248. if (!isset($groups[$key])) {
  6249. $groups[$key] = [];
  6250. }
  6251. $groups[$key][] = $row;
  6252. }
  6253. $out = [];
  6254. foreach ($groups as $ccydh => $rows) {
  6255. if ($rows === []) {
  6256. continue;
  6257. }
  6258. usort($rows, function ($a, $b) {
  6259. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  6260. });
  6261. $head = $rows[0];
  6262. $gymcList = [];
  6263. foreach ($rows as $r) {
  6264. $g = trim((string)($r['CGYMC'] ?? ''));
  6265. if ($g !== '' && !in_array($g, $gymcList, true)) {
  6266. $gymcList[] = $g;
  6267. }
  6268. }
  6269. $merged = $head;
  6270. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  6271. $merged['process_count'] = count($rows);
  6272. $merged['_order_merge_rows'] = $rows;
  6273. $qtyList = [];
  6274. $priceList = [];
  6275. foreach ($rows as $r) {
  6276. if (!is_array($r)) {
  6277. continue;
  6278. }
  6279. $qtyList[] = $this->resolveProcuremenThisQuantity($r);
  6280. $priceList[] = $this->resolveProcuremenCeilingPrice($r);
  6281. }
  6282. if (count($rows) > 1) {
  6283. $merged['CGYMC'] = implode('、', $gymcList);
  6284. // 多工序:数量/限价按有值项顿号间隔(空值不占位)
  6285. $merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  6286. $merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  6287. } else {
  6288. $merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
  6289. $merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
  6290. }
  6291. // 已选供应商:取合并行中首个非空 pick_company_name
  6292. $pickedName = '';
  6293. foreach ($rows as $r) {
  6294. if (!is_array($r)) {
  6295. continue;
  6296. }
  6297. $pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
  6298. if ($pn !== '') {
  6299. $pickedName = $pn;
  6300. break;
  6301. }
  6302. }
  6303. if ($pickedName !== '') {
  6304. $merged['pick_company_name'] = $pickedName;
  6305. $merged['picked_supplier_name'] = $pickedName;
  6306. }
  6307. $mergedPickTime = '';
  6308. foreach ($rows as $r) {
  6309. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  6310. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  6311. $mergedPickTime = $t;
  6312. }
  6313. }
  6314. if ($mergedPickTime !== '') {
  6315. $merged['pick_time'] = $mergedPickTime;
  6316. }
  6317. $out[] = $merged;
  6318. }
  6319. usort($out, function ($a, $b) {
  6320. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  6321. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  6322. if ($ta === $tb) {
  6323. $ida = (int)($a['purchase_order_id'] ?? 0);
  6324. $idb = (int)($b['purchase_order_id'] ?? 0);
  6325. if ($ida !== $idb) {
  6326. return $idb <=> $ida;
  6327. }
  6328. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  6329. }
  6330. if ($ta === '') {
  6331. return 1;
  6332. }
  6333. if ($tb === '') {
  6334. return -1;
  6335. }
  6336. return strcmp($tb, $ta);
  6337. });
  6338. return $out;
  6339. }
  6340. /**
  6341. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  6342. *
  6343. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6344. */
  6345. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  6346. {
  6347. $scydgyId = trim($scydgyId);
  6348. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6349. if ($scydgyId === '') {
  6350. return $empty;
  6351. }
  6352. try {
  6353. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6354. } catch (\Throwable $e) {
  6355. $anchor = null;
  6356. }
  6357. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  6358. return $empty;
  6359. }
  6360. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6361. if ($ccydh === '') {
  6362. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  6363. }
  6364. try {
  6365. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  6366. } catch (\Throwable $e) {
  6367. $pos = [$anchor];
  6368. }
  6369. if (!is_array($pos) || $pos === []) {
  6370. $pos = [$anchor];
  6371. }
  6372. return [
  6373. 'ccydh' => $ccydh,
  6374. 'pos' => $pos,
  6375. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6376. ];
  6377. }
  6378. /**
  6379. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  6380. */
  6381. protected function purchaseOrderRowInConfirmStage(array $po): bool
  6382. {
  6383. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6384. return false;
  6385. }
  6386. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  6387. return false;
  6388. }
  6389. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  6390. return true;
  6391. }
  6392. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  6393. $sid = (int)($po['scydgy_id'] ?? 0);
  6394. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  6395. }
  6396. return false;
  6397. }
  6398. /**
  6399. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  6400. *
  6401. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6402. */
  6403. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  6404. {
  6405. $scydgyId = trim($scydgyId);
  6406. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6407. if ($scydgyId === '') {
  6408. return $empty;
  6409. }
  6410. try {
  6411. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6412. } catch (\Throwable $e) {
  6413. $anchor = null;
  6414. }
  6415. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  6416. return $empty;
  6417. }
  6418. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6419. if ($ccydh === '') {
  6420. return [
  6421. 'ccydh' => '',
  6422. 'pos' => [$anchor],
  6423. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  6424. ];
  6425. }
  6426. try {
  6427. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  6428. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  6429. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  6430. } catch (\Throwable $e) {
  6431. $pos = [$anchor];
  6432. }
  6433. if (!is_array($pos) || $pos === []) {
  6434. $pos = [$anchor];
  6435. }
  6436. $pos = array_values(array_filter($pos, function ($po) {
  6437. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  6438. }));
  6439. if ($pos === []) {
  6440. $pos = [$anchor];
  6441. }
  6442. return [
  6443. 'ccydh' => $ccydh,
  6444. 'pos' => $pos,
  6445. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6446. ];
  6447. }
  6448. /**
  6449. * @param array<int, array<string, mixed>> $purchaseOrders
  6450. * @return array<int, array<string, mixed>>
  6451. */
  6452. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  6453. {
  6454. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  6455. $byId = [];
  6456. foreach ($pool as $r) {
  6457. if (!is_array($r)) {
  6458. continue;
  6459. }
  6460. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  6461. if ($this->isValidScydgyRowId($sid)) {
  6462. $byId[$sid] = $r;
  6463. }
  6464. }
  6465. $out = [];
  6466. foreach ($purchaseOrders as $po) {
  6467. if (!is_array($po)) {
  6468. continue;
  6469. }
  6470. $sid = (int)($po['scydgy_id'] ?? 0);
  6471. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  6472. $out[] = $byId[$sid];
  6473. }
  6474. }
  6475. return $out;
  6476. }
  6477. /**
  6478. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  6479. *
  6480. * @return array<int, array<string, mixed>>
  6481. */
  6482. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  6483. {
  6484. $scydgyId = trim($scydgyId);
  6485. if ($scydgyId === '') {
  6486. return [];
  6487. }
  6488. try {
  6489. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6490. } catch (\Throwable $e) {
  6491. $anchor = null;
  6492. }
  6493. if (!is_array($anchor)) {
  6494. return [];
  6495. }
  6496. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  6497. return [];
  6498. }
  6499. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6500. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  6501. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  6502. try {
  6503. $q = Db::table('purchase_order');
  6504. if ($ccydh !== '') {
  6505. $q->where('CCYDH', $ccydh);
  6506. } else {
  6507. $q->where('scydgy_id', $scydgyId);
  6508. }
  6509. if ($isValidPick) {
  6510. $q->where('pick_time', $pickTime);
  6511. }
  6512. $pos = $q->order('scydgy_id', 'asc')->select();
  6513. } catch (\Throwable $e) {
  6514. $pos = [$anchor];
  6515. }
  6516. if (!is_array($pos) || $pos === []) {
  6517. $pos = [$anchor];
  6518. }
  6519. $pos = array_values(array_filter($pos, function ($po) {
  6520. if (!is_array($po)) {
  6521. return false;
  6522. }
  6523. $mr = $po['mod_rq'] ?? null;
  6524. if ($mr === null || $mr === '') {
  6525. return true;
  6526. }
  6527. $mrs = trim((string)$mr);
  6528. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  6529. }));
  6530. if ($pos === []) {
  6531. $pos = [$anchor];
  6532. }
  6533. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  6534. if ($rows === []) {
  6535. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  6536. }
  6537. return $rows;
  6538. }
  6539. /**
  6540. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  6541. *
  6542. * @param array<int, array<string, mixed>> $mergeRows
  6543. * @return array<int, array<string, mixed>>
  6544. */
  6545. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  6546. {
  6547. $list = array_values($mergeRows);
  6548. $n = count($list);
  6549. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  6550. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  6551. $mergeSame = $n > 1 && $orderKey0 !== '';
  6552. if ($mergeSame) {
  6553. foreach ($list as $rr) {
  6554. if (!is_array($rr)) {
  6555. $mergeSame = false;
  6556. break;
  6557. }
  6558. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  6559. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  6560. $mergeSame = false;
  6561. break;
  6562. }
  6563. }
  6564. }
  6565. $out = [];
  6566. foreach ($list as $idx => $r) {
  6567. if (!is_array($r)) {
  6568. continue;
  6569. }
  6570. $qty = $this->resolveProcuremenThisQuantity($r);
  6571. $price = $this->resolveProcuremenCeilingPrice($r);
  6572. $sid = $this->extractScydgyRowId($r);
  6573. $out[] = [
  6574. 'seq' => $idx + 1,
  6575. 'scydgy_id' => $sid,
  6576. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6577. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6578. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6579. 'CDW' => trim((string)($r['CDW'] ?? '')),
  6580. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  6581. 'NGZL' => $r['NGZL'] ?? '',
  6582. 'This_quantity' => $qty,
  6583. 'ceilingPrice' => $price,
  6584. 'CDF' => trim((string)($r['CDF'] ?? '')),
  6585. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  6586. 'show_order_cells' => !$mergeSame || $idx === 0,
  6587. 'order_rowspan' => $mergeSame ? $n : 1,
  6588. ];
  6589. }
  6590. return $out;
  6591. }
  6592. /**
  6593. * 解析金额/数量(去千分位等非数字字符)
  6594. */
  6595. protected function parseProcuremenMoneyNumber($value): ?float
  6596. {
  6597. if ($value === null || $value === '') {
  6598. return null;
  6599. }
  6600. if (is_numeric($value)) {
  6601. return (float)$value;
  6602. }
  6603. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  6604. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  6605. }
  6606. protected function formatProcuremenMoneyDisplay(?float $amount): string
  6607. {
  6608. if ($amount === null) {
  6609. return '';
  6610. }
  6611. // 保留小数(最多 5 位),去掉末尾无意义的 0,避免 0.25 被显示成 0
  6612. $s = rtrim(rtrim(sprintf('%.5F', (float)$amount), '0'), '.');
  6613. return $s === '' ? '0' : $s;
  6614. }
  6615. /**
  6616. * 列表/详情展示:工作量为 0 时显示空
  6617. */
  6618. protected function formatProcuremenWorkloadDisplay($value): string
  6619. {
  6620. if ($value === null || $value === '') {
  6621. return '';
  6622. }
  6623. $s = trim((string)$value);
  6624. if ($s === '') {
  6625. return '';
  6626. }
  6627. if (is_numeric($s) && (float)$s == 0) {
  6628. return '';
  6629. }
  6630. return $s;
  6631. }
  6632. /**
  6633. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  6634. */
  6635. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  6636. {
  6637. foreach ($details as $d) {
  6638. if (!is_array($d)) {
  6639. continue;
  6640. }
  6641. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  6642. $cn = trim((string)($d['company_name'] ?? ''));
  6643. if ($cn !== '') {
  6644. return $cn;
  6645. }
  6646. }
  6647. }
  6648. return trim((string)($main['pick_company_name'] ?? ''));
  6649. }
  6650. /**
  6651. * 详情报价小计:单价 × 本工序本次数量
  6652. */
  6653. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  6654. {
  6655. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  6656. if ($unit === null) {
  6657. return null;
  6658. }
  6659. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  6660. if ($qty === null || $qty <= 0) {
  6661. return null;
  6662. }
  6663. return $unit * $qty;
  6664. }
  6665. /**
  6666. * 详情页:工序小计 + 供应商分组报价与总计
  6667. *
  6668. * @param array<int, array<string, mixed>> $mergeRows
  6669. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  6670. * @return array{
  6671. * process_rows: array,
  6672. * supplier_groups: array,
  6673. * order_total_text: string,
  6674. * order_total_has: bool,
  6675. * selected_company: string
  6676. * }
  6677. */
  6678. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  6679. {
  6680. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  6681. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  6682. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
  6683. || ((int)($main['manual_pick'] ?? 0) === 1);
  6684. $qtyBySid = [];
  6685. $gymcBySid = [];
  6686. $orderedSids = [];
  6687. foreach ($mergeRows as $mr) {
  6688. if (!is_array($mr)) {
  6689. continue;
  6690. }
  6691. $sid = $this->extractScydgyRowId($mr);
  6692. if ($this->isValidScydgyRowId($sid)) {
  6693. $orderedSids[] = $sid;
  6694. }
  6695. $qty = trim((string)($mr['This_quantity'] ?? ''));
  6696. if ($qty === '') {
  6697. $qty = trim((string)($mr['NGZL'] ?? ''));
  6698. }
  6699. $qtyBySid[$sid] = $qty;
  6700. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  6701. }
  6702. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  6703. $detailByCompanySid = [];
  6704. foreach ($details as $d) {
  6705. if (!is_array($d)) {
  6706. continue;
  6707. }
  6708. $cn = trim((string)($d['company_name'] ?? ''));
  6709. $sid = (int)($d['scydgy_id'] ?? 0);
  6710. if ($cn === '' || $sid === 0) {
  6711. continue;
  6712. }
  6713. if (!isset($detailByCompanySid[$cn])) {
  6714. $detailByCompanySid[$cn] = [];
  6715. }
  6716. $detailByCompanySid[$cn][$sid] = $d;
  6717. }
  6718. $supplierGroups = [];
  6719. foreach ($detailByCompanySid as $cn => $bySid) {
  6720. $lines = [];
  6721. $groupTotal = 0.0;
  6722. $groupHas = false;
  6723. $groupVoid = true;
  6724. $usedSids = [];
  6725. $appendLine = function (int $sid, array $d) use (
  6726. &$lines,
  6727. &$groupTotal,
  6728. &$groupHas,
  6729. &$groupVoid,
  6730. $qtyBySid,
  6731. $gymcBySid,
  6732. $quoteVisible
  6733. ) {
  6734. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  6735. if (!$isVoid) {
  6736. $groupVoid = false;
  6737. }
  6738. $qtyStr = $qtyBySid[$sid] ?? '';
  6739. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  6740. $am = trim((string)($d['amount'] ?? ''));
  6741. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  6742. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  6743. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  6744. $sub = null;
  6745. if (!$isVoid && $amountNum !== null) {
  6746. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  6747. }
  6748. $ct = $this->resolveDetailSupplierOperTime($d);
  6749. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  6750. $leadFilled = ($leadDays !== null);
  6751. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  6752. $line = [
  6753. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  6754. 'amount' => $am,
  6755. 'unit_price_text' => $amountFilled
  6756. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  6757. : '未填写',
  6758. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  6759. 'delivery_ymd' => $deliveryYmd,
  6760. 'amount_filled' => $amountFilled,
  6761. 'delivery_filled' => $deliveryFilled,
  6762. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  6763. 'lead_days' => $leadFilled ? $leadDays : '',
  6764. 'lead_days_filled'=> $leadFilled,
  6765. 'lead_days_show' => $leadText,
  6766. 'lead_days_text' => $leadText,
  6767. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  6768. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  6769. 'is_void' => $isVoid,
  6770. 'oper_time_text' => $ct,
  6771. ];
  6772. if (!$quoteVisible && !$isVoid) {
  6773. $this->maskSupplierQuoteLineBeforeDeadline($line);
  6774. } elseif ($sub !== null) {
  6775. $groupTotal += $sub;
  6776. $groupHas = true;
  6777. }
  6778. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  6779. };
  6780. foreach ($orderedSids as $sid) {
  6781. if (!isset($bySid[$sid])) {
  6782. continue;
  6783. }
  6784. $usedSids[$sid] = true;
  6785. $appendLine($sid, $bySid[$sid]);
  6786. }
  6787. foreach ($bySid as $sid => $d) {
  6788. if (isset($usedSids[$sid])) {
  6789. continue;
  6790. }
  6791. $appendLine((int)$sid, $d);
  6792. }
  6793. $firstDetail = null;
  6794. foreach ($bySid as $d) {
  6795. if (is_array($d)) {
  6796. $firstDetail = $d;
  6797. break;
  6798. }
  6799. }
  6800. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  6801. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  6802. if ($username === '' && $ph !== '') {
  6803. $username = $this->resolveCustomerContactName($ph, $cn);
  6804. }
  6805. $remark = '';
  6806. foreach ($bySid as $d) {
  6807. if (!is_array($d)) {
  6808. continue;
  6809. }
  6810. $rm = '';
  6811. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  6812. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  6813. $rm = trim((string)$d[$rk]);
  6814. break;
  6815. }
  6816. }
  6817. if ($rm !== '') {
  6818. $remark = $rm;
  6819. break;
  6820. }
  6821. }
  6822. $lineCount = count($lines);
  6823. $hasRemark = $lineCount > 0;
  6824. $supplierGroup = [
  6825. 'company_name' => $cn,
  6826. 'username' => $username,
  6827. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  6828. 'phone' => $ph,
  6829. 'remark' => $remark,
  6830. 'has_remark' => $hasRemark,
  6831. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  6832. 'is_void' => $groupVoid,
  6833. 'lines' => $lines,
  6834. 'line_count' => $lineCount,
  6835. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  6836. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  6837. 'has_total' => $lineCount > 0,
  6838. ];
  6839. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  6840. $supplierGroups[] = $supplierGroup;
  6841. }
  6842. usort($supplierGroups, function ($a, $b) {
  6843. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  6844. return ($a['is_void'] ?? false) ? 1 : -1;
  6845. }
  6846. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  6847. return ($a['is_selected'] ?? false) ? -1 : 1;
  6848. }
  6849. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  6850. });
  6851. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  6852. return [
  6853. 'process_rows' => $processRows,
  6854. 'supplier_groups' => $supplierGroups,
  6855. 'order_total_text' => '',
  6856. 'order_total_has' => false,
  6857. 'selected_company' => $selectedCompany,
  6858. ];
  6859. }
  6860. /**
  6861. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  6862. */
  6863. protected function buildProcessLinesPlain(array $mergeRows): string
  6864. {
  6865. $lines = [];
  6866. $i = 1;
  6867. foreach ($mergeRows as $r) {
  6868. if (!is_array($r)) {
  6869. continue;
  6870. }
  6871. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6872. $dw = trim((string)($r['CDW'] ?? ''));
  6873. $gzl = trim((string)($r['NGZL'] ?? ''));
  6874. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  6875. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  6876. if ($dw !== '') {
  6877. $parts[] = '单位:' . $dw;
  6878. }
  6879. if ($gzl !== '') {
  6880. $parts[] = '工作量:' . $gzl;
  6881. }
  6882. if ($qty !== '') {
  6883. $parts[] = '本次数量:' . $qty;
  6884. }
  6885. $lines[] = implode(' ', $parts);
  6886. $i++;
  6887. }
  6888. return implode("\n", $lines);
  6889. }
  6890. /**
  6891. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  6892. *
  6893. * @return array<string, string>
  6894. */
  6895. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  6896. {
  6897. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  6898. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  6899. }
  6900. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  6901. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  6902. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6903. $cyjmc = '';
  6904. foreach ($mergeRows as $mr) {
  6905. if (!is_array($mr)) {
  6906. continue;
  6907. }
  6908. if ($ccydh === '') {
  6909. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  6910. }
  6911. if ($cyjmc === '') {
  6912. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  6913. }
  6914. }
  6915. if ($pos !== []) {
  6916. $firstPo = $pos[0];
  6917. if (is_array($firstPo)) {
  6918. if ($ccydh === '') {
  6919. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  6920. }
  6921. if ($cyjmc === '') {
  6922. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  6923. }
  6924. }
  6925. }
  6926. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  6927. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  6928. if (is_array($any)) {
  6929. if ($ccydh === '') {
  6930. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  6931. }
  6932. if ($cyjmc === '') {
  6933. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  6934. }
  6935. }
  6936. }
  6937. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  6938. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  6939. $cgymc = '';
  6940. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  6941. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  6942. }
  6943. return [
  6944. 'ccydh' => $ccydh,
  6945. 'cyjmc' => $cyjmc,
  6946. 'cgymc' => $cgymc,
  6947. 'process_lines' => $processLines,
  6948. 'process_lines_html' => '',
  6949. ];
  6950. }
  6951. /**
  6952. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  6953. */
  6954. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  6955. {
  6956. $lines = [];
  6957. if ($ccydh !== '') {
  6958. $lines[] = '订单号:' . $ccydh;
  6959. }
  6960. if ($cyjmc !== '') {
  6961. $lines[] = '印件名称:' . $cyjmc;
  6962. }
  6963. if ($processPlain !== '') {
  6964. $lines[] = $processPlain;
  6965. }
  6966. return implode("\n", $lines);
  6967. }
  6968. /**
  6969. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  6970. *
  6971. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6972. */
  6973. protected function buildPlatformLinksPlain(array $detailLinks): string
  6974. {
  6975. $lines = [];
  6976. $i = 1;
  6977. foreach ($detailLinks as $lk) {
  6978. if (!is_array($lk)) {
  6979. continue;
  6980. }
  6981. $url = trim((string)($lk['url'] ?? ''));
  6982. if ($url === '') {
  6983. continue;
  6984. }
  6985. $label = trim((string)($lk['cgymc'] ?? ''));
  6986. if ($label === '') {
  6987. $label = '工序' . $i;
  6988. }
  6989. $lines[] = $label . ':' . $url;
  6990. $i++;
  6991. }
  6992. return implode("\n", $lines);
  6993. }
  6994. /**
  6995. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  6996. *
  6997. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6998. */
  6999. protected function buildPlatformLinksHtml(array $detailLinks): string
  7000. {
  7001. $parts = [];
  7002. $i = 1;
  7003. foreach ($detailLinks as $lk) {
  7004. if (!is_array($lk)) {
  7005. continue;
  7006. }
  7007. $url = trim((string)($lk['url'] ?? ''));
  7008. if ($url === '') {
  7009. continue;
  7010. }
  7011. $label = trim((string)($lk['cgymc'] ?? ''));
  7012. if ($label === '') {
  7013. $label = '工序' . $i;
  7014. }
  7015. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  7016. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  7017. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  7018. $i++;
  7019. }
  7020. return implode("<br>\n", $parts);
  7021. }
  7022. /**
  7023. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  7024. *
  7025. * @return array<string, mixed>
  7026. */
  7027. protected function loadMailerConfig(): array
  7028. {
  7029. try {
  7030. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  7031. } catch (\Throwable $e) {
  7032. $cfg = [];
  7033. }
  7034. return is_array($cfg) ? $cfg : [];
  7035. }
  7036. protected function loadNotifyTemplateRow(string $scene): ?array
  7037. {
  7038. try {
  7039. $row = Db::table('purchase_sms_template')
  7040. ->where('scene', $scene)
  7041. ->where(function ($q) {
  7042. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  7043. })
  7044. ->order('id', 'asc')
  7045. ->find();
  7046. } catch (\Throwable $e) {
  7047. return null;
  7048. }
  7049. if (!is_array($row) || $row === []) {
  7050. return null;
  7051. }
  7052. return [
  7053. 'title' => trim((string)($row['title'] ?? '')),
  7054. 'content' => trim((string)($row['content'] ?? '')),
  7055. ];
  7056. }
  7057. /**
  7058. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  7059. */
  7060. protected function buildProcessLinesHtml(array $mergeRows): string
  7061. {
  7062. if (count($mergeRows) <= 1) {
  7063. $r = $mergeRows[0] ?? [];
  7064. if (!is_array($r)) {
  7065. return '';
  7066. }
  7067. $gymc = trim((string)($r['CGYMC'] ?? ''));
  7068. $dw = trim((string)($r['CDW'] ?? ''));
  7069. $gzl = trim((string)($r['NGZL'] ?? ''));
  7070. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  7071. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  7072. if ($dw !== '') {
  7073. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  7074. }
  7075. if ($gzl !== '') {
  7076. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  7077. }
  7078. if ($qty !== '') {
  7079. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  7080. }
  7081. return $html;
  7082. }
  7083. $rows = '';
  7084. $i = 1;
  7085. foreach ($mergeRows as $r) {
  7086. if (!is_array($r)) {
  7087. continue;
  7088. }
  7089. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  7090. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  7091. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  7092. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  7093. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  7094. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  7095. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  7096. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  7097. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  7098. $i++;
  7099. }
  7100. if ($rows === '') {
  7101. return '';
  7102. }
  7103. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  7104. . '<thead><tr style="background:#f5f5f5;">'
  7105. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  7106. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  7107. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  7108. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  7109. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  7110. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  7111. }
  7112. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  7113. {
  7114. $sysRq = trim($sysRq);
  7115. if ($sysRq === '') {
  7116. if ($required) {
  7117. $this->error('请选择招标截止日期');
  7118. }
  7119. return '';
  7120. }
  7121. $ts = strtotime($sysRq);
  7122. if ($ts === false || $ts <= 0) {
  7123. $this->error('招标截止日期格式无效');
  7124. }
  7125. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  7126. if (!$allowPast) {
  7127. $ymd = date('Y-m-d', $ts);
  7128. if ($ymd < date('Y-m-d')) {
  7129. $this->error('招标截止日期不能早于今天');
  7130. }
  7131. if ($ts <= time()) {
  7132. $this->error('招标截止时间不能早于当前时间');
  7133. }
  7134. }
  7135. return date('Y-m-d H:i:s', $ts);
  7136. }
  7137. /**
  7138. * 确保 purchase_order.czlyq(类型)存在
  7139. */
  7140. protected function ensurePurchaseOrderCzlyqColumn(): void
  7141. {
  7142. static $done = false;
  7143. if ($done) {
  7144. return;
  7145. }
  7146. $done = true;
  7147. try {
  7148. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  7149. if (empty($cols)) {
  7150. Db::execute(
  7151. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  7152. );
  7153. }
  7154. } catch (\Throwable $e) {
  7155. // ignore
  7156. }
  7157. }
  7158. /**
  7159. * 确保 purchase_order.delivery_deadline 存在
  7160. */
  7161. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  7162. {
  7163. static $done = false;
  7164. if ($done) {
  7165. return;
  7166. }
  7167. $done = true;
  7168. try {
  7169. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  7170. if (empty($cols)) {
  7171. Db::execute(
  7172. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  7173. );
  7174. }
  7175. } catch (\Throwable $e) {
  7176. // ignore
  7177. }
  7178. }
  7179. /**
  7180. * 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
  7181. */
  7182. protected function ensurePurchaseOrderScoreRuleIdColumn(): void
  7183. {
  7184. static $done = false;
  7185. if ($done) {
  7186. return;
  7187. }
  7188. $done = true;
  7189. // 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
  7190. $adds = [
  7191. 'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
  7192. 'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
  7193. 'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
  7194. 'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
  7195. 'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
  7196. ];
  7197. $changed = false;
  7198. foreach ($adds as $col => $ddl) {
  7199. try {
  7200. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  7201. if (!is_array($cols) || $cols === []) {
  7202. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  7203. $changed = true;
  7204. }
  7205. } catch (\Throwable $e) {
  7206. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  7207. }
  7208. }
  7209. if ($changed) {
  7210. $this->clearPurchaseOrderTableFieldsCache();
  7211. }
  7212. }
  7213. /**
  7214. * ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
  7215. */
  7216. protected function clearPurchaseOrderTableFieldsCache(): void
  7217. {
  7218. try {
  7219. $db = (string)Config::get('database.database');
  7220. $key = $db . '.purchase_order';
  7221. $ref = new \ReflectionProperty(\think\db\Query::class, 'info');
  7222. $ref->setAccessible(true);
  7223. $info = $ref->getValue();
  7224. if (is_array($info) && isset($info[$key])) {
  7225. unset($info[$key]);
  7226. $ref->setValue(null, $info);
  7227. }
  7228. } catch (\Throwable $e) {
  7229. }
  7230. try {
  7231. $db = (string)Config::get('database.database');
  7232. $schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
  7233. if (is_file($schemaFile)) {
  7234. @unlink($schemaFile);
  7235. }
  7236. } catch (\Throwable $e) {
  7237. }
  7238. }
  7239. /**
  7240. * @return array<string, bool>
  7241. */
  7242. protected function loadPurchaseOrderColumnSet(): array
  7243. {
  7244. static $set = null;
  7245. if (is_array($set)) {
  7246. return $set;
  7247. }
  7248. $set = [];
  7249. try {
  7250. $cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
  7251. } catch (\Throwable $e) {
  7252. return $set;
  7253. }
  7254. if (!is_array($cols)) {
  7255. return $set;
  7256. }
  7257. foreach ($cols as $c) {
  7258. if (!is_array($c)) {
  7259. continue;
  7260. }
  7261. $f = (string)($c['Field'] ?? $c['field'] ?? '');
  7262. if ($f !== '') {
  7263. $set[$f] = true;
  7264. }
  7265. }
  7266. return $set;
  7267. }
  7268. /**
  7269. * 解析交货截止日期(仅年月日)
  7270. */
  7271. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  7272. {
  7273. $raw = trim($raw);
  7274. if ($raw === '') {
  7275. if ($required) {
  7276. $this->error('请选择交货截止日期');
  7277. }
  7278. return '';
  7279. }
  7280. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  7281. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  7282. } else {
  7283. $ts = strtotime(str_replace('/', '-', $raw));
  7284. if ($ts === false || $ts <= 0) {
  7285. $this->error('交货截止日期格式无效');
  7286. }
  7287. $ymd = date('Y-m-d', $ts);
  7288. }
  7289. if ($ymd < date('Y-m-d')) {
  7290. $this->error('交货截止日期不能早于今天');
  7291. }
  7292. return $ymd;
  7293. }
  7294. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  7295. {
  7296. $s = trim((string)$value);
  7297. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  7298. return '';
  7299. }
  7300. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  7301. return $m[1];
  7302. }
  7303. $ts = strtotime(str_replace('/', '-', $s));
  7304. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  7305. }
  7306. /**
  7307. * @param array{pos?:array} $bundle
  7308. */
  7309. protected function resolveBundleDeliveryDeadline(array $bundle): string
  7310. {
  7311. foreach ($bundle['pos'] ?? [] as $po) {
  7312. if (!is_array($po)) {
  7313. continue;
  7314. }
  7315. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7316. if ($d !== '') {
  7317. return $d;
  7318. }
  7319. }
  7320. return '';
  7321. }
  7322. protected function formatProcuremenSysRqForInput($sysRq): string
  7323. {
  7324. $sr = trim((string)$sysRq);
  7325. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  7326. return '';
  7327. }
  7328. $ts = strtotime($sr);
  7329. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  7330. }
  7331. protected function formatProcuremenSysRqForDisplay($sysRq): string
  7332. {
  7333. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  7334. if ($sr === '') {
  7335. return '—';
  7336. }
  7337. $ts = strtotime($sr);
  7338. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  7339. }
  7340. /**
  7341. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  7342. *
  7343. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  7344. * @return array{ccydh?:string,pos:array,merge_rows:array}
  7345. */
  7346. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  7347. {
  7348. return $bundle;
  7349. }
  7350. /**
  7351. * 写入/更新 purchase_order(单道工序行)
  7352. *
  7353. * @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
  7354. */
  7355. protected function upsertPurchaseOrderFromRow(
  7356. array $row,
  7357. string $sysRqDb,
  7358. $wflowStatus = null,
  7359. ?string $pickTime = null,
  7360. ?array $exists = null,
  7361. ?string $deliveryDeadline = null,
  7362. $scoreRuleId = null
  7363. ): void {
  7364. $ids = $this->extractScydgyRowId($row);
  7365. if (!$this->isValidScydgyRowId($ids)) {
  7366. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  7367. }
  7368. if ($exists === null) {
  7369. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7370. }
  7371. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  7372. $this->ensurePurchaseOrderScoreRuleIdColumn();
  7373. $this->ensurePurchaseOrderCzlyqColumn();
  7374. $data = [
  7375. 'scydgy_id' => $ids,
  7376. 'CCYDH' => $row['CCYDH'] ?? null,
  7377. 'CYJMC' => $row['CYJMC'] ?? null,
  7378. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  7379. 'CDXMC' => $row['CDXMC'] ?? null,
  7380. 'CGYBH' => $row['CGYBH'] ?? null,
  7381. 'CGYMC' => $row['CGYMC'] ?? null,
  7382. 'CDW' => $row['CDW'] ?? null,
  7383. 'czlyq' => $row['czlyq'] ?? null,
  7384. 'NGZL' => $row['NGZL'] ?? null,
  7385. 'CDF' => $row['CDF'] ?? null,
  7386. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  7387. 'MBZ' => $row['MBZ'] ?? null,
  7388. 'bwjg' => $row['bwjg'] ?? null,
  7389. 'iStatus' => $row['iStatus'] ?? null,
  7390. 'dStamp' => $row['dStamp'] ?? null,
  7391. 'dputrecord' => $row['dputrecord'] ?? null,
  7392. 'cywyxm' => $row['cywyxm'] ?? null,
  7393. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  7394. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  7395. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7396. 'sys_rq' => $sysRqDb,
  7397. ];
  7398. // 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
  7399. $qtyUp = trim((string)($data['This_quantity'] ?? ''));
  7400. if ($qtyUp === '') {
  7401. $qtyFallback = $this->resolveProcuremenThisQuantity([
  7402. 'This_quantity' => '',
  7403. 'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
  7404. ]);
  7405. if ($qtyFallback !== '') {
  7406. $data['This_quantity'] = $qtyFallback;
  7407. }
  7408. }
  7409. if ($deliveryDeadline !== null) {
  7410. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  7411. }
  7412. // 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
  7413. $scoreRule = null;
  7414. if (is_array($scoreRuleId)) {
  7415. $scoreRule = $scoreRuleId;
  7416. $scoreRuleId = (int)($scoreRule['id'] ?? 0);
  7417. } else {
  7418. $scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
  7419. }
  7420. if ($scoreRuleId !== null && $scoreRuleId > 0) {
  7421. $poCols = $this->loadPurchaseOrderColumnSet();
  7422. if (!empty($poCols['score_rule_id'])) {
  7423. $data['score_rule_id'] = $scoreRuleId;
  7424. if (is_array($scoreRule)) {
  7425. if (!empty($poCols['score_rule_name'])) {
  7426. $data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
  7427. }
  7428. if (!empty($poCols['score_quality_weight'])) {
  7429. $data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
  7430. }
  7431. if (!empty($poCols['score_price_weight'])) {
  7432. $data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
  7433. }
  7434. if (!empty($poCols['score_lead_weight'])) {
  7435. $data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
  7436. }
  7437. }
  7438. }
  7439. }
  7440. if ($wflowStatus !== null && $wflowStatus !== '') {
  7441. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  7442. }
  7443. if ($pickTime !== null && $pickTime !== '') {
  7444. $data['pick_time'] = $pickTime;
  7445. $data['pick_company_name'] = '';
  7446. }
  7447. if ($exists) {
  7448. $upd = $data;
  7449. unset($upd['scydgy_id']);
  7450. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  7451. } else {
  7452. $data['createtime'] = date('Y-m-d H:i:s');
  7453. Db::table('purchase_order')->insert($data);
  7454. }
  7455. }
  7456. /**
  7457. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  7458. *
  7459. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  7460. */
  7461. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
  7462. {
  7463. $toDb = function ($value) {
  7464. if ($value === null) {
  7465. return null;
  7466. }
  7467. if (is_scalar($value)) {
  7468. return $value;
  7469. }
  7470. return json_encode($value, JSON_UNESCAPED_UNICODE);
  7471. };
  7472. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7473. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7474. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7475. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  7476. if ($username === '') {
  7477. $username = $this->resolveCustomerContactName($phone, $companyName);
  7478. }
  7479. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  7480. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  7481. }
  7482. if ($requirePhone && $phone === '') {
  7483. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  7484. }
  7485. $detailLinks = [];
  7486. foreach ($mergeRows as $row) {
  7487. if (!is_array($row)) {
  7488. continue;
  7489. }
  7490. $sid = $this->extractScydgyRowId($row);
  7491. $detailId = 0;
  7492. if ($skipExisting) {
  7493. try {
  7494. $existsQuery = Db::table('purchase_order_detail')
  7495. ->where('scydgy_id', $sid)
  7496. ->where('company_name', $companyName);
  7497. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  7498. $exists = $existsQuery->find();
  7499. } catch (\Throwable $e) {
  7500. $exists = null;
  7501. }
  7502. if (is_array($exists)) {
  7503. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  7504. }
  7505. }
  7506. if ($detailId <= 0) {
  7507. $one = [
  7508. 'scydgy_id' => $toDb($sid),
  7509. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  7510. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  7511. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  7512. 'username' => $username !== '' ? $username : null,
  7513. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  7514. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  7515. 'createtime' => date('Y-m-d H:i:s'),
  7516. 'status' => ProcuremenStatus::POD_UNPICKED,
  7517. 'status_name' => '未提交',
  7518. ];
  7519. Db::table('purchase_order_detail')->insert($one);
  7520. $detailId = (int)Db::getLastInsID();
  7521. }
  7522. $mprocUrl = '';
  7523. if ($buildMobileLinks && $detailId > 0) {
  7524. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  7525. }
  7526. $detailLinks[] = [
  7527. 'detail_id' => $detailId,
  7528. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  7529. 'url' => $mprocUrl,
  7530. ];
  7531. }
  7532. $this->invalidatePickHiddenScydgyCache();
  7533. return $detailLinks;
  7534. }
  7535. /**
  7536. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  7537. * @return array<string, mixed>
  7538. */
  7539. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks, string $emailTplScene = 'review_email'): array
  7540. {
  7541. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7542. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7543. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7544. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  7545. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  7546. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  7547. $isMerge = !empty($ctx['is_merge']);
  7548. $contactName = trim((string)($c['username'] ?? ''));
  7549. if ($contactName === '') {
  7550. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  7551. }
  7552. $notifyVars = [
  7553. 'company_name' => $companyName,
  7554. 'contact_name' => $contactName,
  7555. 'phone' => $phone,
  7556. 'email' => $toEmail,
  7557. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  7558. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  7559. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  7560. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  7561. 'deadline' => (string)($ctx['deadline'] ?? ''),
  7562. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  7563. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  7564. 'order_type' => (string)($ctx['order_type'] ?? ''),
  7565. 'score_weights' => (string)($ctx['score_weights'] ?? ''),
  7566. 'platform_url' => $platformUrl,
  7567. 'platform_links' => $platformLinksPlain,
  7568. 'platform_links_html' => $platformLinksHtml,
  7569. ];
  7570. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  7571. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  7572. $mailPlain = $this->renderNotifyTemplate($emailTplScene, $notifyVars);
  7573. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  7574. return [
  7575. 'company_name' => $companyName,
  7576. 'phone' => $phone,
  7577. 'email' => $toEmail,
  7578. 'sms_content' => $smsContent,
  7579. 'mail_plain' => $mailPlain,
  7580. 'mail_body' => $mailBody,
  7581. 'notify_vars' => $notifyVars,
  7582. 'detail_links' => $detailLinks,
  7583. ];
  7584. }
  7585. /**
  7586. * @param array<string, mixed> $chosen
  7587. * @param array<int, array<string, mixed>> $mergeRows
  7588. * @param array{ccydh:string, pos:array} $bundle
  7589. */
  7590. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue', string $emailTplScene = 'review_email'): void
  7591. {
  7592. if (!$sendSms && !$sendEmail) {
  7593. return;
  7594. }
  7595. $companyName = trim((string)($chosen['name'] ?? ''));
  7596. $phone = trim((string)($chosen['phone'] ?? ''));
  7597. $toEmail = trim((string)($chosen['email'] ?? ''));
  7598. if ($companyName === '') {
  7599. throw new \Exception('供应商名称无效');
  7600. }
  7601. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  7602. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  7603. }
  7604. if ($sendSms && $phone === '') {
  7605. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  7606. }
  7607. $sids = [];
  7608. foreach ($mergeRows as $mr) {
  7609. if (!is_array($mr)) {
  7610. continue;
  7611. }
  7612. $sid = $this->extractScydgyRowId($mr);
  7613. if ($this->isValidScydgyRowId($sid)) {
  7614. $sids[$sid] = true;
  7615. }
  7616. }
  7617. if ($sids === []) {
  7618. throw new \Exception('未找到工序行,无法发送通知');
  7619. }
  7620. $sysRqNotify = '';
  7621. $pos = $bundle['pos'] ?? [];
  7622. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7623. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  7624. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  7625. $ts = strtotime($sr);
  7626. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  7627. }
  7628. }
  7629. try {
  7630. $detailsQuery = Db::table('purchase_order_detail')
  7631. ->where('scydgy_id', 'in', array_keys($sids))
  7632. ->where('company_name', $companyName);
  7633. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7634. $details = $detailsQuery->order('id', 'asc')->select();
  7635. } catch (\Throwable $e) {
  7636. $details = [];
  7637. }
  7638. if (!is_array($details) || $details === []) {
  7639. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  7640. try {
  7641. $detailsQuery = Db::table('purchase_order_detail')
  7642. ->where('scydgy_id', 'in', array_keys($sids))
  7643. ->where('company_name', $companyName);
  7644. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7645. $details = $detailsQuery->order('id', 'asc')->select();
  7646. } catch (\Throwable $e) {
  7647. $details = [];
  7648. }
  7649. }
  7650. if (!is_array($details) || $details === []) {
  7651. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  7652. }
  7653. $detailLinks = [];
  7654. foreach ($details as $d) {
  7655. if (!is_array($d)) {
  7656. continue;
  7657. }
  7658. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  7659. if ($detailId <= 0) {
  7660. continue;
  7661. }
  7662. $sid = (int)($d['scydgy_id'] ?? 0);
  7663. $gymc = '';
  7664. foreach ($mergeRows as $mr) {
  7665. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  7666. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  7667. break;
  7668. }
  7669. }
  7670. $detailLinks[] = [
  7671. 'detail_id' => $detailId,
  7672. 'cgymc' => $gymc,
  7673. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  7674. ];
  7675. }
  7676. if ($detailLinks === []) {
  7677. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  7678. }
  7679. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  7680. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  7681. $orderTypeCtx = $this->resolveIssueNotifyOrderTypeFromBundle($bundle);
  7682. $ctx['order_type'] = (string)($orderTypeCtx['order_type'] ?? '');
  7683. $ctx['score_weights'] = (string)($orderTypeCtx['score_weights'] ?? '');
  7684. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks, $emailTplScene);
  7685. $notifyBundle['email_log_scene'] = $emailLogScene;
  7686. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  7687. $poIdLog = 0;
  7688. $pos = $bundle['pos'] ?? [];
  7689. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7690. $poIdLog = (int)($pos[0]['id'] ?? 0);
  7691. }
  7692. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  7693. if ($sendEmail) {
  7694. $mailTplRow = $this->loadNotifyTemplateRow($emailTplScene);
  7695. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  7696. throw new \Exception($this->notifyTemplateMissingMessage($emailTplScene));
  7697. }
  7698. $mailSubject = $this->resolveProcuremenEmailSubject($emailTplScene);
  7699. $mailConfig = $this->loadMailerConfig();
  7700. if (!$this->isProcuremenNotifyDryRun()) {
  7701. if (empty($mailConfig['host'])) {
  7702. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  7703. }
  7704. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  7705. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  7706. }
  7707. }
  7708. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  7709. }
  7710. if ($sendSms) {
  7711. $this->issueSendSupplierSms($notifyBundle);
  7712. }
  7713. }
  7714. /**
  7715. * @param array<int, array<string, mixed>> $quoteGroups
  7716. * @return array<int, array<string, mixed>>
  7717. */
  7718. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  7719. {
  7720. $names = [];
  7721. if (is_string($companiesJson) && $companiesJson !== '') {
  7722. $decoded = json_decode($companiesJson, true);
  7723. if (is_array($decoded)) {
  7724. foreach ($decoded as $nm) {
  7725. $nm = trim((string)$nm);
  7726. if ($nm !== '') {
  7727. $names[] = $nm;
  7728. }
  7729. }
  7730. }
  7731. }
  7732. $names = array_values(array_unique($names));
  7733. if ($names === [] && $selectedCompany !== '') {
  7734. $names = [$selectedCompany];
  7735. }
  7736. if ($names === []) {
  7737. return $quoteGroups;
  7738. }
  7739. $targets = [];
  7740. foreach ($quoteGroups as $g) {
  7741. if (!is_array($g)) {
  7742. continue;
  7743. }
  7744. $cn = trim((string)($g['name'] ?? ''));
  7745. if ($cn !== '' && in_array($cn, $names, true)) {
  7746. $targets[] = $g;
  7747. }
  7748. }
  7749. return $targets;
  7750. }
  7751. /**
  7752. * @return array{pos:array, merge_rows:array, bundle:array}
  7753. */
  7754. protected function loadAuditResendBundle(string $scydgyId): array
  7755. {
  7756. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7757. $pos = $bundle['pos'];
  7758. $mergeRows = $bundle['merge_rows'];
  7759. if ($pos === [] || $mergeRows === []) {
  7760. $this->error('该订单不在待确认供应商状态');
  7761. }
  7762. $sysRqDb = '';
  7763. if (isset($pos[0]) && is_array($pos[0])) {
  7764. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  7765. }
  7766. foreach ($pos as $i => $poRow) {
  7767. if (is_array($pos[$i]) && $sysRqDb !== '') {
  7768. $pos[$i]['sys_rq'] = $sysRqDb;
  7769. }
  7770. }
  7771. $bundle['pos'] = $pos;
  7772. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  7773. }
  7774. /**
  7775. * @param array<int, array<string, mixed>> $targets
  7776. */
  7777. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  7778. {
  7779. if ($targets === []) {
  7780. $this->error('未找到可通知的供应商');
  7781. }
  7782. $notifyErrors = [];
  7783. try {
  7784. $this->notifyDryRunPreview = [];
  7785. foreach ($targets as $g) {
  7786. if (!is_array($g)) {
  7787. continue;
  7788. }
  7789. $cname = trim((string)($g['name'] ?? ''));
  7790. if ($cname === '') {
  7791. continue;
  7792. }
  7793. $chosen = [
  7794. 'name' => $cname,
  7795. 'company_name' => $cname,
  7796. 'email' => trim((string)($g['email'] ?? '')),
  7797. 'phone' => trim((string)($g['phone'] ?? '')),
  7798. 'username' => trim((string)($g['username'] ?? '')),
  7799. ];
  7800. try {
  7801. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  7802. } catch (\Throwable $e) {
  7803. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7804. }
  7805. }
  7806. } catch (\Throwable $e) {
  7807. $this->error('通知发送失败:' . $e->getMessage());
  7808. }
  7809. if ($notifyErrors !== []) {
  7810. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  7811. }
  7812. if ($this->isProcuremenNotifyDryRun()) {
  7813. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  7814. 'notify_dry_run' => true,
  7815. 'notify_preview' => $this->notifyDryRunPreview,
  7816. ]);
  7817. }
  7818. $nameLabels = [];
  7819. foreach ($targets as $g) {
  7820. if (!is_array($g)) {
  7821. continue;
  7822. }
  7823. $n = trim((string)($g['name'] ?? ''));
  7824. if ($n !== '') {
  7825. $nameLabels[] = $n;
  7826. }
  7827. }
  7828. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  7829. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  7830. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  7831. $seenLogSid = [];
  7832. foreach ($bundle['pos'] ?? [] as $poRow) {
  7833. if (!is_array($poRow)) {
  7834. continue;
  7835. }
  7836. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7837. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  7838. continue;
  7839. }
  7840. $seenLogSid[$sid] = true;
  7841. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7842. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7843. }
  7844. if ($seenLogSid === []) {
  7845. foreach ($mergeRows as $mr) {
  7846. if (!is_array($mr)) {
  7847. continue;
  7848. }
  7849. $sid = $this->extractScydgyRowId($mr);
  7850. if ($this->isValidScydgyRowId($sid)) {
  7851. $this->addOrderLog($sid, $logAction, $logMsg, null);
  7852. break;
  7853. }
  7854. }
  7855. }
  7856. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  7857. }
  7858. /**
  7859. * 协助下发 — 发送短信(一家供应商)
  7860. *
  7861. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  7862. */
  7863. protected function issueSendSupplierSms(array $bundle): void
  7864. {
  7865. $companyName = (string)($bundle['company_name'] ?? '');
  7866. $phone = (string)($bundle['phone'] ?? '');
  7867. $smsContent = (string)($bundle['sms_content'] ?? '');
  7868. $this->logIssueNotifyDebug('短信', [
  7869. 'company' => $companyName,
  7870. 'phone' => $phone,
  7871. 'sms_content' => $smsContent,
  7872. ]);
  7873. if ($this->isProcuremenNotifyDryRun()) {
  7874. $this->recordNotifyDryRunPreview([
  7875. 'scene' => 'issue_sms',
  7876. 'company_name' => $companyName,
  7877. 'phone' => $phone,
  7878. 'sms_content' => $smsContent,
  7879. ]);
  7880. return;
  7881. }
  7882. $this->smsbao($phone, $smsContent);
  7883. }
  7884. /**
  7885. * 协助下发 — 发送邮件(一家供应商)
  7886. *
  7887. * @param array<string, mixed> $bundle
  7888. * @param array<string, mixed> $mailConfig
  7889. */
  7890. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  7891. {
  7892. $companyName = (string)($bundle['company_name'] ?? '');
  7893. $toEmail = (string)($bundle['email'] ?? '');
  7894. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  7895. $mailBody = (string)($bundle['mail_body'] ?? '');
  7896. $this->logIssueNotifyDebug('邮件', [
  7897. 'company' => $companyName,
  7898. 'email' => $toEmail,
  7899. 'mail_subject' => $mailSubject,
  7900. 'mail_body' => $mailPlain,
  7901. ]);
  7902. if ($this->isProcuremenNotifyDryRun()) {
  7903. $this->recordNotifyDryRunPreview([
  7904. 'scene' => 'issue_email',
  7905. 'company_name' => $companyName,
  7906. 'email' => $toEmail,
  7907. 'mail_subject' => $mailSubject,
  7908. 'mail_body' => $mailPlain,
  7909. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  7910. 'notify_vars' => $bundle['notify_vars'] ?? [],
  7911. 'detail_links' => $bundle['detail_links'] ?? [],
  7912. ]);
  7913. return;
  7914. }
  7915. $mail = new PHPMailer(true);
  7916. $mail->isSMTP();
  7917. $mail->Host = $mailConfig['host'];
  7918. $mail->SMTPAuth = true;
  7919. $mail->Username = $mailConfig['addr'];
  7920. $mail->Password = $mailConfig['pass'];
  7921. $mail->SMTPSecure = $mailConfig['security'];
  7922. $mail->Port = $mailConfig['port'];
  7923. $mail->CharSet = $mailConfig['charset'];
  7924. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  7925. $mail->addAddress($toEmail, $companyName);
  7926. $mail->isHTML(true);
  7927. $mail->Subject = $mailSubject;
  7928. $mail->Body = $mailBody;
  7929. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  7930. $sendOk = true;
  7931. $failReason = '';
  7932. try {
  7933. $mail->send();
  7934. } catch (\Throwable $e) {
  7935. $sendOk = false;
  7936. $failReason = $e->getMessage();
  7937. $this->persistEmailSendLog([
  7938. 'from_email' => $fromEmail,
  7939. 'to_email' => $toEmail,
  7940. 'send_time' => date('Y-m-d H:i:s'),
  7941. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7942. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7943. 'company_name' => $companyName,
  7944. 'mail_subject' => $mailSubject,
  7945. 'status' => 0,
  7946. 'fail_reason' => $failReason,
  7947. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7948. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7949. ]);
  7950. throw $e;
  7951. }
  7952. $this->persistEmailSendLog([
  7953. 'from_email' => $fromEmail,
  7954. 'to_email' => $toEmail,
  7955. 'send_time' => date('Y-m-d H:i:s'),
  7956. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7957. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7958. 'company_name' => $companyName,
  7959. 'mail_subject' => $mailSubject,
  7960. 'status' => 1,
  7961. 'fail_reason' => '',
  7962. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7963. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7964. ]);
  7965. }
  7966. /**
  7967. * 下发通知:解析订单类型名称与评分比例文案
  7968. *
  7969. * @param array<string, mixed> $bundle
  7970. * @return array{order_type:string,score_weights:string}
  7971. */
  7972. protected function resolveIssueNotifyOrderTypeFromBundle(array $bundle): array
  7973. {
  7974. $orderType = '';
  7975. $scoreWeights = '';
  7976. $rule = null;
  7977. if (!empty($bundle['score_rule']) && is_array($bundle['score_rule'])) {
  7978. $rule = $bundle['score_rule'];
  7979. }
  7980. $pos = $bundle['pos'] ?? [];
  7981. $po0 = (is_array($pos) && isset($pos[0]) && is_array($pos[0])) ? $pos[0] : null;
  7982. if ($rule === null && is_array($po0)) {
  7983. $ruleId = (int)($po0['score_rule_id'] ?? 0);
  7984. if ($ruleId > 0) {
  7985. try {
  7986. $rule = ProcuremenSupplierScore::getRuleById($ruleId);
  7987. } catch (\Throwable $e) {
  7988. $rule = null;
  7989. }
  7990. }
  7991. if (!is_array($rule) || (int)($rule['id'] ?? 0) <= 0) {
  7992. $qw = (int)($po0['score_quality_weight'] ?? 0);
  7993. $pw = (int)($po0['score_price_weight'] ?? 0);
  7994. $lw = (int)($po0['score_lead_weight'] ?? 0);
  7995. if ($qw > 0 || $pw > 0 || $lw > 0) {
  7996. $rule = [
  7997. 'name' => trim((string)($po0['score_rule_name'] ?? '')),
  7998. 'quality_weight' => $qw,
  7999. 'price_weight' => $pw,
  8000. 'lead_weight' => $lw,
  8001. ];
  8002. }
  8003. }
  8004. }
  8005. if (is_array($rule)) {
  8006. $orderType = trim((string)($rule['name'] ?? ''));
  8007. $scoreWeights = $this->formatScoreRuleWeightsText($rule);
  8008. }
  8009. if ($orderType === '' && is_array($po0)) {
  8010. $orderType = trim((string)($po0['score_rule_name'] ?? ''));
  8011. }
  8012. return [
  8013. 'order_type' => $orderType,
  8014. 'score_weights' => $scoreWeights,
  8015. ];
  8016. }
  8017. /**
  8018. * 评分比例文案:质量30%、价格50%、交货20%
  8019. *
  8020. * @param array{quality_weight?:mixed,price_weight?:mixed,lead_weight?:mixed} $rule
  8021. */
  8022. protected function formatScoreRuleWeightsText(array $rule): string
  8023. {
  8024. $parts = [];
  8025. $qw = max(0, (float)($rule['quality_weight'] ?? 0));
  8026. $pw = max(0, (float)($rule['price_weight'] ?? 0));
  8027. $lw = max(0, (float)($rule['lead_weight'] ?? 0));
  8028. $fmt = static function ($n) {
  8029. $s = rtrim(rtrim(sprintf('%.2F', (float)$n), '0'), '.');
  8030. return $s === '' ? '0' : $s;
  8031. };
  8032. if ($qw > 0) {
  8033. $parts[] = '质量' . $fmt($qw) . '%';
  8034. }
  8035. if ($pw > 0) {
  8036. $parts[] = '价格' . $fmt($pw) . '%';
  8037. }
  8038. if ($lw > 0) {
  8039. $parts[] = '交货' . $fmt($lw) . '%';
  8040. }
  8041. return implode('、', $parts);
  8042. }
  8043. /**
  8044. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  8045. *
  8046. * @param array<int, array<string, mixed>> $mergeRows
  8047. * @return array<string, mixed>
  8048. */
  8049. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  8050. {
  8051. $head = $mergeRows[0] ?? [];
  8052. $isMerge = count($mergeRows) > 1;
  8053. return [
  8054. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  8055. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  8056. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  8057. 'is_merge' => $isMerge,
  8058. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  8059. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  8060. 'deadline' => $sysRqNotify,
  8061. 'order_type' => '',
  8062. 'score_weights' => '',
  8063. ];
  8064. }
  8065. /**
  8066. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  8067. *
  8068. * @param array<string, mixed> $data
  8069. */
  8070. protected function logIssueNotifyDebug(string $type, array $data): void
  8071. {
  8072. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  8073. return;
  8074. }
  8075. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  8076. }
  8077. protected function ensurePurchaseEmailSendLogTableOnce(): void
  8078. {
  8079. try {
  8080. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  8081. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  8082. return;
  8083. } catch (\Throwable $e) {
  8084. }
  8085. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  8086. if (is_file($sqlFile)) {
  8087. $sql = file_get_contents($sqlFile);
  8088. if (is_string($sql) && $sql !== '') {
  8089. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  8090. $stmt = trim($stmt);
  8091. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  8092. continue;
  8093. }
  8094. try {
  8095. Db::execute($stmt);
  8096. } catch (\Throwable $ignore) {
  8097. }
  8098. }
  8099. }
  8100. }
  8101. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  8102. }
  8103. /**
  8104. * @param array<string, mixed> $row
  8105. */
  8106. protected function persistEmailSendLog(array $row): void
  8107. {
  8108. try {
  8109. $this->ensurePurchaseEmailSendLogTableOnce();
  8110. } catch (\Throwable $e) {
  8111. return;
  8112. }
  8113. list($adminId, $adminName) = $this->GetUseName();
  8114. $cut = function ($s, $max) {
  8115. $s = (string)$s;
  8116. if (function_exists('mb_substr')) {
  8117. return mb_substr($s, 0, $max, 'UTF-8');
  8118. }
  8119. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  8120. };
  8121. $data = [
  8122. 'from_email' => $cut($row['from_email'] ?? '', 128),
  8123. 'to_email' => $cut($row['to_email'] ?? '', 128),
  8124. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  8125. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  8126. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  8127. 'company_name' => $cut($row['company_name'] ?? '', 128),
  8128. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  8129. 'status' => !empty($row['status']) ? 1 : 0,
  8130. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  8131. 'admin_id' => (int)$adminId,
  8132. 'admin_name' => $cut($adminName, 64),
  8133. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  8134. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  8135. 'createtime' => date('Y-m-d H:i:s'),
  8136. ];
  8137. try {
  8138. Db::table('purchase_email_send_log')->insert($data);
  8139. } catch (\Throwable $e) {
  8140. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  8141. }
  8142. }
  8143. protected function formatEmailLogSceneText(string $scene): string
  8144. {
  8145. $map = [
  8146. 'pick_issue' => '初选下发',
  8147. 'audit_resend' => '确认页重发',
  8148. 'rfq_salesman' => '询价通知业务员',
  8149. 'rfq_supplier' => '供应商询价通知',
  8150. ];
  8151. return $map[$scene] ?? $scene;
  8152. }
  8153. /**
  8154. * 邮件发送日志列表
  8155. */
  8156. public function emailLog()
  8157. {
  8158. $this->relationSearch = false;
  8159. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  8160. $this->request->filter(['strip_tags', 'trim']);
  8161. $bakModel = $this->model;
  8162. $this->model = new \app\admin\model\Purchaseemailsendlog;
  8163. if ($this->request->isAjax()) {
  8164. $this->ensurePurchaseEmailSendLogTableOnce();
  8165. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  8166. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  8167. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  8168. $list = $this->model
  8169. ->where($where)
  8170. ->order($sortField, $orderDir)
  8171. ->paginate($limit);
  8172. $rows = [];
  8173. foreach ($list->items() as $item) {
  8174. $row = is_array($item) ? $item : $item->toArray();
  8175. $scene = trim((string)($row['scene'] ?? ''));
  8176. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  8177. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  8178. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  8179. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  8180. $rows[] = $row;
  8181. }
  8182. $this->model = $bakModel;
  8183. return json(['total' => $list->total(), 'rows' => $rows]);
  8184. }
  8185. $this->model = $bakModel;
  8186. return $this->view->fetch('procuremen/emaillog');
  8187. }
  8188. /**
  8189. * 协助下发弹窗(选多家供应商并通知)
  8190. */
  8191. public function pickReview()
  8192. {
  8193. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  8194. $this->error(__('You have no permission'));
  8195. }
  8196. if ($this->request->isPost()) {
  8197. $this->error('请使用弹窗内「确认下发」提交');
  8198. }
  8199. $this->view->assign('pickMode', 1);
  8200. $this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
  8201. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  8202. }
  8203. /**
  8204. * 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
  8205. */
  8206. protected function ensurePurchaseOrderNotifySalesmanColumn(): void
  8207. {
  8208. static $done = false;
  8209. if ($done) {
  8210. return;
  8211. }
  8212. $done = true;
  8213. try {
  8214. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'notify_salesman'");
  8215. if (empty($cols)) {
  8216. Db::execute(
  8217. "ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
  8218. );
  8219. } else {
  8220. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  8221. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
  8222. Db::execute(
  8223. "ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
  8224. );
  8225. }
  8226. }
  8227. } catch (\Throwable $e) {
  8228. // ignore
  8229. }
  8230. }
  8231. /**
  8232. * 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
  8233. */
  8234. protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
  8235. {
  8236. static $done = false;
  8237. if ($done) {
  8238. return;
  8239. }
  8240. $done = true;
  8241. try {
  8242. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
  8243. if (empty($cols)) {
  8244. Db::execute(
  8245. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
  8246. );
  8247. }
  8248. } catch (\Throwable $e) {
  8249. // ignore
  8250. }
  8251. try {
  8252. $cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
  8253. if (empty($cols2)) {
  8254. Db::execute(
  8255. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
  8256. );
  8257. }
  8258. } catch (\Throwable $e) {
  8259. // ignore
  8260. }
  8261. }
  8262. /**
  8263. * 确保「采购确认通过/未通过」邮箱模版存在(正文同短信,末尾加平台链接)
  8264. */
  8265. protected function ensureConfirmResultEmailTemplates(): void
  8266. {
  8267. static $done = false;
  8268. if ($done) {
  8269. return;
  8270. }
  8271. $done = true;
  8272. $now = date('Y-m-d H:i:s');
  8273. $seeds = [
  8274. 'confirm_ok_email' => [
  8275. 'title' => '采购确认结果:已通过',
  8276. 'content' => "【可集达】您好,{company_name}:\n\n您参与的外发加工订单采购确认结果:已通过。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  8277. 'remark' => '审批通过-中标供应商邮箱通知;模版名称作邮件主题',
  8278. ],
  8279. 'confirm_fail_email' => [
  8280. 'title' => '采购确认结果:未通过',
  8281. 'content' => "【可集达】您好,{company_name}:\n\n您参与的外发加工订单采购确认结果:未通过。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  8282. 'remark' => '审批通过-未中标供应商邮箱通知;模版名称作邮件主题',
  8283. ],
  8284. ];
  8285. try {
  8286. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8287. } catch (\Throwable $e) {
  8288. return;
  8289. }
  8290. $colNames = [];
  8291. foreach ($cols as $c) {
  8292. if (!is_array($c)) {
  8293. continue;
  8294. }
  8295. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8296. if ($n !== '') {
  8297. $colNames[$n] = true;
  8298. }
  8299. }
  8300. foreach ($seeds as $scene => $seed) {
  8301. try {
  8302. $row = Db::table('purchase_sms_template')->where('scene', $scene)->find();
  8303. } catch (\Throwable $e) {
  8304. continue;
  8305. }
  8306. if (is_array($row) && $row !== []) {
  8307. continue;
  8308. }
  8309. $data = [
  8310. 'scene' => $scene,
  8311. 'title' => $seed['title'],
  8312. 'content' => $seed['content'],
  8313. 'remark' => $seed['remark'],
  8314. 'status' => 1,
  8315. ];
  8316. if (isset($colNames['updatetime'])) {
  8317. $data['updatetime'] = $now;
  8318. }
  8319. if (isset($colNames['createtime'])) {
  8320. $data['createtime'] = $now;
  8321. }
  8322. try {
  8323. Db::table('purchase_sms_template')->insert($data);
  8324. } catch (\Throwable $e) {
  8325. // ignore
  8326. }
  8327. }
  8328. }
  8329. /**
  8330. * 确保「供应商询价通知」邮箱模版存在(查询询价-询价/发邮件;可在短信模版配置中修改)
  8331. */
  8332. protected function ensureRfqSupplierEmailTemplate(): void
  8333. {
  8334. static $done = false;
  8335. if ($done) {
  8336. return;
  8337. }
  8338. $done = true;
  8339. $content = "您好,{company_name}:\n\n"
  8340. . "您有新的协助采购询价需求,请登录平台查看并处理。\n\n"
  8341. . "需求编号:{ccydh}\n"
  8342. . "印件名称:{cyjmc}\n"
  8343. . "{process_lines}\n\n"
  8344. . "请在 {deadline} 前完成回复。\n\n"
  8345. . "平台链接:{platform_url}\n";
  8346. try {
  8347. $row = Db::table('purchase_sms_template')
  8348. ->where('scene', 'rfq_supplier_email')
  8349. ->find();
  8350. } catch (\Throwable $e) {
  8351. return;
  8352. }
  8353. $now = date('Y-m-d H:i:s');
  8354. if (is_array($row) && $row !== []) {
  8355. return;
  8356. }
  8357. try {
  8358. $data = [
  8359. 'scene' => 'rfq_supplier_email',
  8360. 'title' => '供应商询价通知',
  8361. 'content' => $content,
  8362. 'remark' => '查询询价-询价/发邮件通知供应商;模版名称作邮件主题',
  8363. 'status' => 1,
  8364. ];
  8365. try {
  8366. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8367. } catch (\Throwable $e) {
  8368. $cols = [];
  8369. }
  8370. $colNames = [];
  8371. foreach ($cols as $c) {
  8372. if (!is_array($c)) {
  8373. continue;
  8374. }
  8375. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8376. if ($n !== '') {
  8377. $colNames[$n] = true;
  8378. }
  8379. }
  8380. if (isset($colNames['updatetime'])) {
  8381. $data['updatetime'] = $now;
  8382. }
  8383. if (isset($colNames['createtime'])) {
  8384. $data['createtime'] = $now;
  8385. }
  8386. Db::table('purchase_sms_template')->insert($data);
  8387. } catch (\Throwable $e) {
  8388. // ignore
  8389. }
  8390. }
  8391. /**
  8392. * 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
  8393. */
  8394. protected function ensureRfqSalesmanEmailTemplate(): void
  8395. {
  8396. static $done = false;
  8397. if ($done) {
  8398. return;
  8399. }
  8400. $done = true;
  8401. $content = "您好,{contact_name}:\n\n"
  8402. . "有新的协助采购询价需求,请知悉。\n"
  8403. . "印件名称:{cyjmc}\n"
  8404. . "工序名称:{cgymc}\n"
  8405. . "本次数量:{this_quantity}\n"
  8406. . "供应商报价:\n{supplier_quotes}\n"
  8407. . "需求发起人:{cywyxm}\n";
  8408. try {
  8409. $row = Db::table('purchase_sms_template')
  8410. ->where('scene', 'rfq_salesman_email')
  8411. ->find();
  8412. } catch (\Throwable $e) {
  8413. return;
  8414. }
  8415. $now = date('Y-m-d H:i:s');
  8416. if (is_array($row) && $row !== []) {
  8417. $old = (string)($row['content'] ?? '');
  8418. // 仍用旧的「供应商:{supplier_name}」或没有报价占位符时,补上单价表格
  8419. $needMigrate = (strpos($old, '{supplier_quotes}') === false)
  8420. || (strpos($old, '供应商:{supplier_name}') !== false);
  8421. if ($needMigrate) {
  8422. $data = ['content' => $content];
  8423. if (trim((string)($row['title'] ?? '')) === '' || trim((string)($row['title'] ?? '')) === '询价通知') {
  8424. $data['title'] = '业务员询价通知';
  8425. }
  8426. try {
  8427. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
  8428. if (!empty($cols)) {
  8429. $data['updatetime'] = $now;
  8430. }
  8431. } catch (\Throwable $e) {
  8432. }
  8433. try {
  8434. Db::table('purchase_sms_template')
  8435. ->where('id', (int)($row['id'] ?? 0))
  8436. ->update($data);
  8437. } catch (\Throwable $e) {
  8438. }
  8439. }
  8440. return;
  8441. }
  8442. try {
  8443. $data = [
  8444. 'scene' => 'rfq_salesman_email',
  8445. 'title' => '业务员询价通知',
  8446. 'content' => $content,
  8447. 'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
  8448. 'status' => 1,
  8449. ];
  8450. try {
  8451. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8452. } catch (\Throwable $e) {
  8453. $cols = [];
  8454. }
  8455. $colNames = [];
  8456. foreach ($cols as $c) {
  8457. if (!is_array($c)) {
  8458. continue;
  8459. }
  8460. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8461. if ($n !== '') {
  8462. $colNames[$n] = true;
  8463. }
  8464. }
  8465. if (isset($colNames['updatetime'])) {
  8466. $data['updatetime'] = $now;
  8467. }
  8468. if (isset($colNames['createtime'])) {
  8469. $data['createtime'] = $now;
  8470. }
  8471. Db::table('purchase_sms_template')->insert($data);
  8472. } catch (\Throwable $e) {
  8473. // ignore
  8474. }
  8475. }
  8476. /**
  8477. * 通知业务员邮件:供应商报价明细行(仅名称+单价)
  8478. *
  8479. * @return array<int, array{name:string,amount:string}>
  8480. */
  8481. protected function loadRfqSalesmanSupplierQuoteRows(int $sid, string $supplierRaw = ''): array
  8482. {
  8483. $list = [];
  8484. $seen = [];
  8485. try {
  8486. $rows = Db::table('purchase_order_detail')
  8487. ->where('scydgy_id', $sid)
  8488. ->field('company_name,amount')
  8489. ->order('id', 'asc')
  8490. ->select();
  8491. if (is_array($rows)) {
  8492. foreach ($rows as $r) {
  8493. if (!is_array($r)) {
  8494. continue;
  8495. }
  8496. $cn = trim((string)($r['company_name'] ?? ''));
  8497. if ($cn === '' || isset($seen[$cn])) {
  8498. continue;
  8499. }
  8500. $seen[$cn] = true;
  8501. $amount = trim((string)($r['amount'] ?? ''));
  8502. $list[] = [
  8503. 'name' => $cn,
  8504. 'amount' => $amount !== '' ? $amount : '未报价',
  8505. ];
  8506. }
  8507. }
  8508. } catch (\Throwable $e) {
  8509. }
  8510. if ($list === [] && $supplierRaw !== '') {
  8511. foreach ($this->splitRfqSalesmanNames($supplierRaw) as $cn) {
  8512. if ($cn === '' || isset($seen[$cn])) {
  8513. continue;
  8514. }
  8515. $seen[$cn] = true;
  8516. $list[] = [
  8517. 'name' => $cn,
  8518. 'amount' => '未报价',
  8519. ];
  8520. }
  8521. }
  8522. return $list;
  8523. }
  8524. /**
  8525. * 通知业务员邮件:供应商报价 HTML 表格(名称+单价,不含时间)
  8526. */
  8527. protected function buildRfqSalesmanSupplierQuotesHtml(int $sid, string $supplierRaw = ''): string
  8528. {
  8529. $rows = $this->loadRfqSalesmanSupplierQuoteRows($sid, $supplierRaw);
  8530. if ($rows === []) {
  8531. return '<p style="margin:8px 0;color:#888;">暂无报价</p>';
  8532. }
  8533. $html = '<table cellpadding="0" cellspacing="0" border="1" '
  8534. . 'style="border-collapse:collapse;border-color:#ddd;width:100%;max-width:560px;font-size:14px;margin:8px 0;">'
  8535. . '<thead><tr style="background:#f5f5f5;">'
  8536. . '<th style="padding:8px 10px;text-align:center;width:56px;">序号</th>'
  8537. . '<th style="padding:8px 10px;text-align:left;">供应商名称</th>'
  8538. . '<th style="padding:8px 10px;text-align:center;width:100px;">单价</th>'
  8539. . '</tr></thead><tbody>';
  8540. foreach ($rows as $i => $row) {
  8541. $html .= '<tr>'
  8542. . '<td style="padding:8px 10px;text-align:center;">' . ($i + 1) . '</td>'
  8543. . '<td style="padding:8px 10px;">' . htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8') . '</td>'
  8544. . '<td style="padding:8px 10px;text-align:center;">' . htmlspecialchars($row['amount'], ENT_QUOTES, 'UTF-8') . '</td>'
  8545. . '</tr>';
  8546. }
  8547. $html .= '</tbody></table>';
  8548. return $html;
  8549. }
  8550. /**
  8551. * 询价多选字段:数组或字符串统一为顿号拼接
  8552. *
  8553. * @param mixed $raw
  8554. */
  8555. protected function joinRfqMultiSelectValues($raw): string
  8556. {
  8557. $parts = [];
  8558. if (is_array($raw)) {
  8559. foreach ($raw as $item) {
  8560. if (is_array($item)) {
  8561. continue;
  8562. }
  8563. $v = trim((string)$item);
  8564. if ($v !== '') {
  8565. $parts[] = $v;
  8566. }
  8567. }
  8568. } else {
  8569. $s = trim((string)$raw);
  8570. if ($s !== '') {
  8571. foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
  8572. $v = trim((string)$piece);
  8573. if ($v !== '') {
  8574. $parts[] = $v;
  8575. }
  8576. }
  8577. }
  8578. }
  8579. $parts = array_values(array_unique($parts));
  8580. return implode('、', $parts);
  8581. }
  8582. /**
  8583. * 新增询价:可选供应商名称(仅落库记录,不发通知)
  8584. *
  8585. * @return string[]
  8586. */
  8587. protected function loadRfqSupplierNameOptions(): array
  8588. {
  8589. $out = [];
  8590. try {
  8591. $rows = Db::table('customer')
  8592. ->where(function ($q) {
  8593. $q->where('status', 1)
  8594. ->whereOr('status', '1')
  8595. ->whereOr('status', '')
  8596. ->whereNull('status');
  8597. })
  8598. ->order('id', 'desc')
  8599. ->column('company_name');
  8600. } catch (\Throwable $e) {
  8601. return [];
  8602. }
  8603. if (!is_array($rows)) {
  8604. return [];
  8605. }
  8606. foreach ($rows as $name) {
  8607. $name = trim((string)$name);
  8608. if ($name === '' || isset($out[$name])) {
  8609. continue;
  8610. }
  8611. $out[$name] = $name;
  8612. }
  8613. return array_values($out);
  8614. }
  8615. /**
  8616. * 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
  8617. */
  8618. protected function rfqNotifySalesmanAuthGroupId(): int
  8619. {
  8620. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  8621. if ($id > 0) {
  8622. return $id;
  8623. }
  8624. try {
  8625. $found = Db::name('auth_group')
  8626. ->where('name', '业务员')
  8627. ->where('status', 'normal')
  8628. ->order('id', 'asc')
  8629. ->value('id');
  8630. $id = (int)$found;
  8631. } catch (\Throwable $e) {
  8632. $id = 0;
  8633. }
  8634. return $id > 0 ? $id : 12;
  8635. }
  8636. /**
  8637. * 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
  8638. *
  8639. * @return string[]
  8640. */
  8641. protected function loadRfqSalesmanNameOptions(): array
  8642. {
  8643. $out = [];
  8644. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8645. $name = trim((string)($row['name'] ?? ''));
  8646. if ($name !== '') {
  8647. $out[] = $name;
  8648. }
  8649. }
  8650. return $out;
  8651. }
  8652. /**
  8653. * 业务员角色组下管理员:姓名、邮箱、手机
  8654. *
  8655. * @return array<int, array{name:string,email:string,mobile:string}>
  8656. */
  8657. protected function loadRfqSalesmanContactOptions(): array
  8658. {
  8659. $out = [];
  8660. $seen = [];
  8661. $groupId = $this->rfqNotifySalesmanAuthGroupId();
  8662. if ($groupId <= 0) {
  8663. return [];
  8664. }
  8665. try {
  8666. $adminIds = Db::name('auth_group_access')
  8667. ->where('group_id', $groupId)
  8668. ->column('uid');
  8669. } catch (\Throwable $e) {
  8670. return [];
  8671. }
  8672. $adminIds = is_array($adminIds)
  8673. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  8674. : [];
  8675. if ($adminIds === []) {
  8676. return [];
  8677. }
  8678. try {
  8679. $rows = Db::name('admin')
  8680. ->where('status', 'normal')
  8681. ->where('id', 'in', $adminIds)
  8682. ->order('id', 'asc')
  8683. ->field('id,nickname,username,email,mobile')
  8684. ->select();
  8685. } catch (\Throwable $e) {
  8686. return [];
  8687. }
  8688. if (!is_array($rows)) {
  8689. return [];
  8690. }
  8691. foreach ($rows as $row) {
  8692. if (!is_array($row)) {
  8693. continue;
  8694. }
  8695. $name = trim((string)($row['nickname'] ?? ''));
  8696. if ($name === '') {
  8697. $name = trim((string)($row['username'] ?? ''));
  8698. }
  8699. if ($name === '' || isset($seen[$name])) {
  8700. continue;
  8701. }
  8702. $seen[$name] = true;
  8703. $out[] = [
  8704. 'name' => $name,
  8705. 'email' => trim((string)($row['email'] ?? '')),
  8706. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  8707. ];
  8708. }
  8709. return $out;
  8710. }
  8711. /**
  8712. * 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
  8713. *
  8714. * @return string[]
  8715. */
  8716. protected function loadRfqDeptNameOptions(): array
  8717. {
  8718. $out = [];
  8719. // ERP 承揽部门(主来源)
  8720. try {
  8721. $vals = Db::table('mcyd')
  8722. ->where('CCLBMMC', '<>', '')
  8723. ->whereNotNull('CCLBMMC')
  8724. ->distinct(true)
  8725. ->limit(300)
  8726. ->column('CCLBMMC');
  8727. } catch (\Throwable $e) {
  8728. $vals = [];
  8729. }
  8730. if (is_array($vals)) {
  8731. foreach ($vals as $v) {
  8732. $v = trim((string)$v);
  8733. if ($v === '' || isset($out[$v])) {
  8734. continue;
  8735. }
  8736. $out[$v] = $v;
  8737. }
  8738. }
  8739. // 手工询价历史部门补全
  8740. try {
  8741. $poVals = Db::table('purchase_order')
  8742. ->where('CCLBMMC', '<>', '')
  8743. ->whereNotNull('CCLBMMC')
  8744. ->distinct(true)
  8745. ->limit(200)
  8746. ->column('CCLBMMC');
  8747. } catch (\Throwable $e) {
  8748. $poVals = [];
  8749. }
  8750. if (is_array($poVals)) {
  8751. foreach ($poVals as $v) {
  8752. $v = trim((string)$v);
  8753. if ($v === '' || isset($out[$v])) {
  8754. continue;
  8755. }
  8756. $out[$v] = $v;
  8757. }
  8758. }
  8759. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  8760. if (!isset($out[$preset])) {
  8761. $out[$preset] = $preset;
  8762. }
  8763. }
  8764. $list = array_values($out);
  8765. // 常用部门靠前
  8766. usort($list, static function ($a, $b) {
  8767. $weight = [
  8768. '营销中心' => 1,
  8769. '业务部' => 2,
  8770. '市场部' => 3,
  8771. '外贸部' => 4,
  8772. '新华技术业务部' => 5,
  8773. ];
  8774. $wa = $weight[$a] ?? 100;
  8775. $wb = $weight[$b] ?? 100;
  8776. if ($wa !== $wb) {
  8777. return $wa <=> $wb;
  8778. }
  8779. return strcmp((string)$a, (string)$b);
  8780. });
  8781. return $list;
  8782. }
  8783. /**
  8784. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  8785. */
  8786. public function add()
  8787. {
  8788. if ($this->request->isPost()) {
  8789. $params = $this->request->post('row/a');
  8790. if (!is_array($params)) {
  8791. $this->error(__('Parameter %s can not be empty', ''));
  8792. }
  8793. [, $adminName] = $this->GetUseName();
  8794. $params['cywyxm'] = $adminName;
  8795. try {
  8796. $sid = $this->saveManualPickOrder($params);
  8797. } catch (\InvalidArgumentException $e) {
  8798. $this->error($e->getMessage());
  8799. } catch (\Throwable $e) {
  8800. $this->error($e->getMessage());
  8801. }
  8802. $this->success('新增成功', '', [
  8803. 'scydgy_id' => $sid,
  8804. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  8805. ]);
  8806. }
  8807. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8808. [, $adminName] = $this->GetUseName();
  8809. $this->view->assign('adminNickname', $adminName);
  8810. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  8811. $this->view->assign('defaultCclbmmc', '营销中心');
  8812. $this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
  8813. $this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
  8814. $this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
  8815. return $this->view->fetch();
  8816. }
  8817. /**
  8818. * 业务员新增进度查询(手工询价;有查询权限看全部,含手机端新增且未通知业务员的)
  8819. */
  8820. public function rfqlist()
  8821. {
  8822. $this->relationSearch = false;
  8823. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ';
  8824. $this->request->filter(['strip_tags', 'trim']);
  8825. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8826. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8827. $this->ensureRfqSalesmanEmailTemplate();
  8828. $this->ensureRfqSupplierEmailTemplate();
  8829. if ($this->request->isAjax()) {
  8830. try {
  8831. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  8832. $limit = max(10, min(500, (int)$limit));
  8833. $filterYm = trim((string)$this->request->param('filter_ym', ''));
  8834. if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
  8835. $filterYm = date('Y-m');
  8836. }
  8837. $applyFilters = function ($query) use ($where, $filterYm) {
  8838. $query->where('scydgy_id', '<', 0);
  8839. $this->applyPurchaseOrderNotDeletedWhere($query);
  8840. // 查询询价:有菜单权限即可看全部手工单(含手机端新增、尚未通知业务员的)
  8841. $this->applyRfqListMonthFilter($query, $filterYm);
  8842. if (!empty($where)) {
  8843. // 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
  8844. $safeWhere = [];
  8845. $skipFields = [
  8846. 'supplier_name' => true,
  8847. 'progress_text' => true,
  8848. 'createtime_text' => true,
  8849. 'notify_time_text' => true,
  8850. 'can_notify_salesman' => true,
  8851. 'has_issued' => true,
  8852. 'has_quoted' => true,
  8853. ];
  8854. foreach ((array)$where as $cond) {
  8855. if (!is_array($cond) || !isset($cond[0])) {
  8856. continue;
  8857. }
  8858. $field = (string)$cond[0];
  8859. $fieldBase = (string)preg_replace('/\|.*$/', '', $field);
  8860. $fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
  8861. if (isset($skipFields[$fieldBase])) {
  8862. continue;
  8863. }
  8864. if ($fieldBase === 'supplier_name') {
  8865. continue;
  8866. }
  8867. $safeWhere[] = $cond;
  8868. }
  8869. if ($safeWhere !== []) {
  8870. $query->where($safeWhere);
  8871. }
  8872. }
  8873. };
  8874. $countQuery = Db::table('purchase_order');
  8875. $applyFilters($countQuery);
  8876. $total = (int)$countQuery->count();
  8877. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  8878. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  8879. $listQuery = Db::table('purchase_order');
  8880. $applyFilters($listQuery);
  8881. $rows = $listQuery
  8882. ->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')
  8883. ->order($sortField, $orderDir)
  8884. ->limit($offset, $limit)
  8885. ->select();
  8886. if (!is_array($rows)) {
  8887. $rows = [];
  8888. }
  8889. $sidList = [];
  8890. foreach ($rows as $r) {
  8891. if (!is_array($r)) {
  8892. continue;
  8893. }
  8894. $sid = (int)($r['scydgy_id'] ?? 0);
  8895. if ($sid < 0) {
  8896. $sidList[$sid] = true;
  8897. }
  8898. }
  8899. $issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
  8900. $quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
  8901. $out = [];
  8902. foreach ($rows as $r) {
  8903. if (!is_array($r)) {
  8904. continue;
  8905. }
  8906. $sid = (int)($r['scydgy_id'] ?? 0);
  8907. if ($sid >= 0) {
  8908. continue;
  8909. }
  8910. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  8911. if ($createdText === '') {
  8912. $createdText = trim((string)($r['dStamp'] ?? ''));
  8913. }
  8914. $notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
  8915. $supplier = trim((string)($r['cGzzxMc'] ?? ''));
  8916. if ($supplier === '') {
  8917. $supplier = trim((string)($r['pick_company_name'] ?? ''));
  8918. }
  8919. $hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
  8920. || isset($issuedSidSet[$sid]);
  8921. $hasQuoted = isset($quotedSidSet[$sid]);
  8922. $salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
  8923. $canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
  8924. $out[] = [
  8925. 'id' => (int)($r['id'] ?? 0),
  8926. 'scydgy_id' => $sid,
  8927. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  8928. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  8929. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  8930. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  8931. 'CDW' => trim((string)($r['CDW'] ?? '')),
  8932. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  8933. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  8934. 'CDF' => trim((string)($r['CDF'] ?? '')),
  8935. 'supplier_name' => $supplier,
  8936. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  8937. 'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
  8938. 'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
  8939. 'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
  8940. 'notify_time_text' => $notifyTimeText,
  8941. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  8942. 'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
  8943. 'has_issued' => $hasIssued ? 1 : 0,
  8944. 'has_quoted' => $hasQuoted ? 1 : 0,
  8945. 'can_notify_salesman' => $canNotifySalesman,
  8946. 'createtime' => $r['createtime'] ?? null,
  8947. 'createtime_text' => $createdText,
  8948. ];
  8949. }
  8950. return json(['total' => $total, 'rows' => $out]);
  8951. } catch (\Throwable $e) {
  8952. Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
  8953. return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
  8954. }
  8955. }
  8956. $sidebar = $this->loadRfqSidebarYearMonths();
  8957. $defaultYm = $this->resolveRfqListDefaultYm($sidebar);
  8958. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  8959. [, $adminName] = $this->GetUseName();
  8960. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  8961. $this->view->assign('adminNickname', $adminName);
  8962. $this->view->assign('defaultYm', $defaultYm);
  8963. $this->view->assign('sidebarYearMonths', $sidebar);
  8964. return $this->view->fetch('procuremen/rfqlist');
  8965. }
  8966. /**
  8967. * 列表默认月份:当月有数据用当月,否则取最近有数据的月份
  8968. *
  8969. * @param array<int, array{year:string, months:array}> $sidebar
  8970. */
  8971. protected function resolveRfqListDefaultYm(array $sidebar): string
  8972. {
  8973. $current = date('Y-m');
  8974. $yms = $this->flattenProcuremenSidebarYms($sidebar);
  8975. if (in_array($current, $yms, true)) {
  8976. return $current;
  8977. }
  8978. if ($yms !== []) {
  8979. rsort($yms, SORT_STRING);
  8980. return (string)$yms[0];
  8981. }
  8982. return $current;
  8983. }
  8984. /**
  8985. * 手工询价列表左侧月份(按 createtime / dStamp)
  8986. *
  8987. * @return array<int, array{year:string, months:array}>
  8988. */
  8989. protected function loadRfqSidebarYearMonths(): array
  8990. {
  8991. $ymSet = [];
  8992. try {
  8993. $q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
  8994. $this->applyPurchaseOrderNotDeletedWhere($q);
  8995. $rows = $q->field('createtime,dStamp')->limit(5000)->select();
  8996. } catch (\Throwable $e) {
  8997. $rows = [];
  8998. }
  8999. if (!is_array($rows)) {
  9000. $rows = [];
  9001. }
  9002. foreach ($rows as $r) {
  9003. if (!is_array($r)) {
  9004. continue;
  9005. }
  9006. $t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  9007. if ($t === '') {
  9008. $t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
  9009. }
  9010. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  9011. $ymSet[$m[1] . '-' . $m[2]] = true;
  9012. }
  9013. }
  9014. return $this->buildYearMonthSidebar(array_keys($ymSet));
  9015. }
  9016. /**
  9017. * 手工询价可见范围(用于详情/操作校验):
  9018. * 超管、具备「查询询价」权限、需求发起人、通知业务员 → 可见
  9019. * 列表页本身不再按发起人/通知过滤,避免手机端新增后后台看不到。
  9020. */
  9021. protected function applyManualRfqViewerWhere($query): void
  9022. {
  9023. if ($this->auth->isSuperAdmin() || $this->hasProcuremenPerm(['rfqlist'])) {
  9024. return;
  9025. }
  9026. [, $adminName] = $this->GetUseName();
  9027. $adminName = trim((string)$adminName);
  9028. if ($adminName === '') {
  9029. $query->whereRaw('1 = 0');
  9030. return;
  9031. }
  9032. // 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
  9033. $query->where(function ($q) use ($adminName) {
  9034. $q->where('cywyxm', $adminName)
  9035. ->whereOr('notify_salesman', $adminName)
  9036. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  9037. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  9038. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  9039. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  9040. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  9041. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  9042. });
  9043. }
  9044. /**
  9045. * 当前用户是否可查看/操作该手工询价单
  9046. */
  9047. protected function canViewManualRfqOrder(array $po): bool
  9048. {
  9049. if ($this->auth->isSuperAdmin()) {
  9050. return true;
  9051. }
  9052. // 有查询询价权限则可操作全部手工询价(询价/查看报价/通知业务员等)
  9053. if ($this->hasProcuremenPerm(['rfqlist'])) {
  9054. return true;
  9055. }
  9056. [, $adminName] = $this->GetUseName();
  9057. $adminName = trim((string)$adminName);
  9058. if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
  9059. return true;
  9060. }
  9061. if ($adminName !== '') {
  9062. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  9063. if ($n === $adminName) {
  9064. return true;
  9065. }
  9066. }
  9067. }
  9068. return false;
  9069. }
  9070. /**
  9071. * 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
  9072. */
  9073. protected function applyRfqListMonthFilter($query, string $ym): void
  9074. {
  9075. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  9076. $ym = date('Y-m');
  9077. }
  9078. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  9079. // 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
  9080. $query->whereRaw(
  9081. "("
  9082. . "CASE "
  9083. . "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  9084. . "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
  9085. . "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
  9086. . "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  9087. . "THEN TRIM(CAST(createtime AS CHAR(32))) "
  9088. . "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
  9089. . "END"
  9090. . ") LIKE '{$ymEsc}-%'"
  9091. );
  9092. }
  9093. /**
  9094. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  9095. */
  9096. public function rfqlistDetails()
  9097. {
  9098. return $this->details();
  9099. }
  9100. /**
  9101. * 查询询价 — 弹窗:可选通知业务员名单(勾选后确认通知)
  9102. */
  9103. public function rfqnotifysalesmen()
  9104. {
  9105. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman'])) {
  9106. $this->error(__('You have no permission'));
  9107. }
  9108. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9109. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  9110. $sid = (int)$this->request->param('scydgy_id', 0);
  9111. if ($sid >= 0) {
  9112. $this->error('仅支持手工新增询价单');
  9113. }
  9114. $po = $this->loadManualRfqOrderForNotify($sid);
  9115. $selectedMap = [];
  9116. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  9117. $selectedMap[$n] = true;
  9118. }
  9119. $list = [];
  9120. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  9121. $name = trim((string)($row['name'] ?? ''));
  9122. if ($name === '') {
  9123. continue;
  9124. }
  9125. $email = trim((string)($row['email'] ?? ''));
  9126. $mobile = trim((string)($row['mobile'] ?? ''));
  9127. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  9128. $list[] = [
  9129. 'name' => $name,
  9130. 'email' => $email,
  9131. 'mobile' => $mobile,
  9132. 'can_select' => $hasEmail ? 1 : 0,
  9133. 'checked' => (!empty($selectedMap[$name]) && $hasEmail) ? 1 : 0,
  9134. ];
  9135. }
  9136. $canNotify = $this->canRfqNotifySalesman($po);
  9137. $this->success('', null, [
  9138. 'scydgy_id' => $sid,
  9139. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9140. 'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
  9141. 'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
  9142. 'can_notify_salesman' => $canNotify ? 1 : 0,
  9143. 'list' => $list,
  9144. ]);
  9145. }
  9146. /**
  9147. * 查询询价 — 补加通知业务员可选名单
  9148. */
  9149. public function rfqsalesmanoptions()
  9150. {
  9151. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen'])) {
  9152. $this->error(__('You have no permission'));
  9153. }
  9154. $out = [];
  9155. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  9156. $email = trim((string)($row['email'] ?? ''));
  9157. $mobile = trim((string)($row['mobile'] ?? ''));
  9158. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  9159. $out[] = [
  9160. 'name' => (string)($row['name'] ?? ''),
  9161. 'email' => $email,
  9162. 'mobile' => $mobile,
  9163. 'can_select' => $hasEmail ? 1 : 0,
  9164. ];
  9165. }
  9166. $this->success('', null, ['list' => $out]);
  9167. }
  9168. /**
  9169. * 查询询价 — 补加通知业务员(合并更新 notify_salesman)
  9170. */
  9171. public function rfqappendsalesmen()
  9172. {
  9173. if (!$this->request->isPost()) {
  9174. $this->error(__('Invalid parameters'));
  9175. }
  9176. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen'])) {
  9177. $this->error(__('You have no permission'));
  9178. }
  9179. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9180. $sid = (int)$this->request->post('scydgy_id', 0);
  9181. if ($sid >= 0) {
  9182. $this->error('仅支持手工新增询价单');
  9183. }
  9184. $po = $this->loadManualRfqOrderForNotify($sid);
  9185. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9186. $this->error('订单已完结,无法添加业务员');
  9187. }
  9188. $raw = $this->request->post('salesmen/a', []);
  9189. if (!is_array($raw) || $raw === []) {
  9190. $salesmenJson = $this->request->post('salesmen_json', '');
  9191. if (is_string($salesmenJson) && $salesmenJson !== '') {
  9192. $decoded = json_decode($salesmenJson, true);
  9193. $raw = is_array($decoded) ? $decoded : [];
  9194. }
  9195. }
  9196. $addNames = [];
  9197. foreach ((array)$raw as $item) {
  9198. if (is_array($item)) {
  9199. $n = trim((string)($item['name'] ?? ''));
  9200. } else {
  9201. $n = trim((string)$item);
  9202. }
  9203. if ($n !== '') {
  9204. $addNames[] = $n;
  9205. }
  9206. }
  9207. $addNames = array_values(array_unique($addNames));
  9208. if ($addNames === []) {
  9209. $this->error('请选择要添加的业务员');
  9210. }
  9211. $allowedOptions = $this->loadRfqSalesmanContactOptions();
  9212. $allowedMap = [];
  9213. foreach ($allowedOptions as $opt) {
  9214. $n = trim((string)($opt['name'] ?? ''));
  9215. if ($n === '') {
  9216. continue;
  9217. }
  9218. $email = trim((string)($opt['email'] ?? ''));
  9219. $allowedMap[$n] = ($email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL));
  9220. }
  9221. foreach ($addNames as $n) {
  9222. if (!array_key_exists($n, $allowedMap)) {
  9223. $this->error('业务员不在可选名单中:' . $n);
  9224. }
  9225. if (!$allowedMap[$n]) {
  9226. $this->error('业务员未填写有效邮箱,无法添加:' . $n);
  9227. }
  9228. }
  9229. $existingRaw = trim((string)($po['notify_salesman'] ?? ''));
  9230. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9231. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9232. try {
  9233. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['notify_salesman' => $mergedStr]);
  9234. } catch (\Throwable $e) {
  9235. $this->error('保存失败:' . $e->getMessage());
  9236. }
  9237. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9238. $this->addOrderLog($sid, 'rfq_append_salesman', '添加通知业务员:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9239. $this->success('已添加业务员', null, [
  9240. 'scydgy_id' => $sid,
  9241. 'notify_salesman' => $mergedStr,
  9242. 'added_count' => count($addNames),
  9243. ]);
  9244. }
  9245. /**
  9246. * 查询询价 — 勾选业务员后邮箱通知(salesmen_json)
  9247. */
  9248. public function rfqnotifysalesman()
  9249. {
  9250. if (!$this->request->isPost()) {
  9251. $this->error(__('Invalid parameters'));
  9252. }
  9253. if (!$this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen'])) {
  9254. $this->error(__('You have no permission'));
  9255. }
  9256. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9257. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  9258. $sid = (int)$this->request->post('scydgy_id', 0);
  9259. if ($sid >= 0) {
  9260. $this->error('仅支持手工新增询价单');
  9261. }
  9262. $po = $this->loadManualRfqOrderForNotify($sid);
  9263. $this->assertRfqCanNotifySalesman($po);
  9264. $raw = $this->request->post('salesmen/a', []);
  9265. if (!is_array($raw) || $raw === []) {
  9266. $salesmenJson = $this->request->post('salesmen_json', '');
  9267. if (is_string($salesmenJson) && $salesmenJson !== '') {
  9268. $decoded = json_decode($salesmenJson, true);
  9269. $raw = is_array($decoded) ? $decoded : [];
  9270. }
  9271. }
  9272. // 兼容旧参数:notify_all / 单人 name
  9273. if ((!is_array($raw) || $raw === []) && (int)$this->request->post('notify_all', 0) === 1) {
  9274. $raw = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  9275. }
  9276. if ((!is_array($raw) || $raw === [])) {
  9277. $oneName = trim((string)$this->request->post('name', ''));
  9278. if ($oneName !== '') {
  9279. $raw = [$oneName];
  9280. }
  9281. }
  9282. $selectedNames = [];
  9283. foreach ((array)$raw as $item) {
  9284. if (is_array($item)) {
  9285. $n = trim((string)($item['name'] ?? ''));
  9286. } else {
  9287. $n = trim((string)$item);
  9288. }
  9289. if ($n !== '') {
  9290. $selectedNames[] = $n;
  9291. }
  9292. }
  9293. $selectedNames = array_values(array_unique($selectedNames));
  9294. if ($selectedNames === []) {
  9295. $this->error('请选择要通知的业务员');
  9296. }
  9297. $optionMap = [];
  9298. foreach ($this->loadRfqSalesmanContactOptions() as $opt) {
  9299. $n = trim((string)($opt['name'] ?? ''));
  9300. if ($n === '') {
  9301. continue;
  9302. }
  9303. $optionMap[$n] = $opt;
  9304. }
  9305. $targets = [];
  9306. foreach ($selectedNames as $n) {
  9307. if (!isset($optionMap[$n])) {
  9308. $this->error('业务员不在可选名单中:' . $n);
  9309. }
  9310. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  9311. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9312. $this->error('业务员未填写有效邮箱,无法通知:' . $n);
  9313. }
  9314. $resolved = $this->resolveRfqSalesmanContactRows([$n]);
  9315. $targets[] = $resolved[0] ?? [
  9316. 'admin_id' => 0,
  9317. 'name' => $n,
  9318. 'email' => $email,
  9319. ];
  9320. }
  9321. $mergedStr = $this->joinRfqMultiSelectValues($selectedNames);
  9322. try {
  9323. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  9324. 'notify_salesman' => $mergedStr,
  9325. ]);
  9326. } catch (\Throwable $e) {
  9327. $this->error('保存通知业务员失败:' . $e->getMessage());
  9328. }
  9329. $po['notify_salesman'] = $mergedStr;
  9330. $mailConfig = $this->loadMailerConfig();
  9331. if (empty($mailConfig['host'])) {
  9332. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9333. }
  9334. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9335. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9336. }
  9337. $this->ensureRfqSalesmanEmailTemplate();
  9338. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  9339. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  9340. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  9341. $cdw = trim((string)($po['CDW'] ?? ''));
  9342. $qty = trim((string)$this->resolveProcuremenThisQuantity($po));
  9343. $ceiling = trim((string)$this->resolveProcuremenCeilingPrice($po));
  9344. $mbz = trim((string)($po['MBZ'] ?? ''));
  9345. $cywyxm = trim((string)($po['cywyxm'] ?? ''));
  9346. $supplier = trim((string)($po['cGzzxMc'] ?? ''));
  9347. if ($supplier === '') {
  9348. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  9349. }
  9350. $supplierQuotesHtml = $this->buildRfqSalesmanSupplierQuotesHtml($sid, $supplier);
  9351. try {
  9352. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
  9353. } catch (\Throwable $e) {
  9354. $this->error($e->getMessage());
  9355. }
  9356. $okNames = [];
  9357. $failMsgs = [];
  9358. foreach ($targets as $contact) {
  9359. $toEmail = trim((string)($contact['email'] ?? ''));
  9360. $toName = trim((string)($contact['name'] ?? ''));
  9361. $notifyVars = [
  9362. 'contact_name' => $toName,
  9363. 'salesman_name' => $toName,
  9364. 'company_name' => $toName,
  9365. 'email' => $toEmail,
  9366. 'ccydh' => $ccydh,
  9367. 'cyjmc' => $cyjmc,
  9368. 'cgymc' => $cgymc,
  9369. 'cdw' => $cdw,
  9370. 'this_quantity' => $qty,
  9371. 'ceilingPrice' => $ceiling,
  9372. 'MBZ' => $mbz,
  9373. 'supplier_name' => $supplier,
  9374. // 占位符,转 HTML 后再替换成表格,避免被 htmlspecialchars 转义
  9375. 'supplier_quotes' => '__RFQ_SUPPLIER_QUOTES_TABLE__',
  9376. 'cywyxm' => $cywyxm,
  9377. ];
  9378. try {
  9379. $mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
  9380. $mailSubject = $mailSubjectTpl;
  9381. foreach ($notifyVars as $k => $v) {
  9382. if ($k === 'supplier_quotes') {
  9383. continue;
  9384. }
  9385. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  9386. }
  9387. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  9388. $mailSubject = trim((string)$mailSubject);
  9389. if ($mailSubject === '') {
  9390. $mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  9391. }
  9392. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  9393. $mailBody = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', $supplierQuotesHtml, $mailBody);
  9394. $mailPlainForLog = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', strip_tags(str_replace(['</tr>', '</p>'], "\n", $supplierQuotesHtml)), $mailPlain);
  9395. $bundle = [
  9396. 'company_name' => $toName,
  9397. 'email' => $toEmail,
  9398. 'mail_plain' => $mailPlainForLog,
  9399. 'mail_body' => $mailBody,
  9400. 'ccydh' => $ccydh,
  9401. 'email_log_scene' => 'rfq_salesman',
  9402. 'email_log_scydgy_id' => $sid,
  9403. 'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
  9404. 'notify_vars' => $notifyVars,
  9405. ];
  9406. $this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
  9407. $okNames[] = $toName . '(' . $toEmail . ')';
  9408. } catch (\Throwable $e) {
  9409. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  9410. }
  9411. }
  9412. if ($okNames === []) {
  9413. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  9414. }
  9415. $now = date('Y-m-d H:i:s');
  9416. try {
  9417. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  9418. 'rfq_salesman_notified' => 1,
  9419. 'rfq_salesman_notify_time' => $now,
  9420. ]);
  9421. } catch (\Throwable $e) {
  9422. // ignore
  9423. }
  9424. $this->addOrderLog(
  9425. $sid,
  9426. 'rfq_notify_salesman',
  9427. '邮箱通知业务员:' . implode('、', $okNames),
  9428. (int)($po['id'] ?? 0)
  9429. );
  9430. $msg = '已通知 ' . count($okNames) . ' 人';
  9431. if ($failMsgs !== []) {
  9432. $msg .= ';部分失败:' . implode(';', $failMsgs);
  9433. }
  9434. $this->success($msg, null, [
  9435. 'scydgy_id' => $sid,
  9436. 'notify_salesman' => $mergedStr,
  9437. 'rfq_salesman_notified' => 1,
  9438. 'rfq_salesman_notify_time' => $now,
  9439. 'notify_time_text' => $now,
  9440. 'ok_count' => count($okNames),
  9441. 'fail_count' => count($failMsgs),
  9442. ]);
  9443. }
  9444. /**
  9445. * 查询询价 — 下发前:返回将通知的供应商表格数据
  9446. */
  9447. public function rfqissuesuppliers()
  9448. {
  9449. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers'])) {
  9450. $this->error(__('You have no permission'));
  9451. }
  9452. $sid = (int)$this->request->param('scydgy_id', 0);
  9453. if ($sid >= 0) {
  9454. $this->error('仅支持手工新增询价单');
  9455. }
  9456. $po = $this->loadManualRfqOrderForNotify($sid);
  9457. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9458. if ($supplierRaw === '') {
  9459. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9460. }
  9461. $names = $this->splitRfqSalesmanNames($supplierRaw);
  9462. // 已成功发过询价邮件的供应商(含历史 pick_issue 场景)
  9463. $notifiedMap = [];
  9464. try {
  9465. $this->ensurePurchaseEmailSendLogTableOnce();
  9466. $logRows = Db::table('purchase_email_send_log')
  9467. ->where('scydgy_id', $sid)
  9468. ->where('status', 1)
  9469. ->where('scene', 'in', ['rfq_supplier', 'pick_issue'])
  9470. ->field('company_name')
  9471. ->select();
  9472. if (is_array($logRows)) {
  9473. foreach ($logRows as $lr) {
  9474. if (!is_array($lr)) {
  9475. continue;
  9476. }
  9477. $cn = trim((string)($lr['company_name'] ?? ''));
  9478. if ($cn !== '') {
  9479. $notifiedMap[$cn] = true;
  9480. }
  9481. }
  9482. }
  9483. } catch (\Throwable $e) {
  9484. }
  9485. // 兼容:明细已生成(曾下发)也视为已通知
  9486. try {
  9487. $detRows = Db::table('purchase_order_detail')
  9488. ->where('scydgy_id', $sid)
  9489. ->field('company_name')
  9490. ->select();
  9491. if (is_array($detRows)) {
  9492. foreach ($detRows as $dr) {
  9493. if (!is_array($dr)) {
  9494. continue;
  9495. }
  9496. $cn = trim((string)($dr['company_name'] ?? ''));
  9497. if ($cn !== '') {
  9498. $notifiedMap[$cn] = true;
  9499. }
  9500. }
  9501. }
  9502. } catch (\Throwable $e) {
  9503. }
  9504. $list = [];
  9505. foreach ($names as $name) {
  9506. // 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
  9507. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9508. $email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
  9509. $phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
  9510. $username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
  9511. $okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
  9512. $notified = !empty($notifiedMap[$name]) ? 1 : 0;
  9513. $list[] = [
  9514. 'name' => $name,
  9515. 'username' => $username,
  9516. 'email' => $email,
  9517. 'phone' => $phone,
  9518. 'can_notify' => $okEmail ? 1 : 0,
  9519. 'found' => is_array($contact) ? 1 : 0,
  9520. 'notified' => $notified,
  9521. 'notify_status_text' => $notified ? '已通知' : '未通知',
  9522. ];
  9523. }
  9524. $this->success('', null, [
  9525. 'scydgy_id' => $sid,
  9526. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9527. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9528. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9529. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9530. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9531. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9532. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9533. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9534. 'list' => $list,
  9535. ]);
  9536. }
  9537. /**
  9538. * 查询询价 — 补加供应商可选名单
  9539. */
  9540. public function rfqsupplieroptions()
  9541. {
  9542. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
  9543. $this->error(__('You have no permission'));
  9544. }
  9545. $names = array_values($this->loadRfqSupplierNameOptions());
  9546. $out = [];
  9547. foreach ($names as $name) {
  9548. $out[] = ['name' => $name];
  9549. }
  9550. $this->success('', null, ['list' => $out]);
  9551. }
  9552. /**
  9553. * 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
  9554. */
  9555. public function rfqappendsuppliers()
  9556. {
  9557. if (!$this->request->isPost()) {
  9558. $this->error(__('Invalid parameters'));
  9559. }
  9560. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers'])) {
  9561. $this->error(__('You have no permission'));
  9562. }
  9563. $sid = (int)$this->request->post('scydgy_id', 0);
  9564. if ($sid >= 0) {
  9565. $this->error('仅支持手工新增询价单');
  9566. }
  9567. $po = $this->loadManualRfqOrderForNotify($sid);
  9568. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9569. $this->error('订单已完结,无法补加供应商');
  9570. }
  9571. $raw = $this->request->post('suppliers/a', []);
  9572. if (!is_array($raw) || $raw === []) {
  9573. $suppliersJson = $this->request->post('suppliers_json', '');
  9574. if (is_string($suppliersJson) && $suppliersJson !== '') {
  9575. $decoded = json_decode($suppliersJson, true);
  9576. $raw = is_array($decoded) ? $decoded : [];
  9577. }
  9578. }
  9579. $addNames = [];
  9580. foreach ((array)$raw as $item) {
  9581. if (is_array($item)) {
  9582. $n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
  9583. } else {
  9584. $n = trim((string)$item);
  9585. }
  9586. if ($n !== '') {
  9587. $addNames[] = $n;
  9588. }
  9589. }
  9590. $addNames = array_values(array_unique($addNames));
  9591. if ($addNames === []) {
  9592. $this->error('请选择要补加的供应商');
  9593. }
  9594. $existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9595. if ($existingRaw === '') {
  9596. $existingRaw = trim((string)($po['pick_company_name'] ?? ''));
  9597. }
  9598. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9599. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9600. try {
  9601. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
  9602. } catch (\Throwable $e) {
  9603. $this->error('保存失败:' . $e->getMessage());
  9604. }
  9605. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9606. $this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9607. $this->success('已补加供应商', null, [
  9608. 'scydgy_id' => $sid,
  9609. 'cGzzxMc' => $mergedStr,
  9610. 'added_count' => count($addNames),
  9611. ]);
  9612. }
  9613. /**
  9614. * 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
  9615. */
  9616. public function rfqissue()
  9617. {
  9618. if (!$this->request->isPost()) {
  9619. $this->error(__('Invalid parameters'));
  9620. }
  9621. if (!$this->hasProcuremenPerm(['rfqissue'])) {
  9622. $this->error(__('You have no permission'));
  9623. }
  9624. $this->ensureRfqSupplierEmailTemplate();
  9625. $sid = (int)$this->request->post('scydgy_id', 0);
  9626. if ($sid >= 0) {
  9627. $this->error('仅支持手工新增询价单');
  9628. }
  9629. $po = $this->loadManualRfqOrderForNotify($sid);
  9630. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9631. $this->error('订单已完结,无法下发');
  9632. }
  9633. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9634. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9635. $this->error('订单已进入后续流程,无法再下发');
  9636. }
  9637. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9638. if ($supplierRaw === '') {
  9639. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9640. }
  9641. $supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
  9642. if ($supplierNames === []) {
  9643. $this->error('请先在新增询价时选择供应商');
  9644. }
  9645. $companies = [];
  9646. $missing = [];
  9647. $noEmail = [];
  9648. foreach ($supplierNames as $name) {
  9649. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9650. if ($contact === null) {
  9651. $missing[] = $name;
  9652. continue;
  9653. }
  9654. $em = trim((string)($contact['email'] ?? ''));
  9655. if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
  9656. $noEmail[] = $name;
  9657. continue;
  9658. }
  9659. $companies[] = $contact;
  9660. }
  9661. if ($missing !== []) {
  9662. $this->error('未找到供应商档案:' . implode('、', $missing));
  9663. }
  9664. if ($noEmail !== []) {
  9665. $this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
  9666. }
  9667. if ($companies === []) {
  9668. $this->error('没有可通知的供应商');
  9669. }
  9670. $mailConfig = $this->loadMailerConfig();
  9671. if (empty($mailConfig['host'])) {
  9672. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9673. }
  9674. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9675. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9676. }
  9677. $mergeRow = $po;
  9678. $mergeRow['ID'] = $sid;
  9679. $mergeRow['id'] = $sid;
  9680. $mergeRows = [$mergeRow];
  9681. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9682. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9683. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9684. }
  9685. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9686. $issueTime = date('Y-m-d H:i:s');
  9687. $nameLabels = [];
  9688. foreach ($companies as $c) {
  9689. $nameLabels[] = trim((string)($c['name'] ?? ''));
  9690. }
  9691. $logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
  9692. Db::startTrans();
  9693. try {
  9694. $this->upsertPurchaseOrderFromRow(
  9695. $mergeRow,
  9696. $sysRqDb,
  9697. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9698. $issueTime,
  9699. $po,
  9700. null,
  9701. $scoreRule
  9702. );
  9703. foreach ($companies as $c) {
  9704. $this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
  9705. }
  9706. Db::commit();
  9707. } catch (\Throwable $e) {
  9708. Db::rollback();
  9709. $this->error($e->getMessage());
  9710. }
  9711. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9712. if ($poId <= 0) {
  9713. try {
  9714. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9715. } catch (\Throwable $e) {
  9716. $poId = 0;
  9717. }
  9718. }
  9719. $this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
  9720. $posNotify = [];
  9721. try {
  9722. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9723. if (is_array($fresh)) {
  9724. $fresh['sys_rq'] = $sysRqDb;
  9725. $posNotify = [$fresh];
  9726. }
  9727. } catch (\Throwable $e) {
  9728. $posNotify = [$po];
  9729. $posNotify[0]['sys_rq'] = $sysRqDb;
  9730. }
  9731. $notifyBundle = [
  9732. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9733. 'pos' => $posNotify,
  9734. 'merge_rows' => $mergeRows,
  9735. ];
  9736. $notifyErrors = [];
  9737. foreach ($companies as $c) {
  9738. $cname = trim((string)($c['name'] ?? ''));
  9739. try {
  9740. // 询价下发:仅邮箱通知供应商
  9741. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  9742. } catch (\Throwable $e) {
  9743. $notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
  9744. }
  9745. }
  9746. if ($notifyErrors !== []) {
  9747. $this->error('下发已保存,但邮件通知失败:' . implode(';', $notifyErrors));
  9748. }
  9749. $this->success('已询价并邮件通知供应商', null, [
  9750. 'scydgy_id' => $sid,
  9751. 'progress_text' => '待报价',
  9752. 'supplier_count' => count($companies),
  9753. ]);
  9754. }
  9755. /**
  9756. * 查询询价 — 弹窗内向单个供应商发送询价邮件
  9757. */
  9758. public function rfqissuesendmail()
  9759. {
  9760. if (!$this->request->isPost()) {
  9761. $this->error(__('Invalid parameters'));
  9762. }
  9763. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail'])) {
  9764. $this->error(__('You have no permission'));
  9765. }
  9766. $this->ensureRfqSupplierEmailTemplate();
  9767. $sid = (int)$this->request->post('scydgy_id', 0);
  9768. $companyName = trim((string)$this->request->post('company_name', ''));
  9769. if ($sid >= 0) {
  9770. $this->error('仅支持手工新增询价单');
  9771. }
  9772. if ($companyName === '') {
  9773. $this->error('请选择供应商');
  9774. }
  9775. $po = $this->loadManualRfqOrderForNotify($sid);
  9776. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9777. $this->error('订单已完结,无法发送');
  9778. }
  9779. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9780. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9781. $this->error('订单已进入后续流程,无法再发送');
  9782. }
  9783. $contact = $this->resolveCustomerContactByCompanyName($companyName, false);
  9784. if ($contact === null) {
  9785. $this->error('未找到供应商档案:' . $companyName);
  9786. }
  9787. $email = trim((string)($contact['email'] ?? ''));
  9788. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9789. $this->error('该供应商未填写有效邮箱');
  9790. }
  9791. $mailConfig = $this->loadMailerConfig();
  9792. if (empty($mailConfig['host'])) {
  9793. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9794. }
  9795. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9796. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9797. }
  9798. $mergeRow = $po;
  9799. $mergeRow['ID'] = $sid;
  9800. $mergeRow['id'] = $sid;
  9801. $mergeRows = [$mergeRow];
  9802. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9803. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9804. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9805. }
  9806. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9807. $issueTime = date('Y-m-d H:i:s');
  9808. Db::startTrans();
  9809. try {
  9810. $this->upsertPurchaseOrderFromRow(
  9811. $mergeRow,
  9812. $sysRqDb,
  9813. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9814. $issueTime,
  9815. $po,
  9816. null,
  9817. $scoreRule
  9818. );
  9819. $this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
  9820. Db::commit();
  9821. } catch (\Throwable $e) {
  9822. Db::rollback();
  9823. $this->error($e->getMessage());
  9824. }
  9825. $posNotify = [];
  9826. try {
  9827. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9828. if (is_array($fresh)) {
  9829. $fresh['sys_rq'] = $sysRqDb;
  9830. $posNotify = [$fresh];
  9831. }
  9832. } catch (\Throwable $e) {
  9833. $posNotify = [$po];
  9834. $posNotify[0]['sys_rq'] = $sysRqDb;
  9835. }
  9836. $notifyBundle = [
  9837. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9838. 'pos' => $posNotify,
  9839. 'merge_rows' => $mergeRows,
  9840. ];
  9841. try {
  9842. $this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  9843. } catch (\Throwable $e) {
  9844. $this->error('明细已保存,但邮件发送失败:' . $e->getMessage());
  9845. }
  9846. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9847. if ($poId <= 0) {
  9848. try {
  9849. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9850. } catch (\Throwable $e) {
  9851. $poId = 0;
  9852. }
  9853. }
  9854. $this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
  9855. $this->success('已向「' . $companyName . '」发送询价邮件', null, [
  9856. 'scydgy_id' => $sid,
  9857. 'company_name' => $companyName,
  9858. ]);
  9859. }
  9860. /**
  9861. * 查询询价 — 查看各供应商报价(单价)
  9862. */
  9863. public function rfqquotes()
  9864. {
  9865. if (!$this->hasProcuremenPerm(['rfqquotes', 'rfqissue'])) {
  9866. $this->error(__('You have no permission'));
  9867. }
  9868. $sid = (int)$this->request->param('scydgy_id', 0);
  9869. if ($sid >= 0) {
  9870. $this->error('仅支持手工新增询价单');
  9871. }
  9872. $po = $this->loadManualRfqOrderForNotify($sid);
  9873. $rows = [];
  9874. try {
  9875. // 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
  9876. $q = Db::table('purchase_order_detail')
  9877. ->where('scydgy_id', $sid)
  9878. ->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
  9879. ->order('id', 'asc');
  9880. $this->applyActivePurchaseOrderDetailWhere($q);
  9881. $rows = $q->select();
  9882. } catch (\Throwable $e) {
  9883. try {
  9884. $q = Db::table('purchase_order_detail')
  9885. ->where('scydgy_id', $sid)
  9886. ->order('id', 'asc');
  9887. $this->applyActivePurchaseOrderDetailWhere($q);
  9888. $rows = $q->select();
  9889. } catch (\Throwable $e2) {
  9890. $rows = [];
  9891. }
  9892. }
  9893. if (!is_array($rows)) {
  9894. $rows = [];
  9895. }
  9896. $list = [];
  9897. foreach ($rows as $row) {
  9898. if (!is_array($row)) {
  9899. continue;
  9900. }
  9901. $amount = trim((string)($row['amount'] ?? ''));
  9902. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  9903. // 未报价不显示时间(createtime 是下发时间,不是报价时间)
  9904. $oper = '';
  9905. if ($isQuoted) {
  9906. $oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
  9907. if ($oper === '') {
  9908. $oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  9909. }
  9910. }
  9911. $list[] = [
  9912. 'id' => (int)($row['id'] ?? 0),
  9913. 'company_name' => trim((string)($row['company_name'] ?? '')),
  9914. 'amount' => $amount,
  9915. 'amount_text' => $isQuoted ? $amount : '',
  9916. 'is_quoted' => $isQuoted,
  9917. 'quote_label' => $isQuoted ? '已报价' : '未报价',
  9918. 'status_name' => trim((string)($row['status_name'] ?? '')),
  9919. 'oper_time' => $oper,
  9920. ];
  9921. }
  9922. $this->success('', null, [
  9923. 'scydgy_id' => $sid,
  9924. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9925. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9926. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9927. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9928. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9929. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9930. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9931. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9932. 'list' => $list,
  9933. ]);
  9934. }
  9935. /**
  9936. * 手工询价是否已下发(有下发明细或已进入待确认及之后)
  9937. */
  9938. protected function isRfqOrderIssued(array $po): bool
  9939. {
  9940. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  9941. return true;
  9942. }
  9943. $sid = (int)($po['scydgy_id'] ?? 0);
  9944. if ($sid >= 0) {
  9945. return false;
  9946. }
  9947. try {
  9948. $q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  9949. $this->applyActivePurchaseOrderDetailWhere($q);
  9950. return (int)$q->count() > 0;
  9951. } catch (\Throwable $e) {
  9952. return false;
  9953. }
  9954. }
  9955. /**
  9956. * 批量:已有下发明细的手工询价 scydgy_id
  9957. *
  9958. * @param int[] $scydgyIds
  9959. * @return array<int, bool>
  9960. */
  9961. protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
  9962. {
  9963. $set = [];
  9964. $ids = [];
  9965. foreach ($scydgyIds as $sid) {
  9966. $sid = (int)$sid;
  9967. if ($sid < 0) {
  9968. $ids[$sid] = true;
  9969. }
  9970. }
  9971. if ($ids === []) {
  9972. return $set;
  9973. }
  9974. try {
  9975. $q = Db::table('purchase_order_detail')
  9976. ->where('scydgy_id', 'in', array_keys($ids))
  9977. ->field('scydgy_id');
  9978. $this->applyActivePurchaseOrderDetailWhere($q);
  9979. $rows = $q->select();
  9980. } catch (\Throwable $e) {
  9981. return $set;
  9982. }
  9983. if (!is_array($rows)) {
  9984. return $set;
  9985. }
  9986. foreach ($rows as $row) {
  9987. if (!is_array($row)) {
  9988. continue;
  9989. }
  9990. $sid = (int)($row['scydgy_id'] ?? 0);
  9991. if ($sid < 0) {
  9992. $set[$sid] = true;
  9993. }
  9994. }
  9995. return $set;
  9996. }
  9997. /**
  9998. * 批量:已填单价(已报价)的手工询价 scydgy_id
  9999. *
  10000. * @param int[] $scydgyIds
  10001. * @return array<int, bool>
  10002. */
  10003. protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
  10004. {
  10005. $set = [];
  10006. $ids = [];
  10007. foreach ($scydgyIds as $sid) {
  10008. $sid = (int)$sid;
  10009. if ($sid < 0) {
  10010. $ids[$sid] = true;
  10011. }
  10012. }
  10013. if ($ids === []) {
  10014. return $set;
  10015. }
  10016. try {
  10017. $q = Db::table('purchase_order_detail')
  10018. ->where('scydgy_id', 'in', array_keys($ids))
  10019. ->field('scydgy_id,amount');
  10020. $this->applyActivePurchaseOrderDetailWhere($q);
  10021. $rows = $q->select();
  10022. } catch (\Throwable $e) {
  10023. return $set;
  10024. }
  10025. if (!is_array($rows)) {
  10026. return $set;
  10027. }
  10028. foreach ($rows as $row) {
  10029. if (!is_array($row)) {
  10030. continue;
  10031. }
  10032. $amount = trim((string)($row['amount'] ?? ''));
  10033. if ($amount === '' || $amount === '0' || $amount === '0.00') {
  10034. continue;
  10035. }
  10036. $sid = (int)($row['scydgy_id'] ?? 0);
  10037. if ($sid < 0) {
  10038. $set[$sid] = true;
  10039. }
  10040. }
  10041. return $set;
  10042. }
  10043. /**
  10044. * 已下发且至少一家供应商已报价,才允许通知业务员
  10045. */
  10046. protected function canRfqNotifySalesman(array $po): bool
  10047. {
  10048. if (!$this->isRfqOrderIssued($po)) {
  10049. return false;
  10050. }
  10051. $sid = (int)($po['scydgy_id'] ?? 0);
  10052. if ($sid >= 0) {
  10053. return false;
  10054. }
  10055. $quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
  10056. return isset($quoted[$sid]);
  10057. }
  10058. protected function assertRfqCanNotifySalesman(array $po): void
  10059. {
  10060. if (!$this->isRfqOrderIssued($po)) {
  10061. $this->error('请先询价并等待供应商报价后再通知业务员');
  10062. }
  10063. if (!$this->canRfqNotifySalesman($po)) {
  10064. $this->error('供应商尚未报价,暂不能通知业务员');
  10065. }
  10066. }
  10067. /**
  10068. * 加载手工询价单(含可见性校验)
  10069. *
  10070. * @return array<string, mixed>
  10071. */
  10072. protected function loadManualRfqOrderForNotify(int $scydgyId): array
  10073. {
  10074. try {
  10075. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10076. } catch (\Throwable $e) {
  10077. $po = null;
  10078. }
  10079. if (!is_array($po)) {
  10080. $this->error('订单不存在');
  10081. }
  10082. $modRq = trim((string)($po['mod_rq'] ?? ''));
  10083. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  10084. $this->error('订单不存在');
  10085. }
  10086. if ($this->auth->isSuperAdmin()) {
  10087. return $po;
  10088. }
  10089. if ($this->canViewManualRfqOrder($po)) {
  10090. return $po;
  10091. }
  10092. $this->error('无权操作该订单');
  10093. }
  10094. /**
  10095. * @return string[]
  10096. */
  10097. protected function splitRfqSalesmanNames(string $raw): array
  10098. {
  10099. $parts = [];
  10100. $raw = trim($raw);
  10101. if ($raw === '') {
  10102. return [];
  10103. }
  10104. foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
  10105. $v = trim((string)$piece);
  10106. if ($v !== '' && !in_array($v, $parts, true)) {
  10107. $parts[] = $v;
  10108. }
  10109. }
  10110. return $parts;
  10111. }
  10112. /**
  10113. * 按姓名匹配 fa_admin 邮箱
  10114. *
  10115. * @param string[] $names
  10116. * @return array<int, array{admin_id:int,name:string,email:string}>
  10117. */
  10118. protected function resolveRfqSalesmanContactRows(array $names): array
  10119. {
  10120. $out = [];
  10121. foreach ($names as $name) {
  10122. $name = trim((string)$name);
  10123. if ($name === '') {
  10124. continue;
  10125. }
  10126. $adminId = 0;
  10127. $email = '';
  10128. try {
  10129. $row = Db::name('admin')
  10130. ->where(function ($q) use ($name) {
  10131. $q->where('nickname', $name)->whereOr('username', $name);
  10132. })
  10133. ->where('status', 'normal')
  10134. ->order('id', 'asc')
  10135. ->field('id,nickname,username,email')
  10136. ->find();
  10137. } catch (\Throwable $e) {
  10138. $row = null;
  10139. }
  10140. if (is_array($row)) {
  10141. $adminId = (int)($row['id'] ?? 0);
  10142. $email = trim((string)($row['email'] ?? ''));
  10143. $disp = trim((string)($row['nickname'] ?? ''));
  10144. if ($disp === '') {
  10145. $disp = trim((string)($row['username'] ?? ''));
  10146. }
  10147. if ($disp !== '') {
  10148. $name = $disp;
  10149. }
  10150. }
  10151. $out[] = [
  10152. 'admin_id' => $adminId,
  10153. 'name' => $name,
  10154. 'email' => $email,
  10155. ];
  10156. }
  10157. return $out;
  10158. }
  10159. /**
  10160. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  10161. */
  10162. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  10163. {
  10164. if ($scydgyId >= 0) {
  10165. return;
  10166. }
  10167. try {
  10168. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10169. } catch (\Throwable $e) {
  10170. $po = null;
  10171. }
  10172. if (!is_array($po)) {
  10173. $this->error('订单不存在');
  10174. }
  10175. $modRq = trim((string)($po['mod_rq'] ?? ''));
  10176. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  10177. $this->error('订单不存在');
  10178. }
  10179. if ($this->auth->isSuperAdmin()) {
  10180. return;
  10181. }
  10182. [, $adminName] = $this->GetUseName();
  10183. $cywy = trim((string)($po['cywyxm'] ?? ''));
  10184. if ($cywy !== '' && $cywy === $adminName) {
  10185. return;
  10186. }
  10187. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  10188. try {
  10189. if ($this->auth->check($rule)) {
  10190. return;
  10191. }
  10192. } catch (\Throwable $e) {
  10193. }
  10194. }
  10195. $this->error('无权查看该订单');
  10196. }
  10197. /**
  10198. * 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
  10199. */
  10200. protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
  10201. {
  10202. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  10203. return ProcuremenStatus::PO_COMPLETED;
  10204. }
  10205. $sid = (int)($row['scydgy_id'] ?? 0);
  10206. if ($sid < 0) {
  10207. if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
  10208. return '已通知业务员';
  10209. }
  10210. if ($hasQuoted) {
  10211. return '供应商已报价';
  10212. }
  10213. if ($hasIssued
  10214. || ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
  10215. || ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
  10216. return '待报价';
  10217. }
  10218. try {
  10219. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  10220. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  10221. if ((int)$detCntQuery->count() > 0) {
  10222. return '待报价';
  10223. }
  10224. } catch (\Throwable $e) {
  10225. }
  10226. return '待询价';
  10227. }
  10228. if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
  10229. return '待入库评分';
  10230. }
  10231. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  10232. return '待采购确认';
  10233. }
  10234. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  10235. return '待确认供应商';
  10236. }
  10237. return '待协助下发';
  10238. }
  10239. /**
  10240. * 协助初选列表 — 批量软删除
  10241. */
  10242. public function pickDelete()
  10243. {
  10244. if (!$this->request->isPost() || !$this->request->isAjax()) {
  10245. $this->error(__('Invalid parameters'));
  10246. }
  10247. if (!$this->procuremenCanPickDelete()) {
  10248. $this->error(__('You have no permission'));
  10249. }
  10250. $rowsRaw = $this->request->post('rows_json', '[]');
  10251. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  10252. if (!is_array($rows) || $rows === []) {
  10253. $this->error('请至少勾选一条工序');
  10254. }
  10255. $done = 0;
  10256. Db::startTrans();
  10257. try {
  10258. foreach ($rows as $row) {
  10259. if (!is_array($row)) {
  10260. continue;
  10261. }
  10262. $this->softDeleteProcuremenPickRow($row);
  10263. $done++;
  10264. }
  10265. if ($done < 1) {
  10266. throw new \Exception('没有可删除的工序');
  10267. }
  10268. Db::commit();
  10269. } catch (\InvalidArgumentException $e) {
  10270. Db::rollback();
  10271. $this->error($e->getMessage());
  10272. } catch (\Throwable $e) {
  10273. Db::rollback();
  10274. $this->error($e->getMessage());
  10275. }
  10276. $this->pickHiddenScydgySetCache = null;
  10277. $this->success('已删除 ' . $done . ' 条工序');
  10278. }
  10279. /**
  10280. * 下发 — 手工新增工序(弹窗)
  10281. */
  10282. public function pickAdd()
  10283. {
  10284. if ($this->request->isPost()) {
  10285. $params = $this->request->post('row/a');
  10286. if (!is_array($params)) {
  10287. $this->error(__('Parameter %s can not be empty', ''));
  10288. }
  10289. try {
  10290. $sid = $this->saveManualPickOrder($params);
  10291. } catch (\InvalidArgumentException $e) {
  10292. $this->error($e->getMessage());
  10293. } catch (\Throwable $e) {
  10294. $this->error($e->getMessage());
  10295. }
  10296. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  10297. }
  10298. return $this->view->fetch('procuremen/pick_add');
  10299. }
  10300. /**
  10301. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  10302. */
  10303. public function pickSubmit()
  10304. {
  10305. if (!$this->request->isPost()) {
  10306. $this->error(__('Invalid parameters'));
  10307. }
  10308. // ---------- 接口订单数据 ----------
  10309. $rowJson = $this->request->post('row_json', '');
  10310. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  10311. $companiesJson = $this->request->post('companies_json', '[]');
  10312. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  10313. $companies = json_decode($companiesJson, true);
  10314. if (!is_array($companies)) {
  10315. $this->error('供应商数据无效');
  10316. }
  10317. $issueCompanies = $this->normalizePickCompanies($companies);
  10318. if ($issueCompanies === []) {
  10319. $this->error('请至少选择一家合作供应商');
  10320. }
  10321. $issueNameLabels = [];
  10322. foreach ($issueCompanies as $pc) {
  10323. $issueNameLabels[] = $pc['name'];
  10324. }
  10325. $issueNamesSummary = implode('、', $issueNameLabels);
  10326. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  10327. if ($sysRq === '') {
  10328. $this->error('请选择招标截止日期');
  10329. }
  10330. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  10331. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  10332. (string)$this->request->post('delivery_deadline', ''),
  10333. true
  10334. );
  10335. $scoreRuleId = (int)$this->request->post('score_rule_id', 0);
  10336. if ($scoreRuleId <= 0) {
  10337. $this->error('请选择订单类型');
  10338. }
  10339. $scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
  10340. if ((int)($scoreRule['id'] ?? 0) <= 0) {
  10341. $this->error('订单类型无效,请刷新后重选');
  10342. }
  10343. $scoreRuleId = (int)$scoreRule['id'];
  10344. $this->ensurePurchaseOrderScoreRuleIdColumn();
  10345. $isMerge = count($mergeRows) > 1;
  10346. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  10347. $logMsg = '下发' . $procPart
  10348. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  10349. $issueTime = date('Y-m-d H:i:s');
  10350. $logSidList = [];
  10351. foreach ($mergeRows as $row) {
  10352. if (!is_array($row)) {
  10353. continue;
  10354. }
  10355. $sid = $this->extractScydgyRowId($row);
  10356. if ($this->isValidScydgyRowId($sid)) {
  10357. $logSidList[$sid] = true;
  10358. }
  10359. }
  10360. $existingBySid = [];
  10361. if ($logSidList !== []) {
  10362. try {
  10363. $existingRows = Db::table('purchase_order')
  10364. ->where('scydgy_id', 'in', array_keys($logSidList))
  10365. ->select();
  10366. if (is_array($existingRows)) {
  10367. foreach ($existingRows as $poRow) {
  10368. if (!is_array($poRow)) {
  10369. continue;
  10370. }
  10371. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10372. if ($this->isValidScydgyRowId($sid)) {
  10373. $existingBySid[$sid] = $poRow;
  10374. }
  10375. }
  10376. }
  10377. } catch (\Throwable $e) {
  10378. $existingBySid = [];
  10379. }
  10380. }
  10381. Db::startTrans();
  10382. try {
  10383. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  10384. foreach ($mergeRows as $row) {
  10385. if (!is_array($row)) {
  10386. continue;
  10387. }
  10388. $sid = $this->extractScydgyRowId($row);
  10389. $this->upsertPurchaseOrderFromRow(
  10390. $row,
  10391. $sysRqDb,
  10392. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  10393. $issueTime,
  10394. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  10395. $deliveryDeadlineDb,
  10396. $scoreRule
  10397. );
  10398. }
  10399. foreach ($issueCompanies as $c) {
  10400. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10401. }
  10402. Db::commit();
  10403. } catch (\Throwable $e) {
  10404. Db::rollback();
  10405. $this->error($e->getMessage());
  10406. }
  10407. $poIdBySid = [];
  10408. if ($logSidList !== []) {
  10409. try {
  10410. $poIdBySid = Db::table('purchase_order')
  10411. ->where('scydgy_id', 'in', array_keys($logSidList))
  10412. ->column('id', 'scydgy_id');
  10413. } catch (\Throwable $e) {
  10414. $poIdBySid = [];
  10415. }
  10416. }
  10417. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  10418. if ($logSidList !== []) {
  10419. list($adminId, $adminName) = $this->GetUseName();
  10420. $logRows = [];
  10421. $seenLogSid = [];
  10422. foreach ($mergeRows as $row) {
  10423. if (!is_array($row)) {
  10424. continue;
  10425. }
  10426. $ids = $this->extractScydgyRowId($row);
  10427. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  10428. continue;
  10429. }
  10430. $seenLogSid[$ids] = true;
  10431. $poIdLog = null;
  10432. if (isset($poIdBySid[$ids])) {
  10433. $tid = (int)$poIdBySid[$ids];
  10434. $poIdLog = $tid > 0 ? $tid : null;
  10435. }
  10436. $logRows[] = ProcuremenOperLog::buildInsertRow(
  10437. $ids,
  10438. 'issue_submit',
  10439. $logMsg,
  10440. $poIdLog,
  10441. (int)$adminId,
  10442. (string)$adminName
  10443. );
  10444. }
  10445. if ($logRows !== []) {
  10446. try {
  10447. Db::table('purchase_order_oper_log')->insertAll($logRows);
  10448. } catch (\Throwable $e) {
  10449. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  10450. }
  10451. }
  10452. }
  10453. $notifyErrors = [];
  10454. $posNotify = [];
  10455. if ($logSidList !== []) {
  10456. try {
  10457. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  10458. } catch (\Throwable $e) {
  10459. $posNotify = [];
  10460. }
  10461. }
  10462. if (!is_array($posNotify)) {
  10463. $posNotify = [];
  10464. }
  10465. foreach ($posNotify as $i => $prow) {
  10466. if (is_array($posNotify[$i])) {
  10467. $posNotify[$i]['sys_rq'] = $sysRqDb;
  10468. }
  10469. }
  10470. $ccydhPick = '';
  10471. foreach ($mergeRows as $row) {
  10472. if (!is_array($row)) {
  10473. continue;
  10474. }
  10475. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  10476. if ($ccydhPick !== '') {
  10477. break;
  10478. }
  10479. }
  10480. $notifyBundleBase = [
  10481. 'ccydh' => $ccydhPick,
  10482. 'pos' => $posNotify,
  10483. 'merge_rows' => $mergeRows,
  10484. 'score_rule' => is_array($scoreRule) ? $scoreRule : null,
  10485. ];
  10486. try {
  10487. $this->notifyDryRunPreview = [];
  10488. foreach ($issueCompanies as $c) {
  10489. if (!is_array($c)) {
  10490. continue;
  10491. }
  10492. $cname = trim((string)($c['name'] ?? ''));
  10493. if ($cname === '') {
  10494. continue;
  10495. }
  10496. try {
  10497. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  10498. } catch (\Throwable $e) {
  10499. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10500. }
  10501. }
  10502. } catch (\Throwable $e) {
  10503. $this->error('通知发送失败:' . $e->getMessage());
  10504. }
  10505. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10506. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  10507. }
  10508. if ($this->isProcuremenNotifyDryRun()) {
  10509. $this->success('【演练模式】已保存并生成通知预览', '', [
  10510. 'notify_dry_run' => true,
  10511. 'notify_preview' => $this->notifyDryRunPreview,
  10512. ]);
  10513. }
  10514. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  10515. }
  10516. /**
  10517. * 确认供应商弹窗
  10518. */
  10519. public function auditIssue()
  10520. {
  10521. $ids = $this->request->param('ids', $this->request->param('id', ''));
  10522. if (is_array($ids)) {
  10523. $ids = isset($ids[0]) ? $ids[0] : '';
  10524. }
  10525. $ids = trim((string)$ids);
  10526. if ($ids === '') {
  10527. $this->error(__('Invalid parameters'));
  10528. }
  10529. if ($this->request->isPost()) {
  10530. $this->error('请使用弹窗内「确认」提交');
  10531. }
  10532. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10533. $pos = $bundle['pos'];
  10534. if ($pos === []) {
  10535. $this->error('该订单不在待确认供应商状态');
  10536. }
  10537. $po = $pos[0];
  10538. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10539. if ($quoteGroups === []) {
  10540. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  10541. }
  10542. $pickedName = '';
  10543. foreach ($pos as $poRow) {
  10544. if (!is_array($poRow)) {
  10545. continue;
  10546. }
  10547. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  10548. if ($pn !== '') {
  10549. $pickedName = $pn;
  10550. break;
  10551. }
  10552. }
  10553. $this->view->assign('po', $po);
  10554. $this->view->assign('scydgyId', $ids);
  10555. $this->view->assign('orderCcydh', $bundle['ccydh']);
  10556. $mergeRows = $bundle['merge_rows'];
  10557. $this->view->assign('processRows', $mergeRows);
  10558. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  10559. $this->view->assign('processCount', count($mergeRows));
  10560. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  10561. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  10562. $this->view->assign('pickedCompanyName', $pickedName);
  10563. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10564. if ($sysRqForView === '') {
  10565. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10566. }
  10567. $this->view->assign('sysRq', $sysRqForView);
  10568. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  10569. if ($deliveryDeadlineForView === '') {
  10570. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10571. }
  10572. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10573. $this->ensurePurchaseOrderManualPickColumns();
  10574. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
  10575. $manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
  10576. $manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
  10577. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  10578. if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
  10579. $pickedName = $manualPickInfo['company'];
  10580. $this->view->assign('pickedCompanyName', $pickedName);
  10581. }
  10582. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  10583. $this->view->assign('manualPicked', $manualPicked);
  10584. $this->view->assign('manualPickReason', $manualPickInfo['reason']);
  10585. $this->view->assign('quoteVisible', $quoteVisible);
  10586. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
  10587. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  10588. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
  10589. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
  10590. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  10591. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  10592. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  10593. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  10594. return $this->view->fetch('procuremen/audit_issue');
  10595. }
  10596. /**
  10597. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  10598. *
  10599. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10600. */
  10601. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  10602. {
  10603. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10604. return false;
  10605. }
  10606. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10607. return false;
  10608. }
  10609. return true;
  10610. }
  10611. /**
  10612. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  10613. *
  10614. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10615. */
  10616. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  10617. {
  10618. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10619. return false;
  10620. }
  10621. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10622. return false;
  10623. }
  10624. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  10625. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  10626. return true;
  10627. }
  10628. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  10629. }
  10630. /**
  10631. * 确认页 — 补加供应商弹窗
  10632. */
  10633. public function auditAppend()
  10634. {
  10635. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  10636. $this->error(__('You have no permission'));
  10637. }
  10638. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  10639. if (is_array($ids)) {
  10640. $ids = isset($ids[0]) ? $ids[0] : '';
  10641. }
  10642. $ids = trim((string)$ids);
  10643. if ($ids === '') {
  10644. $this->error(__('Invalid parameters'));
  10645. }
  10646. if ($this->request->isPost()) {
  10647. $this->error('请使用弹窗内「确认」提交');
  10648. }
  10649. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10650. if (($bundle['pos'] ?? []) === []) {
  10651. $this->error('该订单不在待确认供应商状态');
  10652. }
  10653. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10654. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10655. $this->error('已开标验证,不能再补加供应商');
  10656. }
  10657. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10658. $this->error('已指定供应商,不能再补加供应商');
  10659. }
  10660. $this->error('已经超过了招标截止日期,不可操作');
  10661. }
  10662. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10663. $existingNames = [];
  10664. foreach ($quoteGroups as $g) {
  10665. if (!is_array($g)) {
  10666. continue;
  10667. }
  10668. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  10669. if ($n !== '') {
  10670. $existingNames[$n] = true;
  10671. }
  10672. }
  10673. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  10674. $mergeRows = $bundle['merge_rows'] ?? [];
  10675. $this->view->assign('scydgyId', $ids);
  10676. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  10677. $this->view->assign('po', $po);
  10678. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  10679. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  10680. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  10681. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10682. if ($sysRqForView === '') {
  10683. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10684. }
  10685. $this->view->assign('sysRq', $sysRqForView);
  10686. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  10687. if ($deliveryDeadlineForView === '') {
  10688. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10689. }
  10690. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10691. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  10692. }
  10693. /**
  10694. * 确认页 — 补加供应商提交
  10695. */
  10696. public function auditAppendSubmit()
  10697. {
  10698. if (!$this->request->isPost()) {
  10699. $this->error(__('Invalid parameters'));
  10700. }
  10701. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  10702. $this->error(__('You have no permission'));
  10703. }
  10704. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  10705. if ($ids === '') {
  10706. $this->error(__('Invalid parameters'));
  10707. }
  10708. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10709. if (($bundle['pos'] ?? []) === []) {
  10710. $this->error('该订单不在待确认供应商状态');
  10711. }
  10712. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10713. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10714. $this->error('已开标验证,不能再补加供应商');
  10715. }
  10716. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10717. $this->error('已指定供应商,不能再补加供应商');
  10718. }
  10719. $this->error('已经超过了招标截止日期,不可操作');
  10720. }
  10721. $companiesJson = $this->request->post('companies_json', '[]');
  10722. $companies = json_decode((string)$companiesJson, true);
  10723. if (!is_array($companies)) {
  10724. $this->error('供应商数据无效');
  10725. }
  10726. $issueCompanies = $this->normalizePickCompanies($companies);
  10727. if ($issueCompanies === []) {
  10728. $this->error('请至少选择一家合作供应商');
  10729. }
  10730. $mergeRows = $bundle['merge_rows'] ?? [];
  10731. if (!is_array($mergeRows) || $mergeRows === []) {
  10732. $this->error('未找到工序行,无法补加');
  10733. }
  10734. $existingNames = [];
  10735. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  10736. if (!is_array($g)) {
  10737. continue;
  10738. }
  10739. $n = trim((string)($g['company_name'] ?? ''));
  10740. if ($n !== '') {
  10741. $existingNames[$n] = true;
  10742. }
  10743. }
  10744. $toAdd = [];
  10745. foreach ($issueCompanies as $c) {
  10746. if (!is_array($c)) {
  10747. continue;
  10748. }
  10749. $n = trim((string)($c['name'] ?? ''));
  10750. if ($n === '' || isset($existingNames[$n])) {
  10751. continue;
  10752. }
  10753. $toAdd[] = $c;
  10754. }
  10755. if ($toAdd === []) {
  10756. $this->error('所选供应商均已在本单中,请选择新的供应商');
  10757. }
  10758. $addedNames = [];
  10759. Db::startTrans();
  10760. try {
  10761. foreach ($toAdd as $c) {
  10762. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10763. $addedNames[] = trim((string)($c['name'] ?? ''));
  10764. }
  10765. Db::commit();
  10766. } catch (\Throwable $e) {
  10767. Db::rollback();
  10768. $this->error($e->getMessage());
  10769. }
  10770. $notifyErrors = [];
  10771. $notifyBundleBase = [
  10772. 'ccydh' => $bundle['ccydh'] ?? '',
  10773. 'pos' => $bundle['pos'] ?? [],
  10774. 'merge_rows' => $mergeRows,
  10775. ];
  10776. foreach ($toAdd as $c) {
  10777. if (!is_array($c)) {
  10778. continue;
  10779. }
  10780. $cname = trim((string)($c['name'] ?? ''));
  10781. if ($cname === '') {
  10782. continue;
  10783. }
  10784. try {
  10785. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  10786. } catch (\Throwable $e) {
  10787. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10788. }
  10789. }
  10790. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  10791. $seenLogSid = [];
  10792. foreach ($bundle['pos'] ?? [] as $poRow) {
  10793. if (!is_array($poRow)) {
  10794. continue;
  10795. }
  10796. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10797. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  10798. continue;
  10799. }
  10800. $seenLogSid[$sid] = true;
  10801. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10802. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10803. }
  10804. if ($seenLogSid === []) {
  10805. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  10806. if ($this->isValidScydgyRowId($logSid)) {
  10807. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  10808. }
  10809. }
  10810. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10811. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  10812. }
  10813. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  10814. }
  10815. /**
  10816. * 开标双重验证 — 可选验证人列表
  10817. */
  10818. public function bidOpenUsers()
  10819. {
  10820. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10821. $this->error('无权限');
  10822. }
  10823. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  10824. if ($scydgyId !== '') {
  10825. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10826. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10827. $this->success('已完成开标验证', null, [
  10828. 'verified' => 1,
  10829. 'users' => [],
  10830. ]);
  10831. }
  10832. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10833. $this->error('本单已指定供应商,无需再开标');
  10834. }
  10835. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10836. }
  10837. $this->success('', null, [
  10838. 'verified' => 0,
  10839. 'users' => $this->listBidOpenVerifierCandidates(),
  10840. ]);
  10841. }
  10842. /**
  10843. * 开标双重验证 — 向指定管理员发送短信验证码
  10844. */
  10845. public function bidOpenSendCode()
  10846. {
  10847. if (!$this->request->isPost()) {
  10848. $this->error(__('Invalid parameters'));
  10849. }
  10850. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10851. $this->error('无权限');
  10852. }
  10853. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10854. $adminId = (int)$this->request->post('admin_id', 0);
  10855. if ($scydgyId === '' || $adminId <= 0) {
  10856. $this->error('参数无效');
  10857. }
  10858. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10859. if ($bundle['pos'] === []) {
  10860. $this->error('该订单不在待确认供应商状态');
  10861. }
  10862. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10863. $this->success('已完成开标验证,无需重复发送');
  10864. }
  10865. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10866. $this->error('本单已指定供应商,无需再开标');
  10867. }
  10868. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10869. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10870. if ($ccydh === '') {
  10871. $this->error('订单号无效');
  10872. }
  10873. $admin = $this->loadBidOpenAdminUser($adminId);
  10874. if ($admin === null) {
  10875. $this->error('验证人无效或未绑定手机号');
  10876. }
  10877. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  10878. $cd = max(30, min(120, $cd));
  10879. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  10880. $this->error('发送过于频繁,请稍后再试');
  10881. }
  10882. $code = (string)random_int(100000, 999999);
  10883. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  10884. $ttl = max(60, min(600, $ttl));
  10885. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  10886. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  10887. try {
  10888. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  10889. } catch (\Throwable $e) {
  10890. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  10891. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  10892. $this->error($e->getMessage());
  10893. }
  10894. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  10895. }
  10896. /**
  10897. * 开标双重验证 — 两人验证码校验并记录
  10898. */
  10899. public function bidOpenVerify()
  10900. {
  10901. if (!$this->request->isPost()) {
  10902. $this->error(__('Invalid parameters'));
  10903. }
  10904. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10905. $this->error('无权限');
  10906. }
  10907. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10908. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  10909. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  10910. $code1 = trim((string)$this->request->post('code1', ''));
  10911. $code2 = trim((string)$this->request->post('code2', ''));
  10912. if ($scydgyId === '') {
  10913. $this->error('参数无效');
  10914. }
  10915. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  10916. $this->error('请选择两位验证人');
  10917. }
  10918. if ($verifier1Id === $verifier2Id) {
  10919. $this->error('两位验证人不能相同');
  10920. }
  10921. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  10922. $this->error('请输入6位短信验证码');
  10923. }
  10924. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10925. if ($bundle['pos'] === []) {
  10926. $this->error('该订单不在待确认供应商状态');
  10927. }
  10928. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10929. if ($ccydh === '') {
  10930. $this->error('订单号无效');
  10931. }
  10932. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10933. $this->success('已完成开标验证');
  10934. }
  10935. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10936. $this->error('本单已指定供应商,无需再开标');
  10937. }
  10938. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10939. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  10940. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  10941. if ($verifier1 === null || $verifier2 === null) {
  10942. $this->error('验证人无效或未绑定手机号');
  10943. }
  10944. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  10945. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  10946. }
  10947. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  10948. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  10949. }
  10950. try {
  10951. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  10952. } catch (\Throwable $e) {
  10953. $this->error($e->getMessage());
  10954. }
  10955. $this->success('开标验证成功,可查看供应商报价与交货日期');
  10956. }
  10957. /**
  10958. * 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
  10959. */
  10960. public function auditManualPick()
  10961. {
  10962. if (!$this->request->isPost()) {
  10963. $this->error(__('Invalid parameters'));
  10964. }
  10965. if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
  10966. $this->error('无权限');
  10967. }
  10968. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10969. if ($scydgyId === '') {
  10970. $this->error('参数无效');
  10971. }
  10972. $companyName = trim((string)$this->request->post('selected_company', ''));
  10973. $reason = trim((string)$this->request->post('pick_reason', ''));
  10974. if ($companyName === '') {
  10975. $this->error('请选择一家供应商');
  10976. }
  10977. if ($reason === '') {
  10978. $this->error('请填写选择说明');
  10979. }
  10980. if (mb_strlen($reason) > 500) {
  10981. $this->error('选择说明不能超过500字');
  10982. }
  10983. $this->ensurePurchaseOrderManualPickColumns();
  10984. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10985. $pos = $bundle['pos'];
  10986. if ($pos === []) {
  10987. $this->error('该订单不在待确认供应商状态');
  10988. }
  10989. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10990. $this->error('本单已开标验证,请直接在列表中选定供应商后确认');
  10991. }
  10992. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10993. if ($quoteGroups === []) {
  10994. $this->error('暂无供应商,请确认已完成协助初选通知');
  10995. }
  10996. $matched = null;
  10997. foreach ($quoteGroups as $g) {
  10998. if (!is_array($g)) {
  10999. continue;
  11000. }
  11001. if (trim((string)($g['name'] ?? '')) === $companyName) {
  11002. $matched = $g;
  11003. break;
  11004. }
  11005. }
  11006. if ($matched === null) {
  11007. $this->error('所选供应商不在本单报价列表中');
  11008. }
  11009. $logMsg = '指定供应商:已选定「' . $companyName . '」;说明:' . $reason;
  11010. Db::startTrans();
  11011. try {
  11012. foreach ($pos as $poRow) {
  11013. if (!is_array($poRow)) {
  11014. continue;
  11015. }
  11016. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11017. if (!$this->isValidScydgyRowId($sid)) {
  11018. continue;
  11019. }
  11020. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11021. 'pick_company_name' => $companyName,
  11022. 'manual_pick' => 1,
  11023. 'manual_pick_reason' => $reason,
  11024. ]);
  11025. }
  11026. Db::commit();
  11027. } catch (\Throwable $e) {
  11028. Db::rollback();
  11029. $this->error($e->getMessage());
  11030. }
  11031. foreach ($pos as $poRow) {
  11032. if (!is_array($poRow)) {
  11033. continue;
  11034. }
  11035. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11036. if (!$this->isValidScydgyRowId($sid)) {
  11037. continue;
  11038. }
  11039. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11040. $this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11041. }
  11042. // 自选后可见报价:按本单规则计算评分(与开标后一致)
  11043. try {
  11044. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11045. if ($ccydh !== '') {
  11046. // 重新加载以拿到未掩码报价参与计分
  11047. $bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11048. $groupsFresh = $this->loadAuditSupplierQuoteGroups($bundleFresh);
  11049. ProcuremenSupplierScore::saveForOrder($ccydh, $groupsFresh, date('Y-m'));
  11050. }
  11051. } catch (\Throwable $e) {
  11052. Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
  11053. }
  11054. $this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
  11055. }
  11056. /**
  11057. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  11058. */
  11059. public function auditSubmit()
  11060. {
  11061. if (!$this->request->isPost()) {
  11062. $this->error(__('Invalid parameters'));
  11063. }
  11064. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11065. if ($scydgyId === '') {
  11066. $this->error('参数无效');
  11067. }
  11068. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11069. $pos = $bundle['pos'];
  11070. $mergeRows = $bundle['merge_rows'];
  11071. if ($pos === [] || $mergeRows === []) {
  11072. $this->error('该订单不在待确认供应商状态');
  11073. }
  11074. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11075. if ($quoteGroups === []) {
  11076. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  11077. }
  11078. $companyName = trim((string)$this->request->post('selected_company', ''));
  11079. if ($companyName === '') {
  11080. $this->error('请选择一家供应商');
  11081. }
  11082. $matched = null;
  11083. foreach ($quoteGroups as $g) {
  11084. if (!is_array($g)) {
  11085. continue;
  11086. }
  11087. if (trim((string)($g['name'] ?? '')) === $companyName) {
  11088. $matched = $g;
  11089. break;
  11090. }
  11091. }
  11092. if ($matched === null) {
  11093. $this->error('所选供应商不在本单报价列表中');
  11094. }
  11095. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  11096. if ($sysRqDb === '') {
  11097. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  11098. } else {
  11099. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  11100. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  11101. }
  11102. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  11103. $this->error('未到招标截止日期,暂不可确认');
  11104. }
  11105. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
  11106. && !$this->isProcuremenManualPickedForBundle($bundle)
  11107. ) {
  11108. $this->error('请先完成开标双重验证或指定供应商后再确认');
  11109. }
  11110. $procCnt = count($mergeRows);
  11111. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  11112. $logMsg = '确认供应商' . $procPart . ':已选定「' . $companyName . '」';
  11113. Db::startTrans();
  11114. try {
  11115. foreach ($pos as $poRow) {
  11116. if (!is_array($poRow)) {
  11117. continue;
  11118. }
  11119. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11120. if (!$this->isValidScydgyRowId($sid)) {
  11121. continue;
  11122. }
  11123. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11124. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  11125. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11126. 'pick_company_name' => $companyName,
  11127. 'sys_rq' => $sysRqDb,
  11128. ]);
  11129. }
  11130. Db::commit();
  11131. } catch (\Throwable $e) {
  11132. Db::rollback();
  11133. $this->error($e->getMessage());
  11134. }
  11135. foreach ($pos as $poRow) {
  11136. if (!is_array($poRow)) {
  11137. continue;
  11138. }
  11139. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11140. if (!$this->isValidScydgyRowId($sid)) {
  11141. continue;
  11142. }
  11143. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11144. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11145. }
  11146. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  11147. }
  11148. /**
  11149. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  11150. */
  11151. public function auditResendSms()
  11152. {
  11153. if (!$this->request->isPost()) {
  11154. $this->error(__('Invalid parameters'));
  11155. }
  11156. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11157. if ($scydgyId === '') {
  11158. $this->error('参数无效');
  11159. }
  11160. $loaded = $this->loadAuditResendBundle($scydgyId);
  11161. $mergeRows = $loaded['merge_rows'];
  11162. $bundle = $loaded['bundle'];
  11163. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  11164. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11165. if ($quoteGroups === []) {
  11166. $this->error('暂无可通知的供应商');
  11167. }
  11168. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  11169. $companiesJson = (string)$this->request->post('companies_json', '');
  11170. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  11171. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  11172. }
  11173. /**
  11174. * 确认供应商 — 二次发送邮件(可选单家/批量)
  11175. */
  11176. public function auditResendEmail()
  11177. {
  11178. if (!$this->request->isPost()) {
  11179. $this->error(__('Invalid parameters'));
  11180. }
  11181. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11182. if ($scydgyId === '') {
  11183. $this->error('参数无效');
  11184. }
  11185. $loaded = $this->loadAuditResendBundle($scydgyId);
  11186. $mergeRows = $loaded['merge_rows'];
  11187. $bundle = $loaded['bundle'];
  11188. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  11189. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11190. if ($quoteGroups === []) {
  11191. $this->error('暂无可通知的供应商');
  11192. }
  11193. $companiesJson = (string)$this->request->post('companies_json', '');
  11194. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  11195. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  11196. if ($companiesJson === '' && $selectedCompany === '') {
  11197. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  11198. }
  11199. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  11200. }
  11201. /**
  11202. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  11203. *
  11204. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  11205. * @return array<int, true> 已处理的 scydgy_id 集合
  11206. */
  11207. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  11208. {
  11209. $pos = $bundle['pos'] ?? [];
  11210. if (!is_array($pos) || $pos === []) {
  11211. return [];
  11212. }
  11213. $sids = [];
  11214. $poIdBySid = [];
  11215. foreach ($pos as $poRow) {
  11216. if (!is_array($poRow)) {
  11217. continue;
  11218. }
  11219. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11220. if ($this->isValidScydgyRowId($sid)) {
  11221. $sids[$sid] = true;
  11222. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11223. if ($poId > 0) {
  11224. $poIdBySid[$sid] = $poId;
  11225. }
  11226. }
  11227. }
  11228. if ($sids === []) {
  11229. return [];
  11230. }
  11231. $logMsg = '重新下发';
  11232. $suffix = trim((string)$logSuffix, ',, ');
  11233. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  11234. $logMsg .= ':从历史存证退回协助初选';
  11235. } else {
  11236. $logMsg .= ':退回协助初选';
  11237. }
  11238. Db::table('purchase_order')
  11239. ->where('scydgy_id', 'in', array_keys($sids))
  11240. ->update([
  11241. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  11242. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11243. 'pick_company_name' => '',
  11244. 'pick_time' => null,
  11245. 'sys_rq' => null,
  11246. 'mod_rq' => null,
  11247. ]);
  11248. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  11249. foreach (array_keys($sids) as $sid) {
  11250. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  11251. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11252. }
  11253. return $sids;
  11254. }
  11255. /**
  11256. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  11257. *
  11258. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  11259. */
  11260. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  11261. {
  11262. $scydgyId = trim($scydgyId);
  11263. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11264. if ($scydgyId === '') {
  11265. return $empty;
  11266. }
  11267. try {
  11268. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  11269. } catch (\Throwable $e) {
  11270. $anchor = null;
  11271. }
  11272. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  11273. return $empty;
  11274. }
  11275. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  11276. if ($ccydh === '') {
  11277. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  11278. }
  11279. try {
  11280. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  11281. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  11282. $pos = $query->order('scydgy_id', 'asc')->select();
  11283. } catch (\Throwable $e) {
  11284. $pos = [$anchor];
  11285. }
  11286. if (!is_array($pos) || $pos === []) {
  11287. $pos = [$anchor];
  11288. }
  11289. return [
  11290. 'ccydh' => $ccydh,
  11291. 'pos' => $pos,
  11292. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  11293. ];
  11294. }
  11295. protected function purchaseOrderRowIsCompleted(array $po): bool
  11296. {
  11297. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11298. }
  11299. /**
  11300. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  11301. *
  11302. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  11303. */
  11304. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  11305. {
  11306. $scydgyId = trim($scydgyId);
  11307. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11308. if ($scydgyId === '') {
  11309. return $empty;
  11310. }
  11311. try {
  11312. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  11313. } catch (\Throwable $e) {
  11314. $anchor = null;
  11315. }
  11316. if (!is_array($anchor)) {
  11317. return $empty;
  11318. }
  11319. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  11320. if ($ccydh === '') {
  11321. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  11322. }
  11323. try {
  11324. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  11325. } catch (\Throwable $e) {
  11326. $pos = [$anchor];
  11327. }
  11328. if (!is_array($pos) || $pos === []) {
  11329. $pos = [$anchor];
  11330. }
  11331. return [
  11332. 'ccydh' => $ccydh,
  11333. 'pos' => $pos,
  11334. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  11335. ];
  11336. }
  11337. /**
  11338. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  11339. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  11340. */
  11341. public function auditAbandon()
  11342. {
  11343. if (!$this->request->isPost()) {
  11344. $this->error(__('Invalid parameters'));
  11345. }
  11346. $anchorIds = [];
  11347. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  11348. if ($batchRaw !== '') {
  11349. $decoded = json_decode($batchRaw, true);
  11350. if (is_array($decoded)) {
  11351. foreach ($decoded as $id) {
  11352. $s = trim((string)$id);
  11353. if ($s !== '') {
  11354. $anchorIds[] = $s;
  11355. }
  11356. }
  11357. }
  11358. }
  11359. if ($anchorIds === []) {
  11360. $single = trim((string)$this->request->post('scydgy_id', ''));
  11361. if ($single !== '') {
  11362. $anchorIds[] = $single;
  11363. }
  11364. }
  11365. if ($anchorIds === []) {
  11366. $this->error('请至少选择一条订单');
  11367. }
  11368. $processedCcydh = [];
  11369. $doneOrders = 0;
  11370. $allSids = [];
  11371. Db::startTrans();
  11372. try {
  11373. foreach ($anchorIds as $anchorId) {
  11374. $fromArchive = false;
  11375. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  11376. if (($bundle['pos'] ?? []) === []) {
  11377. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  11378. $fromArchive = ($bundle['pos'] ?? []) !== [];
  11379. }
  11380. if (($bundle['pos'] ?? []) === []) {
  11381. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  11382. $fromArchive = ($bundle['pos'] ?? []) !== [];
  11383. }
  11384. if (($bundle['pos'] ?? []) === []) {
  11385. continue;
  11386. }
  11387. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11388. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  11389. if (isset($processedCcydh[$dedupeKey])) {
  11390. continue;
  11391. }
  11392. $processedCcydh[$dedupeKey] = true;
  11393. $sids = $fromArchive
  11394. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回协助初选')
  11395. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  11396. if ($sids === []) {
  11397. continue;
  11398. }
  11399. $doneOrders++;
  11400. foreach (array_keys($sids) as $sid) {
  11401. $allSids[(int)$sid] = true;
  11402. }
  11403. }
  11404. if ($doneOrders < 1) {
  11405. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  11406. }
  11407. Db::commit();
  11408. } catch (\Throwable $e) {
  11409. Db::rollback();
  11410. $this->error($e->getMessage());
  11411. }
  11412. $this->pickHiddenScydgySetCache = null;
  11413. $msg = $doneOrders > 1
  11414. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  11415. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  11416. $this->success($msg);
  11417. }
  11418. /**
  11419. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  11420. */
  11421. public function archiveAbandon()
  11422. {
  11423. return $this->auditAbandon();
  11424. }
  11425. /**
  11426. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  11427. */
  11428. public function purchaseApprovalReject()
  11429. {
  11430. if (!$this->request->isPost() || !$this->request->isAjax()) {
  11431. $this->error(__('Invalid parameters'));
  11432. }
  11433. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  11434. $this->error(__('You have no permission'));
  11435. }
  11436. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  11437. $decoded = json_decode($batchRaw, true);
  11438. if (!is_array($decoded) || $decoded === []) {
  11439. $this->error('提交数据无效');
  11440. }
  11441. $done = 0;
  11442. Db::startTrans();
  11443. try {
  11444. foreach ($decoded as $item) {
  11445. if (!is_array($item)) {
  11446. continue;
  11447. }
  11448. $sid = (int)($item['scydgy_id'] ?? 0);
  11449. if (!$this->isValidScydgyRowId($sid)) {
  11450. continue;
  11451. }
  11452. $this->runPurchaseApprovalRejectForSid($sid);
  11453. $done++;
  11454. }
  11455. if ($done < 1) {
  11456. throw new \Exception('所选订单均不在待审批状态');
  11457. }
  11458. Db::commit();
  11459. } catch (\Throwable $e) {
  11460. Db::rollback();
  11461. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  11462. }
  11463. $this->pickHiddenScydgySetCache = null;
  11464. $this->success('已驳回并退回「协助审批下发」');
  11465. }
  11466. /**
  11467. * @throws \Exception
  11468. */
  11469. protected function runPurchaseApprovalRejectForSid(int $sid): void
  11470. {
  11471. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  11472. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  11473. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  11474. $allIds = $this->purchaseOrderDetail($sid);
  11475. if ($allIds === []) {
  11476. throw new \Exception('未找到下发明细');
  11477. }
  11478. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11479. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  11480. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11481. 'pick_company_name' => '',
  11482. ]);
  11483. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  11484. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  11485. $poId = 0;
  11486. try {
  11487. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  11488. if (is_array($po)) {
  11489. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11490. }
  11491. } catch (\Throwable $e) {
  11492. }
  11493. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  11494. }
  11495. /**
  11496. * 审核弹窗(旧入口,POST 已关闭)
  11497. */
  11498. public function review()
  11499. {
  11500. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  11501. $this->error(__('You have no permission'));
  11502. }
  11503. if ($this->request->isPost()) {
  11504. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  11505. }
  11506. $this->view->assign('pickMode', 0);
  11507. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  11508. }
  11509. /**
  11510. * 审核弹窗获取公司列表
  11511. */
  11512. public function reviewCompanies()
  11513. {
  11514. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  11515. $this->error(__('You have no permission'));
  11516. }
  11517. if (!$this->request->isAjax()) {
  11518. $this->error(__('Invalid parameters'));
  11519. }
  11520. $list = [];
  11521. try {
  11522. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  11523. $rows = Db::table('customer')
  11524. ->where(function ($q) {
  11525. $q->where('status', 1)
  11526. ->whereOr('status', '1')
  11527. ->whereOr('status', '')
  11528. ->whereNull('status');
  11529. })
  11530. ->order('id', 'desc')
  11531. ->select();
  11532. } catch (\Throwable $e) {
  11533. $this->success('', '', []);
  11534. return;
  11535. }
  11536. if (!is_array($rows)) {
  11537. $this->success('', '', []);
  11538. return;
  11539. }
  11540. $detailColCandidates = [
  11541. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  11542. 'company_detail', 'company_desc', 'address',
  11543. ];
  11544. foreach ($rows as $row) {
  11545. if (!is_array($row)) {
  11546. continue;
  11547. }
  11548. $norm = [];
  11549. foreach ($row as $k => $v) {
  11550. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  11551. }
  11552. $row = $norm;
  11553. $st = $row['status'] ?? '';
  11554. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  11555. continue;
  11556. }
  11557. $payload = $this->buildCustomerContactPayloadFromRow($row);
  11558. if ($payload === null) {
  11559. continue;
  11560. }
  11561. $detail = '';
  11562. foreach ($detailColCandidates as $dk) {
  11563. if (!isset($row[$dk])) {
  11564. continue;
  11565. }
  11566. $dv = trim((string)$row[$dk]);
  11567. if ($dv !== '') {
  11568. $detail = $dv;
  11569. break;
  11570. }
  11571. }
  11572. $payload['detail'] = $detail;
  11573. $list[] = $this->maskSupplierContactFields($payload);
  11574. }
  11575. $this->success('', '', $list);
  11576. }
  11577. /**
  11578. * 采购确认-下发明细弹窗:
  11579. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  11580. */
  11581. public function outward_detail()
  11582. {
  11583. $ids = $this->request->param('ids', $this->request->param('id', ''));
  11584. if (is_array($ids)) {
  11585. $ids = isset($ids[0]) ? $ids[0] : '';
  11586. }
  11587. $ids = trim((string)$ids);
  11588. if ($ids === '') {
  11589. $this->error(__('Invalid parameters'));
  11590. }
  11591. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  11592. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  11593. $wffTab = 'all';
  11594. }
  11595. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  11596. $purchaseOrderId = 0;
  11597. $po = null;
  11598. try {
  11599. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  11600. if (is_array($po)) {
  11601. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11602. }
  11603. } catch (\Throwable $e) {
  11604. $purchaseOrderId = 0;
  11605. $po = null;
  11606. }
  11607. if (!$isPurchaseConfirm && is_array($po)) {
  11608. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11609. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  11610. $isPurchaseConfirm = true;
  11611. }
  11612. }
  11613. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  11614. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11615. $confirmProcessCount = 1;
  11616. $confirmPickGroups = [];
  11617. $processDisplayRows = [];
  11618. $allDetailsBySid = [];
  11619. $requiredSidList = [];
  11620. $sidList = [$ids];
  11621. if ($isPurchaseConfirm) {
  11622. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  11623. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  11624. if ($mergeRows !== []) {
  11625. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  11626. }
  11627. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  11628. if ($confirmBundle['pos'] !== []) {
  11629. $sidList = [];
  11630. foreach ($confirmBundle['pos'] as $poRow) {
  11631. if (!is_array($poRow)) {
  11632. continue;
  11633. }
  11634. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11635. if (!$this->isValidScydgyRowId($sid)) {
  11636. continue;
  11637. }
  11638. $sidList[] = (string)$sid;
  11639. $requiredSidList[] = $sid;
  11640. }
  11641. }
  11642. if ($sidList === []) {
  11643. $sidList = [$ids];
  11644. $requiredSidList = [(int)$ids];
  11645. }
  11646. $confirmProcessCount = max(1, count($requiredSidList));
  11647. if (is_array($po) && $purchaseOrderId <= 0) {
  11648. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11649. }
  11650. }
  11651. $rows = [];
  11652. try {
  11653. if (count($sidList) === 1) {
  11654. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  11655. } else {
  11656. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  11657. }
  11658. } catch (\Throwable $e) {
  11659. $rows = [];
  11660. }
  11661. if ($isPurchaseConfirm) {
  11662. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  11663. }
  11664. foreach ($rows as &$r) {
  11665. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  11666. $r['id'] = $r['ID'];
  11667. }
  11668. if (isset($r['createtime'])) {
  11669. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  11670. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  11671. } else {
  11672. $r['createtime_text'] = (string)$r['createtime'];
  11673. }
  11674. } else {
  11675. $r['createtime_text'] = '';
  11676. }
  11677. if (is_array($r)) {
  11678. $r = $this->maskSupplierContactFields($r);
  11679. }
  11680. }
  11681. unset($r);
  11682. $pickedCompanyName = '';
  11683. $manualPicked = 0;
  11684. $manualPickReason = '';
  11685. $quoteVisible = 0;
  11686. $bidOpenVerified = 0;
  11687. if ($isPurchaseConfirm) {
  11688. // 确认包为空时,用当前主单兜底,避免指定说明读不到
  11689. if (($confirmBundle['ccydh'] ?? '') === '' && is_array($po)) {
  11690. $confirmBundle['ccydh'] = trim((string)($po['CCYDH'] ?? ''));
  11691. }
  11692. if (($confirmBundle['pos'] ?? []) === [] && is_array($po)) {
  11693. $confirmBundle['pos'] = [$po];
  11694. }
  11695. $manualPickInfo = $this->resolveProcuremenManualPickInfo($confirmBundle);
  11696. $manualPicked = $this->isProcuremenManualPickedForBundle($confirmBundle) ? 1 : 0;
  11697. $manualPickReason = (string)($manualPickInfo['reason'] ?? '');
  11698. if ($manualPickInfo['company'] !== '') {
  11699. $pickedCompanyName = $manualPickInfo['company'];
  11700. }
  11701. if ($pickedCompanyName === '') {
  11702. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  11703. if (!is_array($poRow)) {
  11704. continue;
  11705. }
  11706. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  11707. if ($pn !== '') {
  11708. $pickedCompanyName = $pn;
  11709. break;
  11710. }
  11711. }
  11712. }
  11713. // 再兜底:直接读当前主单字段
  11714. if (is_array($po) && (int)($po['manual_pick'] ?? 0) === 1) {
  11715. $manualPicked = 1;
  11716. if ($manualPickReason === '') {
  11717. $manualPickReason = trim((string)($po['manual_pick_reason'] ?? ''));
  11718. }
  11719. if ($pickedCompanyName === '') {
  11720. $pickedCompanyName = trim((string)($po['pick_company_name'] ?? ''));
  11721. }
  11722. }
  11723. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle) ? 1 : 0;
  11724. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  11725. }
  11726. $this->view->assign('rows', $rows ?: []);
  11727. $this->view->assign('rowCount', count($rows ?: []));
  11728. $this->view->assign('scydgyId', $ids);
  11729. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  11730. $this->view->assign('headTitle', $headTitle);
  11731. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  11732. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  11733. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  11734. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  11735. $this->view->assign('processDisplayRows', $processDisplayRows);
  11736. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  11737. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  11738. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  11739. $this->view->assign('manualPicked', $manualPicked);
  11740. $this->view->assign('manualPickReason', $manualPickReason);
  11741. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  11742. $this->view->assign('quoteVisible', $quoteVisible);
  11743. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
  11744. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  11745. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
  11746. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
  11747. $sysRqDisplay = '—';
  11748. if ($isPurchaseConfirm) {
  11749. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  11750. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  11751. );
  11752. }
  11753. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  11754. $this->view->assign('sysRq', $isPurchaseConfirm
  11755. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  11756. : '');
  11757. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  11758. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  11759. : '');
  11760. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  11761. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  11762. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  11763. if ($isPurchaseConfirm) {
  11764. return $this->view->fetch();
  11765. }
  11766. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  11767. $this->view->engine->layout(false);
  11768. try {
  11769. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  11770. $this->view->assign('dialogBody', $bodyHtml);
  11771. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  11772. } finally {
  11773. if ($restoreLayout) {
  11774. $this->view->engine->layout($restoreLayout);
  11775. }
  11776. }
  11777. }
  11778. /**
  11779. * 月度导出记录表(不存在时自动创建)
  11780. */
  11781. protected function ensurePurchaseMonthExportLogTable(): void
  11782. {
  11783. try {
  11784. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  11785. } catch (\Throwable $e) {
  11786. Db::execute(
  11787. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  11788. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  11789. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  11790. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  11791. `admin_name` varchar(64) NOT NULL DEFAULT '',
  11792. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  11793. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  11794. `createtime` int(10) unsigned DEFAULT NULL,
  11795. PRIMARY KEY (`id`),
  11796. KEY `idx_ym` (`ym`),
  11797. KEY `idx_ct` (`createtime`)
  11798. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  11799. );
  11800. }
  11801. }
  11802. /**
  11803. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  11804. *
  11805. * @param array<int, mixed> $dbRows
  11806. * @return array<int, array<string, mixed>>
  11807. */
  11808. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  11809. {
  11810. $keyword = trim((string)$this->request->get('search', ''));
  11811. if ($keyword === '') {
  11812. $keyword = trim((string)$this->request->request('search', ''));
  11813. }
  11814. $filter = $this->request->get('filter', '');
  11815. $op = $this->request->get('op', '');
  11816. if (is_string($filter) && $filter !== '') {
  11817. $filterArr = (array)json_decode($filter, true);
  11818. } else {
  11819. $filterArr = is_array($filter) ? $filter : [];
  11820. }
  11821. if (is_string($op) && $op !== '') {
  11822. $opArr = (array)json_decode($op, true);
  11823. } else {
  11824. $opArr = is_array($op) ? $op : [];
  11825. }
  11826. if ($keyword === '' && $filterArr === []) {
  11827. return array_values(array_filter($dbRows, 'is_array'));
  11828. }
  11829. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  11830. $out = [];
  11831. foreach ($dbRows as $row) {
  11832. if (!is_array($row)) {
  11833. continue;
  11834. }
  11835. if ($keyword !== '') {
  11836. $hit = false;
  11837. foreach ($searchFields as $f) {
  11838. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  11839. $hit = true;
  11840. break;
  11841. }
  11842. }
  11843. if (!$hit) {
  11844. continue;
  11845. }
  11846. }
  11847. $passFilter = true;
  11848. foreach ($filterArr as $field => $val) {
  11849. $field = (string)$field;
  11850. $val = trim((string)$val);
  11851. if ($field === '' || $val === '') {
  11852. continue;
  11853. }
  11854. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  11855. continue;
  11856. }
  11857. $cell = (string)($row[$field] ?? '');
  11858. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  11859. if ($mode === '=' || $mode === 'EQUAL') {
  11860. if (strcasecmp($cell, $val) !== 0) {
  11861. $passFilter = false;
  11862. break;
  11863. }
  11864. } elseif (mb_stripos($cell, $val) === false) {
  11865. $passFilter = false;
  11866. break;
  11867. }
  11868. }
  11869. if (!$passFilter) {
  11870. continue;
  11871. }
  11872. $out[] = $row;
  11873. }
  11874. return $out;
  11875. }
  11876. /**
  11877. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  11878. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  11879. */
  11880. public function export_month_outward()
  11881. {
  11882. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  11883. $this->error(__('You have no permission'));
  11884. }
  11885. $bundle = $this->prepareMonthOutwardExportBundle();
  11886. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  11887. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  11888. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  11889. $spreadsheet = new Spreadsheet();
  11890. $sheet = $spreadsheet->getActiveSheet();
  11891. $sheet->setTitle('外协加工明细');
  11892. $mon = (int)substr($ym, 5, 2);
  11893. $sheet->mergeCells('A1:H1');
  11894. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  11895. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  11896. $sheet->getStyle('A1')->getAlignment()
  11897. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11898. ->setVertical(Alignment::VERTICAL_CENTER);
  11899. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  11900. $col = 'A';
  11901. foreach ($headers as $h) {
  11902. $sheet->setCellValue($col . '2', $h);
  11903. $col++;
  11904. }
  11905. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  11906. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11907. $rowNum = 3;
  11908. $sumSubtotalCounts = 0;
  11909. $grandAmount = 0.0;
  11910. $globalSeq = 0;
  11911. if ($groups === []) {
  11912. $sheet->mergeCells('A3:H3');
  11913. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  11914. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11915. $rowNum = 4;
  11916. } else {
  11917. foreach ($groups as $items) {
  11918. if ($items === []) {
  11919. continue;
  11920. }
  11921. $groupLineCount = count($items);
  11922. $subAmount = 0.0;
  11923. foreach ($items as $line) {
  11924. $globalSeq++;
  11925. $dr = $line['detail'];
  11926. $amt = $this->procuremenExportAmount($dr);
  11927. $subAmount += $amt;
  11928. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  11929. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  11930. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  11931. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  11932. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  11933. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  11934. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  11935. $sheet->setCellValue('H' . $rowNum, $amt);
  11936. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  11937. $rowNum++;
  11938. }
  11939. $sumSubtotalCounts += $groupLineCount;
  11940. $grandAmount += $subAmount;
  11941. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11942. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  11943. $sheet->getStyle('G' . $rowNum)->getAlignment()
  11944. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  11945. ->setVertical(Alignment::VERTICAL_CENTER);
  11946. $rowNum++;
  11947. }
  11948. }
  11949. $sheet->setCellValue('A' . $rowNum, '总计');
  11950. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  11951. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11952. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  11953. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  11954. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  11955. $lastRow = $rowNum;
  11956. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  11957. 'borders' => [
  11958. 'allBorders' => [
  11959. 'borderStyle' => Border::BORDER_THIN,
  11960. 'color' => ['rgb' => '000000'],
  11961. ],
  11962. ],
  11963. ]);
  11964. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  11965. if ($lastRow >= 3) {
  11966. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11967. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11968. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11969. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11970. }
  11971. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  11972. $sheet->getColumnDimension('A')->setWidth(7);
  11973. $sheet->getColumnDimension('B')->setWidth(16);
  11974. $sheet->getColumnDimension('C')->setWidth(52);
  11975. $sheet->getColumnDimension('D')->setWidth(32);
  11976. $sheet->getColumnDimension('E')->setWidth(12);
  11977. $sheet->getColumnDimension('F')->setWidth(44);
  11978. $sheet->getColumnDimension('G')->setWidth(26);
  11979. $sheet->getColumnDimension('H')->setWidth(13);
  11980. $sheet->getRowDimension(1)->setRowHeight(28);
  11981. $ymCompact = str_replace('-', '', $ym);
  11982. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  11983. $filename = $fileBase . '.xlsx';
  11984. try {
  11985. $this->ensurePurchaseMonthExportLogTable();
  11986. list($adminId, $adminName) = $this->GetUseName();
  11987. Db::table('purchase_month_export_log')->insert([
  11988. 'ym' => $ym,
  11989. 'admin_id' => (int)$adminId,
  11990. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  11991. 'row_count' => count($exportLines),
  11992. 'total_amount' => round($grandAmount, 2),
  11993. 'createtime' => time(),
  11994. ]);
  11995. } catch (\Throwable $e) {
  11996. Log::write('month export log: ' . $e->getMessage(), 'error');
  11997. }
  11998. if (ob_get_length()) {
  11999. ob_end_clean();
  12000. }
  12001. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  12002. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  12003. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  12004. header('Cache-Control: max-age=0');
  12005. $writer = new Xlsx($spreadsheet);
  12006. $writer->save('php://output');
  12007. $spreadsheet->disconnectWorksheets();
  12008. unset($spreadsheet);
  12009. exit;
  12010. }
  12011. /**
  12012. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  12013. */
  12014. public function export_month_quote()
  12015. {
  12016. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  12017. $this->error(__('You have no permission'));
  12018. }
  12019. $bundle = $this->prepareMonthOutwardExportBundle();
  12020. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  12021. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  12022. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  12023. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  12024. $spreadsheet = new Spreadsheet();
  12025. $sheet = $spreadsheet->getActiveSheet();
  12026. $sheet->setTitle('供应商报价明细');
  12027. $mon = (int)substr($ym, 5, 2);
  12028. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  12029. $sheet->getColumnDimension('A')->setWidth(7);
  12030. $sheet->getColumnDimension('B')->setWidth(16);
  12031. $sheet->getColumnDimension('C')->setWidth(52);
  12032. $sheet->getColumnDimension('D')->setWidth(26);
  12033. $sheet->getColumnDimension('E')->setWidth(32);
  12034. $sheet->getColumnDimension('F')->setWidth(12);
  12035. $sheet->getColumnDimension('G')->setWidth(14);
  12036. $sheet->getColumnDimension('H')->setWidth(12);
  12037. if ($quoteLastRow < 1) {
  12038. $quoteLastRow = 3;
  12039. }
  12040. $ymCompact = str_replace('-', '', $ym);
  12041. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  12042. if (ob_get_length()) {
  12043. ob_end_clean();
  12044. }
  12045. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  12046. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  12047. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  12048. header('Cache-Control: max-age=0');
  12049. $writer = new Xlsx($spreadsheet);
  12050. $writer->save('php://output');
  12051. $spreadsheet->disconnectWorksheets();
  12052. unset($spreadsheet);
  12053. exit;
  12054. }
  12055. /**
  12056. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  12057. *
  12058. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  12059. */
  12060. protected function prepareMonthOutwardExportBundle(): array
  12061. {
  12062. $this->request->filter(['strip_tags', 'trim']);
  12063. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  12064. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  12065. $ym = date('Y-m');
  12066. }
  12067. $dbRows = [];
  12068. try {
  12069. $query = Db::table('purchase_order');
  12070. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  12071. $dbRows = $query->select();
  12072. } catch (\Throwable $e) {
  12073. $dbRows = [];
  12074. }
  12075. if (!is_array($dbRows)) {
  12076. $dbRows = [];
  12077. }
  12078. $completeTsMap = [];
  12079. $sidList = [];
  12080. foreach ($dbRows as $dbRow) {
  12081. if (!is_array($dbRow)) {
  12082. continue;
  12083. }
  12084. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  12085. if ($sid > 0) {
  12086. $sidList[$sid] = true;
  12087. }
  12088. }
  12089. if ($sidList !== []) {
  12090. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  12091. }
  12092. // 导出始终按「查看月份」取当月完结单;搜索只在当月内再缩小(勿跨月,否则会与列表不一致)
  12093. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  12094. if (!is_array($dbRow)) {
  12095. return false;
  12096. }
  12097. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  12098. if ($done['ts'] <= 0) {
  12099. return false;
  12100. }
  12101. return date('Y-m', $done['ts']) === $ym;
  12102. }));
  12103. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  12104. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  12105. $mainBySid = [];
  12106. foreach ($pool as $rw) {
  12107. if (!is_array($rw)) {
  12108. continue;
  12109. }
  12110. $rid = (int)($rw['ID'] ?? 0);
  12111. if ($rid > 0) {
  12112. $mainBySid[$rid] = $rw;
  12113. }
  12114. }
  12115. if ($mainBySid === []) {
  12116. $detailRows = [];
  12117. } else {
  12118. try {
  12119. $detailRows = Db::table('purchase_order_detail')
  12120. ->where('scydgy_id', 'in', array_keys($mainBySid))
  12121. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  12122. ->order('status', 'desc')
  12123. ->order('CCYDH', 'asc')
  12124. ->order('company_name', 'asc')
  12125. ->order('id', 'asc')
  12126. ->select();
  12127. } catch (\Throwable $e) {
  12128. try {
  12129. $detailRows = Db::table('purchase_order_detail')
  12130. ->where('scydgy_id', 'in', array_keys($mainBySid))
  12131. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  12132. ->order('status', 'desc')
  12133. ->order('CCYDH', 'asc')
  12134. ->order('company_name', 'asc')
  12135. ->order('ID', 'asc')
  12136. ->select();
  12137. } catch (\Throwable $e2) {
  12138. $detailRows = [];
  12139. }
  12140. }
  12141. }
  12142. if (!is_array($detailRows)) {
  12143. $detailRows = [];
  12144. }
  12145. $exportLines = [];
  12146. $detailSidSeen = [];
  12147. foreach ($detailRows as $dr) {
  12148. if (!is_array($dr)) {
  12149. continue;
  12150. }
  12151. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12152. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  12153. continue;
  12154. }
  12155. if (isset($detailSidSeen[$sid])) {
  12156. continue;
  12157. }
  12158. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  12159. continue;
  12160. }
  12161. $detailSidSeen[$sid] = true;
  12162. $m = $mainBySid[$sid];
  12163. $exportLines[] = [
  12164. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12165. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12166. 'company_name' => (string)($dr['company_name'] ?? ''),
  12167. 'CDF' => (string)($m['CDF'] ?? ''),
  12168. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12169. 'gx' => $this->procuremenExportGxText($m),
  12170. 'detail' => $dr,
  12171. ];
  12172. }
  12173. foreach ($detailRows as $dr) {
  12174. if (!is_array($dr)) {
  12175. continue;
  12176. }
  12177. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12178. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  12179. continue;
  12180. }
  12181. $detailSidSeen[$sid] = true;
  12182. $m = $mainBySid[$sid];
  12183. $exportLines[] = [
  12184. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12185. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12186. 'company_name' => (string)($dr['company_name'] ?? ''),
  12187. 'CDF' => (string)($m['CDF'] ?? ''),
  12188. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12189. 'gx' => $this->procuremenExportGxText($m),
  12190. 'detail' => $dr,
  12191. ];
  12192. }
  12193. foreach ($mainBySid as $sid => $m) {
  12194. if (isset($detailSidSeen[$sid])) {
  12195. continue;
  12196. }
  12197. $company = trim((string)($m['pick_company_name'] ?? ''));
  12198. $exportLines[] = [
  12199. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  12200. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  12201. 'company_name' => $company,
  12202. 'CDF' => (string)($m['CDF'] ?? ''),
  12203. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12204. 'gx' => $this->procuremenExportGxText($m),
  12205. 'detail' => [],
  12206. ];
  12207. }
  12208. $groups = [];
  12209. foreach ($exportLines as $line) {
  12210. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  12211. if (!isset($groups[$k])) {
  12212. $groups[$k] = [];
  12213. }
  12214. $groups[$k][] = $line;
  12215. }
  12216. ksort($groups, SORT_STRING);
  12217. return [
  12218. 'ym' => $ym,
  12219. 'mainBySid' => $mainBySid,
  12220. 'detailRows' => $detailRows,
  12221. 'exportLines' => $exportLines,
  12222. 'groups' => $groups,
  12223. ];
  12224. }
  12225. /**
  12226. * 导出用:工序列文案
  12227. */
  12228. protected function procuremenExportGxText(array $r)
  12229. {
  12230. $a = trim((string)($r['CDXMC'] ?? ''));
  12231. $b = trim((string)($r['CGYMC'] ?? ''));
  12232. if ($a !== '' && $b !== '') {
  12233. return $a . ':' . $b;
  12234. }
  12235. return $a !== '' ? $a : $b;
  12236. }
  12237. /**
  12238. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  12239. */
  12240. protected function procuremenExportAmount(array $r)
  12241. {
  12242. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  12243. if (!array_key_exists($k, $r)) {
  12244. continue;
  12245. }
  12246. $v = $r[$k];
  12247. if ($v === null || $v === '') {
  12248. continue;
  12249. }
  12250. if (is_numeric($v)) {
  12251. return (float)$v;
  12252. }
  12253. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  12254. if ($v !== '' && is_numeric($v)) {
  12255. return (float)$v;
  12256. }
  12257. }
  12258. return 0.0;
  12259. }
  12260. /**
  12261. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  12262. *
  12263. * @param array<int, array<string, mixed>> $detailRows
  12264. * @param array<int, array<string, mixed>> $mainBySid
  12265. * @return array<int, array<string, mixed>>
  12266. */
  12267. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  12268. {
  12269. $lines = [];
  12270. foreach ($detailRows as $dr) {
  12271. if (!is_array($dr)) {
  12272. continue;
  12273. }
  12274. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12275. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  12276. continue;
  12277. }
  12278. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  12279. continue;
  12280. }
  12281. $cn = trim((string)($dr['company_name'] ?? ''));
  12282. if ($cn === '') {
  12283. continue;
  12284. }
  12285. $m = $mainBySid[$sid];
  12286. $am = trim((string)($dr['amount'] ?? ''));
  12287. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  12288. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  12289. $amountText = $amountFilled
  12290. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  12291. : '未填写';
  12292. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  12293. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  12294. if ($deliveryShow === '' && $deliveryRaw !== '') {
  12295. $deliveryShow = $deliveryRaw;
  12296. }
  12297. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  12298. ? $deliveryShow
  12299. : '未填写';
  12300. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  12301. $lines[] = [
  12302. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12303. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12304. 'gx' => $this->procuremenExportGxText($m),
  12305. 'company_name' => $cn,
  12306. 'amount_text' => $amountText,
  12307. 'amount_num' => $amountFilled ? $amountNum : null,
  12308. 'delivery_text' => $deliveryText,
  12309. 'picked_text' => $picked ? '中标' : '未中标',
  12310. 'picked' => $picked,
  12311. ];
  12312. }
  12313. $winnerSupplierByOrder = [];
  12314. foreach ($lines as $line) {
  12315. $dh = trim((string)($line['CCYDH'] ?? ''));
  12316. $cn = trim((string)($line['company_name'] ?? ''));
  12317. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  12318. $winnerSupplierByOrder[$dh][$cn] = true;
  12319. }
  12320. }
  12321. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  12322. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  12323. if ($c !== 0) {
  12324. return $c;
  12325. }
  12326. $dh = trim((string)($a['CCYDH'] ?? ''));
  12327. $aCn = trim((string)($a['company_name'] ?? ''));
  12328. $bCn = trim((string)($b['company_name'] ?? ''));
  12329. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  12330. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  12331. if ($aSupplierWin !== $bSupplierWin) {
  12332. return $aSupplierWin ? -1 : 1;
  12333. }
  12334. $c = strcmp($aCn, $bCn);
  12335. if ($c !== 0) {
  12336. return $c;
  12337. }
  12338. if (!empty($a['picked']) !== !empty($b['picked'])) {
  12339. return !empty($a['picked']) ? -1 : 1;
  12340. }
  12341. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  12342. if ($c !== 0) {
  12343. return $c;
  12344. }
  12345. return 0;
  12346. });
  12347. return $lines;
  12348. }
  12349. /**
  12350. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  12351. *
  12352. * @param array<int, array<string, mixed>> $quoteLines
  12353. */
  12354. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  12355. {
  12356. $mon = (int)substr($ym, 5, 2);
  12357. $titleRow = $startRow;
  12358. $headerRow = $startRow + 1;
  12359. $dataStartRow = $startRow + 2;
  12360. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  12361. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  12362. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  12363. $sheet->getStyle('A' . $titleRow)->getAlignment()
  12364. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12365. ->setVertical(Alignment::VERTICAL_CENTER);
  12366. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  12367. $col = 'A';
  12368. foreach ($headers as $h) {
  12369. $sheet->setCellValue($col . $headerRow, $h);
  12370. $col++;
  12371. }
  12372. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  12373. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12374. $rowNum = $dataStartRow;
  12375. if ($quoteLines === []) {
  12376. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  12377. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  12378. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12379. $rowNum = $dataStartRow + 1;
  12380. } else {
  12381. $i = 0;
  12382. foreach ($quoteLines as $line) {
  12383. $i++;
  12384. $sheet->setCellValue('A' . $rowNum, $i);
  12385. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  12386. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  12387. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  12388. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  12389. if ($line['amount_num'] !== null) {
  12390. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  12391. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  12392. } else {
  12393. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  12394. }
  12395. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  12396. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  12397. if (!empty($line['picked'])) {
  12398. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  12399. }
  12400. $rowNum++;
  12401. }
  12402. }
  12403. $lastRow = $rowNum - 1;
  12404. if ($lastRow >= $headerRow) {
  12405. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  12406. 'borders' => [
  12407. 'allBorders' => [
  12408. 'borderStyle' => Border::BORDER_THIN,
  12409. 'color' => ['rgb' => '000000'],
  12410. ],
  12411. ],
  12412. ]);
  12413. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  12414. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12415. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12416. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12417. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  12418. if ($lastRow >= $dataStartRow) {
  12419. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  12420. }
  12421. }
  12422. return $lastRow;
  12423. }
  12424. /**
  12425. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  12426. */
  12427. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  12428. {
  12429. if ($lastRow < $dataStartRow || $headerRow < 1) {
  12430. return;
  12431. }
  12432. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  12433. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12434. ->setVertical(Alignment::VERTICAL_CENTER);
  12435. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  12436. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12437. ->setVertical(Alignment::VERTICAL_CENTER);
  12438. if ($lastCol > 'B') {
  12439. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  12440. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  12441. ->setVertical(Alignment::VERTICAL_CENTER);
  12442. }
  12443. }
  12444. /**
  12445. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  12446. */
  12447. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  12448. {
  12449. $s = trim($ccydh);
  12450. if ($s === '') {
  12451. return 'ORDER';
  12452. }
  12453. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  12454. $s = trim($s, '._-');
  12455. if ($s === '') {
  12456. return 'ORDER';
  12457. }
  12458. if (function_exists('mb_substr')) {
  12459. return mb_substr($s, 0, 80, 'UTF-8');
  12460. }
  12461. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  12462. }
  12463. /**
  12464. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  12465. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  12466. *
  12467. * @return array{objectKey: string, webPath: string}
  12468. */
  12469. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  12470. {
  12471. $sid = (int)$scydgyId;
  12472. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  12473. $y = date('Y');
  12474. $m = date('m');
  12475. $d = date('d');
  12476. $basename = $safeOrder . '_' . $sid . '.pdf';
  12477. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  12478. return [
  12479. 'objectKey' => $objectKey,
  12480. 'webPath' => '/' . $objectKey,
  12481. ];
  12482. }
  12483. /**
  12484. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  12485. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  12486. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  12487. *
  12488. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  12489. */
  12490. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  12491. {
  12492. if (!$this->isValidScydgyRowId($scydgyId)) {
  12493. return '';
  12494. }
  12495. $ids = trim((string)$scydgyId);
  12496. $prep = $this->prepareProcuremenDetailsView($ids);
  12497. if (!$prep['ok']) {
  12498. return '';
  12499. }
  12500. $ccydh = $prep['ccydh'];
  12501. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  12502. $objectKey = $paths['objectKey'];
  12503. $webPath = $paths['webPath'];
  12504. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  12505. $this->view->assign([
  12506. 'pdf_export' => 1,
  12507. 'pdfMetaLine' => $meta,
  12508. ]);
  12509. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  12510. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  12511. $this->view->engine->layout(false);
  12512. try {
  12513. $html = $this->view->fetch('procuremen/details_pdf_shell');
  12514. } catch (\Throwable $e) {
  12515. if ($restoreLayout) {
  12516. $this->view->engine->layout($restoreLayout);
  12517. }
  12518. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  12519. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12520. return '';
  12521. }
  12522. if ($restoreLayout) {
  12523. $this->view->engine->layout($restoreLayout);
  12524. }
  12525. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12526. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  12527. if (!is_dir($tempDir)) {
  12528. @mkdir($tempDir, 0755, true);
  12529. }
  12530. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  12531. try {
  12532. $mpdf = new \Mpdf\Mpdf([
  12533. 'mode' => 'utf-8',
  12534. 'format' => 'A4',
  12535. 'margin_left' => 12,
  12536. 'margin_right' => 12,
  12537. 'margin_top' => 14,
  12538. 'margin_bottom' => 14,
  12539. 'tempDir' => $tempDir,
  12540. 'autoScriptToLang' => true,
  12541. 'autoLangToFont' => true,
  12542. ]);
  12543. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  12544. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  12545. $mpdf->SetBasePath('http://127.0.0.1/');
  12546. $mpdf->WriteHTML($html);
  12547. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  12548. } catch (\Throwable $e) {
  12549. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  12550. if (is_file($tempPdf)) {
  12551. @unlink($tempPdf);
  12552. }
  12553. return '';
  12554. }
  12555. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  12556. if ($ossUrl !== '') {
  12557. @unlink($tempPdf);
  12558. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12559. return $ossUrl;
  12560. }
  12561. $pi = pathinfo($objectKey);
  12562. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  12563. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  12564. if ($baseFile === '') {
  12565. @unlink($tempPdf);
  12566. return '';
  12567. }
  12568. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  12569. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  12570. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  12571. @unlink($tempPdf);
  12572. return '';
  12573. }
  12574. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  12575. if (!@copy($tempPdf, $fullPath)) {
  12576. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  12577. @unlink($tempPdf);
  12578. return '';
  12579. }
  12580. @unlink($tempPdf);
  12581. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12582. return $webPath;
  12583. }
  12584. /**
  12585. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  12586. */
  12587. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  12588. {
  12589. if ($scydgyId <= 0 || $webPath === '') {
  12590. return;
  12591. }
  12592. try {
  12593. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  12594. } catch (\Throwable $e) {
  12595. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  12596. }
  12597. }
  12598. /**
  12599. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  12600. *
  12601. * @param array<string, string> $vars
  12602. * @return array<string, string>
  12603. */
  12604. protected function normalizeSmsTemplateVars(array $vars): array
  12605. {
  12606. $out = [];
  12607. foreach ($vars as $k => $v) {
  12608. $out[(string)$k] = trim((string)$v);
  12609. }
  12610. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  12611. $out['contact_name'] = $out['company_name'];
  12612. }
  12613. return $out;
  12614. }
  12615. /**
  12616. * 按手机号或公司名称查 customer 表联系人姓名
  12617. */
  12618. protected function resolveCustomerContactName(string $phone, string $companyName): string
  12619. {
  12620. $phone = trim($phone);
  12621. $companyName = trim($companyName);
  12622. try {
  12623. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  12624. $row = Db::table('customer')
  12625. ->where(function ($q) use ($phone) {
  12626. $q->where('phone', $phone)->whereOr('account', $phone);
  12627. })
  12628. ->order('id', 'asc')
  12629. ->find();
  12630. if (is_array($row)) {
  12631. $nm = trim((string)($row['username'] ?? ''));
  12632. if ($nm !== '') {
  12633. return $nm;
  12634. }
  12635. }
  12636. }
  12637. if ($companyName !== '') {
  12638. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  12639. if (is_array($row)) {
  12640. return trim((string)($row['username'] ?? ''));
  12641. }
  12642. }
  12643. } catch (\Throwable $e) {
  12644. }
  12645. return '';
  12646. }
  12647. /**
  12648. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;,保留已替换进的 &lt;a&gt; 等标签
  12649. */
  12650. protected function plainTextToHtmlEmailBody(string $text): string
  12651. {
  12652. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  12653. $parts = explode("\n", $text);
  12654. $out = [];
  12655. foreach ($parts as $line) {
  12656. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  12657. $out[] = $line;
  12658. } else {
  12659. $out[] = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  12660. }
  12661. }
  12662. return implode("<br>\n", $out);
  12663. }
  12664. /**
  12665. * 短信场景:去掉链接类变量,避免误填 URL
  12666. *
  12667. * @param array<string, string> $vars
  12668. * @return array<string, string>
  12669. */
  12670. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  12671. {
  12672. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  12673. return $vars;
  12674. }
  12675. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  12676. $vars[$k] = '';
  12677. }
  12678. return $vars;
  12679. }
  12680. /**
  12681. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  12682. *
  12683. * @param array<string, string> $vars
  12684. */
  12685. protected function renderNotifyTemplate(string $scene, array $vars): string
  12686. {
  12687. $vars = $this->normalizeSmsTemplateVars($vars);
  12688. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  12689. $row = $this->loadNotifyTemplateRow($scene);
  12690. if ($row === null) {
  12691. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12692. }
  12693. $tpl = trim((string)($row['content'] ?? ''));
  12694. if ($tpl === '') {
  12695. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12696. }
  12697. foreach ($vars as $k => $v) {
  12698. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  12699. }
  12700. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  12701. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  12702. return $tpl;
  12703. }
  12704. protected function resolveProcuremenEmailSubject(string $scene): string
  12705. {
  12706. // 询价 / 采购确认结果邮箱:模版名称即邮件主题
  12707. if (in_array($scene, ['rfq_salesman_email', 'rfq_supplier_email', 'confirm_ok_email', 'confirm_fail_email'], true)) {
  12708. $row = $this->loadNotifyTemplateRow($scene);
  12709. $title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
  12710. if ($title !== '') {
  12711. return $title;
  12712. }
  12713. $fallback = [
  12714. 'rfq_supplier_email' => '供应商询价通知',
  12715. 'rfq_salesman_email' => '协助采购询价通知',
  12716. 'confirm_ok_email' => '采购确认结果:已通过',
  12717. 'confirm_fail_email' => '采购确认结果:未通过',
  12718. ];
  12719. return $fallback[$scene] ?? '协助采购通知';
  12720. }
  12721. $map = [
  12722. 'review_email' => '您有新的协助加工订单',
  12723. ];
  12724. $subject = trim((string)($map[$scene] ?? ''));
  12725. if ($subject === '') {
  12726. $this->error('未配置邮件主题:' . $scene);
  12727. }
  12728. return $subject;
  12729. }
  12730. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  12731. {
  12732. $map = [
  12733. 'review_email' => '协助下发-邮箱',
  12734. 'review_sms' => '协助下发-短信',
  12735. 'confirm_ok' => '采购确认-通过',
  12736. 'confirm_fail' => '采购确认-未通过',
  12737. 'confirm_ok_email' => '采购确认通过-邮箱',
  12738. 'confirm_fail_email' => '采购确认未通过-邮箱',
  12739. 'bid_open' => '开标双重验证',
  12740. 'rfq_salesman_email' => '询价通知业务员-邮箱',
  12741. 'rfq_supplier_email' => '供应商询价通知',
  12742. ];
  12743. $label = $map[$scene] ?? $scene;
  12744. if ($titleRequired) {
  12745. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  12746. }
  12747. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  12748. }
  12749. /**
  12750. * 是否开启协助通知演练(不发真实短信/邮件)
  12751. */
  12752. protected function isProcuremenNotifyDryRun(): bool
  12753. {
  12754. return (bool)Config::get('procuremen_notify_dry_run');
  12755. }
  12756. /**
  12757. * @param array<string, mixed> $payload
  12758. */
  12759. protected function recordNotifyDryRunPreview(array $payload): void
  12760. {
  12761. $this->notifyDryRunPreview[] = $payload;
  12762. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  12763. }
  12764. /**
  12765. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  12766. * @throws \Exception
  12767. */
  12768. protected function smsbao($phone, $content)
  12769. {
  12770. if ($this->isProcuremenNotifyDryRun()) {
  12771. $this->recordNotifyDryRunPreview([
  12772. 'scene' => 'sms_only',
  12773. 'phone' => $phone,
  12774. 'sms_content' => $content,
  12775. ]);
  12776. return;
  12777. }
  12778. $statusStr = [
  12779. '0' => '短信发送成功',
  12780. '-1' => '参数不全',
  12781. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  12782. '30' => '密码错误',
  12783. '40' => '账号不存在',
  12784. '41' => '余额不足',
  12785. '42' => '帐户已过期',
  12786. '43' => 'IP地址限制',
  12787. '50' => '内容含有敏感词',
  12788. ];
  12789. $smsapi = 'http://api.smsbao.com/';
  12790. $user = 'zhuwei123';
  12791. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  12792. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  12793. $result = @file_get_contents($sendurl);
  12794. if ($result === false) {
  12795. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  12796. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  12797. }
  12798. $result = trim((string)$result);
  12799. if ($result !== '0') {
  12800. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  12801. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  12802. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  12803. }
  12804. }
  12805. }