Index.php 291 KB

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