Index.php 291 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710
  1. <?php
  2. namespace app\index\controller;
  3. use app\common\controller\Frontend;
  4. use app\common\library\ProcuremenSchema;
  5. use app\common\library\ProcuremenStatus;
  6. use think\Cache;
  7. use think\captcha\Captcha;
  8. use think\Config;
  9. use think\Cookie;
  10. use think\Db;
  11. use think\Log;
  12. use think\Session;
  13. use think\Validate;
  14. /**
  15. * 手机端:协助明细(purchase_order_detail)验证码 / 账号密码登录 + 列表
  16. * 普通用户(customer):登录后进报价列表,可填单价/交期
  17. * 质检中心:登录后进「质量评分」(合格/投诉/中断)
  18. * 生产部(生产员):登录后进「交货情况」(准时/滞后)
  19. * 业务员:登录后进「新增订单询价」
  20. */
  21. class Index extends Frontend
  22. {
  23. protected $noNeedLogin = ['*'];
  24. protected $noNeedRight = ['*'];
  25. protected $layout = '';
  26. /** @var int 登录态有效天数 */
  27. protected $mprocTtlSeconds = 0;
  28. /** @var array<string, string>|null purchase_order_detail 表字段:小写 => 真实列名 */
  29. protected static $mprocProcuremenColumns = null;
  30. public function _initialize()
  31. {
  32. parent::_initialize();
  33. if (is_file(APP_PATH . 'extra/mproc.php')) {
  34. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  35. }
  36. $hours = (int)Config::get('mproc.session_hours');
  37. if ($hours > 0) {
  38. $this->mprocTtlSeconds = max(1, min(720, $hours)) * 3600;
  39. } else {
  40. $days = (int)(Config::get('mproc.session_days') ?: 3);
  41. $days = max(1, min(30, $days));
  42. $this->mprocTtlSeconds = $days * 86400;
  43. }
  44. if (PHP_VERSION_ID >= 70300) {
  45. ini_set('session.cookie_lifetime', (string)$this->mprocTtlSeconds);
  46. ini_set('session.gc_maxlifetime', (string)$this->mprocTtlSeconds);
  47. }
  48. try {
  49. ProcuremenSchema::ensureAll();
  50. } catch (\Throwable $e) {
  51. }
  52. }
  53. /**
  54. * 手机端:HTML 错误不用框架跳转页(哭脸倒计时),改为普通 Toast 后跳转;Ajax/JSON 仍走原逻辑
  55. *
  56. * @param mixed $msg
  57. * @param string $url
  58. * @param mixed $data
  59. * @param int $wait
  60. * @param array $header
  61. * @return void
  62. */
  63. protected function error($msg = '', $url = null, $data = '', $wait = 3, array $header = [])
  64. {
  65. $type = method_exists($this, 'getResponseType') ? (string)$this->getResponseType() : 'html';
  66. if (strtolower($type) === 'html') {
  67. if ($url === null || $url === '') {
  68. $url = (string)url('index/index/index');
  69. } elseif ($url !== '' && strpos((string)$url, '://') === false && strpos((string)$url, '/') !== 0
  70. && strpos((string)$url, 'javascript:') !== 0) {
  71. $url = (string)\think\Url::build((string)$url);
  72. }
  73. if (is_string($url) && stripos($url, 'javascript:') === 0) {
  74. $url = (string)url('index/index/index');
  75. }
  76. $html = $this->view->fetch('toast_tip', [
  77. 'toastMsg' => (string)$msg,
  78. 'redirectUrl' => (string)$url,
  79. 'waitMs' => max(1000, ((int)$wait) * 1000),
  80. ]);
  81. $response = \think\Response::create($html, 'html', 200)->header($header);
  82. throw new \think\exception\HttpResponseException($response);
  83. }
  84. parent::error($msg, $url, $data, $wait, $header);
  85. }
  86. /** 登录有效小时数(用于前端 localStorage 过期时间) */
  87. protected function mprocKeepHours(): int
  88. {
  89. return max(1, (int)round($this->mprocTtlSeconds / 3600));
  90. }
  91. /**
  92. * 当前手机端登录用户;未登录返回 null(支持 Cookie 令牌 + 7 天记住登录)
  93. */
  94. protected function mprocGetUser()
  95. {
  96. $token = $this->mprocReadTokenFromRequest();
  97. if ($token !== '') {
  98. $user = $this->mprocLoadUserByToken($token);
  99. if ($user) {
  100. $token = $this->mprocTouchLoginState($user, $token);
  101. $user['token'] = $token;
  102. return $user;
  103. }
  104. }
  105. $user = $this->mprocUserFromRememberCookie();
  106. if (!$user) {
  107. return null;
  108. }
  109. $token = $this->mprocPackSignedAuthToken($user);
  110. $token = $this->mprocTouchLoginState($user, $token);
  111. $user['token'] = $token;
  112. return $user;
  113. }
  114. protected function mprocReadTokenFromRequest(): string
  115. {
  116. $token = Session::get('mproc_token');
  117. if ($token === null || $token === '') {
  118. $token = Cookie::get('mproc_token');
  119. }
  120. if ($token === null || $token === '') {
  121. $token = $this->request->header('X-Mproc-Token');
  122. }
  123. if ($token === null || $token === '') {
  124. $token = $this->request->request('mproc_token', '');
  125. }
  126. $token = trim((string)$token);
  127. if ($token === '') {
  128. return '';
  129. }
  130. if ($this->mprocIsSignedAuthToken($token)) {
  131. return $token;
  132. }
  133. $token = preg_replace('/[^a-f0-9]/i', '', $token);
  134. return strlen($token) >= 16 ? $token : '';
  135. }
  136. protected function mprocIsSignedAuthToken(string $token): bool
  137. {
  138. return strpos($token, '.') !== false
  139. && preg_match('/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/', $token) === 1;
  140. }
  141. protected function mprocAuthCacheKey(string $token): string
  142. {
  143. return 'mproc_u_' . md5($token);
  144. }
  145. /**
  146. * @return array<string, mixed>|null
  147. */
  148. protected function mprocLoadUserByToken(string $token): ?array
  149. {
  150. if ($this->mprocIsSignedAuthToken($token)) {
  151. if ($this->mprocIsAuthTokenRevoked($token)) {
  152. return null;
  153. }
  154. $user = $this->mprocUserFromSignedToken($token);
  155. if (!$user) {
  156. return null;
  157. }
  158. if (time() - (int)($user['login_time'] ?? 0) > $this->mprocTtlSeconds) {
  159. $this->mprocClearLogin($token);
  160. return null;
  161. }
  162. $user['token'] = $token;
  163. return $user;
  164. }
  165. $user = Cache::get('mproc_u_' . $token);
  166. if (!is_array($user)) {
  167. $user = $this->mprocUserFromRememberCookie();
  168. if (!$user) {
  169. return null;
  170. }
  171. }
  172. if (empty($user['phone']) && empty($user['account']) && empty($user['username'])) {
  173. return null;
  174. }
  175. if (time() - (int)($user['login_time'] ?? 0) > $this->mprocTtlSeconds) {
  176. $this->mprocClearLogin($token);
  177. return null;
  178. }
  179. $user['token'] = $token;
  180. return $user;
  181. }
  182. /**
  183. * 滑动续期:刷新签名令牌 / Cache / Session / Cookie(保留 7 天)
  184. *
  185. * @param array<string, mixed> $user
  186. */
  187. protected function mprocTouchLoginState(array $user, string $token): string
  188. {
  189. $user['login_time'] = time();
  190. if ($this->mprocIsSignedAuthToken($token)) {
  191. $token = $this->mprocPackSignedAuthToken($user);
  192. }
  193. Cache::set($this->mprocAuthCacheKey($token), $user, $this->mprocTtlSeconds + 86400);
  194. if (!$this->mprocIsSignedAuthToken($token)) {
  195. Cache::set('mproc_u_' . $token, $user, $this->mprocTtlSeconds + 86400);
  196. }
  197. Session::set('mproc_token', $token);
  198. $this->mprocSetTokenCookie($token);
  199. $this->mprocSetRememberCookie($user, $token);
  200. return $token;
  201. }
  202. /**
  203. * @return array<string, mixed>
  204. */
  205. protected function mprocCookieOptions(): array
  206. {
  207. $opts = [
  208. 'expire' => $this->mprocTtlSeconds,
  209. 'path' => '/',
  210. 'httponly' => true,
  211. ];
  212. if ($this->request->isSsl()) {
  213. $opts['secure'] = true;
  214. }
  215. if (PHP_VERSION_ID >= 70300) {
  216. $opts['samesite'] = 'Lax';
  217. }
  218. return $opts;
  219. }
  220. protected function mprocSetTokenCookie(string $token): void
  221. {
  222. Cookie::set('mproc_token', $token, $this->mprocCookieOptions());
  223. }
  224. /**
  225. * @param array<string, mixed> $user
  226. */
  227. protected function mprocSetRememberCookie(array $user, ?string $token = null): void
  228. {
  229. $val = $token !== null && $token !== '' ? $token : $this->mprocPackSignedAuthToken($user);
  230. Cookie::set('mproc_remember', $val, $this->mprocCookieOptions());
  231. }
  232. protected function mprocAuthSignSecret(): string
  233. {
  234. $key = trim((string)Config::get('mproc.auth_sign_key'));
  235. if ($key === '') {
  236. $key = (string)Config::get('database.database') . '|' . (string)Config::get('database.hostname') . '|mproc';
  237. }
  238. return hash('sha256', $key);
  239. }
  240. /**
  241. * @param array<string, mixed> $user
  242. */
  243. protected function mprocPackSignedAuthToken(array $user): string
  244. {
  245. $payload = [
  246. 'uid' => (int)($user['customer_user_id'] ?? $user['customer_id'] ?? 0),
  247. 'phone' => trim((string)($user['phone'] ?? '')),
  248. 'uname' => trim((string)($user['username'] ?? $user['account'] ?? '')),
  249. 'admin' => !empty($user['is_admin']) ? 1 : 0,
  250. 'lt' => time(),
  251. ];
  252. $b64 = rtrim(strtr(base64_encode(json_encode($payload, JSON_UNESCAPED_UNICODE)), '+/', '-_'), '=');
  253. $sig = hash_hmac('sha256', $b64, $this->mprocAuthSignSecret());
  254. return $b64 . '.' . $sig;
  255. }
  256. /** @deprecated 使用 mprocPackSignedAuthToken */
  257. protected function mprocPackRememberCookie(array $user): string
  258. {
  259. return $this->mprocPackSignedAuthToken($user);
  260. }
  261. /**
  262. * @return array<string, mixed>|null
  263. */
  264. protected function mprocUserFromSignedToken(string $raw): ?array
  265. {
  266. $parts = explode('.', trim($raw), 2);
  267. if (count($parts) !== 2) {
  268. return null;
  269. }
  270. $b64 = $parts[0];
  271. $sig = $parts[1];
  272. if (!hash_equals(hash_hmac('sha256', $b64, $this->mprocAuthSignSecret()), $sig)) {
  273. return null;
  274. }
  275. $pad = strlen($b64) % 4;
  276. if ($pad > 0) {
  277. $b64 .= str_repeat('=', 4 - $pad);
  278. }
  279. $json = base64_decode(strtr($b64, '-_', '+/'), true);
  280. if ($json === false || $json === '') {
  281. return null;
  282. }
  283. $payload = json_decode($json, true);
  284. if (!is_array($payload)) {
  285. return null;
  286. }
  287. $lt = (int)($payload['lt'] ?? 0);
  288. if ($lt <= 0 || time() - $lt > $this->mprocTtlSeconds) {
  289. return null;
  290. }
  291. return $this->mprocRebuildUserFromRememberPayload($payload, $lt);
  292. }
  293. /**
  294. * @return array<string, mixed>|null
  295. */
  296. protected function mprocUserFromRememberCookie(): ?array
  297. {
  298. $raw = Cookie::get('mproc_remember');
  299. if ($raw === null || $raw === '') {
  300. $raw = Cookie::get('mproc_token');
  301. }
  302. if ($raw === null || $raw === '') {
  303. return null;
  304. }
  305. $raw = (string)$raw;
  306. if ($this->mprocIsAuthTokenRevoked($raw)) {
  307. return null;
  308. }
  309. return $this->mprocUserFromSignedToken($raw);
  310. }
  311. /**
  312. * @param array<string, mixed> $payload
  313. * @return array<string, mixed>|null
  314. */
  315. protected function mprocRebuildUserFromRememberPayload(array $payload, int $loginTime): ?array
  316. {
  317. if (!empty($payload['admin'])) {
  318. $uname = trim((string)($payload['uname'] ?? ''));
  319. if ($uname === '') {
  320. return null;
  321. }
  322. try {
  323. $row = Db::name('admin')->where('username', $uname)->find();
  324. } catch (\Throwable $e) {
  325. $row = null;
  326. }
  327. if (!is_array($row) || ($row['status'] ?? '') === 'hidden') {
  328. return null;
  329. }
  330. return [
  331. 'phone' => trim((string)($row['mobile'] ?? '')),
  332. 'company_name' => '',
  333. 'username' => $uname,
  334. 'customer_user_id' => 0,
  335. 'admin_id' => (int)($row['id'] ?? 0),
  336. 'login_type' => 'remember',
  337. 'is_admin' => 1,
  338. 'login_time' => $loginTime,
  339. ];
  340. }
  341. $cid = (int)($payload['uid'] ?? 0);
  342. if ($cid > 0) {
  343. try {
  344. $cu = Db::table('customer')->where('id', $cid)->find();
  345. } catch (\Throwable $e) {
  346. $cu = null;
  347. }
  348. if (is_array($cu) && $cu !== [] && $this->mprocCustomerUserActive($cu)) {
  349. $user = $this->mprocLoginPayloadFromCustomer($cu, 'remember');
  350. $user['login_time'] = $loginTime;
  351. return $user;
  352. }
  353. }
  354. $phone = trim((string)($payload['phone'] ?? ''));
  355. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  356. $cu = $this->mprocFindCustomerUserByMobile($phone);
  357. if ($cu) {
  358. $user = $this->mprocLoginPayloadFromCustomer($cu, 'remember');
  359. $user['login_time'] = $loginTime;
  360. return $user;
  361. }
  362. }
  363. return null;
  364. }
  365. protected function mprocAuthRevokeCacheKey(string $token): string
  366. {
  367. return 'mproc_revoked_' . md5($token);
  368. }
  369. protected function mprocRevokeAuthToken(string $token): void
  370. {
  371. $token = trim($token);
  372. if ($token === '') {
  373. return;
  374. }
  375. try {
  376. Cache::set($this->mprocAuthRevokeCacheKey($token), 1, $this->mprocTtlSeconds + 86400);
  377. } catch (\Throwable $e) {
  378. }
  379. }
  380. protected function mprocIsAuthTokenRevoked(string $token): bool
  381. {
  382. $token = trim($token);
  383. if ($token === '') {
  384. return false;
  385. }
  386. try {
  387. return (bool)Cache::get($this->mprocAuthRevokeCacheKey($token));
  388. } catch (\Throwable $e) {
  389. return false;
  390. }
  391. }
  392. /**
  393. * 按与写入时相同的 path/secure/samesite 清除 Cookie,避免仅 delete 时删不掉
  394. */
  395. protected function mprocExpireAuthCookies(): void
  396. {
  397. $opts = $this->mprocCookieOptions();
  398. $opts['expire'] = -3600;
  399. try {
  400. Cookie::set('mproc_token', '', $opts);
  401. Cookie::set('mproc_remember', '', $opts);
  402. } catch (\Throwable $e) {
  403. }
  404. try {
  405. Cookie::delete('mproc_token');
  406. Cookie::delete('mproc_remember');
  407. } catch (\Throwable $e) {
  408. }
  409. unset($_COOKIE['mproc_token'], $_COOKIE['mproc_remember']);
  410. $prefix = (string)Config::get('cookie.prefix');
  411. if ($prefix !== '') {
  412. unset($_COOKIE[$prefix . 'mproc_token'], $_COOKIE[$prefix . 'mproc_remember']);
  413. }
  414. }
  415. protected function mprocClearLogin($token)
  416. {
  417. $token = trim((string)($token ?? ''));
  418. if ($token !== '') {
  419. $this->mprocRevokeAuthToken($token);
  420. try {
  421. Cache::rm($this->mprocAuthCacheKey($token));
  422. } catch (\Throwable $e) {
  423. }
  424. if (!$this->mprocIsSignedAuthToken($token)) {
  425. try {
  426. Cache::rm('mproc_u_' . $token);
  427. } catch (\Throwable $e) {
  428. }
  429. }
  430. }
  431. // 同时作废 remember / 另一份 cookie 里可能残留的签名令牌
  432. foreach (['mproc_token', 'mproc_remember'] as $ck) {
  433. $raw = Cookie::get($ck);
  434. if ($raw !== null && $raw !== '' && (string)$raw !== $token) {
  435. $this->mprocRevokeAuthToken((string)$raw);
  436. }
  437. }
  438. Session::delete('mproc_token');
  439. $this->mprocExpireAuthCookies();
  440. }
  441. /**
  442. * 登录成功后的回跳地址校验(仅允许本站手机端首页 / 入库评分页,防止开放重定向)
  443. *
  444. * @param string $raw GET/POST 的 redirect 或当前 REQUEST_URI
  445. */
  446. protected function mprocSanitizeRedirectUrl($raw)
  447. {
  448. $s = str_replace(["\r", "\n", "\0"], '', trim((string)$raw));
  449. if ($s === '') {
  450. return '';
  451. }
  452. if (preg_match('#^https?://#i', $s)) {
  453. $h = parse_url($s, PHP_URL_HOST);
  454. if (!is_string($h) || strcasecmp($h, (string)$this->request->host()) !== 0) {
  455. return '';
  456. }
  457. $path = parse_url($s, PHP_URL_PATH);
  458. $query = parse_url($s, PHP_URL_QUERY);
  459. $s = (is_string($path) && $path !== '' ? $path : '/');
  460. if (is_string($query) && $query !== '') {
  461. $s .= '?' . $query;
  462. }
  463. }
  464. if (strpos($s, '://') !== false) {
  465. return '';
  466. }
  467. if ($s === '' || ($s[0] !== '/' && stripos($s, 'index.php') !== 0)) {
  468. return '';
  469. }
  470. if ($s[0] !== '/') {
  471. $s = '/' . ltrim($s, '/');
  472. }
  473. if (strpos($s, '//') === 0) {
  474. return '';
  475. }
  476. $okHome = stripos($s, 'index/index/index') !== false;
  477. $okInbound = stripos($s, 'index/index/inboundscore') !== false;
  478. $okDelivery = stripos($s, 'index/index/deliveryscore') !== false;
  479. $okRfqAdd = stripos($s, 'index/index/rfqadd') !== false;
  480. $okNote = stripos($s, 'index/index/deliverynote') !== false;
  481. if (!$okHome && !$okInbound && !$okDelivery && !$okRfqAdd && !$okNote) {
  482. return '';
  483. }
  484. if (stripos($s, 'index/index/login') !== false) {
  485. return '';
  486. }
  487. return $s;
  488. }
  489. protected function mprocRememberFocusEid(int $focusEid): void
  490. {
  491. if ($focusEid > 0) {
  492. Session::set('mproc_focus_eid', $focusEid);
  493. }
  494. }
  495. protected function mprocPullSessionFocusEid(): int
  496. {
  497. $fe = (int)Session::get('mproc_focus_eid', 0);
  498. if ($fe > 0) {
  499. Session::delete('mproc_focus_eid');
  500. }
  501. return $fe;
  502. }
  503. /**
  504. * 从 URI/query 中解析 focus_eid(兼容邮件客户端把 &amp;focus_eid 拼进上一参数值的情况)
  505. */
  506. protected function mprocParseFocusEidFromUriString(string $uri): int
  507. {
  508. if ($uri === '' || stripos($uri, 'focus_eid') === false) {
  509. return 0;
  510. }
  511. if (preg_match('/(?:[?&;]|%26)(?:amp;)*focus_eid=(\d+)/i', $uri, $m)) {
  512. return (int)$m[1];
  513. }
  514. $query = parse_url($uri, PHP_URL_QUERY);
  515. if (!is_string($query) || $query === '') {
  516. return 0;
  517. }
  518. $q = [];
  519. parse_str($query, $q);
  520. if (!is_array($q)) {
  521. return 0;
  522. }
  523. if (isset($q['focus_eid'])) {
  524. $fe = (int)$q['focus_eid'];
  525. if ($fe > 0) {
  526. return $fe;
  527. }
  528. }
  529. foreach ($q as $k => $v) {
  530. $blob = (is_string($k) ? $k : '') . '=' . (is_scalar($v) ? (string)$v : '');
  531. if (preg_match('/(?:^|[?&;]|%26)(?:amp;)*focus_eid=(\d+)/i', $blob, $m2)) {
  532. return (int)$m2[1];
  533. }
  534. }
  535. return 0;
  536. }
  537. /**
  538. * 从请求中读取短信/邮件直达明细 ID(兼容 query、pathinfo、REQUEST_URI、登录回跳 Session)
  539. */
  540. protected function mprocReadFocusEidFromRequest(): int
  541. {
  542. $fe = (int)$this->request->param('focus_eid', 0);
  543. if ($fe > 0) {
  544. $this->mprocRememberFocusEid($fe);
  545. return $fe;
  546. }
  547. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  548. $fe = $this->mprocParseFocusEidFromUriString($uri);
  549. if ($fe > 0) {
  550. $this->mprocRememberFocusEid($fe);
  551. return $fe;
  552. }
  553. $fe = (int)Session::get('mproc_focus_eid', 0);
  554. if ($fe > 0) {
  555. return $fe;
  556. }
  557. return 0;
  558. }
  559. /**
  560. * 手机端登录页 URL。注意:勿用 url('...login', ['redirect'=>]),在 url_html_suffix 下会把参数拼进 PATHINFO 导致 404。
  561. *
  562. * @param string $redirectPath 已通过 {@see mprocSanitizeRedirectUrl} 的回跳路径(含 query),空则不带参数
  563. */
  564. protected function mprocBuildLoginUrl($redirectPath = '')
  565. {
  566. $root = rtrim($this->request->root(), '/');
  567. $path = '/index/index/login';
  568. $rp = trim((string)$redirectPath);
  569. if ($rp === '') {
  570. return $root . $path;
  571. }
  572. return $root . $path . '?' . http_build_query(['redirect' => $rp], '', '&', PHP_QUERY_RFC3986);
  573. }
  574. /**
  575. * 登录成功后跳转到订单首页:用当前入口 {@see Request::root} 拼 URL,并从原 redirect 中只保留白名单 query(避免子目录部署丢参、开放重定向)
  576. *
  577. * @param string $redirectPathOrUrl 已通过 {@see mprocSanitizeRedirectUrl} 的路径或完整 URL(可含 ?focus_eid=)
  578. */
  579. protected function mprocBuildAfterLoginIndexUrl($redirectPathOrUrl)
  580. {
  581. $raw = trim((string)$redirectPathOrUrl);
  582. if ($raw === '') {
  583. return url('index/index/index', '', '', true);
  584. }
  585. $queryStr = '';
  586. if (preg_match('#^https?://#i', $raw)) {
  587. $pq = parse_url($raw);
  588. $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
  589. } elseif (isset($raw[0]) && $raw[0] === '/') {
  590. $pq = parse_url('http://127.0.0.1' . $raw);
  591. $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
  592. } else {
  593. $pq = parse_url('http://127.0.0.1/' . ltrim($raw, '/'));
  594. $queryStr = (is_array($pq) && !empty($pq['query']) && is_string($pq['query'])) ? $pq['query'] : '';
  595. }
  596. $q = [];
  597. if ($queryStr !== '') {
  598. parse_str($queryStr, $q);
  599. if (!is_array($q)) {
  600. $q = [];
  601. }
  602. }
  603. $allowed = [];
  604. $fe = 0;
  605. if (isset($q['focus_eid'])) {
  606. $fe = (int)$q['focus_eid'];
  607. }
  608. if ($fe <= 0) {
  609. $fe = $this->mprocParseFocusEidFromUriString($raw);
  610. }
  611. if ($fe <= 0) {
  612. $fe = (int)Session::get('mproc_focus_eid', 0);
  613. }
  614. if ($fe > 0) {
  615. $allowed['focus_eid'] = $fe;
  616. $this->mprocRememberFocusEid($fe);
  617. }
  618. $mt = isset($q['main_tab']) ? trim((string)$q['main_tab']) : '';
  619. if ($mt === 'me' || $mt === 'orders') {
  620. $allowed['main_tab'] = $mt;
  621. }
  622. $tb = isset($q['tab']) ? trim((string)$q['tab']) : '';
  623. if ($tb === 'me' || in_array($this->mprocNormalizeListTab($tb), $this->mprocListTabWhitelist(), true)) {
  624. $allowed['tab'] = ($tb === 'me') ? 'me' : $this->mprocNormalizeListTab($tb);
  625. }
  626. if (isset($q['q']) && trim((string)$q['q']) !== '') {
  627. $allowed['q'] = substr(trim((string)$q['q']), 0, 120);
  628. }
  629. if (isset($allowed['focus_eid']) && !isset($allowed['main_tab'])) {
  630. $allowed['main_tab'] = 'orders';
  631. }
  632. $base = rtrim($this->request->root(true), '/');
  633. $path = '/index/index/index';
  634. if (isset($allowed['focus_eid']) && (int)$allowed['focus_eid'] > 0 && !isset($allowed['q'])) {
  635. $fe = (int)$allowed['focus_eid'];
  636. if (!isset($allowed['tab']) && (!isset($allowed['main_tab']) || $allowed['main_tab'] === 'orders')) {
  637. return $base . $path . '?focus_eid=' . $fe . '#mproc_fe=' . $fe;
  638. }
  639. $ordered = ['focus_eid' => $fe];
  640. if (isset($allowed['tab'])) {
  641. $ordered['tab'] = $allowed['tab'];
  642. }
  643. if (isset($allowed['main_tab'])) {
  644. $ordered['main_tab'] = $allowed['main_tab'];
  645. }
  646. return $base . $path . '?' . http_build_query($ordered, '', '&', PHP_QUERY_RFC3986) . '#mproc_fe=' . $fe;
  647. }
  648. $qs = $allowed !== [] ? ('?' . http_build_query($allowed, '', '&', PHP_QUERY_RFC3986)) : '';
  649. return $base . $path . $qs;
  650. }
  651. /**
  652. * 按登录身份决定首页:供应商→报价;质检→质量评分;生产→交货情况
  653. * 后台账号无手机端角色时返回空串(勿回登录页,避免 302 死循环)
  654. *
  655. * @param array<string, mixed> $user
  656. * @param string $redirectPathOrUrl
  657. */
  658. protected function mprocBuildAfterLoginHomeUrl(array $user, $redirectPathOrUrl = '')
  659. {
  660. if (!empty($user['is_admin'])) {
  661. $canQuality = $this->mprocAdminHasMobileRole($user, 'quality');
  662. $canDelivery = $this->mprocAdminHasMobileRole($user, 'delivery');
  663. $canRfq = $this->mprocAdminHasMobileRole($user, 'rfq');
  664. $raw = $this->mprocSanitizeRedirectUrl($redirectPathOrUrl);
  665. if ($raw !== '') {
  666. if ($canDelivery && stripos($raw, 'deliveryscore') !== false) {
  667. return $this->mprocAbsoluteFromSanitizedPath($raw, 'index/index/deliveryscore');
  668. }
  669. if ($canQuality && stripos($raw, 'inboundscore') !== false) {
  670. return $this->mprocAbsoluteFromSanitizedPath($raw, 'index/index/inboundscore');
  671. }
  672. if ($canRfq && stripos($raw, 'rfqadd') !== false) {
  673. return $this->mprocAbsoluteFromSanitizedPath($raw, 'index/index/rfqadd');
  674. }
  675. }
  676. if ($canQuality) {
  677. return url('index/index/inboundscore', '', '', true);
  678. }
  679. if ($canDelivery) {
  680. return url('index/index/deliveryscore', '', '', true);
  681. }
  682. if ($canRfq) {
  683. return url('index/index/rfqadd', '', '', true);
  684. }
  685. return '';
  686. }
  687. $raw = $this->mprocSanitizeRedirectUrl($redirectPathOrUrl);
  688. if ($raw !== '' && stripos($raw, 'deliverynote') !== false) {
  689. return $this->mprocAbsoluteFromSanitizedPath($raw, 'index/index/deliverynote');
  690. }
  691. return $this->mprocBuildAfterLoginIndexUrl($redirectPathOrUrl);
  692. }
  693. /**
  694. * 操作人员是否具备手机端任一业务角色(质检 / 生产 / 业务员询价,含超管)
  695. *
  696. * @param array<string, mixed> $user
  697. */
  698. protected function mprocAdminHasAnyMobileAccess(array $user): bool
  699. {
  700. return $this->mprocAdminHasMobileRole($user, 'quality')
  701. || $this->mprocAdminHasMobileRole($user, 'delivery')
  702. || $this->mprocAdminHasMobileRole($user, 'rfq');
  703. }
  704. /**
  705. * @param array<string, mixed> $row admin 表行
  706. * @return array<string, mixed>
  707. */
  708. protected function mprocLoginPayloadFromAdmin(array $row, string $loginType): array
  709. {
  710. return [
  711. 'phone' => trim((string)($row['mobile'] ?? '')),
  712. 'company_name' => '',
  713. 'username' => trim((string)($row['username'] ?? '')),
  714. 'account' => trim((string)($row['username'] ?? '')),
  715. 'customer_user_id' => 0,
  716. 'customer_id' => 0,
  717. 'admin_id' => (int)($row['id'] ?? 0),
  718. 'login_type' => $loginType,
  719. 'is_admin' => 1,
  720. ];
  721. }
  722. /** 清除当前请求中的手机端登录态(解决无权限账号卡在登录跳转) */
  723. protected function mprocDropCurrentLogin(): void
  724. {
  725. $token = $this->mprocReadTokenFromRequest();
  726. $this->mprocClearLogin($token);
  727. }
  728. /**
  729. * @param string $rawSanitized
  730. * @param string $fallbackRoute
  731. */
  732. protected function mprocAbsoluteFromSanitizedPath($rawSanitized, $fallbackRoute)
  733. {
  734. $base = rtrim((string)$this->request->root(true), '/');
  735. $path = parse_url($rawSanitized, PHP_URL_PATH);
  736. $query = parse_url($rawSanitized, PHP_URL_QUERY);
  737. if (!is_string($path) || $path === '') {
  738. return url($fallbackRoute, '', '', true);
  739. }
  740. $path = '/' . ltrim(str_replace('\\', '/', $path), '/');
  741. // root(true) 常为 http://host/index.php,而 redirect/REQUEST_URI 也可能以 /index.php 开头,
  742. // 直接拼接会变成 /index.php/index.php/... → 报「模块不存在:index.php」
  743. if (preg_match('#/index\.php$#i', $base)) {
  744. $path = preg_replace('#^/index\.php(?=/|$)#i', '', $path);
  745. if ($path === '' || (isset($path[0]) && $path[0] !== '/')) {
  746. $path = '/' . ltrim((string)$path, '/');
  747. }
  748. }
  749. return $base . $path . (is_string($query) && $query !== '' ? ('?' . $query) : '');
  750. }
  751. /**
  752. * 从 purchase_order_detail 表解析真实列名(SHOW COLUMNS 只查一次,按候选小写名匹配第一条)
  753. *
  754. * @param string[] $candidatesLower 如 ['status','istatus']
  755. * @return string|null
  756. */
  757. protected function mprocResolveProcuremenColumn(array $candidatesLower)
  758. {
  759. if (self::$mprocProcuremenColumns === null) {
  760. self::$mprocProcuremenColumns = [];
  761. try {
  762. $rows = Db::query('SHOW COLUMNS FROM `purchase_order_detail`');
  763. if (is_array($rows)) {
  764. foreach ($rows as $c) {
  765. $name = isset($c['Field']) ? (string)$c['Field'] : '';
  766. if ($name !== '') {
  767. self::$mprocProcuremenColumns[strtolower($name)] = $name;
  768. }
  769. }
  770. }
  771. } catch (\Throwable $e) {
  772. self::$mprocProcuremenColumns = [];
  773. }
  774. }
  775. foreach ($candidatesLower as $low) {
  776. $k = strtolower((string)$low);
  777. if (isset(self::$mprocProcuremenColumns[$k])) {
  778. return self::$mprocProcuremenColumns[$k];
  779. }
  780. }
  781. return null;
  782. }
  783. /**
  784. * 供应商整单备注(purchase_order_detail.remark)
  785. *
  786. * @param array<string, mixed> $row
  787. */
  788. protected function mprocResolveDetailRemark(array $row): string
  789. {
  790. $col = $this->mprocResolveProcuremenColumn(['remark', 'memo', 'bz', 'beizhu']);
  791. if ($col === null) {
  792. return '';
  793. }
  794. foreach ($row as $k => $v) {
  795. if (strcasecmp((string)$k, $col) === 0) {
  796. return trim((string)$v);
  797. }
  798. }
  799. return '';
  800. }
  801. /**
  802. * 供应商自己填的备注;与订单 MBZ 相同视为未填
  803. */
  804. protected function mprocSupplierOwnRemark($detailRemark, $orderMbz = ''): string
  805. {
  806. $own = trim((string)$detailRemark);
  807. $mbz = trim((string)$orderMbz);
  808. if ($own === '' || ($mbz !== '' && $own === $mbz)) {
  809. return '';
  810. }
  811. return $own;
  812. }
  813. /**
  814. * 列表:非管理员按 company_name 与登录单位一致,或 phone 与登录手机号一致(兼容手工下发单位名细微差异)
  815. *
  816. * @return array|callable 可直接 $query->where(...);空数组表示不加条件
  817. */
  818. protected function mprocListWhereForLoginUser(array $user)
  819. {
  820. if (!empty($user['is_admin'])) {
  821. return [];
  822. }
  823. $cCol = $this->mprocResolveProcuremenColumn(['company_name']);
  824. $pCol = $this->mprocResolveProcuremenColumn(['phone']);
  825. if (($cCol === null || $cCol === '') && ($pCol === null || $pCol === '')) {
  826. return ['id' => 0];
  827. }
  828. $cn = trim((string)($user['company_name'] ?? ''));
  829. $phone = trim((string)($user['phone'] ?? ''));
  830. if ($cn === '' && $phone !== '') {
  831. $cn = $this->mprocResolveCompanyForLoginPhone($phone);
  832. }
  833. if ($cn === '' && $phone === '') {
  834. return ['id' => 0];
  835. }
  836. return function ($q) use ($cCol, $pCol, $cn, $phone) {
  837. $first = true;
  838. if ($cCol !== null && $cCol !== '' && $cn !== '') {
  839. $q->where($cCol, $cn);
  840. $first = false;
  841. }
  842. if ($pCol !== null && $pCol !== '' && $phone !== '') {
  843. if ($first) {
  844. $q->where($pCol, $phone);
  845. } else {
  846. $q->whereOr($pCol, $phone);
  847. }
  848. }
  849. if ($first) {
  850. $q->where('id', 0);
  851. }
  852. };
  853. }
  854. /**
  855. * customer 是否允许登录(status:1 / 正常;空视为可登录以兼容旧数据)
  856. */
  857. protected function mprocCustomerUserActive(array $row): bool
  858. {
  859. $st = $row['status'] ?? '';
  860. if ($st === '' || $st === null) {
  861. return true;
  862. }
  863. return $st === 1 || $st === '1';
  864. }
  865. /**
  866. * @return array<string, mixed>|null
  867. */
  868. protected function mprocFindCustomerUserByMobile(string $phone): ?array
  869. {
  870. return $this->mprocFindCustomerRowByPhone($phone);
  871. }
  872. /**
  873. * 按登录账号(account)查找 customer;兼容旧会话把 11 位手机号写在 username 里
  874. *
  875. * @return array<string, mixed>|null
  876. */
  877. protected function mprocFindCustomerUserByUsername(string $username): ?array
  878. {
  879. $username = trim($username);
  880. if ($username === '') {
  881. return null;
  882. }
  883. try {
  884. $row = Db::table('customer')->where('account', $username)->order('id', 'asc')->find();
  885. } catch (\Throwable $e) {
  886. $row = null;
  887. }
  888. if ((!is_array($row) || $row === []) && preg_match('/^1\d{10}$/', $username)) {
  889. $row = $this->mprocFindCustomerRowByPhone($username);
  890. }
  891. if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
  892. return null;
  893. }
  894. return $row;
  895. }
  896. /**
  897. * customer 密码校验(md5(md5) 无 salt;兼容 bcrypt)
  898. */
  899. protected function mprocVerifyCustomerUserPassword(array $row, string $password): bool
  900. {
  901. $stored = (string)($row['password'] ?? '');
  902. if ($stored === '' || $password === '') {
  903. return false;
  904. }
  905. if (preg_match('/^\$2[ayb]\$/', $stored)) {
  906. return password_verify($password, $stored);
  907. }
  908. return hash_equals($stored, md5(md5($password)));
  909. }
  910. /**
  911. * 生成 customer 登录密码密文
  912. */
  913. protected function mprocHashCustomerUserPassword(string $password, string $existingSalt = ''): string
  914. {
  915. unset($existingSalt);
  916. return md5(md5($password));
  917. }
  918. /**
  919. * 手机端强密码校验:通过返回空字符串,否则返回错误提示
  920. */
  921. protected function mprocValidateStrongPassword(string $password): string
  922. {
  923. $len = strlen($password);
  924. if ($len < 8 || $len > 20) {
  925. return '密码长度须为8~20位';
  926. }
  927. if (preg_match('/\s/', $password)) {
  928. return '密码不能包含空格';
  929. }
  930. if (preg_match('/^\d+$/', $password)) {
  931. return '密码不能为纯数字,请同时包含字母';
  932. }
  933. if (preg_match('/^[a-zA-Z]+$/', $password)) {
  934. return '密码不能为纯字母,请同时包含数字';
  935. }
  936. if (!preg_match('/[a-zA-Z]/', $password) || !preg_match('/\d/', $password)) {
  937. return '密码须同时包含字母和数字';
  938. }
  939. if (preg_match('/(.)\1{3,}/', $password)) {
  940. return '密码不能包含过多重复字符(如1111、aaaa)';
  941. }
  942. if ($this->mprocPasswordHasSequentialRun($password, 4)) {
  943. return '密码不能包含连续字符(如1234、abcd)';
  944. }
  945. $weak = [
  946. '12345678', '123456789', '1234567890', '87654321', '01234567',
  947. 'password', 'password1', 'passw0rd', 'qwerty12', 'qwertyui',
  948. 'abc12345', 'abcd1234', 'a1b2c3d4', '11111111', '00000000',
  949. '88888888', '66666666', '11223344', '1qaz2wsx', 'qazwsxed',
  950. ];
  951. if (in_array(strtolower($password), $weak, true)) {
  952. return '密码过于简单,请重新设置';
  953. }
  954. return '';
  955. }
  956. /**
  957. * 是否包含连续递增/递减片段(长度 >= $runLen),如 1234、4321、abcd
  958. */
  959. protected function mprocPasswordHasSequentialRun(string $password, int $runLen = 4): bool
  960. {
  961. $runLen = max(3, $runLen);
  962. $lower = strtolower($password);
  963. $n = strlen($lower);
  964. if ($n < $runLen) {
  965. return false;
  966. }
  967. for ($i = 0; $i <= $n - $runLen; $i++) {
  968. $asc = true;
  969. $desc = true;
  970. for ($j = 1; $j < $runLen; $j++) {
  971. $prev = ord($lower[$i + $j - 1]);
  972. $cur = ord($lower[$i + $j]);
  973. if ($cur !== $prev + 1) {
  974. $asc = false;
  975. }
  976. if ($cur !== $prev - 1) {
  977. $desc = false;
  978. }
  979. if (!$asc && !$desc) {
  980. break;
  981. }
  982. }
  983. if ($asc || $desc) {
  984. return true;
  985. }
  986. }
  987. return false;
  988. }
  989. /**
  990. * @param array<string, mixed> $cu
  991. * @return array<string, mixed>
  992. */
  993. protected function mprocLoginPayloadFromCustomer(array $cu, string $loginType): array
  994. {
  995. $phone = trim((string)($cu['phone'] ?? ''));
  996. $account = trim((string)($cu['account'] ?? ''));
  997. if ($phone === '' && preg_match('/^1\d{10}$/', $account)) {
  998. $phone = $account;
  999. }
  1000. if ($account === '' && preg_match('/^1\d{10}$/', $phone)) {
  1001. $account = $phone;
  1002. }
  1003. $companyName = trim((string)($cu['company_name'] ?? ''));
  1004. if ($companyName === '' && $phone !== '') {
  1005. $companyName = $this->mprocResolveCompanyForLoginPhone($phone);
  1006. }
  1007. $id = (int)($cu['id'] ?? 0);
  1008. return [
  1009. 'phone' => $phone,
  1010. 'account' => $account,
  1011. 'company_name' => $companyName,
  1012. 'username' => trim((string)($cu['username'] ?? '')),
  1013. 'customer_id' => $id,
  1014. 'customer_user_id' => $id,
  1015. 'login_type' => $loginType,
  1016. 'is_admin' => 0,
  1017. ];
  1018. }
  1019. /**
  1020. * 写入手机端登录态并返回跳转 URL
  1021. *
  1022. * @param array<string, mixed> $userData
  1023. */
  1024. protected function mprocFinishLogin(array $userData): void
  1025. {
  1026. $old = Session::get('mproc_token');
  1027. if ($old) {
  1028. $this->mprocClearLogin((string)$old);
  1029. }
  1030. $userData['login_time'] = time();
  1031. $token = $this->mprocPackSignedAuthToken($userData);
  1032. $token = $this->mprocTouchLoginState($userData, $token);
  1033. $postR = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
  1034. $sessR = $this->mprocSanitizeRedirectUrl((string)Session::get('mproc_intended_url', ''));
  1035. Session::delete('mproc_intended_url');
  1036. $raw = $postR !== '' ? $postR : $sessR;
  1037. $jump = $this->mprocBuildAfterLoginHomeUrl($userData, $raw);
  1038. if ($jump === '') {
  1039. $this->mprocClearLogin($token);
  1040. $this->error('账号或密码错误');
  1041. }
  1042. $this->success('登录成功', $jump, [
  1043. 'mproc_token' => $token,
  1044. 'keep_hours' => $this->mprocKeepHours(),
  1045. 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
  1046. ]);
  1047. }
  1048. /**
  1049. * 登录手机号对应的外协单位名称:customer 表;否则 purchase_order_detail
  1050. */
  1051. protected function mprocResolveCompanyForLoginPhone(string $phone): string
  1052. {
  1053. $phone = trim($phone);
  1054. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  1055. return '';
  1056. }
  1057. $cust = $this->mprocFindCustomerRowByPhone($phone);
  1058. if (is_array($cust) && $cust !== []) {
  1059. $co = $this->mprocCustomerPickField($cust, ['company_name', 'name']);
  1060. if ($co !== '') {
  1061. return $co;
  1062. }
  1063. }
  1064. try {
  1065. $one = Db::table('purchase_order_detail')
  1066. ->where('phone', $phone)
  1067. ->order('id', 'desc')
  1068. ->find();
  1069. if (is_array($one)) {
  1070. $n = trim((string)($one['company_name'] ?? ''));
  1071. if ($n !== '') {
  1072. return $n;
  1073. }
  1074. }
  1075. } catch (\Throwable $e) {
  1076. }
  1077. return '';
  1078. }
  1079. /**
  1080. * 按手机号匹配 customer(phone 或 account 单值相等)
  1081. *
  1082. * @return array<string, mixed>|null
  1083. */
  1084. protected function mprocFindCustomerRowByPhone(string $phone): ?array
  1085. {
  1086. $phone = trim($phone);
  1087. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  1088. return null;
  1089. }
  1090. try {
  1091. $row = Db::table('customer')
  1092. ->where(function ($q) use ($phone) {
  1093. $q->where('phone', $phone)->whereOr('account', $phone);
  1094. })
  1095. ->order('id', 'asc')
  1096. ->find();
  1097. } catch (\Throwable $e) {
  1098. return null;
  1099. }
  1100. if (!is_array($row) || $row === [] || !$this->mprocCustomerUserActive($row)) {
  1101. return null;
  1102. }
  1103. return $row;
  1104. }
  1105. /**
  1106. * 管理员表 fa_admin.mobile 与当前手机号一致且未禁用(用于手机验证码管理员通道)
  1107. *
  1108. * @return array<string, mixed>|null
  1109. */
  1110. protected function mprocAdminRowByMobile(string $phone): ?array
  1111. {
  1112. $phone = trim($phone);
  1113. if ($phone === '' || !preg_match('/^1\d{10}$/', $phone)) {
  1114. return null;
  1115. }
  1116. try {
  1117. $row = Db::name('admin')
  1118. ->where('mobile', $phone)
  1119. ->where('status', '<>', 'hidden')
  1120. ->order('id', 'asc')
  1121. ->find();
  1122. } catch (\Throwable $e) {
  1123. return null;
  1124. }
  1125. return is_array($row) && $row !== [] ? $row : null;
  1126. }
  1127. /**
  1128. * 在 customer 表中匹配当前用户:优先手机号,否则按公司名
  1129. *
  1130. * @return array<string, mixed>|null
  1131. */
  1132. protected function mprocFindCustomerRowForUser(array $user): ?array
  1133. {
  1134. $phone = trim((string)($user['phone'] ?? ''));
  1135. if ($phone === '') {
  1136. $phone = trim((string)($user['account'] ?? ''));
  1137. }
  1138. $cn = trim((string)($user['company_name'] ?? ''));
  1139. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  1140. $byPhone = $this->mprocFindCustomerRowByPhone($phone);
  1141. if ($byPhone !== null) {
  1142. return $byPhone;
  1143. }
  1144. }
  1145. if ($cn !== '') {
  1146. try {
  1147. // customer 表无 name 列,勿用 whereOr('name')
  1148. $hit = Db::table('customer')
  1149. ->where('company_name', $cn)
  1150. ->order('id', 'desc')
  1151. ->find();
  1152. } catch (\Throwable $e) {
  1153. $hit = null;
  1154. }
  1155. if (is_array($hit) && $hit !== []) {
  1156. return $hit;
  1157. }
  1158. }
  1159. return null;
  1160. }
  1161. /**
  1162. * 从 customer 行取字段(兼容列名大小写)
  1163. *
  1164. * @param string[] $candidates
  1165. */
  1166. protected function mprocCustomerPickField(array $row, array $candidates): string
  1167. {
  1168. foreach ($candidates as $want) {
  1169. $lw = strtolower($want);
  1170. foreach ($row as $k => $v) {
  1171. if (!is_string($k)) {
  1172. continue;
  1173. }
  1174. if (strtolower($k) !== $lw) {
  1175. continue;
  1176. }
  1177. $s = trim((string)$v);
  1178. if ($s !== '') {
  1179. return $s;
  1180. }
  1181. }
  1182. }
  1183. return '';
  1184. }
  1185. /**
  1186. * 明细表关键字搜索:仅对 purchase_order_detail 真实存在的列 LIKE;
  1187. * 主表 purchase_order 上的订单号、印件、工序等另查 scydgy_id 再 OR 进列表(避免引用不存在的列导致整页查失败)。
  1188. *
  1189. * @param \think\db\Query $query
  1190. */
  1191. protected function mprocApplySearchKeywordToDetailQuery($query, $search)
  1192. {
  1193. $kw = trim((string)$search);
  1194. if ($kw === '') {
  1195. return;
  1196. }
  1197. $map = self::$mprocProcuremenColumns;
  1198. if (!is_array($map) || $map === []) {
  1199. return;
  1200. }
  1201. $like = '%' . addcslashes($kw, '%_\\') . '%';
  1202. $wantLower = ['ccydh', 'cyjmc', 'cdxmc', 'company_name', 'cgzzxmc', 'cgymc', 'cdf', 'phone', 'email'];
  1203. $detailCols = [];
  1204. foreach ($wantLower as $low) {
  1205. if (isset($map[$low])) {
  1206. $detailCols[] = $map[$low];
  1207. }
  1208. }
  1209. $scydgyCol = isset($map['scydgy_id']) ? $map['scydgy_id'] : 'scydgy_id';
  1210. $idCol = isset($map['id']) ? $map['id'] : 'id';
  1211. $poSidList = [];
  1212. $poWant = ['CCYDH', 'CYJMC', 'CDXMC', 'CGYMC', 'cGzzxMc', 'CDF', 'score_rule_name'];
  1213. try {
  1214. $col = Db::table('purchase_order')
  1215. ->where(function ($sub) use ($like, $poWant) {
  1216. $firstPo = true;
  1217. foreach ($poWant as $pf) {
  1218. if ($firstPo) {
  1219. $sub->where($pf, 'like', $like);
  1220. $firstPo = false;
  1221. } else {
  1222. $sub->whereOr($pf, 'like', $like);
  1223. }
  1224. }
  1225. })
  1226. ->column('scydgy_id');
  1227. if (is_array($col)) {
  1228. foreach ($col as $v) {
  1229. $id = (int)$v;
  1230. if ($this->mprocIsValidScydgyRowId($id)) {
  1231. $poSidList[$id] = true;
  1232. }
  1233. }
  1234. }
  1235. $poSidList = array_keys($poSidList);
  1236. } catch (\Throwable $e) {
  1237. $poSidList = [];
  1238. }
  1239. $query->where(function ($q2) use ($like, $detailCols, $poSidList, $scydgyCol, $idCol) {
  1240. $first = true;
  1241. foreach ($detailCols as $col) {
  1242. if ($first) {
  1243. $q2->where($col, 'like', $like);
  1244. $first = false;
  1245. } else {
  1246. $q2->whereOr($col, 'like', $like);
  1247. }
  1248. }
  1249. if ($poSidList !== []) {
  1250. if ($first) {
  1251. $q2->where($scydgyCol, 'in', $poSidList);
  1252. $first = false;
  1253. } else {
  1254. $q2->whereOr($scydgyCol, 'in', $poSidList);
  1255. }
  1256. }
  1257. if ($first) {
  1258. $q2->where($idCol, '=', 0);
  1259. }
  1260. });
  1261. }
  1262. /**
  1263. * 列表:按左侧 Tab 追加 status_name 条件(与数值 status 0/1/2 无关;值由后端维护)
  1264. * - draft:status_name = 未提交
  1265. * - submitted:status_name = 已提交
  1266. * - done:status_name = 已完成
  1267. * 表无 status_name 列时不加条件(三个 Tab 数据相同,待库表补列后再筛)
  1268. *
  1269. * @param mixed $query
  1270. * @param string $tab draft|submitted|done
  1271. * @param string|null $statusNameCol 真实列名,如 status_name
  1272. */
  1273. protected function mprocApplyListTabConditions($query, $tab, $statusNameCol)
  1274. {
  1275. if ($statusNameCol === null) {
  1276. return;
  1277. }
  1278. $map = [
  1279. 'draft' => '未提交',
  1280. 'submitted' => '已提交',
  1281. 'done' => '已完成',
  1282. ];
  1283. $label = $map[$tab] ?? '未提交';
  1284. $query->where($statusNameCol, '=', $label);
  1285. }
  1286. /**
  1287. * 按登录态解析 customer 行
  1288. *
  1289. * @return array<string, mixed>|null
  1290. */
  1291. protected function mprocResolveCustomerUserForSession(array $user): ?array
  1292. {
  1293. if (!empty($user['is_admin'])) {
  1294. return null;
  1295. }
  1296. $cuId = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
  1297. if ($cuId > 0) {
  1298. try {
  1299. $row = Db::table('customer')->where('id', $cuId)->find();
  1300. } catch (\Throwable $e) {
  1301. $row = null;
  1302. }
  1303. if (is_array($row) && $row !== [] && $this->mprocCustomerUserActive($row)) {
  1304. return $row;
  1305. }
  1306. }
  1307. $account = trim((string)($user['account'] ?? ''));
  1308. if ($account !== '') {
  1309. $byAcc = $this->mprocFindCustomerUserByUsername($account);
  1310. if ($byAcc !== null) {
  1311. return $byAcc;
  1312. }
  1313. }
  1314. $phone = trim((string)($user['phone'] ?? ''));
  1315. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  1316. return $this->mprocFindCustomerUserByMobile($phone);
  1317. }
  1318. $uname = trim((string)($user['username'] ?? ''));
  1319. if ($uname !== '' && preg_match('/^1\d{10}$/', $uname)) {
  1320. return $this->mprocFindCustomerUserByMobile($uname);
  1321. }
  1322. return null;
  1323. }
  1324. /**
  1325. * customer 表字段 →「我的」展示结构
  1326. *
  1327. * @param array<string, mixed> $cu
  1328. * @return array{account:string,contact_name:string,department:string,phone:string,email:string,company_name:string}
  1329. */
  1330. protected function mprocProfileFromCustomerUserRow(array $cu): array
  1331. {
  1332. $nm = trim((string)($cu['username'] ?? ''));
  1333. $account = trim((string)($cu['account'] ?? ''));
  1334. $phone = trim((string)($cu['phone'] ?? ''));
  1335. if ($phone === '') {
  1336. $phone = $account;
  1337. }
  1338. $company = trim((string)($cu['company_name'] ?? ''));
  1339. return [
  1340. 'account' => $account !== '' ? $account : $phone,
  1341. 'contact_name' => $nm,
  1342. 'department' => $company,
  1343. 'phone' => $phone,
  1344. 'email' => trim((string)($cu['email'] ?? '')),
  1345. 'company_name' => $company,
  1346. ];
  1347. }
  1348. /**
  1349. * 管理员「我的」:账号、姓名、部门(角色组)、手机、邮箱
  1350. *
  1351. * @return array{account:string,contact_name:string,department:string,phone:string,email:string,company_name:string}
  1352. */
  1353. protected function mprocProfileForAdmin(array $user): array
  1354. {
  1355. $uname = trim((string)($user['username'] ?? ''));
  1356. $out = [
  1357. 'account' => $uname,
  1358. 'contact_name' => $uname !== '' ? $uname : '管理员',
  1359. 'department' => '',
  1360. 'phone' => trim((string)($user['phone'] ?? '')),
  1361. 'email' => '',
  1362. 'company_name' => '',
  1363. ];
  1364. if ($uname === '') {
  1365. return $out;
  1366. }
  1367. try {
  1368. $row = Db::name('admin')->where('username', $uname)->find();
  1369. } catch (\Throwable $e) {
  1370. $row = null;
  1371. }
  1372. if (!is_array($row) || $row === []) {
  1373. return $out;
  1374. }
  1375. $out['account'] = trim((string)($row['username'] ?? $uname));
  1376. $nick = trim((string)($row['nickname'] ?? ''));
  1377. if ($nick !== '') {
  1378. $out['contact_name'] = $nick;
  1379. }
  1380. $mob = trim((string)($row['mobile'] ?? ''));
  1381. if ($mob !== '') {
  1382. $out['phone'] = $mob;
  1383. }
  1384. $em = trim((string)($row['email'] ?? ''));
  1385. if ($em !== '') {
  1386. $out['email'] = $em;
  1387. }
  1388. $dept = $this->mprocAdminDepartmentLabel((int)($row['id'] ?? 0));
  1389. $out['department'] = $dept;
  1390. $out['company_name'] = $dept;
  1391. return $out;
  1392. }
  1393. /**
  1394. * 管理员部门展示:优先质检中心/生产部,否则拼接所属角色组名
  1395. */
  1396. protected function mprocAdminDepartmentLabel(int $adminId): string
  1397. {
  1398. if ($adminId <= 0) {
  1399. return '';
  1400. }
  1401. $names = [];
  1402. try {
  1403. $rows = Db::name('auth_group_access')
  1404. ->alias('aga')
  1405. ->join('auth_group ag', 'aga.group_id = ag.id')
  1406. ->where('aga.uid', $adminId)
  1407. ->where('ag.status', 'normal')
  1408. ->field('ag.id,ag.name')
  1409. ->order('ag.id', 'asc')
  1410. ->select();
  1411. } catch (\Throwable $e) {
  1412. $rows = [];
  1413. }
  1414. if (!is_array($rows)) {
  1415. return '';
  1416. }
  1417. $qualityId = $this->mprocResolveMobileQualityGroupId();
  1418. $deliveryId = $this->mprocResolveMobileDeliveryGroupId();
  1419. $deliveryLabel = trim((string)Config::get('mproc.mobile_delivery_dept_name'));
  1420. if ($deliveryLabel === '') {
  1421. $deliveryLabel = '生产部';
  1422. }
  1423. foreach ($rows as $r) {
  1424. if (!is_array($r)) {
  1425. continue;
  1426. }
  1427. $gid = (int)($r['id'] ?? 0);
  1428. $name = trim((string)($r['name'] ?? ''));
  1429. if ($gid === $qualityId) {
  1430. $names[] = '质检中心';
  1431. continue;
  1432. }
  1433. if ($gid === $deliveryId) {
  1434. $names[] = $deliveryLabel;
  1435. continue;
  1436. }
  1437. if ($name !== '') {
  1438. $names[] = $name;
  1439. }
  1440. }
  1441. $names = array_values(array_unique($names));
  1442. return $names !== [] ? implode('、', $names) : '';
  1443. }
  1444. /**
  1445. * 旧会话补全 customer_id 等字段
  1446. */
  1447. protected function mprocSyncSessionCustomerUser(array $user): array
  1448. {
  1449. if (!empty($user['is_admin'])) {
  1450. return $user;
  1451. }
  1452. $cu = $this->mprocResolveCustomerUserForSession($user);
  1453. if (!$cu) {
  1454. return $user;
  1455. }
  1456. $id = (int)($cu['id'] ?? 0);
  1457. $user['customer_id'] = $id;
  1458. $user['customer_user_id'] = $id;
  1459. $user['username'] = trim((string)($cu['username'] ?? $user['username'] ?? ''));
  1460. $user['company_name'] = trim((string)($cu['company_name'] ?? ''));
  1461. $user['account'] = trim((string)($cu['account'] ?? ''));
  1462. $mob = trim((string)($cu['phone'] ?? ''));
  1463. if ($mob === '') {
  1464. $mob = trim((string)($cu['account'] ?? ''));
  1465. }
  1466. if ($mob !== '') {
  1467. $user['phone'] = $mob;
  1468. }
  1469. $token = Session::get('mproc_token');
  1470. if ($token) {
  1471. $user['login_time'] = (int)($user['login_time'] ?? time());
  1472. $tok = trim((string)$token);
  1473. Cache::set($this->mprocAuthCacheKey($tok), $user, $this->mprocTtlSeconds + 86400);
  1474. if (!$this->mprocIsSignedAuthToken($tok)) {
  1475. Cache::set('mproc_u_' . preg_replace('/[^a-f0-9]/i', '', $tok), $user, $this->mprocTtlSeconds + 86400);
  1476. }
  1477. }
  1478. return $user;
  1479. }
  1480. /**
  1481. * 「我的」:普通用户 customer;管理员 admin
  1482. */
  1483. protected function mprocProfileForUser(array $user)
  1484. {
  1485. if (!empty($user['is_admin'])) {
  1486. return $this->mprocProfileForAdmin($user);
  1487. }
  1488. $cu = $this->mprocResolveCustomerUserForSession($user);
  1489. if (is_array($cu) && $cu !== []) {
  1490. return $this->mprocProfileFromCustomerUserRow($cu);
  1491. }
  1492. $phone = trim((string)($user['phone'] ?? ''));
  1493. if ($phone === '') {
  1494. $phone = trim((string)($user['account'] ?? ''));
  1495. }
  1496. return [
  1497. 'account' => $phone !== '' ? $phone : trim((string)($user['account'] ?? '')),
  1498. 'contact_name' => trim((string)($user['username'] ?? '')),
  1499. 'department' => trim((string)($user['company_name'] ?? '')),
  1500. 'phone' => $phone,
  1501. 'email' => '',
  1502. 'company_name' => trim((string)($user['company_name'] ?? '')),
  1503. ];
  1504. }
  1505. protected function mprocIsValidScydgyRowId($id): bool
  1506. {
  1507. return (int)$id !== 0;
  1508. }
  1509. /**
  1510. * 将 purchase_order(工序行主表)快照合并进 purchase_order_detail 行:订单级信息以主表为准;
  1511. * 金额、交期、外厂 company、明细 status 等仍保留明细表。
  1512. *
  1513. * @param array $row 引用:明细行
  1514. * @param array $poRow purchase_order 一行
  1515. */
  1516. protected function mprocMergePurchaseOrderIntoDetail(array &$row, array $poRow)
  1517. {
  1518. $pl = array_change_key_case($poRow, CASE_LOWER);
  1519. $hdr = [
  1520. 'ccydh' => 'CCYDH',
  1521. 'cyjmc' => 'CYJMC',
  1522. 'cdf' => 'CDF',
  1523. 'cgzzxmc' => 'cGzzxMc',
  1524. 'cgymc' => 'CGYMC',
  1525. 'cdxmc' => 'CDXMC',
  1526. 'ngzl' => 'NGZL',
  1527. 'cdw' => 'CDW',
  1528. 'cgybh' => 'CGYBH',
  1529. 'score_rule_name' => 'score_rule_name',
  1530. ];
  1531. foreach ($hdr as $lk => $out) {
  1532. if (!array_key_exists($lk, $pl)) {
  1533. continue;
  1534. }
  1535. $v = $pl[$lk];
  1536. if ($v !== null && $v !== '') {
  1537. $row[$out] = $v;
  1538. }
  1539. }
  1540. // 本次数量、最高限价:仅存在于主表;PDO 列名大小写可能不一致
  1541. $qtyRaw = '';
  1542. foreach (['this_quantity', 'This_quantity'] as $qk) {
  1543. if (array_key_exists($qk, $pl) && $pl[$qk] !== null && $pl[$qk] !== '') {
  1544. $qtyRaw = trim((string)$pl[$qk]);
  1545. break;
  1546. }
  1547. }
  1548. if ($qtyRaw === '') {
  1549. foreach (['This_quantity', 'this_quantity'] as $qk) {
  1550. if (array_key_exists($qk, $poRow) && $poRow[$qk] !== null && $poRow[$qk] !== '') {
  1551. $qtyRaw = trim((string)$poRow[$qk]);
  1552. break;
  1553. }
  1554. }
  1555. }
  1556. if ($qtyRaw !== '') {
  1557. $row['This_quantity'] = $qtyRaw;
  1558. }
  1559. $ceilRaw = '';
  1560. foreach (['ceilingprice', 'ceiling_price', 'CeilingPrice'] as $ck) {
  1561. if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
  1562. $ceilRaw = trim((string)$pl[$ck]);
  1563. break;
  1564. }
  1565. }
  1566. if ($ceilRaw === '') {
  1567. foreach (['ceilingPrice', 'ceiling_price', 'CeilingPrice'] as $ck) {
  1568. if (array_key_exists($ck, $poRow) && $poRow[$ck] !== null && $poRow[$ck] !== '') {
  1569. $ceilRaw = trim((string)$poRow[$ck]);
  1570. break;
  1571. }
  1572. }
  1573. }
  1574. if ($ceilRaw !== '') {
  1575. $row['ceilingPrice'] = $ceilRaw;
  1576. }
  1577. $sysRq = '';
  1578. foreach (['sys_rq', 'SYS_RQ'] as $sk) {
  1579. if (array_key_exists($sk, $pl) && $pl[$sk] !== null && $pl[$sk] !== '') {
  1580. $sysRq = trim((string)$pl[$sk]);
  1581. break;
  1582. }
  1583. if (array_key_exists($sk, $poRow) && $poRow[$sk] !== null && $poRow[$sk] !== '') {
  1584. $sysRq = trim((string)$poRow[$sk]);
  1585. break;
  1586. }
  1587. }
  1588. if ($sysRq !== '' && !preg_match('/^0000-00-00/i', $sysRq)) {
  1589. $row['sys_rq'] = $sysRq;
  1590. }
  1591. $deliveryDeadline = '';
  1592. foreach (['delivery_deadline', 'Delivery_deadline'] as $dk) {
  1593. if (array_key_exists($dk, $pl) && $pl[$dk] !== null && $pl[$dk] !== '') {
  1594. $deliveryDeadline = trim((string)$pl[$dk]);
  1595. break;
  1596. }
  1597. if (array_key_exists($dk, $poRow) && $poRow[$dk] !== null && $poRow[$dk] !== '') {
  1598. $deliveryDeadline = trim((string)$poRow[$dk]);
  1599. break;
  1600. }
  1601. }
  1602. if ($deliveryDeadline !== '' && !preg_match('/^0000-00-00/i', $deliveryDeadline)) {
  1603. $row['delivery_deadline'] = $deliveryDeadline;
  1604. }
  1605. // 下发备注(purchase_order.MBZ)→ 手机端未提交/已提交/已完成展示
  1606. $mbz = '';
  1607. foreach (['mbz', 'MBZ'] as $mk) {
  1608. if (array_key_exists($mk, $pl) && $pl[$mk] !== null && trim((string)$pl[$mk]) !== '') {
  1609. $mbz = trim((string)$pl[$mk]);
  1610. break;
  1611. }
  1612. if (array_key_exists($mk, $poRow) && $poRow[$mk] !== null && trim((string)$poRow[$mk]) !== '') {
  1613. $mbz = trim((string)$poRow[$mk]);
  1614. break;
  1615. }
  1616. }
  1617. if ($mbz !== '') {
  1618. $row['MBZ'] = $mbz;
  1619. $row['mproc_order_remark'] = $mbz;
  1620. }
  1621. }
  1622. /**
  1623. * @param int[] $sidList
  1624. * @return array<int, string>
  1625. */
  1626. protected function mprocLoadScydgyMbzByIds(array $sidList): array
  1627. {
  1628. $ids = [];
  1629. foreach ($sidList as $sid) {
  1630. $sid = (int)$sid;
  1631. if ($this->mprocIsValidScydgyRowId($sid)) {
  1632. $ids[$sid] = true;
  1633. }
  1634. }
  1635. if ($ids === []) {
  1636. return [];
  1637. }
  1638. try {
  1639. $map = Db::table('scydgy')->where('ID', 'in', array_keys($ids))->column('MBZ', 'ID');
  1640. } catch (\Throwable $e) {
  1641. return [];
  1642. }
  1643. return is_array($map) ? $map : [];
  1644. }
  1645. /**
  1646. * 统一取年月日(无效则空串)
  1647. */
  1648. protected function mprocFormatYmdValue($raw): string
  1649. {
  1650. $s = trim((string)$raw);
  1651. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  1652. return '';
  1653. }
  1654. $s = str_replace(['/', '.'], '-', $s);
  1655. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  1656. return $m[1];
  1657. }
  1658. $ts = strtotime(str_replace('T', ' ', $s));
  1659. if ($ts === false || $ts <= 0) {
  1660. return '';
  1661. }
  1662. return date('Y-m-d', $ts);
  1663. }
  1664. /**
  1665. * 招标截止展示:年月日 + 时分(有秒也保留到分即可)
  1666. */
  1667. protected function mprocFormatYmdHmValue($raw): string
  1668. {
  1669. $s = trim((string)$raw);
  1670. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  1671. return '';
  1672. }
  1673. $s = str_replace(['/', '.'], '-', $s);
  1674. $s = str_replace('T', ' ', $s);
  1675. if (preg_match('/^(\d{4}-\d{2}-\d{2})\s+(\d{2}):(\d{2})(?::\d{2})?/', $s, $m)) {
  1676. return $m[1] . ' ' . $m[2] . ':' . $m[3];
  1677. }
  1678. if (preg_match('/^(\d{4}-\d{2}-\d{2})$/', $s, $m)) {
  1679. return $m[1];
  1680. }
  1681. $ts = strtotime($s);
  1682. if ($ts === false || $ts <= 0) {
  1683. return '';
  1684. }
  1685. return date('Y-m-d H:i', $ts);
  1686. }
  1687. /**
  1688. * 列表展示:招标截止 / 交货截止
  1689. *
  1690. * @param array<string, mixed> $row
  1691. */
  1692. protected function mprocEnrichOrderDeadlineDisplay(array &$row): void
  1693. {
  1694. $sysRqRaw = $this->mprocResolveSysRqFromPo($row);
  1695. $bidRaw = $sysRqRaw !== '' ? $sysRqRaw : trim((string)($row['sys_rq'] ?? ''));
  1696. $bid = $this->mprocFormatYmdHmValue($bidRaw);
  1697. $del = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? '');
  1698. $row['mproc_bid_deadline_display'] = $bid;
  1699. // 完整截止时间供前端保存前校验(含时分秒)
  1700. $row['mproc_bid_deadline'] = $bidRaw;
  1701. $row['mproc_delivery_deadline_display'] = $del;
  1702. $row['mproc_delivery_deadline'] = $del;
  1703. }
  1704. /**
  1705. * 明细对应主表的交货截止日期 Y-m-d
  1706. *
  1707. * @param array<string, mixed> $row
  1708. */
  1709. protected function mprocResolveDeliveryDeadlineYmdForDetailRow(array $row): string
  1710. {
  1711. $fromRow = $this->mprocFormatYmdValue($row['delivery_deadline'] ?? $row['mproc_delivery_deadline'] ?? '');
  1712. if ($fromRow !== '') {
  1713. return $fromRow;
  1714. }
  1715. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1716. if (!$this->mprocIsValidScydgyRowId($sid)) {
  1717. return '';
  1718. }
  1719. try {
  1720. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1721. } catch (\Throwable $e) {
  1722. $po = null;
  1723. }
  1724. if (!is_array($po)) {
  1725. return '';
  1726. }
  1727. return $this->mprocFormatYmdValue($po['delivery_deadline'] ?? $po['Delivery_deadline'] ?? '');
  1728. }
  1729. /**
  1730. * 主表报价截止时间(未设置则视为未截止)
  1731. *
  1732. * @param array<string, mixed>|null $po
  1733. */
  1734. protected function mprocResolveSysRqFromPo(?array $po): string
  1735. {
  1736. if (!is_array($po)) {
  1737. return '';
  1738. }
  1739. $sr = trim((string)($po['sys_rq'] ?? $po['SYS_RQ'] ?? ''));
  1740. if ($sr === '') {
  1741. $pl = array_change_key_case($po, CASE_LOWER);
  1742. $sr = trim((string)($pl['sys_rq'] ?? ''));
  1743. }
  1744. return ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) ? $sr : '';
  1745. }
  1746. /**
  1747. * 从主表/明细解析订单号
  1748. *
  1749. * @param array<string, mixed>|null $po
  1750. * @param array<string, mixed>|null $row
  1751. */
  1752. protected function mprocResolveCcydhFromPoOrRow(?array $po, ?array $row = null): string
  1753. {
  1754. foreach ([$po, $row] as $src) {
  1755. if (!is_array($src)) {
  1756. continue;
  1757. }
  1758. $c = trim((string)($src['CCYDH'] ?? $src['ccydh'] ?? ''));
  1759. if ($c !== '') {
  1760. return $c;
  1761. }
  1762. }
  1763. return '';
  1764. }
  1765. /**
  1766. * 批量:已开标验证的订单号集合(本请求内可复用)
  1767. *
  1768. * @var array<string, bool>|null
  1769. */
  1770. protected $mprocBidOpenVerifiedSet = null;
  1771. /**
  1772. * @param array<int, string> $ccydhs
  1773. * @return array<string, bool>
  1774. */
  1775. protected function mprocLoadBidOpenVerifiedCcydhSet(array $ccydhs): array
  1776. {
  1777. $set = [];
  1778. $list = [];
  1779. foreach ($ccydhs as $c) {
  1780. $c = trim((string)$c);
  1781. if ($c !== '') {
  1782. $list[$c] = true;
  1783. }
  1784. }
  1785. if ($list === []) {
  1786. return $set;
  1787. }
  1788. try {
  1789. $rows = Db::table('purchase_order_bid_open')
  1790. ->where('ccydh', 'in', array_keys($list))
  1791. ->field('ccydh')
  1792. ->select();
  1793. if (!is_array($rows)) {
  1794. return $set;
  1795. }
  1796. foreach ($rows as $row) {
  1797. if (!is_array($row)) {
  1798. continue;
  1799. }
  1800. $c = trim((string)($row['ccydh'] ?? ''));
  1801. if ($c !== '') {
  1802. $set[$c] = true;
  1803. }
  1804. }
  1805. } catch (\Throwable $e) {
  1806. return [];
  1807. }
  1808. return $set;
  1809. }
  1810. /**
  1811. * 该订单是否已完成开标双重验证(有 purchase_order_bid_open 记录)
  1812. */
  1813. protected function mprocIsBidOpenVerified(string $ccydh): bool
  1814. {
  1815. $ccydh = trim($ccydh);
  1816. if ($ccydh === '') {
  1817. return false;
  1818. }
  1819. if (is_array($this->mprocBidOpenVerifiedSet)) {
  1820. return isset($this->mprocBidOpenVerifiedSet[$ccydh]);
  1821. }
  1822. try {
  1823. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  1824. return is_array($row);
  1825. } catch (\Throwable $e) {
  1826. return false;
  1827. }
  1828. }
  1829. /**
  1830. * @param array<string, mixed>|null $po
  1831. * @param array<string, mixed>|null $row
  1832. */
  1833. protected function mprocIsBidOpenVerifiedForPoOrRow(?array $po, ?array $row = null): bool
  1834. {
  1835. return $this->mprocIsBidOpenVerified($this->mprocResolveCcydhFromPoOrRow($po, $row));
  1836. }
  1837. /**
  1838. * 手机端:仅当主表设置了 sys_rq 且已到期时视为截止(无截止时间仍可填报)
  1839. * 保存时务必再调一次,防止页面长时间打开、截止后仍提交
  1840. *
  1841. * @param array<string, mixed>|null $po
  1842. */
  1843. protected function mprocIsQuoteDeadlineReachedForPo(?array $po): bool
  1844. {
  1845. $raw = $this->mprocResolveSysRqFromPo($po);
  1846. if ($raw === '') {
  1847. return false;
  1848. }
  1849. $ts = strtotime(str_replace('T', ' ', $raw));
  1850. if ($ts === false || $ts <= 0) {
  1851. return false;
  1852. }
  1853. return time() >= $ts;
  1854. }
  1855. /**
  1856. * 保存前强制按库中最新招标截止时间校验(避免弹窗久开后仍提交)
  1857. *
  1858. * @param array<string, mixed>|null $po
  1859. */
  1860. protected function mprocAssertQuoteNotDeadlineReached(?array $po, string $label = ''): void
  1861. {
  1862. // 以库中最新主表为准,避免内存中旧快照
  1863. $freshPo = null;
  1864. if (is_array($po)) {
  1865. $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
  1866. if ($this->mprocIsValidScydgyRowId($sid)) {
  1867. try {
  1868. $freshPo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1869. } catch (\Throwable $e) {
  1870. $freshPo = null;
  1871. }
  1872. }
  1873. }
  1874. $checkPo = is_array($freshPo) ? $freshPo : $po;
  1875. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($checkPo) ? $checkPo : null)) {
  1876. throw new \InvalidArgumentException(
  1877. ($label !== '' ? $label : '') . '已超过招标截止时间,不可再提交'
  1878. );
  1879. }
  1880. }
  1881. /**
  1882. * 保存前:截止时间 + 已开标均不可再改
  1883. *
  1884. * @param array<string, mixed>|null $po
  1885. * @param array<string, mixed>|null $row
  1886. */
  1887. protected function mprocAssertQuoteStillEditable(?array $po, string $label = '', ?array $row = null): void
  1888. {
  1889. $sid = 0;
  1890. if (is_array($row)) {
  1891. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1892. }
  1893. if ($sid === 0 && is_array($po)) {
  1894. $sid = (int)($po['scydgy_id'] ?? $po['SCYDGY_ID'] ?? 0);
  1895. }
  1896. // 手工询价无招标截止、不开标
  1897. if ($sid < 0) {
  1898. return;
  1899. }
  1900. $this->mprocAssertQuoteNotDeadlineReached($po, $label);
  1901. $freshPo = is_array($po) ? $po : null;
  1902. if (is_array($po)) {
  1903. if ($this->mprocIsValidScydgyRowId($sid)) {
  1904. try {
  1905. $got = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  1906. if (is_array($got)) {
  1907. $freshPo = $got;
  1908. }
  1909. } catch (\Throwable $e) {
  1910. }
  1911. }
  1912. }
  1913. // 保存场景不走列表缓存,直接查库
  1914. $prev = $this->mprocBidOpenVerifiedSet;
  1915. $this->mprocBidOpenVerifiedSet = null;
  1916. $opened = $this->mprocIsBidOpenVerifiedForPoOrRow($freshPo, $row);
  1917. $this->mprocBidOpenVerifiedSet = $prev;
  1918. if ($opened) {
  1919. throw new \InvalidArgumentException(
  1920. ($label !== '' ? $label : '') . '已开标验证,不可再提交'
  1921. );
  1922. }
  1923. }
  1924. /**
  1925. * 审批通过后:中标 / 未中标
  1926. * 说明:采购终审通过后主单仍为「进行中」(待入库评分),仅 wflow=已审核;
  1927. * 不能等主单「已完结」才标中标,否则手机端会误显示「已截止」。
  1928. *
  1929. * @param array<string, mixed> $row
  1930. * @param array<string, mixed>|null $po
  1931. */
  1932. protected function mprocResolvePickResultText(array $row, ?array $po): string
  1933. {
  1934. if (!is_array($po)) {
  1935. return '';
  1936. }
  1937. $approved = ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')
  1938. || ProcuremenStatus::isPoCompleted($po['status'] ?? $po['STATUS'] ?? '');
  1939. if (!$approved) {
  1940. return '';
  1941. }
  1942. $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
  1943. if (ProcuremenStatus::isPodPicked($detailStatus)) {
  1944. return '中标';
  1945. }
  1946. $sn = trim((string)($row['status_name'] ?? ''));
  1947. if ($sn === '已完成') {
  1948. return '中标';
  1949. }
  1950. return '未中标';
  1951. }
  1952. /**
  1953. * 手机端左侧 Tab:
  1954. * 询价:rfq / rfq_submitted(手工单 scydgy_id&lt;0,仅未提交/已提交)
  1955. * 报价:draft / submitted / done(协助下发)
  1956. *
  1957. * @param array<string, mixed> $row
  1958. * @param array<string, mixed>|null $po
  1959. */
  1960. protected function mprocResolveListTabForRow(array $row, ?array $po, string $effectiveSn): string
  1961. {
  1962. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  1963. // 手工询价:无招标截止;仅未提交/已提交(对应待报价/已报价)
  1964. if ($sid < 0) {
  1965. if ($effectiveSn === '已提交'
  1966. || in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  1967. return 'rfq_submitted';
  1968. }
  1969. return 'rfq';
  1970. }
  1971. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  1972. return 'done';
  1973. }
  1974. if ($this->mprocIsBidOpenVerifiedForPoOrRow($po, $row)
  1975. || $this->mprocIsQuoteDeadlineReachedForPo($po)) {
  1976. // 已开标或已过招标截止 →「已完成」
  1977. return 'done';
  1978. }
  1979. if ($effectiveSn === '已提交') {
  1980. return 'submitted';
  1981. }
  1982. return 'draft';
  1983. }
  1984. /**
  1985. * @return string[]
  1986. */
  1987. protected function mprocListTabWhitelist(): array
  1988. {
  1989. return ['rfq', 'rfq_submitted', 'draft', 'submitted', 'done'];
  1990. }
  1991. /**
  1992. * 兼容旧地址 tab=rfq_done → 询价已提交
  1993. */
  1994. protected function mprocNormalizeListTab(string $tab): string
  1995. {
  1996. if ($tab === 'rfq_done') {
  1997. return 'rfq_submitted';
  1998. }
  1999. if (!in_array($tab, $this->mprocListTabWhitelist(), true)) {
  2000. return 'draft';
  2001. }
  2002. return $tab;
  2003. }
  2004. protected function mprocIsDoneListTab(string $tab): bool
  2005. {
  2006. return $tab === 'done';
  2007. }
  2008. protected function mprocIsRfqListTab(string $tab): bool
  2009. {
  2010. return $tab === 'rfq' || $tab === 'rfq_submitted';
  2011. }
  2012. /**
  2013. * 复合 Tab → 状态维度:draft|submitted|done
  2014. */
  2015. protected function mprocStatusFromListTab(string $tab): string
  2016. {
  2017. if ($tab === 'rfq' || $tab === 'draft') {
  2018. return 'draft';
  2019. }
  2020. if ($tab === 'rfq_submitted' || $tab === 'submitted') {
  2021. return 'submitted';
  2022. }
  2023. if ($this->mprocIsDoneListTab($tab)) {
  2024. return 'done';
  2025. }
  2026. return 'draft';
  2027. }
  2028. /**
  2029. * 同一订单号 + 供应商合并为一张卡片
  2030. *
  2031. * @param array<int, array<string, mixed>> $rows
  2032. * @return array<int, array<string, mixed>>
  2033. */
  2034. protected function mprocGroupRowsByOrder(array $rows): array
  2035. {
  2036. $groups = [];
  2037. $order = [];
  2038. foreach ($rows as $row) {
  2039. if (!is_array($row)) {
  2040. continue;
  2041. }
  2042. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2043. $cname = trim((string)($row['company_name'] ?? ''));
  2044. $isVoid = (int)($row['mproc_is_void'] ?? 0) === 1
  2045. || $this->mprocDetailRowIsVoid($row);
  2046. // 已废弃轮与当前轮拆成两张卡,避免混在一起看不清
  2047. $roundKey = $isVoid
  2048. ? ('void:' . (int)($row['eid'] ?? $row['id'] ?? 0))
  2049. : 'active';
  2050. $key = ($ccydh !== '' ? $ccydh : ('eid_' . (int)($row['eid'] ?? 0))) . '|' . $cname . '|' . $roundKey;
  2051. if (!isset($groups[$key])) {
  2052. $groups[$key] = [
  2053. 'group_key' => $key,
  2054. 'CCYDH' => $ccydh,
  2055. 'CYJMC' => trim((string)($row['CYJMC'] ?? '')),
  2056. 'company_name' => $cname,
  2057. 'score_rule_name' => trim((string)($row['score_rule_name'] ?? '')),
  2058. 'mproc_bid_deadline_display' => trim((string)($row['mproc_bid_deadline_display'] ?? '')),
  2059. 'mproc_bid_deadline' => trim((string)($row['mproc_bid_deadline'] ?? '')),
  2060. 'mproc_delivery_deadline_display' => trim((string)($row['mproc_delivery_deadline_display'] ?? '')),
  2061. 'mproc_delivery_deadline' => trim((string)($row['mproc_delivery_deadline'] ?? '')),
  2062. 'lines' => [],
  2063. ];
  2064. $order[] = $key;
  2065. } else {
  2066. if ($groups[$key]['mproc_delivery_deadline'] === ''
  2067. && trim((string)($row['mproc_delivery_deadline'] ?? '')) !== '') {
  2068. $groups[$key]['mproc_delivery_deadline'] = trim((string)$row['mproc_delivery_deadline']);
  2069. $groups[$key]['mproc_delivery_deadline_display'] = trim((string)($row['mproc_delivery_deadline_display'] ?? ''));
  2070. }
  2071. if ($groups[$key]['mproc_bid_deadline'] === ''
  2072. && trim((string)($row['mproc_bid_deadline'] ?? '')) !== '') {
  2073. $groups[$key]['mproc_bid_deadline'] = trim((string)$row['mproc_bid_deadline']);
  2074. }
  2075. if ($groups[$key]['mproc_bid_deadline_display'] === ''
  2076. && trim((string)($row['mproc_bid_deadline_display'] ?? '')) !== '') {
  2077. $groups[$key]['mproc_bid_deadline_display'] = trim((string)$row['mproc_bid_deadline_display']);
  2078. }
  2079. }
  2080. $groups[$key]['lines'][] = $row;
  2081. }
  2082. $out = [];
  2083. foreach ($order as $key) {
  2084. $g = $groups[$key];
  2085. $lines = is_array($g['lines'] ?? null) ? $g['lines'] : [];
  2086. usort($lines, function ($a, $b) {
  2087. $sa = (int)($a['scydgy_id'] ?? 0);
  2088. $sb = (int)($b['scydgy_id'] ?? 0);
  2089. if ($sa !== $sb) {
  2090. return $sa <=> $sb;
  2091. }
  2092. return ((int)($a['eid'] ?? 0)) <=> ((int)($b['eid'] ?? 0));
  2093. });
  2094. $g['lines'] = $lines;
  2095. $g['line_count'] = count($lines);
  2096. $canEdit = false;
  2097. $bidOpen = false;
  2098. foreach ($lines as $ln) {
  2099. if (!is_array($ln)) {
  2100. continue;
  2101. }
  2102. if ((int)($ln['mproc_can_edit'] ?? 0) === 1) {
  2103. $canEdit = true;
  2104. }
  2105. if ((int)($ln['mproc_bid_open_verified'] ?? 0) === 1) {
  2106. $bidOpen = true;
  2107. }
  2108. }
  2109. $g['can_edit'] = $canEdit ? 1 : 0;
  2110. $g['mproc_bid_open_verified'] = $bidOpen ? 1 : 0;
  2111. $remark = '';
  2112. $orderRemarkList = [];
  2113. $doneLabel = '';
  2114. $pickResult = '';
  2115. $hasWin = false;
  2116. $hasLose = false;
  2117. $hasExpired = false;
  2118. $hasVoid = false;
  2119. foreach ($lines as $ln) {
  2120. if (!is_array($ln)) {
  2121. continue;
  2122. }
  2123. $rm = $this->mprocSupplierOwnRemark(
  2124. (string)($ln['mproc_remark'] ?? ''),
  2125. (string)($ln['mproc_order_remark'] ?? $ln['MBZ'] ?? '')
  2126. );
  2127. if ($rm !== '' && $remark === '') {
  2128. $remark = $rm;
  2129. }
  2130. $ombz = trim((string)($ln['mproc_order_remark'] ?? $ln['MBZ'] ?? ''));
  2131. if ($ombz !== '' && !in_array($ombz, $orderRemarkList, true)) {
  2132. $orderRemarkList[] = $ombz;
  2133. }
  2134. $pr = trim((string)($ln['mproc_pick_result'] ?? ''));
  2135. $dl = trim((string)($ln['mproc_done_label'] ?? ''));
  2136. if ($pr === '中标' || $dl === '中标') {
  2137. $hasWin = true;
  2138. } elseif ($pr === '未中标' || $dl === '未中标') {
  2139. $hasLose = true;
  2140. } elseif ($dl === '已废弃' || (int)($ln['mproc_is_void'] ?? 0) === 1) {
  2141. $hasVoid = true;
  2142. } elseif ($dl === '已截止' || (int)($ln['mproc_deadline_reached'] ?? 0) === 1) {
  2143. $hasExpired = true;
  2144. }
  2145. }
  2146. if ($hasVoid) {
  2147. $doneLabel = '已废弃';
  2148. $pickResult = '';
  2149. } elseif ($hasWin) {
  2150. $doneLabel = '中标';
  2151. $pickResult = '中标';
  2152. } elseif ($hasLose) {
  2153. $doneLabel = '未中标';
  2154. $pickResult = '未中标';
  2155. } elseif ($hasExpired) {
  2156. $doneLabel = '已截止';
  2157. $pickResult = '';
  2158. }
  2159. $g['remark'] = $remark;
  2160. $g['mproc_order_remark'] = $orderRemarkList !== [] ? implode('、', $orderRemarkList) : '';
  2161. $g['mproc_done_label'] = $doneLabel;
  2162. $g['mproc_pick_result'] = $pickResult;
  2163. $out[] = $g;
  2164. }
  2165. return $out;
  2166. }
  2167. /**
  2168. * 查询 purchase_order_detail 列表(订单页)
  2169. * 无搜索词 / 有搜索词:均按左侧 Tab 筛选(draft/submitted/done)
  2170. * 有搜索词时:在当前 Tab 内做关键字匹配
  2171. *
  2172. * @param string $tab draft|submitted|done
  2173. * @param string|null $statusNameCol status_name 真实列名;为 null 时不按 Tab 过滤
  2174. * @return array{rows: array, done_no_status: int}
  2175. */
  2176. protected function mprocFetchProcuremenList(array $user, $tab, $q, $statusNameCol)
  2177. {
  2178. $query = Db::table('purchase_order_detail')->order('id', 'desc');
  2179. // 初选下发已向供应商发送通知后,手机端可见 wflow_status>=1 的明细
  2180. $userWhere = $this->mprocListWhereForLoginUser($user);
  2181. if ($userWhere !== []) {
  2182. $query->where($userWhere);
  2183. }
  2184. if (trim((string)$q) === '' && $this->mprocIsDoneListTab((string)$tab) && $statusNameCol !== null) {
  2185. $this->mprocSyncLegacyApprovedStatusNames($user, $statusNameCol);
  2186. }
  2187. $this->mprocApplySearchKeywordToDetailQuery($query, $q);
  2188. // Tab 筛选在 PHP 层按截止时间、审批结果综合判断(含逾期进「已完成」、未中标等)
  2189. try {
  2190. $rows = $query->limit(500)->select();
  2191. } catch (\Throwable $e) {
  2192. $rows = [];
  2193. }
  2194. if (!is_array($rows)) {
  2195. $rows = [];
  2196. }
  2197. $poBySid = [];
  2198. $sidList = [];
  2199. foreach ($rows as $r0) {
  2200. if (!is_array($r0)) {
  2201. continue;
  2202. }
  2203. $sid0 = (int)($r0['scydgy_id'] ?? $r0['SCYDGY_ID'] ?? 0);
  2204. if ($this->mprocIsValidScydgyRowId($sid0)) {
  2205. $sidList[$sid0] = true;
  2206. }
  2207. }
  2208. if ($sidList !== []) {
  2209. try {
  2210. $poRows = Db::table('purchase_order')
  2211. ->where('scydgy_id', 'in', array_values(array_keys($sidList)))
  2212. ->select();
  2213. if (is_array($poRows)) {
  2214. foreach ($poRows as $pr) {
  2215. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  2216. if ($this->mprocIsValidScydgyRowId($sidk)) {
  2217. $poBySid[$sidk] = $pr;
  2218. }
  2219. }
  2220. }
  2221. } catch (\Throwable $e) {
  2222. }
  2223. }
  2224. $ccydhForBid = [];
  2225. foreach ($poBySid as $pr) {
  2226. if (!is_array($pr)) {
  2227. continue;
  2228. }
  2229. $c = trim((string)($pr['CCYDH'] ?? $pr['ccydh'] ?? ''));
  2230. if ($c !== '') {
  2231. $ccydhForBid[$c] = true;
  2232. }
  2233. }
  2234. foreach ($rows as $r0) {
  2235. if (!is_array($r0)) {
  2236. continue;
  2237. }
  2238. $c = trim((string)($r0['CCYDH'] ?? $r0['ccydh'] ?? ''));
  2239. if ($c !== '') {
  2240. $ccydhForBid[$c] = true;
  2241. }
  2242. }
  2243. $this->mprocBidOpenVerifiedSet = $this->mprocLoadBidOpenVerifiedCcydhSet(array_keys($ccydhForBid));
  2244. $needScydgyMbzSids = [];
  2245. foreach ($poBySid as $sidKey => $pr) {
  2246. if (!is_array($pr)) {
  2247. continue;
  2248. }
  2249. $mbzPo = '';
  2250. foreach (['mbz', 'MBZ'] as $mk) {
  2251. if (array_key_exists($mk, $pr) && $pr[$mk] !== null && trim((string)$pr[$mk]) !== '') {
  2252. $mbzPo = trim((string)$pr[$mk]);
  2253. break;
  2254. }
  2255. }
  2256. if ($mbzPo === '' && $this->mprocIsValidScydgyRowId((int)$sidKey)) {
  2257. $needScydgyMbzSids[(int)$sidKey] = true;
  2258. }
  2259. }
  2260. $scydgyMbzBySid = [];
  2261. if ($needScydgyMbzSids !== []) {
  2262. $loadedMbz = $this->mprocLoadScydgyMbzByIds(array_keys($needScydgyMbzSids));
  2263. foreach ($loadedMbz as $sidKey => $mbzVal) {
  2264. $mbzVal = trim((string)$mbzVal);
  2265. if ($mbzVal !== '') {
  2266. $scydgyMbzBySid[(int)$sidKey] = $mbzVal;
  2267. }
  2268. }
  2269. }
  2270. foreach ($rows as &$row) {
  2271. if (!is_array($row)) {
  2272. continue;
  2273. }
  2274. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? 0);
  2275. $isVoid = $this->mprocDetailRowIsVoid($row);
  2276. // 已废弃:仅展示「填过报价」的旧轮,与当前轮并排,避免供应商误以为没填过
  2277. if ($isVoid && !$this->mprocDetailRowHasQuote($row)) {
  2278. $row = null;
  2279. continue;
  2280. }
  2281. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2282. if ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) {
  2283. $this->mprocMergePurchaseOrderIntoDetail($row, $poBySid[$sid]);
  2284. }
  2285. if (trim((string)($row['mproc_order_remark'] ?? $row['MBZ'] ?? '')) === ''
  2286. && $this->mprocIsValidScydgyRowId($sid)
  2287. && isset($scydgyMbzBySid[$sid])
  2288. && is_string($scydgyMbzBySid[$sid])) {
  2289. $row['MBZ'] = $scydgyMbzBySid[$sid];
  2290. $row['mproc_order_remark'] = $scydgyMbzBySid[$sid];
  2291. }
  2292. $poRow = ($this->mprocIsValidScydgyRowId($sid) && isset($poBySid[$sid])) ? $poBySid[$sid] : null;
  2293. $oldSn = trim((string)($row['status_name'] ?? ''));
  2294. if ($isVoid) {
  2295. $effectiveSn = ProcuremenStatus::POD_VOID;
  2296. $listTab = 'done';
  2297. $row['status_name'] = $effectiveSn;
  2298. $row['mproc_list_tab'] = $listTab;
  2299. $row['mproc_is_void'] = 1;
  2300. $row['mproc_is_rfq'] = ((int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0) < 0) ? 1 : 0;
  2301. $row['mproc_deadline_reached'] = 0;
  2302. $row['mproc_bid_open_verified'] = 0;
  2303. $row['mproc_pick_result'] = '';
  2304. $row['mproc_done_label'] = '已废弃';
  2305. $row['mproc_can_edit'] = 0;
  2306. } else {
  2307. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, $poRow);
  2308. $row['status_name'] = $effectiveSn;
  2309. if ($statusNameCol !== null && $effectiveSn !== $oldSn && $row['eid'] > 0) {
  2310. $this->mprocPersistDetailStatusName((int)$row['eid'], $statusNameCol, $effectiveSn);
  2311. }
  2312. $listTab = $this->mprocResolveListTabForRow($row, $poRow, $effectiveSn);
  2313. $row['mproc_list_tab'] = $listTab;
  2314. $row['mproc_is_void'] = 0;
  2315. $row['mproc_is_rfq'] = ((int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0) < 0) ? 1 : 0;
  2316. if ((int)$row['mproc_is_rfq'] === 1) {
  2317. $row['mproc_bid_deadline'] = '';
  2318. $row['mproc_bid_deadline_display'] = '';
  2319. $row['mproc_delivery_deadline'] = '';
  2320. $row['mproc_delivery_deadline_display'] = '';
  2321. $row['mproc_deadline_reached'] = 0;
  2322. $row['mproc_bid_open_verified'] = 0;
  2323. $row['mproc_pick_result'] = '';
  2324. } else {
  2325. $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
  2326. $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
  2327. $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow($poRow, $row) ? 1 : 0;
  2328. }
  2329. if ($row['mproc_pick_result'] !== '') {
  2330. $row['mproc_done_label'] = $row['mproc_pick_result'];
  2331. } elseif ($this->mprocIsDoneListTab($listTab) && (
  2332. (int)$row['mproc_deadline_reached'] === 1
  2333. || (int)$row['mproc_bid_open_verified'] === 1
  2334. )) {
  2335. $row['mproc_done_label'] = '已截止';
  2336. } else {
  2337. $row['mproc_done_label'] = '';
  2338. }
  2339. if (!isset($row['status_name']) || $row['status_name'] === null) {
  2340. $row['status_name'] = '';
  2341. } else {
  2342. $row['status_name'] = trim((string)$row['status_name']);
  2343. }
  2344. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
  2345. }
  2346. $am = $row['amount'] ?? null;
  2347. if ($am === null || $am === '' || (is_string($am) && trim($am) === '')) {
  2348. $row['amount_display'] = '';
  2349. } else {
  2350. $row['amount_display'] = is_scalar($am) ? (string)$am : '';
  2351. }
  2352. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2353. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  2354. $row['delivery_display'] = $m[1];
  2355. } elseif ($dv !== '') {
  2356. $row['delivery_display'] = $dv;
  2357. } else {
  2358. $row['delivery_display'] = '';
  2359. }
  2360. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  2361. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  2362. $this->mprocEnrichLeadDaysDisplay($row);
  2363. if ((int)$row['mproc_is_rfq'] === 1) {
  2364. $row['mproc_bid_deadline'] = '';
  2365. $row['mproc_bid_deadline_display'] = '';
  2366. $row['mproc_delivery_deadline'] = '';
  2367. $row['mproc_delivery_deadline_display'] = '';
  2368. } else {
  2369. $this->mprocEnrichOrderDeadlineDisplay($row);
  2370. }
  2371. $row['mproc_fill_hint'] = '';
  2372. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  2373. $orderRemark = trim((string)($row['mproc_order_remark'] ?? $row['MBZ'] ?? ''));
  2374. $detailRemark = $this->mprocResolveDetailRemark($row);
  2375. if ($orderRemark === '') {
  2376. $row['mproc_order_remark'] = '';
  2377. }
  2378. $row['mproc_remark'] = $this->mprocSupplierOwnRemark($detailRemark, $orderRemark);
  2379. }
  2380. unset($row);
  2381. $rows = array_values(array_filter($rows, function ($r) {
  2382. return is_array($r);
  2383. }));
  2384. // 同一供应商同一工序:保留最新有效轮 + 最近一轮已废弃且有报价的记录
  2385. $rows = $this->mprocDedupeDetailRowsByCompanyProcess($rows);
  2386. // 始终按 Tab 过滤(含搜索):未中标/已截止等只出现在「已完成」
  2387. $rows = array_values(array_filter($rows, function ($r) use ($tab) {
  2388. return is_array($r) && trim((string)($r['mproc_list_tab'] ?? '')) === $tab;
  2389. }));
  2390. // 「已完成」仅保留近三个月(按招标截止日,缺省则交货截止/创建时间)
  2391. if ($this->mprocIsDoneListTab((string)$tab)) {
  2392. $rows = array_values(array_filter($rows, function ($r) {
  2393. return is_array($r) && $this->mprocIsWithinRecentMonths($r, 3);
  2394. }));
  2395. }
  2396. // 按招标截止日期排序:未提交/已提交截止近的在前;已完成最近截止的在前
  2397. $rows = $this->mprocSortRowsByBidDeadline($rows, $this->mprocIsDoneListTab((string)$tab) ? 'desc' : 'asc');
  2398. $groups = $this->mprocGroupRowsByOrder($rows);
  2399. return [
  2400. 'rows' => $rows ?: [],
  2401. 'groups' => $groups ?: [],
  2402. 'done_no_status' => (int)($statusNameCol === null),
  2403. ];
  2404. }
  2405. /**
  2406. * 按招标截止时间排序(无截止时间的排最后)
  2407. *
  2408. * @param array<int, array<string, mixed>> $rows
  2409. * @param string $dir asc|desc
  2410. * @return array<int, array<string, mixed>>
  2411. */
  2412. protected function mprocSortRowsByBidDeadline(array $rows, string $dir = 'asc'): array
  2413. {
  2414. $dir = strtolower($dir) === 'desc' ? 'desc' : 'asc';
  2415. usort($rows, function ($a, $b) use ($dir) {
  2416. $ta = $this->mprocBidDeadlineSortTs(is_array($a) ? $a : []);
  2417. $tb = $this->mprocBidDeadlineSortTs(is_array($b) ? $b : []);
  2418. $ha = $ta > 0;
  2419. $hb = $tb > 0;
  2420. if ($ha !== $hb) {
  2421. return $ha ? -1 : 1;
  2422. }
  2423. if ($ha && $ta !== $tb) {
  2424. return $dir === 'desc' ? ($tb <=> $ta) : ($ta <=> $tb);
  2425. }
  2426. $ida = (int)($a['eid'] ?? $a['id'] ?? 0);
  2427. $idb = (int)($b['eid'] ?? $b['id'] ?? 0);
  2428. return $idb <=> $ida;
  2429. });
  2430. return array_values($rows);
  2431. }
  2432. /**
  2433. * @param array<string, mixed> $row
  2434. */
  2435. protected function mprocBidDeadlineSortTs(array $row): int
  2436. {
  2437. $raw = trim((string)($row['mproc_bid_deadline'] ?? $row['sys_rq'] ?? $row['SYS_RQ'] ?? ''));
  2438. if ($raw === '') {
  2439. $raw = trim((string)($row['mproc_bid_deadline_display'] ?? ''));
  2440. }
  2441. if ($raw === '') {
  2442. return 0;
  2443. }
  2444. $ts = strtotime(str_replace('T', ' ', $raw));
  2445. return ($ts !== false && $ts > 0) ? (int)$ts : 0;
  2446. }
  2447. /**
  2448. * 是否属于近 N 个月(优先招标截止,其次交货截止,再次创建/更新时间)
  2449. *
  2450. * @param array<string, mixed> $row
  2451. */
  2452. protected function mprocIsWithinRecentMonths(array $row, int $months = 3): bool
  2453. {
  2454. $months = max(1, $months);
  2455. $since = strtotime(date('Y-m-d 00:00:00', strtotime('-' . $months . ' months')));
  2456. if ($since === false) {
  2457. return true;
  2458. }
  2459. $candidates = [
  2460. $row['mproc_bid_deadline'] ?? '',
  2461. $row['sys_rq'] ?? '',
  2462. $row['SYS_RQ'] ?? '',
  2463. $row['mproc_bid_deadline_display'] ?? '',
  2464. $row['mproc_delivery_deadline'] ?? '',
  2465. $row['delivery_deadline'] ?? '',
  2466. $row['mproc_delivery_deadline_display'] ?? '',
  2467. $row['createtime'] ?? '',
  2468. $row['updatetime'] ?? '',
  2469. ];
  2470. foreach ($candidates as $raw) {
  2471. $raw = trim((string)$raw);
  2472. if ($raw === '' || stripos($raw, '0000-00-00') === 0) {
  2473. continue;
  2474. }
  2475. $ts = strtotime(str_replace('T', ' ', $raw));
  2476. if ($ts === false || $ts <= 0) {
  2477. continue;
  2478. }
  2479. return $ts >= $since;
  2480. }
  2481. return false;
  2482. }
  2483. /**
  2484. * 同一供应商 + 同一工序:
  2485. * - 有效轮只保留 id 最大的一条
  2486. * - 已废弃且有报价的,再保留 id 最大的一条(与有效轮并排展示)
  2487. *
  2488. * @param array<int, array<string, mixed>> $rows
  2489. * @return array<int, array<string, mixed>>
  2490. */
  2491. protected function mprocDedupeDetailRowsByCompanyProcess(array $rows): array
  2492. {
  2493. $bestActive = [];
  2494. $bestVoid = [];
  2495. $orderKeys = [];
  2496. foreach ($rows as $row) {
  2497. if (!is_array($row)) {
  2498. continue;
  2499. }
  2500. $cn = trim((string)($row['company_name'] ?? ''));
  2501. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2502. $eid = (int)($row['eid'] ?? $row['id'] ?? $row['ID'] ?? 0);
  2503. if ($this->mprocIsValidScydgyRowId($sid)) {
  2504. $key = $cn . '|sid:' . $sid;
  2505. } else {
  2506. $key = $cn . '|eid:' . $eid;
  2507. }
  2508. $isVoid = (int)($row['mproc_is_void'] ?? 0) === 1 || $this->mprocDetailRowIsVoid($row);
  2509. if ($isVoid) {
  2510. if (!$this->mprocDetailRowHasQuote($row)) {
  2511. continue;
  2512. }
  2513. if (!isset($bestVoid[$key])) {
  2514. $bestVoid[$key] = $row;
  2515. if (!isset($bestActive[$key]) && !in_array($key, $orderKeys, true)) {
  2516. $orderKeys[] = $key;
  2517. }
  2518. continue;
  2519. }
  2520. $prevEid = (int)($bestVoid[$key]['eid'] ?? $bestVoid[$key]['id'] ?? 0);
  2521. if ($eid > $prevEid) {
  2522. $bestVoid[$key] = $row;
  2523. }
  2524. continue;
  2525. }
  2526. if (!isset($bestActive[$key])) {
  2527. $bestActive[$key] = $row;
  2528. if (!in_array($key, $orderKeys, true)) {
  2529. $orderKeys[] = $key;
  2530. }
  2531. continue;
  2532. }
  2533. $prevEid = (int)($bestActive[$key]['eid'] ?? $bestActive[$key]['id'] ?? 0);
  2534. if ($eid > $prevEid) {
  2535. $bestActive[$key] = $row;
  2536. }
  2537. }
  2538. $out = [];
  2539. foreach ($orderKeys as $key) {
  2540. // 先当前轮,后已废弃轮(列表里当前在上更直观)
  2541. if (isset($bestActive[$key])) {
  2542. $out[] = $bestActive[$key];
  2543. }
  2544. if (isset($bestVoid[$key])) {
  2545. $activeEid = isset($bestActive[$key])
  2546. ? (int)($bestActive[$key]['eid'] ?? $bestActive[$key]['id'] ?? 0)
  2547. : 0;
  2548. $voidEid = (int)($bestVoid[$key]['eid'] ?? $bestVoid[$key]['id'] ?? 0);
  2549. if ($voidEid > 0 && $voidEid !== $activeEid) {
  2550. $out[] = $bestVoid[$key];
  2551. }
  2552. }
  2553. }
  2554. return $out;
  2555. }
  2556. /**
  2557. * @param array<string, mixed> $row
  2558. */
  2559. protected function mprocDetailRowIsVoid(array $row): bool
  2560. {
  2561. return ProcuremenStatus::isPodVoid($row['status'] ?? '')
  2562. || trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  2563. }
  2564. /**
  2565. * @param array<string, mixed> $row
  2566. */
  2567. protected function mprocDetailRowHasQuote(array $row): bool
  2568. {
  2569. $am = $row['amount'] ?? null;
  2570. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  2571. return true;
  2572. }
  2573. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2574. if ($dv !== '' && !preg_match('/^0000-00-00/i', $dv)) {
  2575. return true;
  2576. }
  2577. $ld = $row['lead_days'] ?? null;
  2578. return $ld !== null && $ld !== '' && is_numeric($ld);
  2579. }
  2580. /**
  2581. * status_name → 手机端左侧 Tab
  2582. */
  2583. protected function mprocStatusNameToListTab(string $statusName): string
  2584. {
  2585. $map = ['未提交' => 'draft', '已提交' => 'submitted', '已完成' => 'done', '未通过' => 'done', '已废弃' => 'done'];
  2586. $sn = trim($statusName);
  2587. return isset($map[$sn]) ? $map[$sn] : '';
  2588. }
  2589. /**
  2590. * 短信/邮件 focus_eid 应落在的列表 Tab
  2591. */
  2592. protected function mprocResolveListTabForFocusEid(int $focusEid, array $user): string
  2593. {
  2594. if ($focusEid <= 0) {
  2595. return '';
  2596. }
  2597. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2598. if ($idCol === null) {
  2599. return '';
  2600. }
  2601. try {
  2602. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  2603. $qw = $this->mprocListWhereForLoginUser($user);
  2604. if ($qw !== []) {
  2605. $qrow->where($qw);
  2606. }
  2607. $dr = $qrow->find();
  2608. } catch (\Throwable $e) {
  2609. $dr = null;
  2610. }
  2611. if (!is_array($dr) || $dr === []) {
  2612. return '';
  2613. }
  2614. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  2615. $po = null;
  2616. if ($this->mprocIsValidScydgyRowId($sid)) {
  2617. try {
  2618. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2619. } catch (\Throwable $e) {
  2620. $po = null;
  2621. }
  2622. }
  2623. return $this->mprocResolveListTabForRow(
  2624. $dr,
  2625. is_array($po) ? $po : null,
  2626. $this->mprocResolveEffectiveStatusName($dr, is_array($po) ? $po : null)
  2627. );
  2628. }
  2629. /**
  2630. * 短信/邮件直达链接:确保 focus 对应明细出现在当前列表(便于高亮定位)
  2631. *
  2632. * @param array<string, mixed> $bundle
  2633. * @param array<string, mixed> $user
  2634. * @return array<string, mixed>
  2635. */
  2636. protected function mprocEnsureFocusRowInList(
  2637. array $bundle,
  2638. int $focusEid,
  2639. array $user,
  2640. $statusNameCol,
  2641. string $tab = 'draft',
  2642. string $q = ''
  2643. ): array {
  2644. if ($focusEid <= 0) {
  2645. return $bundle;
  2646. }
  2647. $rows = isset($bundle['rows']) && is_array($bundle['rows']) ? $bundle['rows'] : [];
  2648. $foundIdx = -1;
  2649. foreach ($rows as $idx => $r) {
  2650. if (!is_array($r)) {
  2651. continue;
  2652. }
  2653. if ((int)($r['eid'] ?? $r['id'] ?? $r['ID'] ?? 0) === $focusEid) {
  2654. $foundIdx = (int)$idx;
  2655. break;
  2656. }
  2657. }
  2658. if ($foundIdx > 0) {
  2659. $hit = $rows[$foundIdx];
  2660. array_splice($rows, $foundIdx, 1);
  2661. array_unshift($rows, $hit);
  2662. $bundle['rows'] = $rows;
  2663. $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
  2664. return $bundle;
  2665. }
  2666. if ($foundIdx === 0) {
  2667. return $bundle;
  2668. }
  2669. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2670. if ($idCol === null) {
  2671. return $bundle;
  2672. }
  2673. try {
  2674. $qrow = Db::table('purchase_order_detail')->where($idCol, $focusEid);
  2675. $qw = $this->mprocListWhereForLoginUser($user);
  2676. if ($qw !== []) {
  2677. $qrow->where($qw);
  2678. }
  2679. $dr = $qrow->find();
  2680. } catch (\Throwable $e) {
  2681. $dr = null;
  2682. }
  2683. if (!is_array($dr) || $dr === []) {
  2684. return $bundle;
  2685. }
  2686. $row = $dr;
  2687. $row['eid'] = (int)($row['id'] ?? $row['ID'] ?? $focusEid);
  2688. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  2689. $poRow = null;
  2690. if ($this->mprocIsValidScydgyRowId($sid)) {
  2691. try {
  2692. $poRow = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2693. } catch (\Throwable $e) {
  2694. $poRow = null;
  2695. }
  2696. if (is_array($poRow)) {
  2697. $this->mprocMergePurchaseOrderIntoDetail($row, $poRow);
  2698. }
  2699. }
  2700. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($poRow) ? $poRow : null);
  2701. $rowTab = $this->mprocResolveListTabForRow($row, is_array($poRow) ? $poRow : null, $effectiveSn);
  2702. if ($rowTab !== '' && $rowTab !== $tab) {
  2703. return $bundle;
  2704. }
  2705. $row['status_name'] = $effectiveSn;
  2706. $listTab = $rowTab;
  2707. $row['mproc_list_tab'] = $listTab;
  2708. $row['mproc_deadline_reached'] = $this->mprocIsQuoteDeadlineReachedForPo($poRow) ? 1 : 0;
  2709. $row['mproc_pick_result'] = $this->mprocResolvePickResultText($row, $poRow);
  2710. $row['mproc_bid_open_verified'] = $this->mprocIsBidOpenVerifiedForPoOrRow(is_array($poRow) ? $poRow : null, $row) ? 1 : 0;
  2711. if ($row['mproc_pick_result'] !== '') {
  2712. $row['mproc_done_label'] = $row['mproc_pick_result'];
  2713. } elseif ($this->mprocIsDoneListTab($listTab) && (
  2714. (int)$row['mproc_deadline_reached'] === 1
  2715. || (int)$row['mproc_bid_open_verified'] === 1
  2716. )) {
  2717. $row['mproc_done_label'] = '已截止';
  2718. } else {
  2719. $row['mproc_done_label'] = '';
  2720. }
  2721. $row['mproc_can_edit'] = $this->mprocCanEditRow($user, $row, $poRow) ? 1 : 0;
  2722. $am = $row['amount'] ?? null;
  2723. $row['amount_display'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? '' : (is_scalar($am) ? (string)$am : '');
  2724. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2725. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  2726. $row['delivery_display'] = $m[1];
  2727. } elseif ($dv !== '') {
  2728. $row['delivery_display'] = $dv;
  2729. } else {
  2730. $row['delivery_display'] = '';
  2731. }
  2732. $row['amount_missing'] = ($am === null || $am === '' || (is_string($am) && trim($am) === '')) ? 1 : 0;
  2733. $row['delivery_missing'] = ($dv === '' || preg_match('/^0000-00-00/i', $dv)) ? 1 : 0;
  2734. $this->mprocEnrichLeadDaysDisplay($row);
  2735. $this->mprocEnrichOrderDeadlineDisplay($row);
  2736. $row['mproc_fill_hint'] = '';
  2737. $row['mproc_this_quantity_display'] = $this->mprocResolveDisplayThisQuantity($row);
  2738. array_unshift($rows, $row);
  2739. $bundle['rows'] = $rows;
  2740. $bundle['groups'] = $this->mprocGroupRowsByOrder($rows);
  2741. return $bundle;
  2742. }
  2743. /**
  2744. * 列表展示用「本次数量」:主表本次数量为空时回退显示 NGZL(工作量)
  2745. *
  2746. * @param array<string, mixed> $row
  2747. */
  2748. protected function mprocResolveDisplayThisQuantity(array $row): string
  2749. {
  2750. $qty = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  2751. if ($qty !== '') {
  2752. return $qty;
  2753. }
  2754. $gzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  2755. if ($gzl === null || $gzl === '') {
  2756. return '';
  2757. }
  2758. return is_scalar($gzl) ? trim((string)$gzl) : '';
  2759. }
  2760. /**
  2761. * 明细是否已填写单价或交货日期
  2762. *
  2763. * @param array<string, mixed> $row
  2764. */
  2765. protected function mprocDetailQuoteSubmitted(array $row): bool
  2766. {
  2767. $am = $row['amount'] ?? null;
  2768. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  2769. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  2770. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  2771. return $amountFilled || $deliveryFilled;
  2772. }
  2773. /**
  2774. * 手机端列表 Tab 用 status_name;审批通过后主表 status=1 时按明细 status 纠偏
  2775. *
  2776. * @param array<string, mixed> $row
  2777. * @param array<string, mixed>|null $po
  2778. */
  2779. protected function mprocResolveEffectiveStatusName(array $row, ?array $po): string
  2780. {
  2781. $sn = trim((string)($row['status_name'] ?? ''));
  2782. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  2783. return $sn;
  2784. }
  2785. if (!is_array($po)) {
  2786. if ($sn === '未提交' && $this->mprocDetailQuoteSubmitted($row)) {
  2787. return '已提交';
  2788. }
  2789. if ($sn !== '') {
  2790. return $sn;
  2791. }
  2792. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  2793. }
  2794. $poStatus = $po['status'] ?? $po['STATUS'] ?? '';
  2795. if (!ProcuremenStatus::isPoCompleted($poStatus)) {
  2796. // 库中仍写「未提交」但已填单价/交期:按已提交展示(手工单常见)
  2797. if ($sn === '未提交' && $this->mprocDetailQuoteSubmitted($row)) {
  2798. return '已提交';
  2799. }
  2800. if ($sn !== '') {
  2801. return $sn;
  2802. }
  2803. return $this->mprocDetailQuoteSubmitted($row) ? '已提交' : '未提交';
  2804. }
  2805. $detailStatus = $row['status'] ?? $row['STATUS'] ?? '';
  2806. if (ProcuremenStatus::isPodPicked($detailStatus)) {
  2807. return '已完成';
  2808. }
  2809. if ($sn === '已提交') {
  2810. return '未通过';
  2811. }
  2812. return $sn !== '' ? $sn : '未提交';
  2813. }
  2814. /**
  2815. * 将纠偏后的 status_name 写回库表(兼容历史已审批数据)
  2816. */
  2817. protected function mprocPersistDetailStatusName(int $detailId, string $statusNameCol, string $statusName): void
  2818. {
  2819. if ($detailId <= 0 || $statusNameCol === '') {
  2820. return;
  2821. }
  2822. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2823. if ($idCol === null || $idCol === '') {
  2824. return;
  2825. }
  2826. try {
  2827. Db::table('purchase_order_detail')->where($idCol, $detailId)->update([$statusNameCol => $statusName]);
  2828. } catch (\Throwable $e) {
  2829. }
  2830. }
  2831. /**
  2832. * 纠偏历史数据:主表已审批(status=1)但明细 status_name 仍为「已提交」
  2833. *
  2834. * @param array<string, mixed> $user
  2835. */
  2836. protected function mprocSyncLegacyApprovedStatusNames(array $user, string $statusNameCol): void
  2837. {
  2838. $userWhere = $this->mprocListWhereForLoginUser($user);
  2839. try {
  2840. $query = Db::table('purchase_order_detail')->where($statusNameCol, '已提交');
  2841. if ($userWhere !== []) {
  2842. $query->where($userWhere);
  2843. }
  2844. $candidates = $query->limit(200)->select();
  2845. } catch (\Throwable $e) {
  2846. return;
  2847. }
  2848. if (!is_array($candidates) || $candidates === []) {
  2849. return;
  2850. }
  2851. $sidList = [];
  2852. foreach ($candidates as $cr) {
  2853. if (!is_array($cr)) {
  2854. continue;
  2855. }
  2856. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  2857. if ($this->mprocIsValidScydgyRowId($sid)) {
  2858. $sidList[$sid] = true;
  2859. }
  2860. }
  2861. if ($sidList === []) {
  2862. return;
  2863. }
  2864. $poBySid = [];
  2865. try {
  2866. $poRows = Db::table('purchase_order')
  2867. ->where('scydgy_id', 'in', array_keys($sidList))
  2868. ->whereIn('status', ProcuremenStatus::poCompletedValues())
  2869. ->select();
  2870. if (is_array($poRows)) {
  2871. foreach ($poRows as $pr) {
  2872. $sidk = (int)($pr['scydgy_id'] ?? $pr['SCYDGY_ID'] ?? 0);
  2873. if ($this->mprocIsValidScydgyRowId($sidk)) {
  2874. $poBySid[$sidk] = $pr;
  2875. }
  2876. }
  2877. }
  2878. } catch (\Throwable $e) {
  2879. return;
  2880. }
  2881. if ($poBySid === []) {
  2882. return;
  2883. }
  2884. $idCol = $this->mprocResolveProcuremenColumn(['id']);
  2885. if ($idCol === null || $idCol === '') {
  2886. return;
  2887. }
  2888. foreach ($candidates as $cr) {
  2889. if (!is_array($cr)) {
  2890. continue;
  2891. }
  2892. $sid = (int)($cr['scydgy_id'] ?? $cr['SCYDGY_ID'] ?? 0);
  2893. if (!isset($poBySid[$sid])) {
  2894. continue;
  2895. }
  2896. $detailId = (int)($cr[$idCol] ?? $cr['id'] ?? $cr['ID'] ?? 0);
  2897. if ($detailId <= 0) {
  2898. continue;
  2899. }
  2900. $targetSn = $this->mprocResolveEffectiveStatusName($cr, $poBySid[$sid]);
  2901. if ($targetSn === '已提交') {
  2902. continue;
  2903. }
  2904. $this->mprocPersistDetailStatusName($detailId, $statusNameCol, $targetSn);
  2905. }
  2906. }
  2907. /**
  2908. * 协助明细首页(需登录)
  2909. * GET:main_tab=orders|me,orders 时 tab=draft|submitted|done 对应 status_name:未提交|已提交|已完成;q 搜索词
  2910. */
  2911. public function index()
  2912. {
  2913. $user = $this->mprocGetUser();
  2914. if (!$user) {
  2915. $pendingFocus = $this->mprocReadFocusEidFromRequest();
  2916. if ($pendingFocus > 0) {
  2917. $this->mprocRememberFocusEid($pendingFocus);
  2918. }
  2919. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  2920. $safe = $this->mprocSanitizeRedirectUrl($uri);
  2921. if ($safe !== '' && $pendingFocus > 0 && stripos($safe, 'focus_eid') === false) {
  2922. $safe .= (strpos($safe, '?') !== false ? '&' : '?') . 'focus_eid=' . $pendingFocus;
  2923. }
  2924. if ($safe !== '') {
  2925. Session::set('mproc_intended_url', $safe);
  2926. }
  2927. $this->redirect($this->mprocBuildLoginUrl($safe));
  2928. return;
  2929. }
  2930. // 管理员进对应业务页,不进供应商报价列表
  2931. if (!empty($user['is_admin'])) {
  2932. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  2933. if ($jump === '') {
  2934. $this->mprocDropCurrentLogin();
  2935. $this->redirect(url('index/index/login'));
  2936. return;
  2937. }
  2938. $this->redirect($jump);
  2939. return;
  2940. }
  2941. $user = $this->mprocSyncSessionCustomerUser($user);
  2942. $tabParamRaw = $this->request->get('tab', null);
  2943. $hasExplicitTab = ($tabParamRaw !== null && trim((string)$tabParamRaw) !== '');
  2944. $tabParam = trim((string)($tabParamRaw ?? 'draft'));
  2945. $mainTab = trim((string)$this->request->get('main_tab', 'orders'));
  2946. // 旧地址 ?tab=me 表示「我的」
  2947. if ($tabParam === 'me') {
  2948. $mainTab = 'me';
  2949. }
  2950. if (!in_array($mainTab, ['orders', 'me'], true)) {
  2951. $mainTab = 'orders';
  2952. }
  2953. $tab = $tabParam === 'me' ? 'draft' : $this->mprocNormalizeListTab($tabParam);
  2954. $q = trim((string)$this->request->get('q', ''));
  2955. $mprocFocusEid = 0;
  2956. $focusEid = $this->mprocReadFocusEidFromRequest();
  2957. if ($focusEid > 0 && $mainTab === 'orders') {
  2958. $resolvedTab = $this->mprocResolveListTabForFocusEid($focusEid, $user);
  2959. // 用户已手动点了其他左侧 Tab:取消定位锁定,避免刷新又跳回
  2960. if ($hasExplicitTab && $resolvedTab !== '' && $resolvedTab !== $tab) {
  2961. Session::delete('mproc_focus_eid');
  2962. $focusEid = 0;
  2963. } else {
  2964. $mprocFocusEid = $focusEid;
  2965. // 仅邮件/短信直链且 URL 未带 tab 时,自动切到定位单所在 Tab
  2966. $focusFromUrl = (int)$this->request->param('focus_eid', 0) > 0;
  2967. if (!$focusFromUrl) {
  2968. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  2969. $focusFromUrl = $this->mprocParseFocusEidFromUriString($uri) > 0;
  2970. }
  2971. if ($focusFromUrl && trim((string)$q) === '' && !$hasExplicitTab) {
  2972. if ($resolvedTab !== '') {
  2973. $tab = $resolvedTab;
  2974. }
  2975. }
  2976. }
  2977. }
  2978. // 左侧 Tab 按 purchase_order_detail.status_name(未提交/已提交/已完成),与数值 status 无关
  2979. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  2980. $profile = $this->mprocProfileForUser($user);
  2981. $this->view->assign('mprocMainTab', $mainTab);
  2982. $this->view->assign('mprocTab', $tab);
  2983. $this->view->assign('mprocIsRfqTab', $this->mprocIsRfqListTab($tab) ? 1 : 0);
  2984. $this->view->assign('mprocStatusTab', $this->mprocStatusFromListTab($tab));
  2985. $this->view->assign('mprocSearchQ', $q);
  2986. $this->view->assign('mprocProfile', $profile);
  2987. $this->view->assign('mprocIsAdmin', !empty($user['is_admin']) ? 1 : 0);
  2988. $cid = (int)($user['customer_id'] ?? $user['customer_user_id'] ?? 0);
  2989. $this->view->assign('mprocCanChangePwd', empty($user['is_admin']) && $cid > 0 ? 1 : 0);
  2990. $this->view->assign('mprocFocusEid', $mprocFocusEid);
  2991. $mprocFocusTab = $mprocFocusEid > 0 ? $this->mprocResolveListTabForFocusEid($mprocFocusEid, $user) : '';
  2992. $this->view->assign('mprocFocusTab', $mprocFocusTab);
  2993. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  2994. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  2995. $this->view->assign('mprocDeliveryNoteUrl', url('index/index/deliverynote'));
  2996. if ($mainTab === 'me') {
  2997. $this->view->assign('rows', []);
  2998. return $this->view->fetch();
  2999. }
  3000. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  3001. if ($mprocFocusEid > 0) {
  3002. $bundle = $this->mprocEnsureFocusRowInList($bundle, $mprocFocusEid, $user, $statusNameCol, $tab, $q);
  3003. }
  3004. $this->view->assign('rows', $bundle['rows']);
  3005. $this->view->assign('groups', $bundle['groups'] ?? $this->mprocGroupRowsByOrder($bundle['rows']));
  3006. return $this->view->fetch();
  3007. }
  3008. /**
  3009. * 协助明细列表 JSON(需登录)
  3010. * main_tab=orders|me;orders 时 tab=draft|submitted|done、q=搜索词
  3011. */
  3012. public function mprocList()
  3013. {
  3014. $user = $this->mprocGetUser();
  3015. if (!$user) {
  3016. $this->error('请先登录', url('index/index/login'));
  3017. }
  3018. $user = $this->mprocSyncSessionCustomerUser($user);
  3019. $tabParam = trim((string)$this->request->request('tab', 'draft'));
  3020. $mainTab = trim((string)$this->request->request('main_tab', 'orders'));
  3021. if ($tabParam === 'me') {
  3022. $mainTab = 'me';
  3023. }
  3024. if (!in_array($mainTab, ['orders', 'me'], true)) {
  3025. $mainTab = 'orders';
  3026. }
  3027. $tab = $tabParam === 'me' ? 'draft' : $this->mprocNormalizeListTab($tabParam);
  3028. $q = trim((string)$this->request->request('q', ''));
  3029. if ($mainTab === 'me') {
  3030. // Jump::success($msg, $url, $data, …) 第二参是 URL,数据必须放第三参
  3031. $this->success('ok', '', [
  3032. 'main_tab' => 'me',
  3033. 'tab' => $tab,
  3034. 'rows' => [],
  3035. 'profile' => $this->mprocProfileForUser($user),
  3036. 'done_no_status' => 0,
  3037. ]);
  3038. }
  3039. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  3040. if ((int)$this->request->request('clear_focus', 0) === 1) {
  3041. Session::delete('mproc_focus_eid');
  3042. $focusEid = 0;
  3043. $focusTab = '';
  3044. } else {
  3045. $focusEid = $this->mprocReadFocusEidFromRequest();
  3046. $focusTab = $focusEid > 0 ? $this->mprocResolveListTabForFocusEid($focusEid, $user) : '';
  3047. // 列表请求已指定 Tab,且与定位单所在 Tab 不同:视为用户离开锁定页
  3048. if ($focusEid > 0 && $focusTab !== '' && $focusTab !== $tab) {
  3049. Session::delete('mproc_focus_eid');
  3050. $focusEid = 0;
  3051. $focusTab = '';
  3052. }
  3053. }
  3054. $bundle = $this->mprocFetchProcuremenList($user, $tab, $q, $statusNameCol);
  3055. if ($focusEid > 0) {
  3056. $bundle = $this->mprocEnsureFocusRowInList($bundle, $focusEid, $user, $statusNameCol, $tab, $q);
  3057. }
  3058. $this->success('ok', '', array_merge([
  3059. 'main_tab' => 'orders',
  3060. 'tab' => $tab,
  3061. 'focus_tab' => $focusTab,
  3062. 'is_admin' => !empty($user['is_admin']) ? 1 : 0,
  3063. 'focus_eid' => $focusEid,
  3064. ], $bundle));
  3065. }
  3066. /**
  3067. * 登录页(手机号验证码 / 账号密码)
  3068. */
  3069. public function login()
  3070. {
  3071. $redirect = $this->mprocSanitizeRedirectUrl($this->request->get('redirect', ''));
  3072. $user = $this->mprocGetUser();
  3073. if ($user) {
  3074. $jump = $this->mprocBuildAfterLoginHomeUrl($user, $redirect);
  3075. if ($jump !== '') {
  3076. $this->redirect($jump);
  3077. return;
  3078. }
  3079. // 已登录但无手机端权限(其它后台账号):清会话,避免登录页↔自身 302 死循环
  3080. $this->mprocDropCurrentLogin();
  3081. }
  3082. if ($redirect !== '') {
  3083. Session::set('mproc_intended_url', $redirect);
  3084. }
  3085. $this->view->assign('mprocLoginRedirect', $redirect);
  3086. $this->view->assign('mprocCaptchaUrl', url('index/index/captcha'));
  3087. $this->view->assign('mprocCaptchaLen', (int)(Config::get('captcha.length') ?: 4));
  3088. return $this->view->fetch();
  3089. }
  3090. /**
  3091. * 图形验证码(手机号登录用)
  3092. */
  3093. public function captcha($id = '')
  3094. {
  3095. $captcha = new Captcha((array)Config::get('captcha'));
  3096. return $captcha->entry($id);
  3097. }
  3098. /**
  3099. * 发送登录验证码(POST:phone、captcha)
  3100. */
  3101. public function sendSms()
  3102. {
  3103. if (!$this->request->isPost()) {
  3104. $this->error('请使用 POST');
  3105. }
  3106. $phone = trim((string)$this->request->post('phone', ''));
  3107. $captcha = trim((string)$this->request->post('captcha', ''));
  3108. if (!preg_match('/^1\d{10}$/', $phone)) {
  3109. $this->error('请输入正确的11位手机号');
  3110. }
  3111. if ($captcha === '') {
  3112. $this->error('请输入图形验证码');
  3113. }
  3114. $cu = $this->mprocFindCustomerUserByMobile($phone);
  3115. $adminRow = $cu ? null : $this->mprocAdminRowByMobile($phone);
  3116. if (!$cu && !$adminRow) {
  3117. $this->error('账号或密码错误');
  3118. }
  3119. if ($adminRow) {
  3120. $probe = $this->mprocLoginPayloadFromAdmin($adminRow, 'sms');
  3121. if (!$this->mprocAdminHasAnyMobileAccess($probe)) {
  3122. $this->error('账号或密码错误');
  3123. }
  3124. }
  3125. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  3126. if (Cache::get('mproc_sms_wait_' . $phone)) {
  3127. $this->error('发送过于频繁,请稍后再试');
  3128. }
  3129. if (!Validate::is($captcha, 'captcha')) {
  3130. $this->error('图形验证码不正确');
  3131. }
  3132. $code = (string)random_int(100000, 999999);
  3133. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  3134. $ttl = max(60, min(600, $ttl));
  3135. Cache::set('mproc_code_' . $phone, $code, $ttl);
  3136. Cache::set('mproc_sms_wait_' . $phone, 1, $cd);
  3137. try {
  3138. $tpl = trim((string)Config::get('mproc.sms_login_template'));
  3139. if ($tpl === '') {
  3140. $tpl = '【可集达】您的验证码是{code}。如非本人操作,请忽略本短信';
  3141. }
  3142. $content = str_replace('{code}', $code, $tpl);
  3143. $this->mprocSmsSend($phone, $content);
  3144. } catch (\Exception $e) {
  3145. Cache::rm('mproc_code_' . $phone);
  3146. Cache::rm('mproc_sms_wait_' . $phone);
  3147. $this->error($e->getMessage());
  3148. }
  3149. $this->success('验证码已发送');
  3150. }
  3151. /**
  3152. * 验证码登录(POST:phone、code)
  3153. */
  3154. public function doLogin()
  3155. {
  3156. if (!$this->request->isPost()) {
  3157. $this->error('请使用 POST');
  3158. }
  3159. $phone = trim((string)$this->request->post('phone', ''));
  3160. $code = trim((string)$this->request->post('code', ''));
  3161. if (!preg_match('/^1\d{10}$/', $phone)) {
  3162. $this->error('手机号格式不正确');
  3163. }
  3164. if (!preg_match('/^\d{6}$/', $code)) {
  3165. $this->error('请输入6位验证码');
  3166. }
  3167. // 本地调试:application/extra/mproc.php 中配置 mock_sms_code 与输入一致时,不校验短信缓存(生产务必留空)
  3168. $mock = Config::get('mproc.mock_sms_code');
  3169. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3170. Cache::rm('mproc_code_' . $phone);
  3171. } else {
  3172. $cached = Cache::get('mproc_code_' . $phone);
  3173. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3174. $this->error('验证码错误或已过期');
  3175. }
  3176. Cache::rm('mproc_code_' . $phone);
  3177. }
  3178. $cu = $this->mprocFindCustomerUserByMobile($phone);
  3179. if ($cu) {
  3180. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'sms'));
  3181. return;
  3182. }
  3183. $adminRow = $this->mprocAdminRowByMobile($phone);
  3184. if ($adminRow) {
  3185. $payload = $this->mprocLoginPayloadFromAdmin($adminRow, 'sms');
  3186. if (!$this->mprocAdminHasAnyMobileAccess($payload)) {
  3187. $this->error('账号或密码错误');
  3188. }
  3189. $this->mprocFinishLogin($payload);
  3190. return;
  3191. }
  3192. $this->error('账号或密码错误');
  3193. }
  3194. /**
  3195. * 用本地保存的 token 恢复登录态(POST:mproc_token)
  3196. */
  3197. public function mprocRestore()
  3198. {
  3199. if (!$this->request->isPost()) {
  3200. $this->error('请使用 POST');
  3201. }
  3202. $token = $this->mprocReadTokenFromRequest();
  3203. $user = null;
  3204. if ($token !== '') {
  3205. $user = $this->mprocLoadUserByToken($token);
  3206. }
  3207. if (!$user) {
  3208. $user = $this->mprocUserFromRememberCookie();
  3209. if ($user) {
  3210. $token = $this->mprocPackSignedAuthToken($user);
  3211. }
  3212. }
  3213. if (!$user) {
  3214. $this->error('登录已过期,请重新登录', url('index/index/login'));
  3215. }
  3216. $token = $this->mprocTouchLoginState($user, $token !== '' ? $token : $this->mprocPackSignedAuthToken($user));
  3217. $redirect = $this->mprocSanitizeRedirectUrl($this->request->post('redirect', ''));
  3218. $jump = $this->mprocBuildAfterLoginHomeUrl($user, $redirect);
  3219. if ($jump === '') {
  3220. $this->mprocClearLogin($token);
  3221. $this->error('账号或密码错误', url('index/index/login'));
  3222. }
  3223. $this->success('ok', $jump, [
  3224. 'mproc_token' => $token,
  3225. 'keep_hours' => $this->mprocKeepHours(),
  3226. 'keep_days' => max(1, (int)round($this->mprocTtlSeconds / 86400)),
  3227. ]);
  3228. }
  3229. /**
  3230. * 账号密码登录(POST:username、password)
  3231. * 先 customer(account),未命中再 admin;admin 密码规则同 FastAdmin Auth::login
  3232. */
  3233. public function doLoginPwd()
  3234. {
  3235. if (!$this->request->isPost()) {
  3236. $this->error('请使用 POST');
  3237. }
  3238. $username = trim((string)$this->request->post('username', ''));
  3239. $password = (string)$this->request->post('password', '');
  3240. if ($username === '' || $password === '') {
  3241. $this->error('请输入账号和密码');
  3242. }
  3243. $cu = $this->mprocFindCustomerUserByUsername($username);
  3244. if ($cu) {
  3245. if (!$this->mprocVerifyCustomerUserPassword($cu, $password)) {
  3246. $this->error('账号或密码错误');
  3247. }
  3248. $this->mprocFinishLogin($this->mprocLoginPayloadFromCustomer($cu, 'pwd'));
  3249. }
  3250. // 管理员:表 admin
  3251. $row = null;
  3252. try {
  3253. $row = Db::name('admin')
  3254. ->field('id,username,password,salt,status,loginfailure,updatetime,mobile')
  3255. ->where('username', $username)
  3256. ->find();
  3257. } catch (\Throwable $e) {
  3258. $row = null;
  3259. }
  3260. if (!$row || !is_array($row)) {
  3261. $this->error('账号或密码错误');
  3262. }
  3263. $id = (int)($row['id'] ?? 0);
  3264. if (($row['status'] ?? '') == 'hidden') {
  3265. $this->error('该账号已禁用');
  3266. }
  3267. if (Config::get('fastadmin.login_failure_retry') && (int)($row['loginfailure'] ?? 0) >= 10 && time() - (int)($row['updatetime'] ?? 0) < 86400) {
  3268. $this->error('登录失败次数过多,请24小时后再试');
  3269. }
  3270. $salt = (string)($row['salt'] ?? '');
  3271. $hashStored = (string)($row['password'] ?? '');
  3272. $hashInput = md5(md5($password) . $salt);
  3273. if ($hashStored === '' || $hashInput !== $hashStored) {
  3274. if ($id > 0) {
  3275. try {
  3276. Db::name('admin')->where('id', $id)->update([
  3277. 'loginfailure' => (int)($row['loginfailure'] ?? 0) + 1,
  3278. 'updatetime' => time(),
  3279. ]);
  3280. } catch (\Throwable $e) {
  3281. }
  3282. }
  3283. $this->error('账号或密码错误');
  3284. }
  3285. if ($id > 0) {
  3286. try {
  3287. Db::name('admin')->where('id', $id)->update([
  3288. 'loginfailure' => 0,
  3289. 'updatetime' => time(),
  3290. ]);
  3291. } catch (\Throwable $e) {
  3292. }
  3293. }
  3294. $payload = $this->mprocLoginPayloadFromAdmin($row, 'pwd');
  3295. if (!$this->mprocAdminHasAnyMobileAccess($payload)) {
  3296. $this->error('账号或密码错误');
  3297. }
  3298. $this->mprocFinishLogin($payload);
  3299. }
  3300. /**
  3301. * 是否允许当前登录用户修改该条 purchase_order_detail 的金额、交期
  3302. * 仅普通用户(customer)可改;管理员(admin)仅可查看
  3303. */
  3304. protected function mprocCanEditRow(array $user, array $row, ?array $po = null)
  3305. {
  3306. if (!empty($user['is_admin'])) {
  3307. return false;
  3308. }
  3309. $sn = trim((string)($row['status_name'] ?? ''));
  3310. if (in_array($sn, ['已完成', '未通过', '已废弃'], true)) {
  3311. return false;
  3312. }
  3313. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  3314. // 手工询价无招标截止/开标限制
  3315. if ($sid >= 0) {
  3316. if ($this->mprocIsQuoteDeadlineReachedForPo($po)) {
  3317. return false;
  3318. }
  3319. if ($this->mprocIsBidOpenVerifiedForPoOrRow($po, $row)) {
  3320. return false;
  3321. }
  3322. }
  3323. $uCo = trim((string)($user['company_name'] ?? ''));
  3324. if ($uCo === '') {
  3325. $uPhone = trim((string)($user['phone'] ?? ''));
  3326. if ($uPhone !== '') {
  3327. $uCo = $this->mprocResolveCompanyForLoginPhone($uPhone);
  3328. }
  3329. }
  3330. $rCo = trim((string)($row['company_name'] ?? ''));
  3331. if ($uCo !== '' && $rCo !== '' && strcmp($rCo, $uCo) === 0) {
  3332. return true;
  3333. }
  3334. $uPhone = trim((string)($user['phone'] ?? ''));
  3335. $rPhone = trim((string)($row['phone'] ?? ''));
  3336. return $uPhone !== '' && $rPhone !== '' && strcasecmp($rPhone, $uPhone) === 0;
  3337. }
  3338. /**
  3339. * 明细行对应最高限价(来自 purchase_order;无或无效则返回 null,不校验)
  3340. *
  3341. * @param array<string, mixed> $detailRow
  3342. */
  3343. protected function mprocResolveCeilingPriceForDetailRow(array $detailRow): ?float
  3344. {
  3345. $sid = (int)($detailRow['scydgy_id'] ?? $detailRow['SCYDGY_ID'] ?? 0);
  3346. $raw = trim((string)($detailRow['ceilingPrice'] ?? $detailRow['ceiling_price'] ?? ''));
  3347. if ($raw === '' && $this->mprocIsValidScydgyRowId($sid)) {
  3348. try {
  3349. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3350. } catch (\Throwable $e) {
  3351. $po = null;
  3352. }
  3353. if (is_array($po)) {
  3354. $pl = array_change_key_case($po, CASE_LOWER);
  3355. foreach (['ceilingprice', 'ceiling_price'] as $ck) {
  3356. if (array_key_exists($ck, $pl) && $pl[$ck] !== null && $pl[$ck] !== '') {
  3357. $raw = trim((string)$pl[$ck]);
  3358. break;
  3359. }
  3360. }
  3361. if ($raw === '') {
  3362. $raw = trim((string)($po['ceilingPrice'] ?? $po['ceiling_price'] ?? ''));
  3363. }
  3364. }
  3365. }
  3366. if ($raw === '' || !preg_match('/^-?\d+(\.\d{1,5})?$/', $raw)) {
  3367. return null;
  3368. }
  3369. return (float)$raw;
  3370. }
  3371. protected function mprocFormatCeilingPriceDisplay(float $n): string
  3372. {
  3373. $s = rtrim(rtrim(sprintf('%.5F', $n), '0'), '.');
  3374. return $s === '' ? '0' : $s;
  3375. }
  3376. /**
  3377. * 确保 purchase_order_detail.lead_days 字段存在
  3378. */
  3379. protected function mprocEnsureLeadDaysColumn(): void
  3380. {
  3381. static $done = false;
  3382. if ($done) {
  3383. return;
  3384. }
  3385. $done = true;
  3386. try {
  3387. $cols = Db::query("SHOW COLUMNS FROM `purchase_order_detail` LIKE 'lead_days'");
  3388. if (empty($cols)) {
  3389. Db::execute(
  3390. "ALTER TABLE `purchase_order_detail` ADD COLUMN `lead_days` int(10) unsigned DEFAULT NULL COMMENT '预估工期(天)' AFTER `delivery`"
  3391. );
  3392. }
  3393. } catch (\Throwable $e) {
  3394. // 忽略:保存时再按列是否存在处理
  3395. }
  3396. }
  3397. /**
  3398. * 交货日期相对今天的天数(可负数,调用方自行 clamp)
  3399. */
  3400. protected function mprocCalcLeadDaysFromDeliveryYmd(string $ymd): ?int
  3401. {
  3402. if (!preg_match('/^(\d{4}-\d{2}-\d{2})/', $ymd, $m)) {
  3403. return null;
  3404. }
  3405. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  3406. $t2 = strtotime($m[1] . ' 00:00:00');
  3407. if ($t1 === false || $t2 === false) {
  3408. return null;
  3409. }
  3410. return (int)round(($t2 - $t1) / 86400);
  3411. }
  3412. protected function mprocAddDaysToToday(int $days): string
  3413. {
  3414. $base = strtotime(date('Y-m-d') . ' 00:00:00');
  3415. if ($base === false) {
  3416. $base = time();
  3417. }
  3418. return date('Y-m-d', strtotime('+' . max(0, $days) . ' days', $base));
  3419. }
  3420. /**
  3421. * @param array<string, mixed> $row
  3422. */
  3423. protected function mprocEnrichLeadDaysDisplay(array &$row): void
  3424. {
  3425. $days = null;
  3426. $raw = $row['lead_days'] ?? null;
  3427. if ($raw !== null && $raw !== '' && is_numeric($raw)) {
  3428. $days = max(0, (int)$raw);
  3429. } else {
  3430. $dd = trim((string)($row['delivery_display'] ?? ''));
  3431. if ($dd === '') {
  3432. $dv = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  3433. if ($dv !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dv, $m)) {
  3434. $dd = $m[1];
  3435. }
  3436. }
  3437. if ($dd !== '') {
  3438. $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($dd);
  3439. if ($calc !== null) {
  3440. $days = max(0, $calc);
  3441. }
  3442. }
  3443. }
  3444. if ($days !== null) {
  3445. $row['lead_days'] = $days;
  3446. $row['lead_days_display'] = (string)$days;
  3447. $row['lead_days_missing'] = 0;
  3448. } else {
  3449. $row['lead_days'] = '';
  3450. $row['lead_days_display'] = '';
  3451. $row['lead_days_missing'] = 1;
  3452. }
  3453. }
  3454. /**
  3455. * 保存单条协助明细的金额、交期、工期(内部)
  3456. *
  3457. * @param array<string, mixed> $user
  3458. * @param int $id
  3459. * @param string $amountRaw
  3460. * @param string $deliveryRaw
  3461. * @param string|int|null $leadDaysRaw
  3462. * @return string 工序名(用于批量错误提示)
  3463. */
  3464. protected function mprocSaveDetailQuote(array $user, int $id, string $amountRaw, string $deliveryRaw, $leadDaysRaw = null): string
  3465. {
  3466. if ($id <= 0) {
  3467. throw new \InvalidArgumentException('参数错误');
  3468. }
  3469. $row = null;
  3470. try {
  3471. $row = Db::table('purchase_order_detail')->where('id', $id)->find();
  3472. if (!$row) {
  3473. $row = Db::table('purchase_order_detail')->where('ID', $id)->find();
  3474. }
  3475. } catch (\Throwable $e) {
  3476. $row = null;
  3477. }
  3478. if (!$row || !is_array($row)) {
  3479. throw new \InvalidArgumentException('记录不存在');
  3480. }
  3481. $gymc = trim((string)($row['CGYMC'] ?? $row['cgymc'] ?? ''));
  3482. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  3483. $po = null;
  3484. if ($this->mprocIsValidScydgyRowId($sid)) {
  3485. try {
  3486. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3487. } catch (\Throwable $e) {
  3488. $po = null;
  3489. }
  3490. if (is_array($po)) {
  3491. $this->mprocMergePurchaseOrderIntoDetail($row, $po);
  3492. if ($gymc === '') {
  3493. $gymc = trim((string)($row['CGYMC'] ?? ''));
  3494. }
  3495. }
  3496. }
  3497. $label = $gymc !== '' ? ('工序「' . $gymc . '」') : ('记录#' . $id);
  3498. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
  3499. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  3500. throw new \InvalidArgumentException($label . '已结束,不能再修改');
  3501. }
  3502. $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, $label, $row);
  3503. if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
  3504. if (!empty($user['is_admin'])) {
  3505. throw new \InvalidArgumentException('当前账号仅可查看,不能修改单价与交货日期');
  3506. }
  3507. // 截止后 / 已开标 canEdit=false,统一给明确文案
  3508. if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
  3509. throw new \InvalidArgumentException($label . '已开标验证,不可再提交');
  3510. }
  3511. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
  3512. throw new \InvalidArgumentException($label . '已超过招标截止时间,不可再提交');
  3513. }
  3514. throw new \InvalidArgumentException($label . '无权修改');
  3515. }
  3516. $this->mprocEnsureLeadDaysColumn();
  3517. $amountRaw = trim($amountRaw);
  3518. $deliveryRaw = trim($deliveryRaw);
  3519. $leadRaw = trim((string)($leadDaysRaw ?? ''));
  3520. $hasAmt = $amountRaw !== '';
  3521. $hasLead = $leadRaw !== '';
  3522. $hasDel = $deliveryRaw !== '';
  3523. $isManualRfq = ($sid < 0);
  3524. if ($isManualRfq) {
  3525. // 手工询价:只需填写单价
  3526. if (!$hasAmt) {
  3527. throw new \InvalidArgumentException($label . '请填写单价');
  3528. }
  3529. } else {
  3530. $filledCount = ($hasAmt ? 1 : 0) + ($hasLead ? 1 : 0) + ($hasDel ? 1 : 0);
  3531. if ($filledCount === 0) {
  3532. throw new \InvalidArgumentException($label . '请填写单价、工期、交期');
  3533. }
  3534. if ($filledCount < 3) {
  3535. if (!$hasAmt) {
  3536. throw new \InvalidArgumentException($label . '请填写单价');
  3537. }
  3538. if (!$hasLead) {
  3539. throw new \InvalidArgumentException($label . '请填写工期');
  3540. }
  3541. throw new \InvalidArgumentException($label . '请填写交期');
  3542. }
  3543. }
  3544. $leadDays = null;
  3545. if ($leadRaw !== '') {
  3546. if (!preg_match('/^\d+$/', $leadRaw)) {
  3547. throw new \InvalidArgumentException($label . '工期须为非负整数(天)');
  3548. }
  3549. $leadDays = (int)$leadRaw;
  3550. }
  3551. $data = [];
  3552. if ($amountRaw === '') {
  3553. $data['amount'] = null;
  3554. } else {
  3555. if (!preg_match('/^\d+(\.\d{1,5})?$/', $amountRaw)) {
  3556. throw new \InvalidArgumentException($label . '单价格式不正确,最多五位小数');
  3557. }
  3558. if ((float)$amountRaw <= 0) {
  3559. throw new \InvalidArgumentException($label . '单价必须大于0');
  3560. }
  3561. $ceilingLimit = $this->mprocResolveCeilingPriceForDetailRow($row);
  3562. if ($ceilingLimit !== null && (float)$amountRaw > $ceilingLimit) {
  3563. throw new \InvalidArgumentException(
  3564. $label . '单价不能超过最高限价 ' . $this->mprocFormatCeilingPriceDisplay($ceilingLimit)
  3565. );
  3566. }
  3567. $data['amount'] = $amountRaw;
  3568. }
  3569. if ($deliveryRaw === '') {
  3570. $data['delivery'] = null;
  3571. } elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryRaw)) {
  3572. $existingDel = isset($row['delivery']) ? trim((string)$row['delivery']) : '';
  3573. $timePart = date('H:i:s');
  3574. if ($existingDel !== '') {
  3575. $tsEx = strtotime(str_replace('T', ' ', $existingDel));
  3576. if ($tsEx !== false) {
  3577. $hms = date('H:i:s', $tsEx);
  3578. if ($hms !== '00:00:00') {
  3579. $timePart = $hms;
  3580. }
  3581. }
  3582. }
  3583. $data['delivery'] = $deliveryRaw . ' ' . $timePart;
  3584. } else {
  3585. $deliveryRaw = str_replace('T', ' ', $deliveryRaw);
  3586. $ts = strtotime($deliveryRaw);
  3587. if ($ts === false) {
  3588. throw new \InvalidArgumentException($label . '交期时间格式不正确');
  3589. }
  3590. $data['delivery'] = date('Y-m-d H:i:s', $ts);
  3591. }
  3592. // 工期 ↔ 交货日期互通:仅填工期则推交期;仅填交期则推工期
  3593. if (($data['delivery'] === null || $data['delivery'] === '') && $leadDays !== null) {
  3594. $data['delivery'] = $this->mprocAddDaysToToday($leadDays) . ' ' . date('H:i:s');
  3595. }
  3596. if ($leadDays === null && !empty($data['delivery'])) {
  3597. $ymd = substr((string)$data['delivery'], 0, 10);
  3598. $calc = $this->mprocCalcLeadDaysFromDeliveryYmd($ymd);
  3599. if ($calc !== null) {
  3600. $leadDays = max(0, $calc);
  3601. }
  3602. }
  3603. $data['lead_days'] = $leadDays;
  3604. $dcCol = $this->mprocResolveProcuremenColumn(['delivery_createtime', 'deliverycreatetime']);
  3605. if ($dcCol !== null) {
  3606. $shouldStampQuoteTime = false;
  3607. if (array_key_exists('delivery', $data) && $data['delivery'] !== null && $data['delivery'] !== '') {
  3608. $shouldStampQuoteTime = true;
  3609. }
  3610. // 手工询价只填单价:有单价也记报价时间
  3611. if ($isManualRfq && array_key_exists('amount', $data) && $data['amount'] !== null && $data['amount'] !== '') {
  3612. $shouldStampQuoteTime = true;
  3613. }
  3614. if ($shouldStampQuoteTime) {
  3615. $data[$dcCol] = date('Y-m-d H:i:s');
  3616. }
  3617. }
  3618. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3619. if ($upCol !== null) {
  3620. $data[$upCol] = date('Y-m-d H:i:s');
  3621. }
  3622. $statusNameCol = $this->mprocResolveProcuremenColumn(['status_name', 'status_txt', 'status_text']);
  3623. if ($statusNameCol !== null) {
  3624. $curSn = '';
  3625. foreach ($row as $k => $v) {
  3626. if (strcasecmp((string)$k, $statusNameCol) === 0) {
  3627. $curSn = trim((string)$v);
  3628. break;
  3629. }
  3630. }
  3631. if ($curSn !== '已完成') {
  3632. $effAm = array_key_exists('amount', $data) ? $data['amount'] : ($row['amount'] ?? null);
  3633. $effDv = array_key_exists('delivery', $data) ? trim((string)$data['delivery']) : trim((string)($row['delivery'] ?? ''));
  3634. $amountFilled = !($effAm === null || $effAm === '' || (is_string($effAm) && trim($effAm) === ''));
  3635. $deliveryFilled = ($effDv !== '' && !preg_match('/^0000-00-00/i', $effDv));
  3636. $data[$statusNameCol] = ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  3637. }
  3638. }
  3639. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  3640. $pkVal = (int)($row[$pkField] ?? $id);
  3641. try {
  3642. $aff = Db::table('purchase_order_detail')->where($pkField, $pkVal)->update($data);
  3643. } catch (\Throwable $e) {
  3644. $msg = $e->getMessage();
  3645. if (stripos($msg, 'Unknown column') !== false) {
  3646. $msg = '请确认数据表 purchase_order_detail 已包含 amount、delivery、lead_days 字段';
  3647. }
  3648. throw new \RuntimeException('保存失败:' . $msg);
  3649. }
  3650. if ($aff === false) {
  3651. throw new \RuntimeException($label . '保存失败');
  3652. }
  3653. return $gymc;
  3654. }
  3655. /**
  3656. * 保存同订单号+供应商下的整单备注(写入该组全部明细行)
  3657. *
  3658. * @param array<string, mixed> $user
  3659. * @param int[] $detailIds 本次保存涉及的明细 ID
  3660. * @param string $remarkRaw
  3661. */
  3662. protected function mprocSaveOrderGroupRemark(array $user, array $detailIds, string $remarkRaw): void
  3663. {
  3664. $remarkCol = $this->mprocResolveProcuremenColumn(['remark', 'memo', 'bz', 'beizhu']);
  3665. if ($remarkCol === null) {
  3666. return;
  3667. }
  3668. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  3669. if ($detailIds === []) {
  3670. return;
  3671. }
  3672. $anchorId = $detailIds[0];
  3673. $row = null;
  3674. try {
  3675. $row = Db::table('purchase_order_detail')->where('id', $anchorId)->find();
  3676. if (!$row) {
  3677. $row = Db::table('purchase_order_detail')->where('ID', $anchorId)->find();
  3678. }
  3679. } catch (\Throwable $e) {
  3680. $row = null;
  3681. }
  3682. if (!$row || !is_array($row)) {
  3683. throw new \InvalidArgumentException('记录不存在');
  3684. }
  3685. $sid = (int)($row['scydgy_id'] ?? $row['SCYDGY_ID'] ?? 0);
  3686. $po = null;
  3687. if ($this->mprocIsValidScydgyRowId($sid)) {
  3688. try {
  3689. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  3690. } catch (\Throwable $e) {
  3691. $po = null;
  3692. }
  3693. if (is_array($po)) {
  3694. $this->mprocMergePurchaseOrderIntoDetail($row, $po);
  3695. }
  3696. }
  3697. $effectiveSn = $this->mprocResolveEffectiveStatusName($row, is_array($po) ? $po : null);
  3698. if (in_array($effectiveSn, ['已完成', '未通过', '已废弃'], true)) {
  3699. throw new \InvalidArgumentException('订单已结束,不能再修改备注');
  3700. }
  3701. $this->mprocAssertQuoteStillEditable(is_array($po) ? $po : null, '', $row);
  3702. if (!$this->mprocCanEditRow($user, array_merge($row, ['status_name' => $effectiveSn]), is_array($po) ? $po : null)) {
  3703. if (!empty($user['is_admin'])) {
  3704. throw new \InvalidArgumentException('当前账号仅可查看,不能修改备注');
  3705. }
  3706. if ($this->mprocIsBidOpenVerifiedForPoOrRow(is_array($po) ? $po : null, $row)) {
  3707. throw new \InvalidArgumentException('已开标验证,不可再提交');
  3708. }
  3709. if ($this->mprocIsQuoteDeadlineReachedForPo(is_array($po) ? $po : null)) {
  3710. throw new \InvalidArgumentException('已超过招标截止时间,不可再提交');
  3711. }
  3712. throw new \InvalidArgumentException('无权修改备注');
  3713. }
  3714. $orderMbz = '';
  3715. if (is_array($po)) {
  3716. $orderMbz = trim((string)($po['MBZ'] ?? $po['mbz'] ?? ''));
  3717. }
  3718. $remarkRaw = $this->mprocSupplierOwnRemark($remarkRaw, $orderMbz);
  3719. $ccydhCol = $this->mprocResolveProcuremenColumn(['ccydh']);
  3720. $companyCol = $this->mprocResolveProcuremenColumn(['company_name']);
  3721. if ($ccydhCol === null || $companyCol === null) {
  3722. return;
  3723. }
  3724. $ccydh = '';
  3725. $company = '';
  3726. foreach ($row as $k => $v) {
  3727. if (strcasecmp((string)$k, $ccydhCol) === 0) {
  3728. $ccydh = trim((string)$v);
  3729. } elseif (strcasecmp((string)$k, $companyCol) === 0) {
  3730. $company = trim((string)$v);
  3731. }
  3732. }
  3733. if ($ccydh === '' || $company === '') {
  3734. $pkField = isset($row['id']) ? 'id' : (isset($row['ID']) ? 'ID' : 'id');
  3735. $data = [$remarkCol => ($remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8'))];
  3736. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3737. if ($upCol !== null) {
  3738. $data[$upCol] = date('Y-m-d H:i:s');
  3739. }
  3740. Db::table('purchase_order_detail')->where($pkField, (int)($row[$pkField] ?? $anchorId))->update($data);
  3741. return;
  3742. }
  3743. $remarkVal = $remarkRaw === '' ? null : mb_substr($remarkRaw, 0, 500, 'UTF-8');
  3744. $data = [$remarkCol => $remarkVal];
  3745. $upCol = $this->mprocResolveProcuremenColumn(['updatetime']);
  3746. if ($upCol !== null) {
  3747. $data[$upCol] = date('Y-m-d H:i:s');
  3748. }
  3749. $query = Db::table('purchase_order_detail')
  3750. ->where($ccydhCol, $ccydh)
  3751. ->where($companyCol, $company);
  3752. $userWhere = $this->mprocListWhereForLoginUser($user);
  3753. if ($userWhere !== []) {
  3754. $query->where($userWhere);
  3755. }
  3756. try {
  3757. $query->update($data);
  3758. } catch (\Throwable $e) {
  3759. throw new \RuntimeException('备注保存失败:' . $e->getMessage());
  3760. }
  3761. }
  3762. /**
  3763. * 保存协助明细金额、交期、工期
  3764. * 单条:POST id、amount、delivery、lead_days
  3765. * 批量:POST items=[{id,amount,delivery,lead_days},...] JSON
  3766. */
  3767. public function mprocSave()
  3768. {
  3769. if (!$this->request->isPost()) {
  3770. $this->error('请使用 POST');
  3771. }
  3772. $user = $this->mprocGetUser();
  3773. if (!$user) {
  3774. $this->error('请先登录', url('index/index/login'));
  3775. }
  3776. // Frontend 默认 filter 含 htmlspecialchars,会把 JSON 的双引号变成 &quot; 导致解析失败
  3777. $itemsRaw = $this->request->post('items', '', null);
  3778. if ($itemsRaw === '' || $itemsRaw === null) {
  3779. $itemsRaw = isset($_POST['items']) ? $_POST['items'] : '';
  3780. }
  3781. if (is_string($itemsRaw) && $itemsRaw !== '' && strpos($itemsRaw, '&quot;') !== false) {
  3782. $itemsRaw = htmlspecialchars_decode($itemsRaw, ENT_QUOTES);
  3783. }
  3784. $items = [];
  3785. if (is_string($itemsRaw) && trim($itemsRaw) !== '') {
  3786. $decoded = json_decode($itemsRaw, true);
  3787. if (!is_array($decoded)) {
  3788. $decoded = json_decode(htmlspecialchars_decode($itemsRaw, ENT_QUOTES), true);
  3789. }
  3790. if (is_array($decoded)) {
  3791. $items = $decoded;
  3792. }
  3793. } elseif (is_array($itemsRaw)) {
  3794. $items = $itemsRaw;
  3795. }
  3796. if ($items === []) {
  3797. $id = (int)$this->request->post('id', 0, null);
  3798. if ($id <= 0) {
  3799. $this->error('保存失败,请关闭弹窗后重试');
  3800. }
  3801. $items = [[
  3802. 'id' => $id,
  3803. 'amount' => (string)$this->request->post('amount', '', null),
  3804. 'delivery' => (string)$this->request->post('delivery', '', null),
  3805. 'lead_days' => (string)$this->request->post('lead_days', '', null),
  3806. ]];
  3807. }
  3808. $saved = 0;
  3809. $savedIds = [];
  3810. $remarkRaw = $this->request->post('remark', '', null);
  3811. if ($remarkRaw === '' || $remarkRaw === null) {
  3812. $remarkRaw = isset($_POST['remark']) ? $_POST['remark'] : '';
  3813. }
  3814. $remarkRaw = trim(htmlspecialchars_decode((string)$remarkRaw, ENT_QUOTES));
  3815. Db::startTrans();
  3816. try {
  3817. foreach ($items as $it) {
  3818. if (!is_array($it)) {
  3819. continue;
  3820. }
  3821. $id = (int)($it['id'] ?? $it['eid'] ?? 0);
  3822. if ($id <= 0) {
  3823. continue;
  3824. }
  3825. $delivery = (string)($it['delivery'] ?? '');
  3826. // 兼容部分手机浏览器把日期显示/提交成 2026/07/24
  3827. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})$/', trim($delivery), $dm)) {
  3828. $delivery = sprintf('%04d-%02d-%02d', (int)$dm[1], (int)$dm[2], (int)$dm[3]);
  3829. }
  3830. $leadDays = (string)($it['lead_days'] ?? $it['leadDays'] ?? '');
  3831. $amount = trim((string)($it['amount'] ?? ''));
  3832. $leadDays = trim($leadDays);
  3833. $delivery = trim($delivery);
  3834. // 全空工序跳过:多工序时允许只保存已填全的
  3835. if ($amount === '' && $leadDays === '' && $delivery === '') {
  3836. continue;
  3837. }
  3838. $this->mprocSaveDetailQuote(
  3839. $user,
  3840. $id,
  3841. $amount,
  3842. $delivery,
  3843. $leadDays
  3844. );
  3845. $saved++;
  3846. $savedIds[] = $id;
  3847. }
  3848. if ($saved < 1) {
  3849. throw new \InvalidArgumentException('请填写单价、工期、交期');
  3850. }
  3851. $this->mprocSaveOrderGroupRemark($user, $savedIds, $remarkRaw);
  3852. Db::commit();
  3853. } catch (\InvalidArgumentException $e) {
  3854. Db::rollback();
  3855. $this->error($e->getMessage());
  3856. } catch (\Throwable $e) {
  3857. Db::rollback();
  3858. $this->error($e->getMessage());
  3859. }
  3860. $this->success($saved > 1 ? ('已保存 ' . $saved . ' 道工序') : '已保存');
  3861. }
  3862. /**
  3863. * 修改密码(POST:old_password、new_password、renew_password)
  3864. * 支持供应商 customer 与手机端管理员 admin
  3865. */
  3866. public function mprocChangePwd()
  3867. {
  3868. if (!$this->request->isPost()) {
  3869. $this->error('请使用 POST');
  3870. }
  3871. $user = $this->mprocGetUser();
  3872. if (!$user) {
  3873. $this->error('请先登录', url('index/index/login'));
  3874. }
  3875. $oldPwd = (string)$this->request->post('old_password', '');
  3876. $newPwd = (string)$this->request->post('new_password', '');
  3877. $renewPwd = (string)$this->request->post('renew_password', '');
  3878. if ($oldPwd === '' || $newPwd === '' || $renewPwd === '') {
  3879. $this->error('请填写完整');
  3880. }
  3881. $pwdErr = $this->mprocValidateStrongPassword($newPwd);
  3882. if ($pwdErr !== '') {
  3883. $this->error($pwdErr);
  3884. }
  3885. if ($newPwd !== $renewPwd) {
  3886. $this->error('两次输入的新密码不一致');
  3887. }
  3888. if ($oldPwd === $newPwd) {
  3889. $this->error('新密码不能与旧密码相同');
  3890. }
  3891. if (!empty($user['is_admin'])) {
  3892. $adminId = (int)($user['admin_id'] ?? 0);
  3893. if ($adminId <= 0) {
  3894. $this->error('账号不存在或已禁用');
  3895. }
  3896. $row = null;
  3897. try {
  3898. $row = Db::name('admin')
  3899. ->field('id,username,password,salt,status')
  3900. ->where('id', $adminId)
  3901. ->find();
  3902. } catch (\Throwable $e) {
  3903. $row = null;
  3904. }
  3905. if (!$row || !is_array($row) || (($row['status'] ?? '') === 'hidden')) {
  3906. $this->error('账号不存在或已禁用');
  3907. }
  3908. $salt = (string)($row['salt'] ?? '');
  3909. $hashStored = (string)($row['password'] ?? '');
  3910. $hashOld = md5(md5($oldPwd) . $salt);
  3911. if ($hashStored === '' || $hashOld !== $hashStored) {
  3912. $this->error('原密码不正确');
  3913. }
  3914. $hashNew = md5(md5($newPwd) . $salt);
  3915. try {
  3916. Db::name('admin')->where('id', $adminId)->update([
  3917. 'password' => $hashNew,
  3918. 'updatetime' => time(),
  3919. ]);
  3920. } catch (\Throwable $e) {
  3921. $this->error('修改失败:' . $e->getMessage());
  3922. }
  3923. } else {
  3924. $user = $this->mprocSyncSessionCustomerUser($user);
  3925. $cu = $this->mprocResolveCustomerUserForSession($user);
  3926. if (!$cu) {
  3927. $this->error('账号不存在或已禁用');
  3928. }
  3929. $cuId = (int)($cu['id'] ?? 0);
  3930. if (!$this->mprocVerifyCustomerUserPassword($cu, $oldPwd)) {
  3931. $this->error('原密码不正确');
  3932. }
  3933. $data = [
  3934. 'password' => $this->mprocHashCustomerUserPassword($newPwd),
  3935. 'updatetime' => date('Y-m-d H:i:s'),
  3936. ];
  3937. try {
  3938. Db::table('customer')->where('id', $cuId)->update($data);
  3939. } catch (\Throwable $e) {
  3940. $this->error('修改失败:' . $e->getMessage());
  3941. }
  3942. }
  3943. // 改密后强制重新登录
  3944. $token = Session::get('mproc_token');
  3945. if ($token === null || $token === '') {
  3946. $token = Cookie::get('mproc_token');
  3947. }
  3948. if ($token === null || $token === '') {
  3949. $token = Cookie::get('mproc_remember');
  3950. }
  3951. $this->mprocClearLogin((string)$token);
  3952. $this->success('密码已修改,请重新登录', url('index/index/login'));
  3953. }
  3954. /**
  3955. * 退出登录
  3956. */
  3957. public function logout()
  3958. {
  3959. $token = Session::get('mproc_token');
  3960. if ($token === null || $token === '') {
  3961. $token = Cookie::get('mproc_token');
  3962. }
  3963. if ($token === null || $token === '') {
  3964. $token = Cookie::get('mproc_remember');
  3965. }
  3966. // 无论有无 token 都清 Cookie/Session,避免「记住登录」把用户又带回来
  3967. $this->mprocClearLogin((string)$token);
  3968. $this->redirect(url('index/index/login'));
  3969. }
  3970. /**
  3971. * 短信宝(与后台协助审核一致,便于复用账号)
  3972. *
  3973. * @throws \Exception
  3974. */
  3975. protected function mprocSmsSend($phone, $content)
  3976. {
  3977. $statusStr = [
  3978. '0' => '短信发送成功',
  3979. '-1' => '参数不全',
  3980. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  3981. '30' => '密码错误',
  3982. '40' => '账号不存在',
  3983. '41' => '余额不足',
  3984. '42' => '帐户已过期',
  3985. '43' => 'IP地址限制',
  3986. '50' => '内容含有敏感词',
  3987. ];
  3988. $smsapi = 'http://api.smsbao.com/';
  3989. $user = trim((string)Config::get('mproc.smsbao_user'));
  3990. if ($user === '') {
  3991. $user = 'zhuwei123';
  3992. }
  3993. $passPlain = Config::get('mproc.smsbao_pass');
  3994. $pass = ($passPlain !== null && $passPlain !== '')
  3995. ? md5((string)$passPlain)
  3996. : md5('1d1e605c101e4c1f8a156c6d7b19f126');
  3997. $phone = trim((string)$phone);
  3998. $content = trim((string)$content);
  3999. if ($phone === '' || $content === '') {
  4000. throw new \Exception('短信发送失败:参数不全');
  4001. }
  4002. $sendurl = $smsapi . 'sms?u=' . rawurlencode($user) . '&p=' . $pass . '&m=' . rawurlencode($phone) . '&c=' . rawurlencode($content);
  4003. $result = @file_get_contents($sendurl);
  4004. if ($result === false) {
  4005. Log::record('smsbao 请求失败 phone=' . $phone . ' content=' . $content, 'error');
  4006. throw new \Exception('短信发送失败:网络异常');
  4007. }
  4008. $result = trim((string)$result);
  4009. if ($result !== '0') {
  4010. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  4011. Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg . ' content=' . $content, 'error');
  4012. throw new \Exception('短信发送失败:' . $msg);
  4013. }
  4014. Log::record('smsbao 发送成功 phone=' . $phone . ' content=' . $content, 'info');
  4015. }
  4016. /**
  4017. * 质量评分页(质检中心:合格/投诉/中断)
  4018. */
  4019. public function inboundscore()
  4020. {
  4021. $user = $this->mprocGetUser();
  4022. if (!$user) {
  4023. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  4024. $safe = $this->mprocSanitizeRedirectUrl($uri);
  4025. if ($safe !== '') {
  4026. Session::set('mproc_intended_url', $safe);
  4027. }
  4028. $this->redirect($this->mprocBuildLoginUrl($safe));
  4029. return;
  4030. }
  4031. if (empty($user['is_admin']) || !$this->mprocAdminHasMobileRole($user, 'quality')) {
  4032. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  4033. if ($jump === '') {
  4034. $this->mprocDropCurrentLogin();
  4035. $this->redirect(url('index/index/login'));
  4036. return;
  4037. }
  4038. $this->redirect($jump);
  4039. return;
  4040. }
  4041. $this->mprocEnsureInboundScoreTable();
  4042. $q = trim((string)$this->request->get('q', ''));
  4043. $profile = $this->mprocProfileForUser($user);
  4044. $this->view->assign('mprocSearchQ', $q);
  4045. $this->view->assign('mprocProfile', $profile);
  4046. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  4047. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  4048. $this->view->assign('mprocScoreScope', 'quality');
  4049. $this->view->assign('rows', $this->mprocLoadInboundScoreRows('pending', $q, (int)($user['admin_id'] ?? 0), 'quality'));
  4050. return $this->view->fetch();
  4051. }
  4052. /**
  4053. * 交货情况页(生产部:准时/滞后)
  4054. */
  4055. public function deliveryscore()
  4056. {
  4057. $user = $this->mprocGetUser();
  4058. if (!$user) {
  4059. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  4060. $safe = $this->mprocSanitizeRedirectUrl($uri);
  4061. if ($safe !== '') {
  4062. Session::set('mproc_intended_url', $safe);
  4063. }
  4064. $this->redirect($this->mprocBuildLoginUrl($safe));
  4065. return;
  4066. }
  4067. if (empty($user['is_admin']) || !$this->mprocAdminHasMobileRole($user, 'delivery')) {
  4068. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  4069. if ($jump === '') {
  4070. $this->mprocDropCurrentLogin();
  4071. $this->redirect(url('index/index/login'));
  4072. return;
  4073. }
  4074. $this->redirect($jump);
  4075. return;
  4076. }
  4077. $this->mprocEnsureInboundScoreTable();
  4078. $ccydh = trim((string)$this->request->get('ccydh', ''));
  4079. $q = trim((string)$this->request->get('q', ''));
  4080. if ($q === '' && $ccydh !== '') {
  4081. $q = $ccydh;
  4082. }
  4083. if ($ccydh === '' && $q !== '') {
  4084. $ccydh = $q;
  4085. }
  4086. $adminId = (int)($user['admin_id'] ?? 0);
  4087. $scoreTab = trim((string)$this->request->get('tab', ''));
  4088. if (!in_array($scoreTab, ['pending', 'scored'], true)) {
  4089. $scoreTab = 'pending';
  4090. }
  4091. $rows = $this->mprocLoadInboundScoreRows($scoreTab, $q, $adminId, 'delivery');
  4092. if ($ccydh !== '' && $rows === [] && $scoreTab === 'pending') {
  4093. $scored = $this->mprocLoadInboundScoreRows('scored', $q, $adminId, 'delivery');
  4094. if ($scored !== []) {
  4095. $scoreTab = 'scored';
  4096. $rows = $scored;
  4097. }
  4098. }
  4099. $profile = $this->mprocProfileForUser($user);
  4100. $this->view->assign('mprocSearchQ', $q);
  4101. $this->view->assign('mprocFocusCcydh', $ccydh);
  4102. $this->view->assign('mprocScoreTab', $scoreTab);
  4103. $this->view->assign('mprocProfile', $profile);
  4104. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  4105. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  4106. $this->view->assign('mprocScoreScope', 'delivery');
  4107. $this->view->assign('rows', $rows);
  4108. return $this->view->fetch();
  4109. }
  4110. /**
  4111. * 供应商送货单(中标后出示二维码,生产部扫码进入交货评估)
  4112. */
  4113. public function deliverynote()
  4114. {
  4115. $user = $this->mprocGetUser();
  4116. if (!$user) {
  4117. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  4118. $safe = $this->mprocSanitizeRedirectUrl($uri);
  4119. if ($safe !== '') {
  4120. Session::set('mproc_intended_url', $safe);
  4121. }
  4122. $this->redirect($this->mprocBuildLoginUrl($safe));
  4123. return;
  4124. }
  4125. if (!empty($user['is_admin'])) {
  4126. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  4127. if ($jump === '') {
  4128. $this->mprocDropCurrentLogin();
  4129. $this->redirect(url('index/index/login'));
  4130. return;
  4131. }
  4132. $this->redirect($jump);
  4133. return;
  4134. }
  4135. $user = $this->mprocSyncSessionCustomerUser($user);
  4136. $ccydh = trim((string)$this->request->param('ccydh', ''));
  4137. $checkOnly = (int)$this->request->param('check', 0) === 1;
  4138. $note = $this->mprocLoadWonDeliveryNote($user, $ccydh);
  4139. if ($note === null) {
  4140. // 列表点「送货码」先 Ajax check:当前页 Toast;直达链接仍走轻提示页
  4141. $this->error('未找到该中标订单的送货单', $checkOnly ? null : url('index/index/index', ['tab' => 'done']));
  4142. return;
  4143. }
  4144. if ($checkOnly) {
  4145. $this->success('ok');
  4146. return;
  4147. }
  4148. $this->view->assign('note', $note);
  4149. return $this->view->fetch();
  4150. }
  4151. /**
  4152. * 当前供应商的中标送货单数据;无权或不存在返回 null
  4153. *
  4154. * @param array<string, mixed> $user
  4155. * @return array<string, mixed>|null
  4156. */
  4157. protected function mprocLoadWonDeliveryNote(array $user, string $ccydh): ?array
  4158. {
  4159. $ccydh = trim($ccydh);
  4160. if ($ccydh === '') {
  4161. return null;
  4162. }
  4163. $company = trim((string)($user['company_name'] ?? ''));
  4164. $phone = trim((string)($user['phone'] ?? ''));
  4165. if ($company === '' && $phone !== '') {
  4166. $company = $this->mprocResolveCompanyForLoginPhone($phone);
  4167. }
  4168. try {
  4169. $poRows = Db::table('purchase_order')
  4170. ->where('CCYDH', $ccydh)
  4171. ->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%\')')
  4172. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,CDW,CDF,MBZ,cGzzxMc,CCLBMMC,CDXMC,This_quantity,NGZL,pick_company_name,pick_time,wflow_status,status')
  4173. ->order('id', 'asc')
  4174. ->select();
  4175. } catch (\Throwable $e) {
  4176. $poRows = [];
  4177. }
  4178. if (!is_array($poRows) || $poRows === []) {
  4179. return null;
  4180. }
  4181. $won = false;
  4182. $gymcList = [];
  4183. $qtyList = [];
  4184. foreach ($poRows as $po) {
  4185. if (!is_array($po)) {
  4186. continue;
  4187. }
  4188. $pick = trim((string)($po['pick_company_name'] ?? ''));
  4189. if ($pick !== '' && $company !== '' && $pick === $company) {
  4190. $won = true;
  4191. }
  4192. $gx = trim((string)($po['CGYMC'] ?? ''));
  4193. if ($gx !== '' && !in_array($gx, $gymcList, true)) {
  4194. $gymcList[] = $gx;
  4195. }
  4196. $qDisp = $this->mprocResolveDisplayThisQuantity($po);
  4197. if ($qDisp !== '') {
  4198. $qtyList[] = $qDisp;
  4199. }
  4200. }
  4201. $qtyList = array_values(array_unique($qtyList));
  4202. $orderQty = $qtyList !== [] ? implode('、', $qtyList) : '';
  4203. // 本次送货数量暂无独立数据,留空由页面原样展示
  4204. $deliveryQty = '';
  4205. $detailPhone = '';
  4206. try {
  4207. $dq = Db::table('purchase_order_detail')->where('CCYDH', $ccydh);
  4208. $userWhere = $this->mprocListWhereForLoginUser($user);
  4209. if ($userWhere !== []) {
  4210. $dq->where($userWhere);
  4211. }
  4212. $details = $dq->field('id,scydgy_id,company_name,phone,status,status_name,remark')->select();
  4213. } catch (\Throwable $e) {
  4214. $details = [];
  4215. }
  4216. if (is_array($details)) {
  4217. foreach ($details as $d) {
  4218. if (!is_array($d)) {
  4219. continue;
  4220. }
  4221. if ($detailPhone === '') {
  4222. $detailPhone = trim((string)($d['phone'] ?? ''));
  4223. }
  4224. $dCn = trim((string)($d['company_name'] ?? ''));
  4225. if ($dCn !== '' && $company !== '' && $dCn === $company) {
  4226. if (ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  4227. $won = true;
  4228. }
  4229. }
  4230. }
  4231. }
  4232. if (!$won) {
  4233. return null;
  4234. }
  4235. $pickFirst = static function (array $rows, array $keys): string {
  4236. foreach ($rows as $row) {
  4237. if (!is_array($row)) {
  4238. continue;
  4239. }
  4240. foreach ($keys as $k) {
  4241. $v = trim((string)($row[$k] ?? ''));
  4242. if ($v !== '') {
  4243. return $v;
  4244. }
  4245. }
  4246. }
  4247. return '';
  4248. };
  4249. $profile = $this->mprocProfileForUser($user);
  4250. $supplierName = trim((string)($profile['company_name'] ?? ''));
  4251. if ($supplierName === '') {
  4252. $supplierName = $company;
  4253. }
  4254. if ($supplierName === '') {
  4255. $supplierName = $pickFirst($poRows, ['pick_company_name']);
  4256. }
  4257. $mobile = trim((string)($profile['phone'] ?? ''));
  4258. if ($mobile === '') {
  4259. $mobile = $phone !== '' ? $phone : $detailPhone;
  4260. }
  4261. $contact = trim((string)($profile['contact_name'] ?? ''));
  4262. $customerName = trim((string)Config::get('mproc.delivery_customer_name'));
  4263. if ($customerName === '') {
  4264. $customerName = '浙江新华数码印务有限公司';
  4265. }
  4266. $address = trim((string)Config::get('mproc.delivery_address'));
  4267. if ($address === '') {
  4268. $address = '杭州市经济技术开发区文海北路369号';
  4269. }
  4270. $base = $this->mprocDeliveryScanBaseUrl();
  4271. $scanUrl = $base . $this->mprocDeliveryScanPath() . '?' . http_build_query(
  4272. ['ccydh' => $ccydh, 'q' => $ccydh],
  4273. '',
  4274. '&',
  4275. PHP_QUERY_RFC3986
  4276. );
  4277. return [
  4278. 'generated_at' => $this->mprocDeliveryNoteGeneratedAt($ccydh, $supplierName),
  4279. 'ccydh' => $ccydh,
  4280. 'cyjmc' => $pickFirst($poRows, ['CYJMC']),
  4281. 'cgymc' => $gymcList !== [] ? implode('、', $gymcList) : '',
  4282. 'cdw' => $pickFirst($poRows, ['CDW']),
  4283. 'cdf' => $pickFirst($poRows, ['CDF']),
  4284. 'remark' => $pickFirst($poRows, ['MBZ']),
  4285. 'order_qty' => $orderQty,
  4286. 'delivery_qty' => $deliveryQty,
  4287. 'customer_name' => $customerName,
  4288. 'address' => $address,
  4289. 'supplier_name' => $supplierName,
  4290. 'contact_name' => $contact,
  4291. 'mobile' => $mobile,
  4292. 'scan_url' => $scanUrl,
  4293. 'qr_data_uri' => $this->mprocDeliveryQrDataUri($scanUrl),
  4294. ];
  4295. }
  4296. /**
  4297. * 送货单首次生成时间:点过送货码后保持不变
  4298. */
  4299. protected function mprocDeliveryNoteGeneratedAt(string $ccydh, string $company): string
  4300. {
  4301. $now = date('Y-m-d H:i:s');
  4302. $this->mprocEnsureDeliveryNoteTable();
  4303. try {
  4304. $q = Db::table('purchase_order_delivery_note')->where('ccydh', $ccydh);
  4305. if ($company !== '') {
  4306. $q->where('company_name', $company);
  4307. }
  4308. $row = $q->order('id', 'asc')->find();
  4309. if (is_array($row) && trim((string)($row['generated_at'] ?? '')) !== '') {
  4310. $t = strtotime((string)$row['generated_at']);
  4311. return $t ? date('Y-m-d H:i', $t) : date('Y-m-d H:i');
  4312. }
  4313. Db::table('purchase_order_delivery_note')->insert([
  4314. 'ccydh' => $ccydh,
  4315. 'company_name' => $company,
  4316. 'generated_at' => $now,
  4317. 'createtime' => $now,
  4318. 'updatetime' => $now,
  4319. ]);
  4320. return date('Y-m-d H:i');
  4321. } catch (\Throwable $e) {
  4322. return date('Y-m-d H:i');
  4323. }
  4324. }
  4325. protected function mprocEnsureDeliveryNoteTable(): void
  4326. {
  4327. static $ok = false;
  4328. if ($ok) {
  4329. return;
  4330. }
  4331. try {
  4332. Db::query('SELECT 1 FROM `purchase_order_delivery_note` LIMIT 1');
  4333. $ok = true;
  4334. } catch (\Throwable $e) {
  4335. try {
  4336. Db::execute("CREATE TABLE IF NOT EXISTS `purchase_order_delivery_note` (
  4337. `id` int unsigned NOT NULL AUTO_INCREMENT,
  4338. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  4339. `company_name` varchar(255) NOT NULL DEFAULT '' COMMENT '供应商',
  4340. `generated_at` datetime NOT NULL COMMENT '首次生成时间',
  4341. `createtime` datetime DEFAULT NULL,
  4342. `updatetime` datetime DEFAULT NULL,
  4343. PRIMARY KEY (`id`),
  4344. UNIQUE KEY `uk_ccydh_company` (`ccydh`,`company_name`(64))
  4345. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='送货单首次生成记录'");
  4346. $ok = true;
  4347. } catch (\Throwable $e2) {
  4348. }
  4349. }
  4350. }
  4351. /**
  4352. * QR Code 容错 H(约 30%),输出 data URI,避免手机端 canvas 空白
  4353. */
  4354. protected function mprocDeliveryQrDataUri(string $text): string
  4355. {
  4356. $text = trim($text);
  4357. if ($text === '' || !function_exists('imagepng')) {
  4358. return '';
  4359. }
  4360. $lib = ROOT_PATH . 'extend' . DIRECTORY_SEPARATOR . 'phpqrcode' . DIRECTORY_SEPARATOR . 'phpqrcode.php';
  4361. if (!is_file($lib)) {
  4362. return '';
  4363. }
  4364. if (!class_exists('QRcode', false)) {
  4365. require_once $lib;
  4366. }
  4367. if (!class_exists('QRcode')) {
  4368. return '';
  4369. }
  4370. $tmp = tempnam(sys_get_temp_dir(), 'dnqr');
  4371. if ($tmp === false) {
  4372. return '';
  4373. }
  4374. $bin = '';
  4375. try {
  4376. \QRcode::png($text, $tmp, 'H', 6, 2);
  4377. $bin = is_file($tmp) ? (string)file_get_contents($tmp) : '';
  4378. } catch (\Throwable $e) {
  4379. $bin = '';
  4380. }
  4381. if (is_file($tmp)) {
  4382. @unlink($tmp);
  4383. }
  4384. if ($bin === '' || strncmp($bin, "\x89PNG", 4) !== 0) {
  4385. return '';
  4386. }
  4387. return 'data:image/png;base64,' . base64_encode($bin);
  4388. }
  4389. /**
  4390. * 送货单二维码根地址:与邮件链接共用 mproc.mobile_base_url;未配则用当前访问根地址。
  4391. */
  4392. protected function mprocDeliveryScanBaseUrl(): string
  4393. {
  4394. $cfg = rtrim(trim((string)Config::get('mproc.mobile_base_url')), '/');
  4395. if ($cfg !== '' && preg_match('#^https?://#i', $cfg)) {
  4396. return $cfg;
  4397. }
  4398. return rtrim((string)$this->request->root(true), '/');
  4399. }
  4400. /**
  4401. * 送货单扫码路径。局域网 IP 通常没有伪静态,必须带 /index.php
  4402. */
  4403. protected function mprocDeliveryScanPath(): string
  4404. {
  4405. $indexPath = trim((string)Config::get('mproc.mobile_index_path'));
  4406. if ($indexPath === '') {
  4407. $indexPath = '/index.php/index/index/index';
  4408. } else {
  4409. $indexPath = '/' . ltrim($indexPath, '/');
  4410. }
  4411. $path = preg_replace('#/index$#', '/deliveryscore', rtrim($indexPath, '/'));
  4412. if (!is_string($path) || $path === '' || substr($path, -6) === '/index') {
  4413. return '/index.php/index/index/deliveryscore';
  4414. }
  4415. return $path;
  4416. }
  4417. protected function mprocIsLanIpv4(string $ip): bool
  4418. {
  4419. if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  4420. return false;
  4421. }
  4422. if ($ip === '127.0.0.1' || strpos($ip, '127.') === 0 || strpos($ip, '169.254.') === 0) {
  4423. return false;
  4424. }
  4425. return (bool)preg_match('/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|20\.0\.)/', $ip);
  4426. }
  4427. protected function mprocDetectLanIpv4(): string
  4428. {
  4429. if (function_exists('socket_create')) {
  4430. $sock = @socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
  4431. if ($sock) {
  4432. @socket_connect($sock, '8.8.8.8', 53);
  4433. $addr = '';
  4434. @socket_getsockname($sock, $addr);
  4435. @socket_close($sock);
  4436. if (is_string($addr) && $this->mprocIsLanIpv4($addr)) {
  4437. return $addr;
  4438. }
  4439. }
  4440. }
  4441. if (strncasecmp(PHP_OS, 'WIN', 3) === 0) {
  4442. $out = @shell_exec('ipconfig');
  4443. if (is_string($out) && preg_match_all('/IPv4[^0-9]+(\d+\.\d+\.\d+\.\d+)/', $out, $m)) {
  4444. foreach ($m[1] as $ip) {
  4445. if ($this->mprocIsLanIpv4((string)$ip)) {
  4446. return (string)$ip;
  4447. }
  4448. }
  4449. }
  4450. }
  4451. $guess = gethostbyname(gethostname());
  4452. if (is_string($guess) && $this->mprocIsLanIpv4($guess)) {
  4453. return $guess;
  4454. }
  4455. return '';
  4456. }
  4457. /**
  4458. * 质量评分列表 JSON(质检;tab=pending|scored)
  4459. */
  4460. public function inboundscorelist()
  4461. {
  4462. $user = $this->mprocRequireQualityUser();
  4463. $this->mprocEnsureInboundScoreTable();
  4464. $q = trim((string)$this->request->request('q', ''));
  4465. $tab = trim((string)$this->request->request('tab', 'pending'));
  4466. if (!in_array($tab, ['pending', 'scored', 'pass', 'fail'], true)) {
  4467. $tab = 'pending';
  4468. }
  4469. if ($tab === 'pass' || $tab === 'fail') {
  4470. $tab = 'scored';
  4471. }
  4472. $adminId = (int)($user['admin_id'] ?? 0);
  4473. $rows = $this->mprocLoadInboundScoreRows($tab, $q, $adminId, 'quality');
  4474. $this->success('ok', '', [
  4475. 'tab' => $tab,
  4476. 'q' => $q,
  4477. 'scope' => 'quality',
  4478. 'rows' => $rows,
  4479. 'count' => count($rows),
  4480. ]);
  4481. }
  4482. /**
  4483. * 交货情况列表 JSON(生产部;tab=pending|scored)
  4484. */
  4485. public function deliveryscorelist()
  4486. {
  4487. $user = $this->mprocRequireDeliveryUser();
  4488. $this->mprocEnsureInboundScoreTable();
  4489. $q = trim((string)$this->request->request('q', ''));
  4490. $tab = trim((string)$this->request->request('tab', 'pending'));
  4491. if (!in_array($tab, ['pending', 'scored'], true)) {
  4492. $tab = 'pending';
  4493. }
  4494. $adminId = (int)($user['admin_id'] ?? 0);
  4495. $rows = $this->mprocLoadInboundScoreRows($tab, $q, $adminId, 'delivery');
  4496. $this->success('ok', '', [
  4497. 'tab' => $tab,
  4498. 'q' => $q,
  4499. 'scope' => 'delivery',
  4500. 'rows' => $rows,
  4501. 'count' => count($rows),
  4502. ]);
  4503. }
  4504. /**
  4505. * 交货情况 — 历史库位(去重,按使用次数多到少)
  4506. */
  4507. public function deliverystoragelocations()
  4508. {
  4509. $this->mprocRequireDeliveryUser();
  4510. $this->mprocEnsureInboundScoreTable();
  4511. $list = [];
  4512. try {
  4513. $rows = Db::table('purchase_order_inbound_score')
  4514. ->where('storage_location', '<>', '')
  4515. ->whereRaw("TRIM(storage_location) <> ''")
  4516. ->field('storage_location, COUNT(*) AS use_cnt')
  4517. ->group('storage_location')
  4518. ->order('use_cnt', 'desc')
  4519. ->order('storage_location', 'asc')
  4520. ->limit(100)
  4521. ->select();
  4522. } catch (\Throwable $e) {
  4523. $rows = [];
  4524. }
  4525. $seen = [];
  4526. if (is_array($rows)) {
  4527. foreach ($rows as $row) {
  4528. if (!is_array($row)) {
  4529. continue;
  4530. }
  4531. $loc = trim((string)($row['storage_location'] ?? ''));
  4532. if ($loc === '' || isset($seen[$loc])) {
  4533. continue;
  4534. }
  4535. $seen[$loc] = true;
  4536. $list[] = $loc;
  4537. }
  4538. }
  4539. // group 失败时回退:按出现次数统计
  4540. if ($list === []) {
  4541. try {
  4542. $raw = Db::table('purchase_order_inbound_score')
  4543. ->where('storage_location', '<>', '')
  4544. ->field('storage_location')
  4545. ->order('id', 'desc')
  4546. ->limit(1000)
  4547. ->select();
  4548. } catch (\Throwable $e) {
  4549. $raw = [];
  4550. }
  4551. $cntMap = [];
  4552. if (is_array($raw)) {
  4553. foreach ($raw as $row) {
  4554. if (!is_array($row)) {
  4555. continue;
  4556. }
  4557. $loc = trim((string)($row['storage_location'] ?? ''));
  4558. if ($loc === '') {
  4559. continue;
  4560. }
  4561. $cntMap[$loc] = isset($cntMap[$loc]) ? ($cntMap[$loc] + 1) : 1;
  4562. }
  4563. }
  4564. arsort($cntMap, SORT_NUMERIC);
  4565. $list = array_keys($cntMap);
  4566. if (count($list) > 100) {
  4567. $list = array_slice($list, 0, 100);
  4568. }
  4569. }
  4570. $this->success('ok', '', ['list' => array_values($list)]);
  4571. }
  4572. /**
  4573. * 保存质量评分(质检中心)
  4574. * POST:ccydh、result、order_interrupt、remark
  4575. * 客诉事后由 inboundscorecomplaint 补登,首次默认否
  4576. */
  4577. public function inboundscoresave()
  4578. {
  4579. $user = $this->mprocRequireQualityUser();
  4580. if (!$this->request->isPost()) {
  4581. $this->error('请使用 POST');
  4582. }
  4583. $this->mprocEnsureInboundScoreTable();
  4584. $ccydh = trim((string)$this->request->post('ccydh', ''));
  4585. $sid = (int)$this->request->post('scydgy_id', 0);
  4586. $batchNo = trim((string)$this->request->post('order_batch_no', ''));
  4587. $companyName = trim((string)$this->request->post('pick_company_name', ''));
  4588. $result = trim((string)$this->request->post('result', ''));
  4589. if ($result !== '合格' && $result !== '不合格') {
  4590. $this->error('请选择生产是否合格');
  4591. }
  4592. $orderInterrupt = (int)$this->request->post('order_interrupt', -1);
  4593. if ($orderInterrupt !== 0 && $orderInterrupt !== 1) {
  4594. $this->error('请选择生产是否中断');
  4595. }
  4596. $remark = trim((string)$this->request->post('remark', ''));
  4597. if ($result === '不合格' && $remark === '') {
  4598. $this->error('请填写不合格原因');
  4599. }
  4600. if (mb_strlen($remark) > 500) {
  4601. $remark = mb_substr($remark, 0, 500);
  4602. }
  4603. $poRows = $this->mprocLoadApprovedPoRowsForScore($ccydh, $sid, $batchNo, $companyName);
  4604. $now = date('Y-m-d H:i:s');
  4605. $adminId = (int)($user['admin_id'] ?? 0);
  4606. $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
  4607. $saved = 0;
  4608. $firstSid = 0;
  4609. $firstPoId = 0;
  4610. $deliveryReady = true;
  4611. try {
  4612. Db::startTrans();
  4613. foreach ($poRows as $po) {
  4614. if (!is_array($po)) {
  4615. continue;
  4616. }
  4617. $rowSid = (int)($po['scydgy_id'] ?? 0);
  4618. if ($rowSid <= 0) {
  4619. continue;
  4620. }
  4621. if ($firstSid <= 0) {
  4622. $firstSid = $rowSid;
  4623. $firstPoId = (int)($po['id'] ?? 0);
  4624. }
  4625. $exist = Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->find();
  4626. $existDs = is_array($exist) ? trim((string)($exist['delivery_status'] ?? '')) : '';
  4627. if ($existDs !== '准时' && $existDs !== '滞后') {
  4628. $deliveryReady = false;
  4629. }
  4630. $data = [
  4631. 'scydgy_id' => $rowSid,
  4632. 'purchase_order_id' => (int)($po['id'] ?? 0),
  4633. 'ccydh' => trim((string)($po['CCYDH'] ?? $ccydh)),
  4634. 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
  4635. 'cgymc' => trim((string)($po['CGYMC'] ?? '')),
  4636. 'company_name' => trim((string)($po['pick_company_name'] ?? '')),
  4637. 'result' => $result,
  4638. 'order_interrupt' => $orderInterrupt,
  4639. 'remark' => $remark,
  4640. 'admin_id' => $adminId,
  4641. 'admin_name' => $adminName,
  4642. 'updatetime' => $now,
  4643. ];
  4644. if (is_array($exist) && $exist !== []) {
  4645. // 客诉事后补登,首次评分不覆盖已有客诉
  4646. Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->update($data);
  4647. } else {
  4648. $data['customer_complaint'] = 0;
  4649. $data['complaint_remark'] = '';
  4650. $data['delivery_status'] = '';
  4651. $data['createtime'] = $now;
  4652. Db::table('purchase_order_inbound_score')->insert($data);
  4653. $deliveryReady = false;
  4654. }
  4655. $saved++;
  4656. }
  4657. if ($saved < 1) {
  4658. throw new \RuntimeException('没有可保存的工序');
  4659. }
  4660. if ($deliveryReady) {
  4661. foreach ($poRows as $po) {
  4662. if (!is_array($po)) {
  4663. continue;
  4664. }
  4665. $rowSid = (int)($po['scydgy_id'] ?? 0);
  4666. if ($rowSid > 0) {
  4667. Db::table('purchase_order')->where('scydgy_id', $rowSid)->update([
  4668. 'status' => ProcuremenStatus::PO_COMPLETED,
  4669. ]);
  4670. }
  4671. }
  4672. }
  4673. Db::commit();
  4674. } catch (\Throwable $e) {
  4675. try {
  4676. Db::rollback();
  4677. } catch (\Throwable $e2) {
  4678. }
  4679. Log::record('inboundscoresave fail: ' . $e->getMessage(), 'error');
  4680. $this->error('保存失败,请稍后重试');
  4681. }
  4682. $logDetail = '质量评分:生产是否合格=' . $result
  4683. . ';生产是否中断:' . ($orderInterrupt === 1 ? '是' : '否');
  4684. if ($remark !== '') {
  4685. $logDetail .= ';备注:' . $remark;
  4686. }
  4687. \app\common\library\ProcuremenOperLog::write(
  4688. $firstSid,
  4689. 'inbound_score',
  4690. $logDetail,
  4691. $firstPoId > 0 ? $firstPoId : null,
  4692. [$adminId, $adminName]
  4693. );
  4694. $this->mprocSyncMonthlyAfterInboundScore($poRows, $now);
  4695. if ($deliveryReady) {
  4696. $this->mprocRefreshCompletedArchivePdfs($poRows);
  4697. }
  4698. $this->success('操作成功', '', [
  4699. 'ccydh' => $ccydh,
  4700. 'result' => $result,
  4701. 'order_interrupt' => $orderInterrupt,
  4702. 'remark' => $remark,
  4703. 'count' => $saved,
  4704. 'completed' => $deliveryReady ? 1 : 0,
  4705. ]);
  4706. }
  4707. /**
  4708. * 事后投诉反馈(质检中心,仅已质量评分订单)
  4709. * POST:ccydh、customer_complaint=0|1、complaint_remark(投诉为是时必填)
  4710. */
  4711. public function inboundscorecomplaint()
  4712. {
  4713. $user = $this->mprocRequireQualityUser();
  4714. if (!$this->request->isPost()) {
  4715. $this->error('请使用 POST');
  4716. }
  4717. $this->mprocEnsureInboundScoreTable();
  4718. $ccydh = trim((string)$this->request->post('ccydh', ''));
  4719. $sid = (int)$this->request->post('scydgy_id', 0);
  4720. $customerComplaint = (int)$this->request->post('customer_complaint', -1);
  4721. if ($customerComplaint !== 0 && $customerComplaint !== 1) {
  4722. $this->error('请选择客户是否投诉');
  4723. }
  4724. $complaintRemark = trim((string)$this->request->post('complaint_remark', ''));
  4725. if ($customerComplaint === 1 && $complaintRemark === '') {
  4726. $this->error('请填写投诉说明');
  4727. }
  4728. if ($customerComplaint !== 1) {
  4729. $complaintRemark = '';
  4730. }
  4731. if (mb_strlen($complaintRemark) > 500) {
  4732. $complaintRemark = mb_substr($complaintRemark, 0, 500);
  4733. }
  4734. if ($ccydh === '' && $sid > 0) {
  4735. try {
  4736. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
  4737. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  4738. } catch (\Throwable $e) {
  4739. $ccydh = '';
  4740. }
  4741. }
  4742. if ($ccydh === '') {
  4743. $this->error('缺少订单号');
  4744. }
  4745. try {
  4746. $scoreRows = Db::table('purchase_order_inbound_score')
  4747. ->where('ccydh', $ccydh)
  4748. ->field('id,scydgy_id,purchase_order_id,result,company_name')
  4749. ->select();
  4750. } catch (\Throwable $e) {
  4751. $scoreRows = [];
  4752. }
  4753. if (!is_array($scoreRows) || $scoreRows === []) {
  4754. $this->error('请先完成质量评分后再投诉反馈');
  4755. }
  4756. $hasQuality = false;
  4757. foreach ($scoreRows as $sc) {
  4758. if (!is_array($sc)) {
  4759. continue;
  4760. }
  4761. $res = trim((string)($sc['result'] ?? ''));
  4762. if ($res === '合格' || $res === '不合格') {
  4763. $hasQuality = true;
  4764. break;
  4765. }
  4766. }
  4767. if (!$hasQuality) {
  4768. $this->error('请先完成质量评分后再投诉反馈');
  4769. }
  4770. $now = date('Y-m-d H:i:s');
  4771. $adminId = (int)($user['admin_id'] ?? 0);
  4772. $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
  4773. $firstSid = 0;
  4774. $firstPoId = 0;
  4775. $companyName = '';
  4776. $updated = 0;
  4777. try {
  4778. Db::startTrans();
  4779. foreach ($scoreRows as $sc) {
  4780. if (!is_array($sc)) {
  4781. continue;
  4782. }
  4783. $rowSid = (int)($sc['scydgy_id'] ?? 0);
  4784. $id = (int)($sc['id'] ?? 0);
  4785. if ($id <= 0) {
  4786. continue;
  4787. }
  4788. if ($firstSid <= 0 && $rowSid > 0) {
  4789. $firstSid = $rowSid;
  4790. $firstPoId = (int)($sc['purchase_order_id'] ?? 0);
  4791. }
  4792. if ($companyName === '') {
  4793. $companyName = trim((string)($sc['company_name'] ?? ''));
  4794. }
  4795. Db::table('purchase_order_inbound_score')->where('id', $id)->update([
  4796. 'customer_complaint' => $customerComplaint,
  4797. 'complaint_remark' => $complaintRemark,
  4798. 'updatetime' => $now,
  4799. ]);
  4800. $updated++;
  4801. }
  4802. if ($updated < 1) {
  4803. throw new \RuntimeException('没有可更新的记录');
  4804. }
  4805. Db::commit();
  4806. } catch (\Throwable $e) {
  4807. try {
  4808. Db::rollback();
  4809. } catch (\Throwable $e2) {
  4810. }
  4811. Log::record('inboundscorecomplaint fail: ' . $e->getMessage(), 'error');
  4812. $this->error('保存失败,请稍后重试');
  4813. }
  4814. if ($firstSid > 0) {
  4815. $logDetail = '投诉反馈:客户投诉=' . ($customerComplaint === 1 ? '是' : '否');
  4816. if ($complaintRemark !== '') {
  4817. $logDetail .= ';投诉说明:' . $complaintRemark;
  4818. }
  4819. \app\common\library\ProcuremenOperLog::write(
  4820. $firstSid,
  4821. 'inbound_score',
  4822. $logDetail,
  4823. $firstPoId > 0 ? $firstPoId : null,
  4824. [$adminId, $adminName]
  4825. );
  4826. }
  4827. if ($companyName !== '') {
  4828. $scoreYm = date('Y-m', strtotime($now) ?: time());
  4829. try {
  4830. \app\common\library\ProcuremenSupplierScore::syncQualityScoreFromInbound($scoreYm, $companyName);
  4831. } catch (\Throwable $e) {
  4832. Log::record('inboundscorecomplaint quality sync: ' . $e->getMessage(), 'error');
  4833. }
  4834. }
  4835. $this->success('操作成功', '', [
  4836. 'ccydh' => $ccydh,
  4837. 'customer_complaint' => $customerComplaint,
  4838. 'complaint_remark' => $complaintRemark,
  4839. 'count' => $updated,
  4840. ]);
  4841. }
  4842. /**
  4843. * 保存交货情况(生产部)
  4844. * POST:ccydh、storage_location、delivery_status=准时|滞后、delivery_date=YYYY-MM-DD、remark
  4845. */
  4846. public function deliveryscoresave()
  4847. {
  4848. $user = $this->mprocRequireDeliveryUser();
  4849. if (!$this->request->isPost()) {
  4850. $this->error('请使用 POST');
  4851. }
  4852. $this->mprocEnsureInboundScoreTable();
  4853. $ccydh = trim((string)$this->request->post('ccydh', ''));
  4854. $sid = (int)$this->request->post('scydgy_id', 0);
  4855. $batchNo = trim((string)$this->request->post('order_batch_no', ''));
  4856. $companyName = trim((string)$this->request->post('pick_company_name', ''));
  4857. $storageLocation = trim((string)$this->request->post('storage_location', ''));
  4858. if ($storageLocation === '') {
  4859. $this->error('请填写库位');
  4860. }
  4861. if (mb_strlen($storageLocation) > 64) {
  4862. $this->error('库位最多64个字符');
  4863. }
  4864. $deliveryStatus = trim((string)$this->request->post('delivery_status', ''));
  4865. if ($deliveryStatus !== '准时' && $deliveryStatus !== '滞后') {
  4866. $this->error('请选择交货情况');
  4867. }
  4868. $deliveryDate = trim((string)$this->request->post('delivery_date', ''));
  4869. if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $deliveryDate)) {
  4870. $this->error('请选择交货日期');
  4871. }
  4872. $ts = strtotime($deliveryDate . ' 00:00:00');
  4873. if ($ts === false) {
  4874. $this->error('交货日期格式不正确');
  4875. }
  4876. $deliveryDate = date('Y-m-d', $ts);
  4877. $remark = trim((string)$this->request->post('remark', ''));
  4878. if ($deliveryStatus === '滞后' && $remark === '') {
  4879. $this->error('请填写滞后原因');
  4880. }
  4881. if (mb_strlen($remark) > 500) {
  4882. $remark = mb_substr($remark, 0, 500);
  4883. }
  4884. $poRows = $this->mprocLoadApprovedPoRowsForScore($ccydh, $sid, $batchNo, $companyName);
  4885. $deadlineYmd = '';
  4886. foreach ($poRows as $po) {
  4887. if (!is_array($po)) {
  4888. continue;
  4889. }
  4890. $deadlineYmd = $this->mprocFormatYmdValue($po['delivery_deadline'] ?? $po['Delivery_deadline'] ?? '');
  4891. if ($deadlineYmd !== '') {
  4892. break;
  4893. }
  4894. }
  4895. if ($deadlineYmd !== '' && $deliveryDate > $deadlineYmd && $deliveryStatus === '准时') {
  4896. $this->error('交货日期已超过截止日期,只能选择滞后');
  4897. }
  4898. if ($deadlineYmd !== '' && $deliveryDate <= $deadlineYmd && $deliveryStatus === '滞后') {
  4899. $this->error('已选择滞后请确认交货日期');
  4900. }
  4901. $now = date('Y-m-d H:i:s');
  4902. $adminId = (int)($user['admin_id'] ?? 0);
  4903. $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
  4904. $saved = 0;
  4905. $firstSid = 0;
  4906. $firstPoId = 0;
  4907. $qualityReady = true;
  4908. try {
  4909. Db::startTrans();
  4910. foreach ($poRows as $po) {
  4911. if (!is_array($po)) {
  4912. continue;
  4913. }
  4914. $rowSid = (int)($po['scydgy_id'] ?? 0);
  4915. if ($rowSid <= 0) {
  4916. continue;
  4917. }
  4918. if ($firstSid <= 0) {
  4919. $firstSid = $rowSid;
  4920. $firstPoId = (int)($po['id'] ?? 0);
  4921. }
  4922. $exist = Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->find();
  4923. $existResult = is_array($exist) ? trim((string)($exist['result'] ?? '')) : '';
  4924. if ($existResult !== '合格' && $existResult !== '不合格') {
  4925. $qualityReady = false;
  4926. }
  4927. $data = [
  4928. 'scydgy_id' => $rowSid,
  4929. 'purchase_order_id' => (int)($po['id'] ?? 0),
  4930. 'ccydh' => trim((string)($po['CCYDH'] ?? $ccydh)),
  4931. 'cyjmc' => trim((string)($po['CYJMC'] ?? '')),
  4932. 'cgymc' => trim((string)($po['CGYMC'] ?? '')),
  4933. 'company_name' => trim((string)($po['pick_company_name'] ?? '')),
  4934. 'storage_location' => $storageLocation,
  4935. 'delivery_status' => $deliveryStatus,
  4936. 'delivery_date' => $deliveryDate,
  4937. 'remark' => $remark,
  4938. 'delivery_admin_id' => $adminId,
  4939. 'delivery_admin_name' => $adminName,
  4940. 'updatetime' => $now,
  4941. ];
  4942. if (is_array($exist) && $exist !== []) {
  4943. Db::table('purchase_order_inbound_score')->where('scydgy_id', $rowSid)->update($data);
  4944. } else {
  4945. $data['result'] = '';
  4946. $data['customer_complaint'] = 0;
  4947. $data['complaint_remark'] = '';
  4948. $data['order_interrupt'] = 0;
  4949. $data['admin_id'] = $adminId;
  4950. $data['admin_name'] = $adminName;
  4951. $data['createtime'] = $now;
  4952. Db::table('purchase_order_inbound_score')->insert($data);
  4953. $qualityReady = false;
  4954. }
  4955. $saved++;
  4956. }
  4957. if ($saved < 1) {
  4958. throw new \RuntimeException('没有可保存的工序');
  4959. }
  4960. if ($qualityReady) {
  4961. foreach ($poRows as $po) {
  4962. if (!is_array($po)) {
  4963. continue;
  4964. }
  4965. $rowSid = (int)($po['scydgy_id'] ?? 0);
  4966. if ($rowSid > 0) {
  4967. Db::table('purchase_order')->where('scydgy_id', $rowSid)->update([
  4968. 'status' => ProcuremenStatus::PO_COMPLETED,
  4969. ]);
  4970. }
  4971. }
  4972. }
  4973. Db::commit();
  4974. } catch (\Throwable $e) {
  4975. try {
  4976. Db::rollback();
  4977. } catch (\Throwable $e2) {
  4978. }
  4979. Log::record('deliveryscoresave fail: ' . $e->getMessage(), 'error');
  4980. $this->error('保存失败,请稍后重试');
  4981. }
  4982. $logDetail = '库位:' . $storageLocation . ';交货情况:' . $deliveryStatus . ';交货日期:' . $deliveryDate;
  4983. if ($remark !== '') {
  4984. $logDetail .= ';备注:' . $remark;
  4985. }
  4986. \app\common\library\ProcuremenOperLog::write(
  4987. $firstSid,
  4988. 'delivery_score',
  4989. $logDetail,
  4990. $firstPoId > 0 ? $firstPoId : null,
  4991. [$adminId, $adminName]
  4992. );
  4993. $this->mprocSyncMonthlyAfterInboundScore($poRows, $now);
  4994. if ($qualityReady) {
  4995. $this->mprocRefreshCompletedArchivePdfs($poRows);
  4996. }
  4997. $this->success('操作成功', '', [
  4998. 'ccydh' => $ccydh,
  4999. 'storage_location' => $storageLocation,
  5000. 'delivery_status' => $deliveryStatus,
  5001. 'delivery_date' => $deliveryDate,
  5002. 'remark' => $remark,
  5003. 'count' => $saved,
  5004. 'completed' => $qualityReady ? 1 : 0,
  5005. ]);
  5006. }
  5007. /**
  5008. * 交货情况(已确认)— 通知人员名单(质检中心 + 业务员)
  5009. */
  5010. public function deliverynotifymen()
  5011. {
  5012. $user = $this->mprocRequireDeliveryUser();
  5013. $ccydh = trim((string)$this->request->request('ccydh', ''));
  5014. $sid = (int)$this->request->request('scydgy_id', 0);
  5015. $order = $this->mprocLoadDeliveryNotifyOrder($ccydh, $sid);
  5016. if ($order === null) {
  5017. $this->error('未找到可通知的订单');
  5018. }
  5019. $selfAdminId = (int)($user['admin_id'] ?? 0);
  5020. $list = [];
  5021. foreach ($this->mprocLoadArrivalNotifyStaffOptions() as $opt) {
  5022. $email = trim((string)($opt['email'] ?? ''));
  5023. $adminId = (int)($opt['admin_id'] ?? 0);
  5024. $list[] = [
  5025. 'name' => (string)($opt['name'] ?? ''),
  5026. 'email' => $email,
  5027. 'mobile' => (string)($opt['mobile'] ?? ''),
  5028. 'role' => (string)($opt['role'] ?? ''),
  5029. 'admin_id' => $adminId,
  5030. 'can_select' => ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL)) ? 1 : 0,
  5031. 'is_self' => ($selfAdminId > 0 && $adminId === $selfAdminId) ? 1 : 0,
  5032. ];
  5033. }
  5034. $this->success('ok', '', [
  5035. 'ccydh' => (string)($order['CCYDH'] ?? ''),
  5036. 'cyjmc' => (string)($order['CYJMC'] ?? ''),
  5037. 'cgymc' => (string)($order['CGYMC'] ?? ''),
  5038. 'this_quantity' => (string)($order['order_qty'] ?? ''),
  5039. 'supplier_name' => (string)($order['pick_company_name'] ?? ''),
  5040. 'delivery_deadline' => (string)($order['delivery_deadline'] ?? ''),
  5041. 'list' => $list,
  5042. ]);
  5043. }
  5044. /**
  5045. * 交货情况(已确认)— 邮箱通知所选质检/业务员:订单已到货
  5046. * POST:ccydh、staff_json=["姓名",...]
  5047. */
  5048. public function deliverynotify()
  5049. {
  5050. $user = $this->mprocRequireDeliveryUser();
  5051. if (!$this->request->isPost()) {
  5052. $this->error('请使用 POST');
  5053. }
  5054. $ccydh = trim((string)$this->request->post('ccydh', ''));
  5055. $sid = (int)$this->request->post('scydgy_id', 0);
  5056. $order = $this->mprocLoadDeliveryNotifyOrder($ccydh, $sid);
  5057. if ($order === null) {
  5058. $this->error('未找到可通知的订单');
  5059. }
  5060. $ccydh = trim((string)($order['CCYDH'] ?? $ccydh));
  5061. $raw = $this->request->post('staff/a', []);
  5062. if (!is_array($raw) || $raw === []) {
  5063. // 关闭过滤器,避免 staff_json 中的引号被转义导致 json_decode 失败
  5064. $staffJson = (string)$this->request->post('staff_json', '', null);
  5065. if ($staffJson === '') {
  5066. $staffJson = (string)($this->request->param('staff_json', '', null) ?: '');
  5067. }
  5068. if ($staffJson !== '') {
  5069. $decoded = json_decode(html_entity_decode($staffJson, ENT_QUOTES, 'UTF-8'), true);
  5070. if (!is_array($decoded)) {
  5071. $decoded = json_decode($staffJson, true);
  5072. }
  5073. $raw = is_array($decoded) ? $decoded : [];
  5074. }
  5075. }
  5076. $selectedNames = [];
  5077. foreach ((array)$raw as $item) {
  5078. $n = is_array($item) ? trim((string)($item['name'] ?? '')) : trim((string)$item);
  5079. if ($n !== '') {
  5080. $selectedNames[] = $n;
  5081. }
  5082. }
  5083. $selectedNames = array_values(array_unique($selectedNames));
  5084. if ($selectedNames === []) {
  5085. $this->error('请选择要通知的人员');
  5086. }
  5087. $optionMap = [];
  5088. foreach ($this->mprocLoadArrivalNotifyStaffOptions() as $opt) {
  5089. $n = trim((string)($opt['name'] ?? ''));
  5090. if ($n !== '') {
  5091. $optionMap[$n] = $opt;
  5092. }
  5093. }
  5094. $targets = [];
  5095. foreach ($selectedNames as $n) {
  5096. if (!isset($optionMap[$n])) {
  5097. $this->error('人员不在可选名单中:' . $n);
  5098. }
  5099. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  5100. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  5101. $this->error('未填写有效邮箱,无法通知:' . $n);
  5102. }
  5103. $targets[] = $optionMap[$n];
  5104. }
  5105. try {
  5106. $mailConfig = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  5107. } catch (\Throwable $e) {
  5108. $mailConfig = [];
  5109. }
  5110. if (!is_array($mailConfig) || empty($mailConfig['host'])) {
  5111. $this->error('邮件 SMTP 未配置');
  5112. }
  5113. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  5114. $this->error('发件邮箱未配置');
  5115. }
  5116. $this->mprocEnsureArrivalNotifyEmailTemplate();
  5117. try {
  5118. $platformUrl = $this->mprocBuildInboundscoreNotifyUrl($ccydh);
  5119. } catch (\Throwable $e) {
  5120. $this->error($e->getMessage());
  5121. }
  5122. $tpl = $this->mprocLoadNotifyTemplateRow('arrival_notify_email');
  5123. if ($tpl === null || trim((string)($tpl['content'] ?? '')) === '') {
  5124. $tpl = $this->mprocLoadNotifyTemplateRow('delivery_notify_email');
  5125. }
  5126. if ($tpl === null || trim((string)($tpl['content'] ?? '')) === '') {
  5127. $this->error('邮件模版未配置,请在后台「短信模版配置」维护「订单已到货通知-邮箱」');
  5128. }
  5129. $subjectTpl = trim((string)($tpl['title'] ?? ''));
  5130. if ($subjectTpl === '' || stripos($subjectTpl, '交货情况') !== false) {
  5131. $subjectTpl = '订单已到货通知 - {ccydh}';
  5132. }
  5133. $contentTpl = (string)$tpl['content'];
  5134. $ok = 0;
  5135. $okNames = [];
  5136. $failMsgs = [];
  5137. $firstSid = (int)($order['scydgy_id'] ?? 0);
  5138. $firstPoId = (int)($order['id'] ?? 0);
  5139. $adminId = (int)($user['admin_id'] ?? 0);
  5140. $adminName = $this->mprocResolveAdminDisplayName($user, $adminId);
  5141. foreach ($targets as $contact) {
  5142. $toName = trim((string)($contact['name'] ?? ''));
  5143. $toEmail = trim((string)($contact['email'] ?? ''));
  5144. $vars = [
  5145. 'contact_name' => $toName,
  5146. 'company_name' => $toName,
  5147. 'email' => $toEmail,
  5148. 'ccydh' => $ccydh,
  5149. 'cyjmc' => (string)($order['CYJMC'] ?? ''),
  5150. 'cgymc' => (string)($order['CGYMC'] ?? ''),
  5151. 'this_quantity' => (string)($order['order_qty'] ?? ''),
  5152. 'supplier_name' => (string)($order['pick_company_name'] ?? ''),
  5153. 'delivery_deadline' => (string)($order['delivery_deadline'] ?? ''),
  5154. 'delivery_status' => (string)($order['delivery_status'] ?? ''),
  5155. 'delivery_date' => (string)($order['delivery_date'] ?? ''),
  5156. 'storage_location' => (string)($order['storage_location'] ?? ''),
  5157. 'remark' => (string)($order['delivery_remark'] ?? ''),
  5158. 'platform_url' => $platformUrl,
  5159. ];
  5160. $mailPlain = $contentTpl;
  5161. $mailSubject = $subjectTpl;
  5162. foreach ($vars as $k => $v) {
  5163. $mailPlain = str_replace('{' . $k . '}', (string)$v, $mailPlain);
  5164. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  5165. }
  5166. $mailPlain = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailPlain);
  5167. $mailSubject = trim((string)preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject));
  5168. if ($mailSubject === '') {
  5169. $mailSubject = '订单已到货通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  5170. }
  5171. $mailBody = $this->mprocPlainTextToHtmlEmailBody($mailPlain);
  5172. try {
  5173. $this->mprocSendNotifyEmail($mailConfig, $toEmail, $toName, $mailSubject, $mailBody, $toEmail);
  5174. $ok++;
  5175. if ($toName !== '') {
  5176. $okNames[] = $toName;
  5177. }
  5178. $this->mprocPersistEmailSendLog([
  5179. 'from_email' => trim((string)($mailConfig['addr'] ?? '')),
  5180. 'to_email' => $toEmail,
  5181. 'scene' => '订单已到货通知',
  5182. 'order_batch_no' => trim((string)($order['order_batch_no'] ?? $order['issue_batch_no'] ?? '')),
  5183. 'ccydh' => $ccydh,
  5184. 'company_name' => $toName,
  5185. 'mail_subject' => $mailSubject,
  5186. 'status' => 1,
  5187. 'fail_reason' => '',
  5188. 'scydgy_id' => $firstSid,
  5189. 'purchase_order_id' => $firstPoId,
  5190. 'admin_id' => $adminId,
  5191. 'admin_name' => $adminName,
  5192. ]);
  5193. } catch (\Throwable $e) {
  5194. $failMsgs[] = $toName . ':' . $e->getMessage();
  5195. $this->mprocPersistEmailSendLog([
  5196. 'from_email' => trim((string)($mailConfig['addr'] ?? '')),
  5197. 'to_email' => $toEmail,
  5198. 'scene' => '订单已到货通知',
  5199. 'order_batch_no' => trim((string)($order['order_batch_no'] ?? $order['issue_batch_no'] ?? '')),
  5200. 'ccydh' => $ccydh,
  5201. 'company_name' => $toName,
  5202. 'mail_subject' => $mailSubject,
  5203. 'status' => 0,
  5204. 'fail_reason' => $e->getMessage(),
  5205. 'scydgy_id' => $firstSid,
  5206. 'purchase_order_id' => $firstPoId,
  5207. 'admin_id' => $adminId,
  5208. 'admin_name' => $adminName,
  5209. ]);
  5210. }
  5211. }
  5212. if ($ok < 1) {
  5213. $this->error('发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  5214. }
  5215. $mergedStaff = $this->mprocPersistArrivalNotifyStaff($ccydh, $okNames);
  5216. if ($firstSid > 0) {
  5217. \app\common\library\ProcuremenOperLog::write(
  5218. $firstSid,
  5219. 'arrival_notify',
  5220. '手机端交货情况通知已到货(质检/业务员):' . implode('、', $okNames),
  5221. $firstPoId > 0 ? $firstPoId : null,
  5222. [$adminId, $adminName]
  5223. );
  5224. }
  5225. $msg = '已通知 ' . $ok . ' 人';
  5226. if ($failMsgs !== []) {
  5227. $msg .= ';部分失败:' . implode(';', $failMsgs);
  5228. }
  5229. $this->success($msg, '', [
  5230. 'ok_count' => $ok,
  5231. 'fail_count' => count($failMsgs),
  5232. 'arrival_notify_staff' => $mergedStaff,
  5233. ]);
  5234. }
  5235. /**
  5236. * 已到货通知可选人员:质检中心 + 业务员
  5237. *
  5238. * @return array<int, array{admin_id:int,name:string,email:string,mobile:string,role:string}>
  5239. */
  5240. protected function mprocLoadArrivalNotifyStaffOptions(): array
  5241. {
  5242. $groups = [
  5243. ['id' => $this->mprocResolveMobileQualityGroupId(), 'role' => '质检'],
  5244. ['id' => $this->mprocResolveMobileRfqGroupId(), 'role' => '业务员'],
  5245. ];
  5246. $out = [];
  5247. $seen = [];
  5248. foreach ($groups as $g) {
  5249. $groupId = (int)($g['id'] ?? 0);
  5250. $role = (string)($g['role'] ?? '');
  5251. if ($groupId <= 0) {
  5252. continue;
  5253. }
  5254. try {
  5255. $adminIds = Db::name('auth_group_access')->where('group_id', $groupId)->column('uid');
  5256. } catch (\Throwable $e) {
  5257. continue;
  5258. }
  5259. $adminIds = is_array($adminIds)
  5260. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  5261. : [];
  5262. if ($adminIds === []) {
  5263. continue;
  5264. }
  5265. try {
  5266. $rows = Db::name('admin')
  5267. ->where('status', 'normal')
  5268. ->where('id', 'in', $adminIds)
  5269. ->order('id', 'asc')
  5270. ->field('id,nickname,username,email,mobile')
  5271. ->select();
  5272. } catch (\Throwable $e) {
  5273. continue;
  5274. }
  5275. if (!is_array($rows)) {
  5276. continue;
  5277. }
  5278. foreach ($rows as $row) {
  5279. if (!is_array($row)) {
  5280. continue;
  5281. }
  5282. $name = trim((string)($row['nickname'] ?? ''));
  5283. if ($name === '') {
  5284. $name = trim((string)($row['username'] ?? ''));
  5285. }
  5286. if ($name === '' || isset($seen[$name])) {
  5287. continue;
  5288. }
  5289. $seen[$name] = true;
  5290. $out[] = [
  5291. 'admin_id' => (int)($row['id'] ?? 0),
  5292. 'name' => $name,
  5293. 'email' => trim((string)($row['email'] ?? '')),
  5294. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  5295. 'role' => $role,
  5296. ];
  5297. }
  5298. }
  5299. return $out;
  5300. }
  5301. /**
  5302. * @return array<int, array{admin_id:int,name:string,email:string,mobile:string}>
  5303. */
  5304. protected function mprocLoadDeliveryStaffOptions(): array
  5305. {
  5306. $out = [];
  5307. $seen = [];
  5308. $groupId = $this->mprocResolveMobileDeliveryGroupId();
  5309. if ($groupId <= 0) {
  5310. return [];
  5311. }
  5312. try {
  5313. $adminIds = Db::name('auth_group_access')->where('group_id', $groupId)->column('uid');
  5314. } catch (\Throwable $e) {
  5315. return [];
  5316. }
  5317. $adminIds = is_array($adminIds)
  5318. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  5319. : [];
  5320. if ($adminIds === []) {
  5321. return [];
  5322. }
  5323. try {
  5324. $rows = Db::name('admin')
  5325. ->where('status', 'normal')
  5326. ->where('id', 'in', $adminIds)
  5327. ->order('id', 'asc')
  5328. ->field('id,nickname,username,email,mobile')
  5329. ->select();
  5330. } catch (\Throwable $e) {
  5331. return [];
  5332. }
  5333. if (!is_array($rows)) {
  5334. return [];
  5335. }
  5336. foreach ($rows as $row) {
  5337. if (!is_array($row)) {
  5338. continue;
  5339. }
  5340. $name = trim((string)($row['nickname'] ?? ''));
  5341. if ($name === '') {
  5342. $name = trim((string)($row['username'] ?? ''));
  5343. }
  5344. if ($name === '' || isset($seen[$name])) {
  5345. continue;
  5346. }
  5347. $seen[$name] = true;
  5348. $out[] = [
  5349. 'admin_id' => (int)($row['id'] ?? 0),
  5350. 'name' => $name,
  5351. 'email' => trim((string)($row['email'] ?? '')),
  5352. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  5353. ];
  5354. }
  5355. return $out;
  5356. }
  5357. /**
  5358. * 合并已通知人员姓名(去重,顿号分隔)
  5359. *
  5360. * @param string $old
  5361. * @param string[] $names
  5362. */
  5363. protected function mprocMergeArrivalNotifyStaffNames(string $old, array $names): string
  5364. {
  5365. $map = [];
  5366. foreach (preg_split('/[、,,;;]+/u', $old) ?: [] as $p) {
  5367. $p = trim((string)$p);
  5368. if ($p !== '') {
  5369. $map[$p] = true;
  5370. }
  5371. }
  5372. foreach ($names as $n) {
  5373. $n = trim((string)$n);
  5374. if ($n !== '') {
  5375. $map[$n] = true;
  5376. }
  5377. }
  5378. return implode('、', array_keys($map));
  5379. }
  5380. /**
  5381. * 记录订单已到货通知人员(写入 inbound_score,按订单号合并)
  5382. *
  5383. * @param string[] $names
  5384. */
  5385. protected function mprocPersistArrivalNotifyStaff(string $ccydh, array $names): string
  5386. {
  5387. $ccydh = trim($ccydh);
  5388. $names = array_values(array_filter(array_map(static function ($n) {
  5389. return trim((string)$n);
  5390. }, $names)));
  5391. if ($ccydh === '' || $names === []) {
  5392. return '';
  5393. }
  5394. $this->mprocEnsureInboundScoreTable();
  5395. $now = date('Y-m-d H:i:s');
  5396. $merged = implode('、', $names);
  5397. try {
  5398. $rows = Db::table('purchase_order_inbound_score')
  5399. ->where('ccydh', $ccydh)
  5400. ->field('id,arrival_notify_staff')
  5401. ->select();
  5402. } catch (\Throwable $e) {
  5403. try {
  5404. $rows = Db::table('purchase_order_inbound_score')
  5405. ->where('CCYDH', $ccydh)
  5406. ->field('id,arrival_notify_staff')
  5407. ->select();
  5408. } catch (\Throwable $e2) {
  5409. $rows = [];
  5410. }
  5411. }
  5412. if (!is_array($rows) || $rows === []) {
  5413. // 按工序写入:订单下已确认交货的 scydgy
  5414. try {
  5415. $sids = Db::table('purchase_order')
  5416. ->where('CCYDH', $ccydh)
  5417. ->where('scydgy_id', '>', 0)
  5418. ->column('scydgy_id');
  5419. } catch (\Throwable $e) {
  5420. $sids = [];
  5421. }
  5422. $sids = is_array($sids) ? array_values(array_unique(array_filter(array_map('intval', $sids)))) : [];
  5423. if ($sids !== []) {
  5424. try {
  5425. $rows = Db::table('purchase_order_inbound_score')
  5426. ->where('scydgy_id', 'in', $sids)
  5427. ->field('id,arrival_notify_staff')
  5428. ->select();
  5429. } catch (\Throwable $e) {
  5430. $rows = [];
  5431. }
  5432. }
  5433. }
  5434. if (!is_array($rows) || $rows === []) {
  5435. return $merged;
  5436. }
  5437. foreach ($rows as $row) {
  5438. if (!is_array($row)) {
  5439. continue;
  5440. }
  5441. $id = (int)($row['id'] ?? 0);
  5442. if ($id <= 0) {
  5443. continue;
  5444. }
  5445. $staff = $this->mprocMergeArrivalNotifyStaffNames((string)($row['arrival_notify_staff'] ?? ''), $names);
  5446. $merged = $staff !== '' ? $staff : $merged;
  5447. try {
  5448. Db::table('purchase_order_inbound_score')->where('id', $id)->update([
  5449. 'arrival_notify_staff' => $staff,
  5450. 'arrival_notify_time' => $now,
  5451. 'updatetime' => $now,
  5452. ]);
  5453. } catch (\Throwable $e) {
  5454. try {
  5455. Db::table('purchase_order_inbound_score')->where('id', $id)->update([
  5456. 'arrival_notify_staff' => $staff,
  5457. 'arrival_notify_time' => $now,
  5458. ]);
  5459. } catch (\Throwable $e2) {
  5460. }
  5461. }
  5462. }
  5463. return $merged;
  5464. }
  5465. /**
  5466. * @return array<string, mixed>|null
  5467. */
  5468. protected function mprocLoadDeliveryNotifyOrder(string $ccydh, int $sid = 0): ?array
  5469. {
  5470. $ccydh = trim($ccydh);
  5471. if ($ccydh === '' && $sid > 0) {
  5472. try {
  5473. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH')->find();
  5474. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  5475. } catch (\Throwable $e) {
  5476. $ccydh = '';
  5477. }
  5478. }
  5479. if ($ccydh === '') {
  5480. return null;
  5481. }
  5482. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  5483. $approvedIn = implode(',', array_map(static function ($v) {
  5484. return "'" . str_replace("'", "''", (string)$v) . "'";
  5485. }, $approvedVals));
  5486. try {
  5487. $rows = Db::table('purchase_order')
  5488. ->where('CCYDH', $ccydh)
  5489. ->where('scydgy_id', '>', 0)
  5490. ->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%\')')
  5491. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  5492. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  5493. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,This_quantity,NGZL,pick_company_name,delivery_deadline')
  5494. ->order('id', 'asc')
  5495. ->select();
  5496. } catch (\Throwable $e) {
  5497. $rows = [];
  5498. }
  5499. if (!is_array($rows) || $rows === []) {
  5500. return null;
  5501. }
  5502. $gymc = [];
  5503. $qty = [];
  5504. $first = null;
  5505. foreach ($rows as $r) {
  5506. if (!is_array($r)) {
  5507. continue;
  5508. }
  5509. if ($first === null) {
  5510. $first = $r;
  5511. }
  5512. $g = trim((string)($r['CGYMC'] ?? ''));
  5513. if ($g !== '' && !in_array($g, $gymc, true)) {
  5514. $gymc[] = $g;
  5515. }
  5516. $q = $this->mprocResolveDisplayThisQuantity($r);
  5517. if ($q !== '' && !in_array($q, $qty, true)) {
  5518. $qty[] = $q;
  5519. }
  5520. }
  5521. if (!is_array($first)) {
  5522. return null;
  5523. }
  5524. $dl = trim((string)($first['delivery_deadline'] ?? ''));
  5525. if ($dl !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', str_replace(['/', '.'], '-', $dl), $m)) {
  5526. $dl = $m[1];
  5527. } elseif ($dl !== '' && preg_match('/^0000-00-00/', $dl)) {
  5528. $dl = '';
  5529. }
  5530. $first['CGYMC'] = $gymc !== [] ? implode('、', $gymc) : '';
  5531. $first['order_qty'] = $qty !== [] ? implode('、', $qty) : '';
  5532. $first['delivery_deadline'] = $dl;
  5533. $first['delivery_date'] = '';
  5534. $first['storage_location'] = '';
  5535. $first['delivery_status'] = '';
  5536. $first['delivery_remark'] = '';
  5537. $sids = [];
  5538. foreach ($rows as $r) {
  5539. if (!is_array($r)) {
  5540. continue;
  5541. }
  5542. $sidOne = (int)($r['scydgy_id'] ?? 0);
  5543. if ($sidOne > 0) {
  5544. $sids[$sidOne] = true;
  5545. }
  5546. }
  5547. if ($sids !== []) {
  5548. try {
  5549. $scores = Db::table('purchase_order_inbound_score')
  5550. ->where('scydgy_id', 'in', array_keys($sids))
  5551. ->field('scydgy_id,delivery_status,delivery_date,storage_location,remark')
  5552. ->select();
  5553. } catch (\Throwable $e) {
  5554. try {
  5555. $scores = Db::table('purchase_order_inbound_score')
  5556. ->where('scydgy_id', 'in', array_keys($sids))
  5557. ->field('scydgy_id,delivery_date,storage_location')
  5558. ->select();
  5559. } catch (\Throwable $e2) {
  5560. $scores = [];
  5561. }
  5562. }
  5563. if (is_array($scores)) {
  5564. foreach ($scores as $sc) {
  5565. if (!is_array($sc)) {
  5566. continue;
  5567. }
  5568. $ds = trim((string)($sc['delivery_status'] ?? ''));
  5569. if ($ds !== '' && $first['delivery_status'] === '') {
  5570. $first['delivery_status'] = $ds;
  5571. }
  5572. $dd = trim((string)($sc['delivery_date'] ?? ''));
  5573. if ($dd !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', str_replace(['/', '.'], '-', $dd), $mdd)
  5574. && $first['delivery_date'] === '') {
  5575. $first['delivery_date'] = $mdd[1];
  5576. }
  5577. $loc = trim((string)($sc['storage_location'] ?? ''));
  5578. if ($loc !== '' && $first['storage_location'] === '') {
  5579. $first['storage_location'] = $loc;
  5580. }
  5581. $rm = trim((string)($sc['remark'] ?? ''));
  5582. if ($rm !== '' && $first['delivery_remark'] === '') {
  5583. $first['delivery_remark'] = $rm;
  5584. }
  5585. }
  5586. }
  5587. }
  5588. return $first;
  5589. }
  5590. protected function mprocBuildInboundscoreNotifyUrl(string $ccydh): string
  5591. {
  5592. $base = rtrim(trim((string)Config::get('mproc.mobile_base_url')), '/');
  5593. if ($base === '' || !preg_match('#^https?://#i', $base)) {
  5594. $base = rtrim((string)$this->request->root(true), '/');
  5595. }
  5596. if ($base === '') {
  5597. throw new \RuntimeException('无法生成通知链接');
  5598. }
  5599. $ccydh = trim($ccydh);
  5600. return $base . '/index.php/index/index/inboundscore' . ($ccydh !== '' ? ('?ccydh=' . rawurlencode($ccydh)) : '');
  5601. }
  5602. /** @deprecated 兼容旧调用,已改跳转质量评分 */
  5603. protected function mprocBuildDeliveryscoreNotifyUrl(string $ccydh): string
  5604. {
  5605. return $this->mprocBuildInboundscoreNotifyUrl($ccydh);
  5606. }
  5607. /**
  5608. * @return array{title:string,content:string}|null
  5609. */
  5610. protected function mprocLoadNotifyTemplateRow(string $scene): ?array
  5611. {
  5612. try {
  5613. $row = Db::table('purchase_sms_template')
  5614. ->where('scene', $scene)
  5615. ->where(function ($q) {
  5616. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  5617. })
  5618. ->order('id', 'asc')
  5619. ->find();
  5620. } catch (\Throwable $e) {
  5621. return null;
  5622. }
  5623. if (!is_array($row) || $row === []) {
  5624. return null;
  5625. }
  5626. return [
  5627. 'title' => trim((string)($row['title'] ?? '')),
  5628. 'content' => trim((string)($row['content'] ?? '')),
  5629. ];
  5630. }
  5631. protected function mprocEnsureArrivalNotifyEmailTemplate(): void
  5632. {
  5633. static $done = false;
  5634. if ($done) {
  5635. return;
  5636. }
  5637. $done = true;
  5638. $content = "您好,{contact_name}:\n\n"
  5639. . "订单已到货,请知悉。\n\n"
  5640. . "订单信息\n"
  5641. . "\t订单号:{ccydh}\n"
  5642. . "\t印件名称:{cyjmc}\n"
  5643. . "\t工序名称:{cgymc}\n"
  5644. . "\t订单数量:{this_quantity}\n"
  5645. . "\t供应商:{supplier_name}\n"
  5646. . "\t交货截止日期:{delivery_deadline}\n\n"
  5647. . "交货信息\n"
  5648. . "\t交货情况:{delivery_status}\n"
  5649. . "\t交货日期:{delivery_date}\n"
  5650. . "\t库位:{storage_location}\n"
  5651. . "\t备注:{remark}\n";
  5652. $title = '订单已到货通知 - {ccydh}';
  5653. $remark = '手机端交货情况-通知质检/业务员已到货;模版名称作邮件主题';
  5654. try {
  5655. $row = Db::table('purchase_sms_template')->where('scene', 'arrival_notify_email')->find();
  5656. } catch (\Throwable $e) {
  5657. return;
  5658. }
  5659. $now = date('Y-m-d H:i:s');
  5660. try {
  5661. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  5662. } catch (\Throwable $e) {
  5663. $cols = [];
  5664. }
  5665. $colNames = [];
  5666. foreach ($cols as $c) {
  5667. if (!is_array($c)) {
  5668. continue;
  5669. }
  5670. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  5671. if ($n !== '') {
  5672. $colNames[$n] = true;
  5673. }
  5674. }
  5675. try {
  5676. if (is_array($row) && $row !== []) {
  5677. $upd = [
  5678. 'title' => $title,
  5679. 'content' => $content,
  5680. 'remark' => $remark,
  5681. 'status' => 1,
  5682. ];
  5683. if (isset($colNames['updatetime'])) {
  5684. $upd['updatetime'] = $now;
  5685. }
  5686. Db::table('purchase_sms_template')
  5687. ->where('id', (int)($row['id'] ?? 0))
  5688. ->update($upd);
  5689. return;
  5690. }
  5691. $data = [
  5692. 'scene' => 'arrival_notify_email',
  5693. 'title' => $title,
  5694. 'content' => $content,
  5695. 'remark' => $remark,
  5696. 'status' => 1,
  5697. ];
  5698. if (isset($colNames['updatetime'])) {
  5699. $data['updatetime'] = $now;
  5700. }
  5701. if (isset($colNames['createtime'])) {
  5702. $data['createtime'] = $now;
  5703. }
  5704. Db::table('purchase_sms_template')->insert($data);
  5705. } catch (\Throwable $e) {
  5706. }
  5707. }
  5708. /** @deprecated 兼容旧调用 */
  5709. protected function mprocEnsureDeliveryNotifyEmailTemplate(): void
  5710. {
  5711. $this->mprocEnsureArrivalNotifyEmailTemplate();
  5712. }
  5713. protected function mprocPlainTextToHtmlEmailBody(string $plain): string
  5714. {
  5715. $esc = htmlspecialchars($plain, ENT_QUOTES, 'UTF-8');
  5716. $esc = preg_replace(
  5717. '#(https?://[^\s<]+)#u',
  5718. '<a href="$1" style="color:#3c8dbc;word-break:break-all;">$1</a>',
  5719. $esc
  5720. );
  5721. $esc = nl2br($esc);
  5722. return '<div style="font-size:14px;line-height:1.7;color:#333;font-family:sans-serif;">' . $esc . '</div>';
  5723. }
  5724. /**
  5725. * @param array<string, mixed> $mailConfig
  5726. */
  5727. protected function mprocSendNotifyEmail(array $mailConfig, string $toEmail, string $toName, string $subject, string $htmlBody, string $excludeCc = ''): void
  5728. {
  5729. $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
  5730. $mail->isSMTP();
  5731. $mail->Host = (string)($mailConfig['host'] ?? '');
  5732. $mail->SMTPAuth = true;
  5733. $mail->Username = (string)($mailConfig['addr'] ?? '');
  5734. $mail->Password = (string)($mailConfig['pass'] ?? '');
  5735. $mail->SMTPSecure = (string)($mailConfig['security'] ?? 'ssl');
  5736. $mail->Port = (int)($mailConfig['port'] ?? 465);
  5737. $mail->CharSet = (string)($mailConfig['charset'] ?? 'utf-8');
  5738. $mail->setFrom((string)($mailConfig['addr'] ?? ''), (string)($mailConfig['name'] ?? '协助采购'));
  5739. $mail->addAddress($toEmail, $toName);
  5740. $ccRaw = trim((string)Config::get('mproc.cc_email'));
  5741. if ($ccRaw !== '') {
  5742. $exclude = strtolower(trim($excludeCc));
  5743. foreach (preg_split('/[,;,;\s]+/', $ccRaw) ?: [] as $piece) {
  5744. $cc = strtolower(trim((string)$piece));
  5745. if ($cc === '' || !filter_var($cc, FILTER_VALIDATE_EMAIL)) {
  5746. continue;
  5747. }
  5748. if ($exclude !== '' && $cc === $exclude) {
  5749. continue;
  5750. }
  5751. $mail->addCC($cc);
  5752. }
  5753. }
  5754. $mail->isHTML(true);
  5755. $mail->Subject = $subject;
  5756. $mail->Body = $htmlBody;
  5757. $mail->send();
  5758. }
  5759. /**
  5760. * @param array<string, mixed> $row
  5761. */
  5762. protected function mprocPersistEmailSendLog(array $row): void
  5763. {
  5764. try {
  5765. $data = [
  5766. 'from_email' => (string)($row['from_email'] ?? ''),
  5767. 'to_email' => (string)($row['to_email'] ?? ''),
  5768. 'send_time' => date('Y-m-d H:i:s'),
  5769. 'scene' => (string)($row['scene'] ?? ''),
  5770. 'order_batch_no' => (string)($row['order_batch_no'] ?? ''),
  5771. 'ccydh' => (string)($row['ccydh'] ?? ''),
  5772. 'company_name' => (string)($row['company_name'] ?? ''),
  5773. 'mail_subject' => (string)($row['mail_subject'] ?? ''),
  5774. 'status' => (int)($row['status'] ?? 0),
  5775. 'fail_reason' => (string)($row['fail_reason'] ?? ''),
  5776. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  5777. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  5778. 'admin_id' => (int)($row['admin_id'] ?? 0),
  5779. 'admin_name' => (string)($row['admin_name'] ?? ''),
  5780. ];
  5781. try {
  5782. Db::table('purchase_email_send_log')->insert($data);
  5783. } catch (\Throwable $e) {
  5784. if (stripos($e->getMessage(), 'order_batch_no') === false) {
  5785. throw $e;
  5786. }
  5787. unset($data['order_batch_no']);
  5788. Db::table('purchase_email_send_log')->insert($data);
  5789. }
  5790. } catch (\Throwable $e) {
  5791. Log::record('mprocPersistEmailSendLog: ' . $e->getMessage(), 'error');
  5792. }
  5793. }
  5794. /**
  5795. * 质量+交货均完成后,按最新详情重存存证 PDF
  5796. *
  5797. * @param array<int, mixed> $poRows
  5798. */
  5799. protected function mprocRefreshCompletedArchivePdfs(array $poRows): void
  5800. {
  5801. $done = [];
  5802. foreach ($poRows as $po) {
  5803. if (!is_array($po)) {
  5804. continue;
  5805. }
  5806. $sid = (int)($po['scydgy_id'] ?? 0);
  5807. if ($sid <= 0 || isset($done[$sid])) {
  5808. continue;
  5809. }
  5810. $done[$sid] = true;
  5811. try {
  5812. \app\admin\controller\Procuremen::regenerateArchivePdfWithoutAuth($sid, true);
  5813. } catch (\Throwable $e) {
  5814. Log::record('完结存证PDF刷新失败 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  5815. }
  5816. }
  5817. }
  5818. /**
  5819. * @return array<int, array<string, mixed>>
  5820. */
  5821. /**
  5822. * 交货/质量评分作用域键:订单号 + 批次号 + 中标供应商
  5823. * (同订单号下不同批次/供应商必须分开,避免串单)
  5824. */
  5825. protected function mprocBuildScoreGroupKey(string $ccydh, string $batchNo, string $companyName): string
  5826. {
  5827. $ccydh = trim($ccydh);
  5828. $batchNo = trim($batchNo);
  5829. $companyName = trim($companyName);
  5830. return $ccydh . "\x1e" . ($batchNo !== '' ? $batchNo : '_') . "\x1e" . ($companyName !== '' ? $companyName : '_');
  5831. }
  5832. /**
  5833. * @param array<string, mixed> $po
  5834. */
  5835. protected function mprocResolvePoBatchNo(array $po): string
  5836. {
  5837. foreach (['order_batch_no', 'issue_batch_no'] as $k) {
  5838. $v = trim((string)($po[$k] ?? ''));
  5839. if ($v !== '') {
  5840. return $v;
  5841. }
  5842. }
  5843. return '';
  5844. }
  5845. /**
  5846. * 已审核可评分主单:仅限同一订单号 + 同一批次 + 同一中标供应商
  5847. *
  5848. * @return array<int, array<string, mixed>>
  5849. */
  5850. protected function mprocLoadApprovedPoRowsForScore(string $ccydh, int $sid, string $batchNo = '', string $companyName = ''): array
  5851. {
  5852. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  5853. $approvedIn = implode(',', array_map(static function ($v) {
  5854. return "'" . str_replace("'", "''", (string)$v) . "'";
  5855. }, $approvedVals));
  5856. try {
  5857. $q = Db::table('purchase_order')
  5858. ->where('scydgy_id', '>', 0)
  5859. ->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%\')')
  5860. ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
  5861. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  5862. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  5863. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,delivery_deadline,pick_company_name,pick_time,wflow_status,status,order_batch_no');
  5864. if ($ccydh !== '') {
  5865. $q->where('CCYDH', $ccydh);
  5866. } elseif ($sid > 0) {
  5867. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH,order_batch_no,pick_company_name')->find();
  5868. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  5869. if ($ccydh === '') {
  5870. $this->error('缺少订单号');
  5871. }
  5872. if ($batchNo === '' && is_array($one)) {
  5873. $batchNo = $this->mprocResolvePoBatchNo($one);
  5874. }
  5875. if ($companyName === '' && is_array($one)) {
  5876. $companyName = trim((string)($one['pick_company_name'] ?? ''));
  5877. }
  5878. $q->where('CCYDH', $ccydh);
  5879. } else {
  5880. $this->error('缺少订单号');
  5881. }
  5882. $poRows = $q->order('id', 'asc')->select();
  5883. } catch (\Throwable $e) {
  5884. // 兼容缺 order_batch_no 列
  5885. try {
  5886. $q = Db::table('purchase_order')
  5887. ->where('scydgy_id', '>', 0)
  5888. ->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%\')')
  5889. ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
  5890. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  5891. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  5892. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,delivery_deadline,pick_company_name,pick_time,wflow_status,status');
  5893. if ($ccydh !== '') {
  5894. $q->where('CCYDH', $ccydh);
  5895. } elseif ($sid > 0) {
  5896. $one = Db::table('purchase_order')->where('scydgy_id', $sid)->field('CCYDH,pick_company_name')->find();
  5897. $ccydh = is_array($one) ? trim((string)($one['CCYDH'] ?? '')) : '';
  5898. if ($ccydh === '') {
  5899. $this->error('缺少订单号');
  5900. }
  5901. if ($companyName === '' && is_array($one)) {
  5902. $companyName = trim((string)($one['pick_company_name'] ?? ''));
  5903. }
  5904. $q->where('CCYDH', $ccydh);
  5905. } else {
  5906. $this->error('缺少订单号');
  5907. }
  5908. $poRows = $q->order('id', 'asc')->select();
  5909. } catch (\Throwable $e2) {
  5910. $poRows = [];
  5911. }
  5912. }
  5913. if (!is_array($poRows) || $poRows === []) {
  5914. $this->error('未找到可评分的已审核订单');
  5915. }
  5916. // 用锚点工序补齐批次/供应商作用域
  5917. if ($sid > 0 && ($batchNo === '' || $companyName === '')) {
  5918. foreach ($poRows as $po) {
  5919. if (!is_array($po) || (int)($po['scydgy_id'] ?? 0) !== $sid) {
  5920. continue;
  5921. }
  5922. if ($batchNo === '') {
  5923. $batchNo = $this->mprocResolvePoBatchNo($po);
  5924. }
  5925. if ($companyName === '') {
  5926. $companyName = trim((string)($po['pick_company_name'] ?? ''));
  5927. }
  5928. break;
  5929. }
  5930. }
  5931. $scopeKey = '';
  5932. if ($batchNo !== '' || $companyName !== '' || $sid > 0) {
  5933. // 若仍缺公司名,用 sid 所在行;再不行用首行(兼容仅一单)
  5934. if ($companyName === '' && $sid <= 0 && count($poRows) === 1 && is_array($poRows[0])) {
  5935. $companyName = trim((string)($poRows[0]['pick_company_name'] ?? ''));
  5936. $batchNo = $batchNo !== '' ? $batchNo : $this->mprocResolvePoBatchNo($poRows[0]);
  5937. }
  5938. $scopeKey = $this->mprocBuildScoreGroupKey($ccydh, $batchNo, $companyName);
  5939. }
  5940. $filtered = [];
  5941. $groupKeys = [];
  5942. foreach ($poRows as $po) {
  5943. if (!is_array($po)) {
  5944. continue;
  5945. }
  5946. $rowBatch = $this->mprocResolvePoBatchNo($po);
  5947. $rowCompany = trim((string)($po['pick_company_name'] ?? ''));
  5948. $rowCcydh = trim((string)($po['CCYDH'] ?? $ccydh));
  5949. $gk = $this->mprocBuildScoreGroupKey($rowCcydh, $rowBatch, $rowCompany);
  5950. $groupKeys[$gk] = true;
  5951. if ($scopeKey !== '' && $gk !== $scopeKey) {
  5952. continue;
  5953. }
  5954. $filtered[] = $po;
  5955. }
  5956. if ($scopeKey === '' && count($groupKeys) > 1) {
  5957. $this->error('该订单存在多个批次或中标供应商,请刷新页面后按卡片分别填写');
  5958. }
  5959. if ($filtered === []) {
  5960. $this->error('未找到可评分的已审核订单(批次/供应商不匹配)');
  5961. }
  5962. return $filtered;
  5963. }
  5964. /**
  5965. * 操作人展示名:优先后台管理员昵称(名称),避免记成登录账号
  5966. *
  5967. * @param array<string, mixed> $user
  5968. */
  5969. protected function mprocResolveAdminDisplayName(array $user, int $adminId): string
  5970. {
  5971. $adminName = '';
  5972. if ($adminId > 0) {
  5973. try {
  5974. $adminRow = Db::name('admin')->where('id', $adminId)->field('nickname,username')->find();
  5975. if (is_array($adminRow)) {
  5976. $nick = trim((string)($adminRow['nickname'] ?? ''));
  5977. $uname = trim((string)($adminRow['username'] ?? ''));
  5978. if ($nick !== '') {
  5979. $adminName = $nick;
  5980. } elseif ($uname !== '') {
  5981. $adminName = $uname;
  5982. }
  5983. }
  5984. } catch (\Throwable $e) {
  5985. }
  5986. }
  5987. if ($adminName === '') {
  5988. $adminName = trim((string)($user['nickname'] ?? ''));
  5989. }
  5990. if ($adminName === '') {
  5991. $adminName = trim((string)($user['username'] ?? ''));
  5992. }
  5993. return $adminName !== '' ? $adminName : '管理员';
  5994. }
  5995. /**
  5996. * @param array<int, mixed> $poRows
  5997. */
  5998. protected function mprocSyncMonthlyAfterInboundScore(array $poRows, string $now): void
  5999. {
  6000. $companyName = '';
  6001. foreach ($poRows as $po) {
  6002. if (!is_array($po)) {
  6003. continue;
  6004. }
  6005. $companyName = trim((string)($po['pick_company_name'] ?? ''));
  6006. if ($companyName !== '') {
  6007. break;
  6008. }
  6009. }
  6010. $scoreYm = date('Y-m', strtotime($now) ?: time());
  6011. if ($companyName === '') {
  6012. return;
  6013. }
  6014. try {
  6015. \app\common\library\ProcuremenSupplierScore::syncQualityScoreFromInbound($scoreYm, $companyName);
  6016. } catch (\Throwable $e) {
  6017. Log::record('inboundscoresave quality sync: ' . $e->getMessage(), 'error');
  6018. }
  6019. }
  6020. /**
  6021. * @return array<string, mixed>
  6022. */
  6023. protected function mprocRequireAdminUser(): array
  6024. {
  6025. $user = $this->mprocGetUser();
  6026. if (!$user) {
  6027. $this->error('请先登录', url('index/index/login'));
  6028. }
  6029. if (empty($user['is_admin'])) {
  6030. $this->error('仅系统管理员可操作');
  6031. }
  6032. return $user;
  6033. }
  6034. /** 质检中心角色组 id */
  6035. protected function mprocResolveMobileQualityGroupId(): int
  6036. {
  6037. $id = (int)Config::get('mproc.mobile_quality_group_id');
  6038. if ($id > 0) {
  6039. return $id;
  6040. }
  6041. try {
  6042. $found = Db::name('auth_group')
  6043. ->where('name', '质检中心')
  6044. ->where('status', 'normal')
  6045. ->order('id', 'asc')
  6046. ->value('id');
  6047. $id = (int)$found;
  6048. } catch (\Throwable $e) {
  6049. $id = 0;
  6050. }
  6051. return $id > 0 ? $id : 16;
  6052. }
  6053. /** 生产部/生产员角色组 id */
  6054. protected function mprocResolveMobileDeliveryGroupId(): int
  6055. {
  6056. $id = (int)Config::get('mproc.mobile_delivery_group_id');
  6057. if ($id > 0) {
  6058. return $id;
  6059. }
  6060. try {
  6061. $found = Db::name('auth_group')
  6062. ->where('name', 'in', ['生产部', '生产员'])
  6063. ->where('status', 'normal')
  6064. ->order('id', 'asc')
  6065. ->value('id');
  6066. $id = (int)$found;
  6067. } catch (\Throwable $e) {
  6068. $id = 0;
  6069. }
  6070. return $id > 0 ? $id : 15;
  6071. }
  6072. /** 业务员(手机端新增询价)角色组 id */
  6073. protected function mprocResolveMobileRfqGroupId(): int
  6074. {
  6075. $id = (int)Config::get('mproc.mobile_rfq_group_id');
  6076. if ($id <= 0) {
  6077. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  6078. }
  6079. if ($id > 0) {
  6080. return $id;
  6081. }
  6082. try {
  6083. $found = Db::name('auth_group')
  6084. ->where('name', '业务员')
  6085. ->where('status', 'normal')
  6086. ->order('id', 'asc')
  6087. ->value('id');
  6088. $id = (int)$found;
  6089. } catch (\Throwable $e) {
  6090. $id = 0;
  6091. }
  6092. return $id > 0 ? $id : 12;
  6093. }
  6094. /**
  6095. * @return int[]
  6096. */
  6097. protected function mprocAdminGroupIds(int $adminId): array
  6098. {
  6099. if ($adminId <= 0) {
  6100. return [];
  6101. }
  6102. try {
  6103. $ids = Db::name('auth_group_access')->where('uid', $adminId)->column('group_id');
  6104. } catch (\Throwable $e) {
  6105. return [];
  6106. }
  6107. if (!is_array($ids)) {
  6108. return [];
  6109. }
  6110. return array_values(array_unique(array_filter(array_map('intval', $ids))));
  6111. }
  6112. /** 超管(角色组 rules=*)或协同「管理员」组 */
  6113. protected function mprocAdminIsMobileSuper(int $adminId): bool
  6114. {
  6115. if ($adminId <= 0) {
  6116. return false;
  6117. }
  6118. try {
  6119. $rows = Db::name('auth_group_access')
  6120. ->alias('aga')
  6121. ->join('auth_group ag', 'aga.group_id = ag.id')
  6122. ->where('aga.uid', $adminId)
  6123. ->field('ag.id,ag.rules')
  6124. ->select();
  6125. } catch (\Throwable $e) {
  6126. return false;
  6127. }
  6128. if (!is_array($rows)) {
  6129. return false;
  6130. }
  6131. foreach ($rows as $r) {
  6132. if (!is_array($r)) {
  6133. continue;
  6134. }
  6135. if (trim((string)($r['rules'] ?? '')) === '*') {
  6136. return true;
  6137. }
  6138. // 供应链协同「管理员」组
  6139. if ((int)($r['id'] ?? 0) === 11) {
  6140. return true;
  6141. }
  6142. }
  6143. return false;
  6144. }
  6145. /**
  6146. * @param array<string, mixed> $user
  6147. * @param string $role quality|delivery|rfq
  6148. */
  6149. protected function mprocAdminHasMobileRole(array $user, string $role): bool
  6150. {
  6151. if (empty($user['is_admin'])) {
  6152. return false;
  6153. }
  6154. $adminId = (int)($user['admin_id'] ?? 0);
  6155. if ($adminId <= 0) {
  6156. return false;
  6157. }
  6158. if ($this->mprocAdminIsMobileSuper($adminId)) {
  6159. return true;
  6160. }
  6161. $gids = $this->mprocAdminGroupIds($adminId);
  6162. if ($role === 'quality') {
  6163. $need = $this->mprocResolveMobileQualityGroupId();
  6164. return $need > 0 && in_array($need, $gids, true);
  6165. }
  6166. if ($role === 'delivery') {
  6167. $need = $this->mprocResolveMobileDeliveryGroupId();
  6168. return $need > 0 && in_array($need, $gids, true);
  6169. }
  6170. if ($role === 'rfq') {
  6171. $need = $this->mprocResolveMobileRfqGroupId();
  6172. return $need > 0 && in_array($need, $gids, true);
  6173. }
  6174. return false;
  6175. }
  6176. /**
  6177. * @return array<string, mixed>
  6178. */
  6179. protected function mprocRequireRfqUser(): array
  6180. {
  6181. $user = $this->mprocRequireAdminUser();
  6182. if (!$this->mprocAdminHasMobileRole($user, 'rfq')) {
  6183. $this->error('仅业务员账号可新增订单询价');
  6184. }
  6185. return $user;
  6186. }
  6187. /**
  6188. * @return array<string, mixed>
  6189. */
  6190. protected function mprocRequireQualityUser(): array
  6191. {
  6192. $user = $this->mprocRequireAdminUser();
  6193. if (!$this->mprocAdminHasMobileRole($user, 'quality')) {
  6194. $this->error('仅质检中心账号可操作质量评分');
  6195. }
  6196. return $user;
  6197. }
  6198. /**
  6199. * @return array<string, mixed>
  6200. */
  6201. protected function mprocRequireDeliveryUser(): array
  6202. {
  6203. $user = $this->mprocRequireAdminUser();
  6204. if (!$this->mprocAdminHasMobileRole($user, 'delivery')) {
  6205. $this->error('仅生产部账号可操作交货情况');
  6206. }
  6207. return $user;
  6208. }
  6209. protected function mprocEnsureInboundScoreTable(): void
  6210. {
  6211. static $ok = false;
  6212. if ($ok) {
  6213. return;
  6214. }
  6215. try {
  6216. Db::query('SELECT 1 FROM `purchase_order_inbound_score` LIMIT 1');
  6217. } catch (\Throwable $e) {
  6218. try {
  6219. Db::execute("CREATE TABLE IF NOT EXISTS `purchase_order_inbound_score` (
  6220. `id` int unsigned NOT NULL AUTO_INCREMENT,
  6221. `scydgy_id` int NOT NULL DEFAULT 0 COMMENT '工序ID',
  6222. `purchase_order_id` int unsigned NOT NULL DEFAULT 0 COMMENT 'purchase_order.id',
  6223. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  6224. `cyjmc` varchar(255) NOT NULL DEFAULT '' COMMENT '印件名称',
  6225. `cgymc` varchar(255) NOT NULL DEFAULT '' COMMENT '工序名称',
  6226. `company_name` varchar(255) NOT NULL DEFAULT '' COMMENT '中标供应商',
  6227. `result` varchar(16) NOT NULL DEFAULT '' COMMENT '合格/不合格',
  6228. `delivery_status` varchar(16) NOT NULL DEFAULT '' COMMENT '交货情况 准时/滞后',
  6229. `delivery_date` date DEFAULT NULL COMMENT '交货日期',
  6230. `storage_location` varchar(64) NOT NULL DEFAULT '' COMMENT '库位',
  6231. `customer_complaint` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '客户是否投诉 1=是',
  6232. `complaint_remark` varchar(500) NOT NULL DEFAULT '' COMMENT '投诉说明',
  6233. `order_interrupt` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '订单是否中断 1=是',
  6234. `admin_id` int unsigned NOT NULL DEFAULT 0,
  6235. `admin_name` varchar(64) NOT NULL DEFAULT '',
  6236. `delivery_admin_id` int unsigned NOT NULL DEFAULT 0 COMMENT '交货确认人ID',
  6237. `delivery_admin_name` varchar(64) NOT NULL DEFAULT '' COMMENT '交货确认人',
  6238. `remark` varchar(500) NOT NULL DEFAULT '',
  6239. `createtime` datetime DEFAULT NULL,
  6240. `updatetime` datetime DEFAULT NULL,
  6241. PRIMARY KEY (`id`),
  6242. UNIQUE KEY `uk_scydgy_id` (`scydgy_id`),
  6243. KEY `idx_ccydh` (`ccydh`),
  6244. KEY `idx_result` (`result`),
  6245. KEY `idx_updatetime` (`updatetime`)
  6246. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='质量评分'");
  6247. } catch (\Throwable $e2) {
  6248. Log::record('mprocEnsureInboundScoreTable: ' . $e2->getMessage(), 'error');
  6249. return;
  6250. }
  6251. }
  6252. foreach ([
  6253. 'delivery_status' => "ADD COLUMN `delivery_status` varchar(16) NOT NULL DEFAULT '' COMMENT '交货情况 准时/滞后' AFTER `result`",
  6254. 'delivery_date' => "ADD COLUMN `delivery_date` date DEFAULT NULL COMMENT '交货日期' AFTER `delivery_status`",
  6255. 'storage_location' => "ADD COLUMN `storage_location` varchar(64) NOT NULL DEFAULT '' COMMENT '库位' AFTER `delivery_date`",
  6256. 'customer_complaint' => "ADD COLUMN `customer_complaint` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '客户是否投诉 1=是' AFTER `storage_location`",
  6257. 'complaint_remark' => "ADD COLUMN `complaint_remark` varchar(500) NOT NULL DEFAULT '' COMMENT '投诉说明' AFTER `customer_complaint`",
  6258. 'order_interrupt' => "ADD COLUMN `order_interrupt` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '订单是否中断 1=是' AFTER `complaint_remark`",
  6259. 'delivery_admin_id' => "ADD COLUMN `delivery_admin_id` int unsigned NOT NULL DEFAULT 0 COMMENT '交货确认人ID' AFTER `admin_name`",
  6260. 'delivery_admin_name'=> "ADD COLUMN `delivery_admin_name` varchar(64) NOT NULL DEFAULT '' COMMENT '交货确认人' AFTER `delivery_admin_id`",
  6261. 'arrival_notify_staff' => "ADD COLUMN `arrival_notify_staff` varchar(500) NOT NULL DEFAULT '' COMMENT '已到货已通知人员' AFTER `delivery_admin_name`",
  6262. 'arrival_notify_time' => "ADD COLUMN `arrival_notify_time` datetime DEFAULT NULL COMMENT '已到货通知时间' AFTER `arrival_notify_staff`",
  6263. ] as $col => $ddl) {
  6264. try {
  6265. $cols = Db::query("SHOW COLUMNS FROM `purchase_order_inbound_score` LIKE '{$col}'");
  6266. if (!is_array($cols) || $cols === []) {
  6267. Db::execute("ALTER TABLE `purchase_order_inbound_score` {$ddl}");
  6268. }
  6269. } catch (\Throwable $e) {
  6270. Log::record("mprocEnsureInboundScoreTable {$col}: " . $e->getMessage(), 'error');
  6271. }
  6272. }
  6273. $ok = true;
  6274. }
  6275. /**
  6276. * 质量评分列表:按订单号合并(一单一行,工序顿号合并)
  6277. * tab=pending 待评分;scored 已评分(仅当前管理员操作过的)
  6278. *
  6279. * @return array<int, array<string, mixed>>
  6280. */
  6281. protected function mprocLoadInboundScoreRows(string $tab, string $keyword = '', int $adminId = 0, string $scope = 'quality'): array
  6282. {
  6283. $this->mprocEnsureInboundScoreTable();
  6284. $keyword = trim($keyword);
  6285. $scope = $scope === 'delivery' ? 'delivery' : 'quality';
  6286. if (!in_array($tab, ['pending', 'scored', 'pass', 'fail'], true)) {
  6287. $tab = 'pending';
  6288. }
  6289. if ($tab === 'pass' || $tab === 'fail') {
  6290. $tab = 'scored';
  6291. }
  6292. try {
  6293. $approvedVals = ProcuremenStatus::wflowApprovedValues();
  6294. $approvedIn = implode(',', array_map(static function ($v) {
  6295. return "'" . str_replace("'", "''", (string)$v) . "'";
  6296. }, $approvedVals));
  6297. $poRows = Db::table('purchase_order')
  6298. ->where('scydgy_id', '>', 0)
  6299. ->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%\')')
  6300. ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
  6301. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  6302. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  6303. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,CCLBMMC,CDW,This_quantity,NGZL,delivery_deadline,pick_company_name,pick_time,wflow_status,status,order_batch_no')
  6304. ->order('pick_time', 'desc')
  6305. ->order('id', 'asc')
  6306. ->limit(800)
  6307. ->select();
  6308. } catch (\Throwable $e) {
  6309. try {
  6310. $poRows = Db::table('purchase_order')
  6311. ->where('scydgy_id', '>', 0)
  6312. ->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%\')')
  6313. ->whereRaw("pick_time IS NOT NULL AND CAST(pick_time AS CHAR) NOT LIKE '0000-00-00%' AND TRIM(CAST(pick_time AS CHAR)) <> ''")
  6314. ->whereRaw("pick_company_name IS NOT NULL AND TRIM(pick_company_name) <> ''")
  6315. ->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . $approvedIn . ')')
  6316. ->field('id,scydgy_id,CCYDH,CYJMC,CGYMC,CCLBMMC,CDW,This_quantity,NGZL,delivery_deadline,pick_company_name,pick_time,wflow_status,status')
  6317. ->order('pick_time', 'desc')
  6318. ->order('id', 'asc')
  6319. ->limit(800)
  6320. ->select();
  6321. } catch (\Throwable $e2) {
  6322. Log::record('mprocLoadInboundScoreRows: ' . $e2->getMessage(), 'error');
  6323. return [];
  6324. }
  6325. }
  6326. if (!is_array($poRows) || $poRows === []) {
  6327. return [];
  6328. }
  6329. $sids = [];
  6330. foreach ($poRows as $po) {
  6331. if (!is_array($po)) {
  6332. continue;
  6333. }
  6334. $sid = (int)($po['scydgy_id'] ?? 0);
  6335. if ($sid > 0) {
  6336. $sids[$sid] = true;
  6337. }
  6338. }
  6339. $scoreMap = [];
  6340. if ($sids !== []) {
  6341. try {
  6342. $scores = Db::table('purchase_order_inbound_score')
  6343. ->where('scydgy_id', 'in', array_keys($sids))
  6344. ->field('scydgy_id,result,delivery_status,delivery_date,storage_location,customer_complaint,complaint_remark,order_interrupt,remark,admin_id,admin_name,delivery_admin_id,delivery_admin_name,arrival_notify_staff,arrival_notify_time,updatetime,createtime')
  6345. ->select();
  6346. } catch (\Throwable $e) {
  6347. try {
  6348. $scores = Db::table('purchase_order_inbound_score')
  6349. ->where('scydgy_id', 'in', array_keys($sids))
  6350. ->field('scydgy_id,result,delivery_status,delivery_date,storage_location,customer_complaint,complaint_remark,order_interrupt,remark,admin_id,admin_name,delivery_admin_id,delivery_admin_name,updatetime,createtime')
  6351. ->select();
  6352. } catch (\Throwable $e2) {
  6353. try {
  6354. $scores = Db::table('purchase_order_inbound_score')
  6355. ->where('scydgy_id', 'in', array_keys($sids))
  6356. ->field('scydgy_id,result,delivery_status,delivery_date,customer_complaint,complaint_remark,order_interrupt,remark,admin_id,admin_name,updatetime,createtime')
  6357. ->select();
  6358. } catch (\Throwable $e3) {
  6359. try {
  6360. $scores = Db::table('purchase_order_inbound_score')
  6361. ->where('scydgy_id', 'in', array_keys($sids))
  6362. ->field('scydgy_id,result,delivery_status,customer_complaint,order_interrupt,remark,admin_id,admin_name,updatetime,createtime')
  6363. ->select();
  6364. } catch (\Throwable $e4) {
  6365. $scores = [];
  6366. }
  6367. }
  6368. }
  6369. }
  6370. if (is_array($scores)) {
  6371. foreach ($scores as $sc) {
  6372. if (!is_array($sc)) {
  6373. continue;
  6374. }
  6375. $sid = (int)($sc['scydgy_id'] ?? 0);
  6376. if ($sid > 0) {
  6377. $scoreMap[$sid] = $sc;
  6378. }
  6379. }
  6380. }
  6381. }
  6382. /** @var array<string, array<string, mixed>> $groups */
  6383. $groups = [];
  6384. foreach ($poRows as $po) {
  6385. if (!is_array($po)) {
  6386. continue;
  6387. }
  6388. $sid = (int)($po['scydgy_id'] ?? 0);
  6389. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  6390. if ($sid <= 0 || $ccydh === '') {
  6391. continue;
  6392. }
  6393. $batchNo = $this->mprocResolvePoBatchNo($po);
  6394. $company = trim((string)($po['pick_company_name'] ?? ''));
  6395. $groupKey = $this->mprocBuildScoreGroupKey($ccydh, $batchNo, $company);
  6396. if (!isset($groups[$groupKey])) {
  6397. $pickRaw = trim((string)($po['pick_time'] ?? ''));
  6398. $pickDisp = $pickRaw !== '' ? \app\common\library\ProcuremenTime::formatDisplayDateTime($pickRaw) : '';
  6399. $groups[$groupKey] = [
  6400. 'CCYDH' => $ccydh,
  6401. 'order_batch_no' => $batchNo,
  6402. 'scydgy_id' => $sid,
  6403. 'scydgy_ids' => [],
  6404. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  6405. 'CCLBMMC' => trim((string)($po['CCLBMMC'] ?? '')),
  6406. 'CGYMC_list' => [],
  6407. 'qty_list' => [],
  6408. 'pick_company_name' => $company,
  6409. 'pick_time' => $pickDisp !== '' ? $pickDisp : $pickRaw,
  6410. 'pick_time_raw' => $pickRaw,
  6411. 'process_count' => 0,
  6412. 'results' => [],
  6413. 'score_admin_ids' => [],
  6414. 'score_time_raw' => '',
  6415. 'score_operator' => '',
  6416. 'quality_operator' => '',
  6417. 'customer_complaint'=> 0,
  6418. 'complaint_remark' => '',
  6419. 'order_interrupt' => 0,
  6420. 'delivery_status' => '',
  6421. 'delivery_date' => '',
  6422. 'delivery_deadline' => '',
  6423. 'storage_location' => '',
  6424. 'remark' => '',
  6425. 'arrival_notify_staff' => '',
  6426. 'arrival_notify_time' => '',
  6427. ];
  6428. }
  6429. $g = &$groups[$groupKey];
  6430. $g['scydgy_ids'][] = $sid;
  6431. $g['process_count']++;
  6432. if ($g['scydgy_id'] <= 0) {
  6433. $g['scydgy_id'] = $sid;
  6434. }
  6435. if ($g['CYJMC'] === '') {
  6436. $g['CYJMC'] = trim((string)($po['CYJMC'] ?? ''));
  6437. }
  6438. if ($g['CCLBMMC'] === '') {
  6439. $g['CCLBMMC'] = trim((string)($po['CCLBMMC'] ?? ''));
  6440. }
  6441. if ($g['pick_company_name'] === '') {
  6442. $g['pick_company_name'] = $company;
  6443. }
  6444. if ($g['order_batch_no'] === '' && $batchNo !== '') {
  6445. $g['order_batch_no'] = $batchNo;
  6446. }
  6447. if ($g['delivery_deadline'] === '') {
  6448. $g['delivery_deadline'] = $this->mprocFormatYmdValue($po['delivery_deadline'] ?? $po['Delivery_deadline'] ?? '');
  6449. }
  6450. $pt = trim((string)($po['pick_time'] ?? ''));
  6451. if ($pt !== '' && ($g['pick_time_raw'] === '' || strcmp($pt, $g['pick_time_raw']) > 0)) {
  6452. $g['pick_time_raw'] = $pt;
  6453. $disp = \app\common\library\ProcuremenTime::formatDisplayDateTime($pt);
  6454. $g['pick_time'] = $disp !== '' ? $disp : $pt;
  6455. }
  6456. $gymc = trim((string)($po['CGYMC'] ?? ''));
  6457. if ($gymc !== '' && !in_array($gymc, $g['CGYMC_list'], true)) {
  6458. $g['CGYMC_list'][] = $gymc;
  6459. }
  6460. $qDisp = $this->mprocResolveDisplayThisQuantity($po);
  6461. if ($qDisp !== '' && !in_array($qDisp, $g['qty_list'], true)) {
  6462. $g['qty_list'][] = $qDisp;
  6463. }
  6464. $sc = $scoreMap[$sid] ?? null;
  6465. $res = is_array($sc) ? trim((string)($sc['result'] ?? '')) : '';
  6466. $g['results'][] = $res;
  6467. if (is_array($sc)) {
  6468. $ns = trim((string)($sc['arrival_notify_staff'] ?? ''));
  6469. if ($ns !== '') {
  6470. $g['arrival_notify_staff'] = $this->mprocMergeArrivalNotifyStaffNames(
  6471. (string)($g['arrival_notify_staff'] ?? ''),
  6472. preg_split('/[、,,;;]+/u', $ns) ?: []
  6473. );
  6474. }
  6475. $nt = trim((string)($sc['arrival_notify_time'] ?? ''));
  6476. if ($nt !== '' && ((string)($g['arrival_notify_time'] ?? '') === '' || strcmp($nt, (string)$g['arrival_notify_time']) > 0)) {
  6477. $g['arrival_notify_time'] = $nt;
  6478. }
  6479. }
  6480. if (is_array($sc) && $res !== '') {
  6481. $aid = (int)($sc['admin_id'] ?? 0);
  6482. if ($aid > 0) {
  6483. $g['score_admin_ids'][$aid] = true;
  6484. }
  6485. $qOp = trim((string)($sc['admin_name'] ?? ''));
  6486. if ($qOp !== '') {
  6487. $g['quality_operator'] = $qOp;
  6488. }
  6489. if ((int)($sc['customer_complaint'] ?? 0) === 1) {
  6490. $g['customer_complaint'] = 1;
  6491. }
  6492. $crm = trim((string)($sc['complaint_remark'] ?? ''));
  6493. if ($crm !== '' && $g['complaint_remark'] === '') {
  6494. $g['complaint_remark'] = $crm;
  6495. }
  6496. if ((int)($sc['order_interrupt'] ?? 0) === 1) {
  6497. $g['order_interrupt'] = 1;
  6498. }
  6499. $ds = trim((string)($sc['delivery_status'] ?? ''));
  6500. if ($ds !== '' && $g['delivery_status'] === '') {
  6501. $g['delivery_status'] = $ds;
  6502. }
  6503. if ($ds !== '' && $g['score_operator'] === '') {
  6504. $op = trim((string)($sc['delivery_admin_name'] ?? ''));
  6505. if ($op === '') {
  6506. $op = trim((string)($sc['admin_name'] ?? ''));
  6507. }
  6508. if ($op !== '') {
  6509. $g['score_operator'] = $op;
  6510. }
  6511. }
  6512. $dd = trim((string)($sc['delivery_date'] ?? ''));
  6513. if ($dd !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dd, $mdd) && $g['delivery_date'] === '') {
  6514. $g['delivery_date'] = $mdd[1];
  6515. }
  6516. $loc = trim((string)($sc['storage_location'] ?? ''));
  6517. if ($loc !== '' && $g['storage_location'] === '') {
  6518. $g['storage_location'] = $loc;
  6519. }
  6520. $rm = trim((string)($sc['remark'] ?? ''));
  6521. if ($rm !== '' && $g['remark'] === '') {
  6522. $g['remark'] = $rm;
  6523. }
  6524. $st = trim((string)($sc['updatetime'] ?? ''));
  6525. if ($st === '') {
  6526. $st = trim((string)($sc['createtime'] ?? ''));
  6527. }
  6528. if ($st !== '' && ($g['score_time_raw'] === '' || strcmp($st, $g['score_time_raw']) > 0)) {
  6529. $g['score_time_raw'] = $st;
  6530. $op = trim((string)($sc['delivery_admin_name'] ?? ''));
  6531. if ($op === '') {
  6532. $op = trim((string)($sc['admin_name'] ?? ''));
  6533. }
  6534. if ($op !== '') {
  6535. $g['score_operator'] = $op;
  6536. }
  6537. }
  6538. } elseif (is_array($sc)) {
  6539. // 仅填了交货、尚未质量评分
  6540. $ds = trim((string)($sc['delivery_status'] ?? ''));
  6541. if ($ds !== '' && $g['delivery_status'] === '') {
  6542. $g['delivery_status'] = $ds;
  6543. }
  6544. if ($ds !== '' && $g['score_operator'] === '') {
  6545. $op = trim((string)($sc['delivery_admin_name'] ?? ''));
  6546. if ($op === '') {
  6547. $op = trim((string)($sc['admin_name'] ?? ''));
  6548. }
  6549. if ($op !== '') {
  6550. $g['score_operator'] = $op;
  6551. }
  6552. }
  6553. $dd = trim((string)($sc['delivery_date'] ?? ''));
  6554. if ($dd !== '' && preg_match('/^(\d{4}-\d{2}-\d{2})/', $dd, $mdd) && $g['delivery_date'] === '') {
  6555. $g['delivery_date'] = $mdd[1];
  6556. }
  6557. $loc = trim((string)($sc['storage_location'] ?? ''));
  6558. if ($loc !== '' && $g['storage_location'] === '') {
  6559. $g['storage_location'] = $loc;
  6560. }
  6561. $rm = trim((string)($sc['remark'] ?? ''));
  6562. if ($rm !== '' && $g['remark'] === '') {
  6563. $g['remark'] = $rm;
  6564. }
  6565. $st = trim((string)($sc['updatetime'] ?? ''));
  6566. if ($st === '') {
  6567. $st = trim((string)($sc['createtime'] ?? ''));
  6568. }
  6569. if ($st !== '' && ($g['score_time_raw'] === '' || strcmp($st, $g['score_time_raw']) > 0)) {
  6570. $g['score_time_raw'] = $st;
  6571. $op = trim((string)($sc['delivery_admin_name'] ?? ''));
  6572. if ($op === '') {
  6573. $op = trim((string)($sc['admin_name'] ?? ''));
  6574. }
  6575. if ($op !== '') {
  6576. $g['score_operator'] = $op;
  6577. }
  6578. }
  6579. }
  6580. unset($g);
  6581. }
  6582. $out = [];
  6583. foreach ($groups as $g) {
  6584. $ccydh = (string)($g['CCYDH'] ?? '');
  6585. $gymcList = is_array($g['CGYMC_list'] ?? null) ? $g['CGYMC_list'] : [];
  6586. $company = (string)($g['pick_company_name'] ?? '');
  6587. $batchNo = (string)($g['order_batch_no'] ?? '');
  6588. $cyjmc = (string)($g['CYJMC'] ?? '');
  6589. if ($keyword !== '') {
  6590. $blob = $ccydh . ' ' . $batchNo . ' ' . $cyjmc . ' ' . implode('、', $gymcList) . ' ' . $company;
  6591. if (mb_stripos($blob, $keyword) === false) {
  6592. continue;
  6593. }
  6594. }
  6595. $results = is_array($g['results'] ?? null) ? $g['results'] : [];
  6596. $uniq = [];
  6597. $allScored = true;
  6598. foreach ($results as $r) {
  6599. $r = trim((string)$r);
  6600. if ($r === '') {
  6601. $allScored = false;
  6602. continue;
  6603. }
  6604. $uniq[$r] = true;
  6605. }
  6606. $orderResult = '';
  6607. if ($allScored && count($uniq) === 1) {
  6608. $keys = array_keys($uniq);
  6609. $orderResult = (string)($keys[0] ?? '');
  6610. } elseif ($allScored && count($uniq) > 1) {
  6611. $orderResult = '';
  6612. }
  6613. $deliveryStatus = trim((string)($g['delivery_status'] ?? ''));
  6614. $hasDelivery = ($deliveryStatus === '准时' || $deliveryStatus === '滞后');
  6615. if ($scope === 'quality') {
  6616. if ($tab === 'pending' && $orderResult !== '') {
  6617. continue;
  6618. }
  6619. if ($tab === 'scored') {
  6620. if ($orderResult !== '合格' && $orderResult !== '不合格') {
  6621. continue;
  6622. }
  6623. if ($adminId <= 0) {
  6624. continue;
  6625. }
  6626. $adminIds = is_array($g['score_admin_ids'] ?? null) ? $g['score_admin_ids'] : [];
  6627. if (empty($adminIds[$adminId])) {
  6628. continue;
  6629. }
  6630. }
  6631. } else {
  6632. // 交货:待评=尚未填准时/滞后;已评=已填
  6633. if ($tab === 'pending' && $hasDelivery) {
  6634. continue;
  6635. }
  6636. if ($tab === 'scored' && !$hasDelivery) {
  6637. continue;
  6638. }
  6639. }
  6640. $scoreTimeRaw = trim((string)($g['score_time_raw'] ?? ''));
  6641. if ($scoreTimeRaw === '') {
  6642. $scoreTime = '';
  6643. } elseif ($scope === 'delivery') {
  6644. // 交货确认列表:操作时间仅年月日
  6645. $scoreTime = $this->mprocFormatYmdValue($scoreTimeRaw);
  6646. } else {
  6647. $scoreTime = \app\common\library\ProcuremenTime::formatDisplayDateTime($scoreTimeRaw);
  6648. }
  6649. $qtyList = is_array($g['qty_list'] ?? null) ? $g['qty_list'] : [];
  6650. $out[] = [
  6651. 'CCYDH' => $ccydh,
  6652. 'order_batch_no' => $batchNo,
  6653. 'scydgy_id' => (int)($g['scydgy_id'] ?? 0),
  6654. 'scydgy_ids' => array_values(array_unique(array_map('intval', $g['scydgy_ids'] ?? []))),
  6655. 'CYJMC' => $cyjmc,
  6656. 'CGYMC' => $gymcList !== [] ? implode('、', $gymcList) : '',
  6657. 'CCLBMMC' => (string)($g['CCLBMMC'] ?? ''),
  6658. 'pick_company_name' => $company,
  6659. 'pick_time' => (string)($g['pick_time'] ?? ''),
  6660. 'score_time' => $scoreTime !== '' ? $scoreTime : $scoreTimeRaw,
  6661. 'score_time_raw' => $scoreTimeRaw,
  6662. 'score_operator' => $scope === 'quality'
  6663. ? (string)($g['quality_operator'] ?? '')
  6664. : (string)($g['score_operator'] ?? ''),
  6665. 'process_count' => (int)($g['process_count'] ?? 0),
  6666. 'order_qty' => $qtyList !== [] ? implode('、', $qtyList) : '',
  6667. 'result' => $orderResult,
  6668. 'customer_complaint' => (int)($g['customer_complaint'] ?? 0),
  6669. 'complaint_remark' => (string)($g['complaint_remark'] ?? ''),
  6670. 'order_interrupt' => (int)($g['order_interrupt'] ?? 0),
  6671. 'delivery_status' => (string)($g['delivery_status'] ?? ''),
  6672. 'delivery_date' => (string)($g['delivery_date'] ?? ''),
  6673. 'delivery_deadline' => (string)($g['delivery_deadline'] ?? ''),
  6674. 'storage_location' => (string)($g['storage_location'] ?? ''),
  6675. 'remark' => (string)($g['remark'] ?? ''),
  6676. 'arrival_notify_staff' => (string)($g['arrival_notify_staff'] ?? ''),
  6677. 'arrival_notify_time' => (string)($g['arrival_notify_time'] ?? ''),
  6678. ];
  6679. }
  6680. usort($out, static function ($a, $b) use ($tab) {
  6681. if ($tab === 'scored') {
  6682. $ta = (string)($a['score_time_raw'] ?? '');
  6683. $tb = (string)($b['score_time_raw'] ?? '');
  6684. if ($ta !== $tb) {
  6685. return strcmp($tb, $ta);
  6686. }
  6687. }
  6688. $ta = (string)($a['pick_time'] ?? '');
  6689. $tb = (string)($b['pick_time'] ?? '');
  6690. if ($ta !== $tb) {
  6691. return strcmp($tb, $ta);
  6692. }
  6693. $ca = (string)($a['CCYDH'] ?? '');
  6694. $cb = (string)($b['CCYDH'] ?? '');
  6695. if ($ca !== $cb) {
  6696. return strcmp($cb, $ca);
  6697. }
  6698. $ba = (string)($a['order_batch_no'] ?? '');
  6699. $bb = (string)($b['order_batch_no'] ?? '');
  6700. return strcmp($bb, $ba);
  6701. });
  6702. return $out;
  6703. }
  6704. /**
  6705. * 业务员:新增订单询价页
  6706. */
  6707. public function rfqadd()
  6708. {
  6709. $user = $this->mprocGetUser();
  6710. if (!$user) {
  6711. $uri = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
  6712. $safe = $this->mprocSanitizeRedirectUrl($uri);
  6713. if ($safe !== '') {
  6714. Session::set('mproc_intended_url', $safe);
  6715. }
  6716. $this->redirect($this->mprocBuildLoginUrl($safe));
  6717. return;
  6718. }
  6719. if (empty($user['is_admin']) || !$this->mprocAdminHasMobileRole($user, 'rfq')) {
  6720. $jump = $this->mprocBuildAfterLoginHomeUrl($user);
  6721. if ($jump === '') {
  6722. $this->mprocDropCurrentLogin();
  6723. $this->redirect(url('index/index/login'));
  6724. return;
  6725. }
  6726. $this->redirect($jump);
  6727. return;
  6728. }
  6729. $profile = $this->mprocProfileForUser($user);
  6730. $defaultDept = trim((string)($profile['department'] ?? ''));
  6731. if ($defaultDept === '' || $defaultDept === '业务员' || $defaultDept === '管理员') {
  6732. $defaultDept = '营销中心';
  6733. }
  6734. $statusTab = trim((string)$this->request->get('status', 'pending'));
  6735. if ($statusTab !== 'quoted') {
  6736. $statusTab = 'pending';
  6737. }
  6738. $focusSid = (int)$this->request->param('focus_sid', 0);
  6739. if ($focusSid >= 0) {
  6740. $focusSid = 0;
  6741. }
  6742. $this->view->assign('mprocProfile', $profile);
  6743. $this->view->assign('mprocBootstrapToken', trim((string)($user['token'] ?? '')));
  6744. $this->view->assign('mprocBootstrapKeepHours', $this->mprocKeepHours());
  6745. $this->view->assign('nextOrderCcydh', $this->mprocAllocateManualOrderCcydh());
  6746. $this->view->assign('defaultCclbmmc', $defaultDept);
  6747. $this->view->assign('adminNickname', trim((string)($profile['contact_name'] ?? '')) ?: '业务员');
  6748. $this->view->assign('rfqDeptOptions', $this->mprocLoadRfqDeptNameOptions());
  6749. $this->view->assign('rfqStatusTab', $statusTab);
  6750. $this->view->assign('rfqFocusSid', $focusSid);
  6751. $this->view->assign('rows', $this->mprocLoadRfqAddRows($user, '', $statusTab));
  6752. return $this->view->fetch();
  6753. }
  6754. /**
  6755. * 业务员询价列表 JSON(本人发起或被通知)
  6756. * GET:q、status=pending|quoted
  6757. */
  6758. public function rfqaddlist()
  6759. {
  6760. $user = $this->mprocRequireRfqUser();
  6761. $q = trim((string)$this->request->get('q', ''));
  6762. $status = trim((string)$this->request->get('status', 'pending'));
  6763. if ($status !== 'quoted') {
  6764. $status = 'pending';
  6765. }
  6766. $rows = $this->mprocLoadRfqAddRows($user, $q, $status);
  6767. $this->success('ok', null, ['rows' => $rows, 'total' => count($rows), 'status' => $status]);
  6768. }
  6769. /**
  6770. * 业务员查看询价报价(供应商 + 单价)
  6771. * GET:scydgy_id
  6772. */
  6773. public function rfqaddquotes()
  6774. {
  6775. $user = $this->mprocRequireRfqUser();
  6776. $sid = (int)$this->request->param('scydgy_id', 0);
  6777. if ($sid >= 0) {
  6778. $this->error('仅支持手工询价单');
  6779. }
  6780. $po = $this->mprocLoadAccessibleRfqOrder($user, $sid);
  6781. if (!$po) {
  6782. $this->error('询价单不存在或无权查看');
  6783. }
  6784. $list = [];
  6785. try {
  6786. $rows = Db::table('purchase_order_detail')
  6787. ->where('scydgy_id', $sid)
  6788. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  6789. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')')
  6790. ->field('id,company_name,amount')
  6791. ->order('id', 'asc')
  6792. ->select();
  6793. } catch (\Throwable $e) {
  6794. try {
  6795. $rows = Db::table('purchase_order_detail')
  6796. ->where('scydgy_id', $sid)
  6797. ->field('id,company_name,amount')
  6798. ->order('id', 'asc')
  6799. ->select();
  6800. } catch (\Throwable $e2) {
  6801. $rows = [];
  6802. }
  6803. }
  6804. if (!is_array($rows)) {
  6805. $rows = [];
  6806. }
  6807. foreach ($rows as $row) {
  6808. if (!is_array($row)) {
  6809. continue;
  6810. }
  6811. $amount = trim((string)($row['amount'] ?? ''));
  6812. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  6813. $list[] = [
  6814. 'company_name' => trim((string)($row['company_name'] ?? '')),
  6815. 'amount' => $amount,
  6816. 'amount_text' => $isQuoted ? $amount : '',
  6817. 'is_quoted' => $isQuoted,
  6818. ];
  6819. }
  6820. $this->success('ok', null, [
  6821. 'scydgy_id' => $sid,
  6822. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  6823. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  6824. 'list' => $list,
  6825. ]);
  6826. }
  6827. /**
  6828. * 业务员提交新增订单询价
  6829. * POST:CYJMC、CCLBMMC、CGYMC、CDW、This_quantity、ceilingPrice、CDF、MBZ
  6830. */
  6831. public function rfqaddsave()
  6832. {
  6833. $user = $this->mprocRequireRfqUser();
  6834. if (!$this->request->isPost()) {
  6835. $this->error('请使用 POST');
  6836. }
  6837. $profile = $this->mprocProfileForUser($user);
  6838. $cyjmc = trim((string)$this->request->post('CYJMC', ''));
  6839. $cgymc = trim((string)$this->request->post('CGYMC', ''));
  6840. $cclbmmc = trim((string)$this->request->post('CCLBMMC', ''));
  6841. if ($cyjmc === '') {
  6842. $this->error('请填写印件名称');
  6843. }
  6844. if ($cclbmmc === '') {
  6845. $cclbmmc = trim((string)($profile['department'] ?? ''));
  6846. }
  6847. if ($cclbmmc === '') {
  6848. $cclbmmc = '营销中心';
  6849. }
  6850. $cywyxm = trim((string)($profile['contact_name'] ?? ''));
  6851. if ($cywyxm === '') {
  6852. $cywyxm = trim((string)($user['username'] ?? ''));
  6853. }
  6854. $now = date('Y-m-d H:i:s');
  6855. $lockName = 'procuremen_manual_order_alloc';
  6856. if (!$this->mprocAcquireNamedLock($lockName, 10)) {
  6857. $this->error('系统繁忙,请稍后重试');
  6858. }
  6859. try {
  6860. $ccydh = $this->mprocAllocateManualOrderCcydh();
  6861. $sid = $this->mprocAllocateManualScydgyId();
  6862. $data = [
  6863. 'scydgy_id' => $sid,
  6864. 'CCYDH' => $ccydh,
  6865. 'CYJMC' => $cyjmc,
  6866. 'CGYMC' => $cgymc,
  6867. 'CCLBMMC' => $cclbmmc,
  6868. 'CDW' => trim((string)$this->request->post('CDW', '')),
  6869. 'NGZL' => '',
  6870. 'CDF' => trim((string)$this->request->post('CDF', '')),
  6871. 'cGzzxMc' => '',
  6872. 'MBZ' => trim((string)$this->request->post('MBZ', '')),
  6873. 'cywyxm' => $cywyxm,
  6874. 'notify_salesman' => '',
  6875. 'rfq_salesman_notified' => 0,
  6876. 'rfq_salesman_notify_time' => null,
  6877. 'This_quantity' => trim((string)$this->request->post('This_quantity', '')),
  6878. 'ceilingPrice' => trim((string)$this->request->post('ceilingPrice', '')),
  6879. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  6880. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  6881. 'createtime' => $now,
  6882. 'dStamp' => $now,
  6883. 'dputrecord' => $now,
  6884. ];
  6885. try {
  6886. $this->mprocEnsureRfqSalesmanColumns();
  6887. Db::table('purchase_order')->insert($data);
  6888. } catch (\Throwable $e) {
  6889. $this->error('新增失败:' . $e->getMessage());
  6890. }
  6891. $nextCcydh = $this->mprocAllocateManualOrderCcydh();
  6892. } finally {
  6893. $this->mprocReleaseNamedLock($lockName);
  6894. }
  6895. $this->success('新增成功', '', [
  6896. 'scydgy_id' => $sid,
  6897. 'CCYDH' => $ccydh,
  6898. 'nextOrderCcydh' => $nextCcydh,
  6899. ]);
  6900. }
  6901. /**
  6902. * MySQL 命名锁(跨连接防并发撞号)
  6903. */
  6904. protected function mprocAcquireNamedLock(string $name, int $timeoutSec = 10): bool
  6905. {
  6906. $name = trim($name);
  6907. if ($name === '') {
  6908. return false;
  6909. }
  6910. try {
  6911. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  6912. $rows = Db::query('SELECT GET_LOCK(\'' . $nameSql . '\', ' . max(1, $timeoutSec) . ') AS locked');
  6913. if (!is_array($rows) || $rows === []) {
  6914. return false;
  6915. }
  6916. $v = $rows[0]['locked'] ?? $rows[0]['LOCKED'] ?? null;
  6917. return (int)$v === 1;
  6918. } catch (\Throwable $e) {
  6919. return false;
  6920. }
  6921. }
  6922. protected function mprocReleaseNamedLock(string $name): void
  6923. {
  6924. $name = trim($name);
  6925. if ($name === '') {
  6926. return;
  6927. }
  6928. try {
  6929. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  6930. Db::query('SELECT RELEASE_LOCK(\'' . $nameSql . '\')');
  6931. } catch (\Throwable $e) {
  6932. }
  6933. }
  6934. protected function mprocAllocateManualScydgyId(): int
  6935. {
  6936. try {
  6937. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  6938. $min = (int)$min;
  6939. return $min < 0 ? $min - 1 : -1;
  6940. } catch (\Throwable $e) {
  6941. return -1;
  6942. }
  6943. }
  6944. /**
  6945. * 手工新增订单号:YW + 年月日 + 3 位当日序号(如 YW20260618001)
  6946. * 调用方须在命名锁内执行,避免并发重复
  6947. */
  6948. protected function mprocAllocateManualOrderCcydh(): string
  6949. {
  6950. $prefix = 'YW' . date('Ymd');
  6951. $maxSeq = 0;
  6952. try {
  6953. $rows = Db::table('purchase_order')
  6954. ->where('CCYDH', 'like', $prefix . '%')
  6955. ->column('CCYDH');
  6956. if (is_array($rows)) {
  6957. foreach ($rows as $ccydh) {
  6958. $ccydh = trim((string)$ccydh);
  6959. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3,})$/', $ccydh, $m)) {
  6960. $maxSeq = max($maxSeq, (int)$m[1]);
  6961. }
  6962. }
  6963. }
  6964. } catch (\Throwable $e) {
  6965. }
  6966. $next = $maxSeq + 1;
  6967. $width = $next > 999 ? strlen((string)$next) : 3;
  6968. return $prefix . str_pad((string)$next, $width, '0', STR_PAD_LEFT);
  6969. }
  6970. /**
  6971. * @return string[]
  6972. */
  6973. protected function mprocLoadRfqDeptNameOptions(): array
  6974. {
  6975. $out = [];
  6976. try {
  6977. $vals = Db::table('mcyd')
  6978. ->where('CCLBMMC', '<>', '')
  6979. ->whereNotNull('CCLBMMC')
  6980. ->distinct(true)
  6981. ->limit(300)
  6982. ->column('CCLBMMC');
  6983. } catch (\Throwable $e) {
  6984. $vals = [];
  6985. }
  6986. if (is_array($vals)) {
  6987. foreach ($vals as $v) {
  6988. $v = trim((string)$v);
  6989. if ($v === '' || isset($out[$v])) {
  6990. continue;
  6991. }
  6992. $out[$v] = $v;
  6993. }
  6994. }
  6995. try {
  6996. $poVals = Db::table('purchase_order')
  6997. ->where('CCLBMMC', '<>', '')
  6998. ->whereNotNull('CCLBMMC')
  6999. ->distinct(true)
  7000. ->limit(200)
  7001. ->column('CCLBMMC');
  7002. } catch (\Throwable $e) {
  7003. $poVals = [];
  7004. }
  7005. if (is_array($poVals)) {
  7006. foreach ($poVals as $v) {
  7007. $v = trim((string)$v);
  7008. if ($v === '' || isset($out[$v])) {
  7009. continue;
  7010. }
  7011. $out[$v] = $v;
  7012. }
  7013. }
  7014. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  7015. if (!isset($out[$preset])) {
  7016. $out[$preset] = $preset;
  7017. }
  7018. }
  7019. $list = array_values($out);
  7020. usort($list, static function ($a, $b) {
  7021. $weight = [
  7022. '营销中心' => 1,
  7023. '业务部' => 2,
  7024. '市场部' => 3,
  7025. '外贸部' => 4,
  7026. '新华技术业务部' => 5,
  7027. ];
  7028. $wa = $weight[$a] ?? 100;
  7029. $wb = $weight[$b] ?? 100;
  7030. if ($wa !== $wb) {
  7031. return $wa <=> $wb;
  7032. }
  7033. return strcmp((string)$a, (string)$b);
  7034. });
  7035. return $list;
  7036. }
  7037. protected function mprocEnsureRfqSalesmanColumns(): void
  7038. {
  7039. static $ok = false;
  7040. if ($ok) {
  7041. return;
  7042. }
  7043. $alters = [
  7044. 'notify_salesman' => "ADD COLUMN `notify_salesman` varchar(500) NOT NULL DEFAULT '' COMMENT '通知业务员' AFTER `cywyxm`",
  7045. 'rfq_salesman_notified' => "ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '是否已通知业务员' AFTER `notify_salesman`",
  7046. 'rfq_salesman_notify_time' => "ADD COLUMN `rfq_salesman_notify_time` datetime DEFAULT NULL COMMENT '通知业务员时间' AFTER `rfq_salesman_notified`",
  7047. ];
  7048. foreach ($alters as $col => $sql) {
  7049. try {
  7050. $exists = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  7051. if (is_array($exists) && $exists !== []) {
  7052. continue;
  7053. }
  7054. Db::execute('ALTER TABLE `purchase_order` ' . $sql);
  7055. } catch (\Throwable $e) {
  7056. }
  7057. }
  7058. $ok = true;
  7059. }
  7060. /**
  7061. * 校验业务员是否可访问该手工询价单
  7062. *
  7063. * @param array<string, mixed> $user
  7064. * @return array<string, mixed>|null
  7065. */
  7066. protected function mprocLoadAccessibleRfqOrder(array $user, int $sid): ?array
  7067. {
  7068. if ($sid >= 0) {
  7069. return null;
  7070. }
  7071. $profile = $this->mprocProfileForUser($user);
  7072. $adminName = trim((string)($profile['contact_name'] ?? ''));
  7073. if ($adminName === '') {
  7074. $adminName = trim((string)($user['username'] ?? ''));
  7075. }
  7076. $isSuper = $this->mprocAdminIsMobileSuper((int)($user['admin_id'] ?? 0));
  7077. $this->mprocEnsureRfqSalesmanColumns();
  7078. try {
  7079. $query = Db::table('purchase_order')
  7080. ->where('scydgy_id', $sid)
  7081. ->whereRaw(
  7082. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  7083. );
  7084. if (!$isSuper) {
  7085. if ($adminName === '') {
  7086. return null;
  7087. }
  7088. $query->where(function ($q2) use ($adminName) {
  7089. $q2->where('cywyxm', $adminName)
  7090. ->whereOr('notify_salesman', $adminName)
  7091. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  7092. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  7093. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  7094. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  7095. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  7096. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  7097. });
  7098. }
  7099. $row = $query->find();
  7100. } catch (\Throwable $e) {
  7101. return null;
  7102. }
  7103. return is_array($row) ? $row : null;
  7104. }
  7105. /**
  7106. * 手机端业务员询价列表(本人发起 / 被通知)
  7107. *
  7108. * @param array<string, mixed> $user
  7109. * @param string $status pending|quoted|''(空=全部)
  7110. * @return array<int, array<string, mixed>>
  7111. */
  7112. protected function mprocLoadRfqAddRows(array $user, string $q, string $status = ''): array
  7113. {
  7114. $profile = $this->mprocProfileForUser($user);
  7115. $adminName = trim((string)($profile['contact_name'] ?? ''));
  7116. if ($adminName === '') {
  7117. $adminName = trim((string)($user['username'] ?? ''));
  7118. }
  7119. $isSuper = $this->mprocAdminIsMobileSuper((int)($user['admin_id'] ?? 0));
  7120. $this->mprocEnsureRfqSalesmanColumns();
  7121. try {
  7122. $query = Db::table('purchase_order')
  7123. ->where('scydgy_id', '<', 0)
  7124. ->whereRaw(
  7125. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  7126. );
  7127. if (!$isSuper) {
  7128. if ($adminName === '') {
  7129. return [];
  7130. }
  7131. $query->where(function ($q2) use ($adminName) {
  7132. $q2->where('cywyxm', $adminName)
  7133. ->whereOr('notify_salesman', $adminName)
  7134. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  7135. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  7136. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  7137. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  7138. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  7139. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  7140. });
  7141. }
  7142. $q = trim($q);
  7143. if ($q !== '') {
  7144. $like = '%' . str_replace(['%', '_'], ['\\%', '\\_'], $q) . '%';
  7145. $query->where(function ($q2) use ($like) {
  7146. $q2->where('CCYDH', 'like', $like)
  7147. ->whereOr('CYJMC', 'like', $like)
  7148. ->whereOr('CGYMC', 'like', $like)
  7149. ->whereOr('CCLBMMC', 'like', $like)
  7150. ->whereOr('MBZ', 'like', $like);
  7151. });
  7152. }
  7153. $rows = $query
  7154. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,CDW,CDF,This_quantity,ceilingPrice,cywyxm,MBZ,status,wflow_status,rfq_salesman_notified,createtime,dStamp')
  7155. ->order('id', 'desc')
  7156. ->limit(200)
  7157. ->select();
  7158. } catch (\Throwable $e) {
  7159. $rows = [];
  7160. }
  7161. if (!is_array($rows)) {
  7162. $rows = [];
  7163. }
  7164. $out = [];
  7165. $sids = [];
  7166. foreach ($rows as $r) {
  7167. if (!is_array($r)) {
  7168. continue;
  7169. }
  7170. $sid = (int)($r['scydgy_id'] ?? 0);
  7171. if ($sid < 0) {
  7172. $sids[$sid] = $sid;
  7173. }
  7174. }
  7175. $quotedMap = $this->mprocLoadRfqQuotedSidMap(array_values($sids));
  7176. $status = trim($status);
  7177. if ($status !== 'pending' && $status !== 'quoted') {
  7178. $status = '';
  7179. }
  7180. foreach ($rows as $r) {
  7181. if (!is_array($r)) {
  7182. continue;
  7183. }
  7184. $sid = (int)($r['scydgy_id'] ?? 0);
  7185. $isQuoted = !empty($quotedMap[$sid]);
  7186. if ($status === 'pending' && $isQuoted) {
  7187. continue;
  7188. }
  7189. if ($status === 'quoted' && !$isQuoted) {
  7190. continue;
  7191. }
  7192. $created = trim((string)($r['createtime'] ?? ''));
  7193. if ($created === '' || stripos($created, '0000-00-00') === 0) {
  7194. $created = trim((string)($r['dStamp'] ?? ''));
  7195. }
  7196. if (preg_match('/^\d{10,}$/', $created)) {
  7197. $created = date('Y-m-d H:i:s', (int)$created);
  7198. }
  7199. if ($created !== '' && stripos($created, '0000-00-00') === 0) {
  7200. $created = '';
  7201. }
  7202. $out[] = [
  7203. 'id' => (int)($r['id'] ?? 0),
  7204. 'scydgy_id' => $sid,
  7205. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  7206. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  7207. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  7208. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  7209. 'CDW' => trim((string)($r['CDW'] ?? '')),
  7210. 'CDF' => trim((string)($r['CDF'] ?? '')),
  7211. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  7212. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  7213. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  7214. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  7215. 'progress_text' => $isQuoted ? '已报价' : '待询价',
  7216. 'createtime' => $created,
  7217. ];
  7218. }
  7219. return $out;
  7220. }
  7221. /**
  7222. * 哪些手工询价单已有有效报价(amount 非空且非 0)
  7223. *
  7224. * @param array<int, int> $sids
  7225. * @return array<int, bool>
  7226. */
  7227. protected function mprocLoadRfqQuotedSidMap(array $sids): array
  7228. {
  7229. $out = [];
  7230. $sids = array_values(array_unique(array_filter(array_map('intval', $sids), static function ($v) {
  7231. return $v < 0;
  7232. })));
  7233. if ($sids === []) {
  7234. return $out;
  7235. }
  7236. foreach (array_chunk($sids, 200) as $chunk) {
  7237. try {
  7238. $rows = Db::table('purchase_order_detail')
  7239. ->where('scydgy_id', 'in', $chunk)
  7240. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  7241. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')')
  7242. ->where('amount', '<>', '')
  7243. ->whereNotNull('amount')
  7244. ->where('amount', '<>', '0')
  7245. ->where('amount', '<>', '0.00')
  7246. ->field('scydgy_id')
  7247. ->group('scydgy_id')
  7248. ->select();
  7249. } catch (\Throwable $e) {
  7250. try {
  7251. $rows = Db::table('purchase_order_detail')
  7252. ->where('scydgy_id', 'in', $chunk)
  7253. ->where('amount', '<>', '')
  7254. ->whereNotNull('amount')
  7255. ->where('amount', '<>', '0')
  7256. ->where('amount', '<>', '0.00')
  7257. ->field('scydgy_id')
  7258. ->group('scydgy_id')
  7259. ->select();
  7260. } catch (\Throwable $e2) {
  7261. $rows = [];
  7262. }
  7263. }
  7264. if (!is_array($rows)) {
  7265. continue;
  7266. }
  7267. foreach ($rows as $r) {
  7268. if (!is_array($r)) {
  7269. continue;
  7270. }
  7271. $sid = (int)($r['scydgy_id'] ?? 0);
  7272. if ($sid < 0) {
  7273. $out[$sid] = true;
  7274. }
  7275. }
  7276. }
  7277. return $out;
  7278. }
  7279. /**
  7280. * @param array<string, mixed> $row
  7281. */
  7282. protected function mprocFormatRfqProgressText(array $row): string
  7283. {
  7284. $sid = (int)($row['scydgy_id'] ?? 0);
  7285. if ($sid < 0) {
  7286. $map = $this->mprocLoadRfqQuotedSidMap([$sid]);
  7287. if (!empty($map[$sid])) {
  7288. return '已报价';
  7289. }
  7290. }
  7291. return '待询价';
  7292. }
  7293. }