Procuremen.php 528 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenGuard;
  6. use app\common\library\ProcuremenOperLog;
  7. use app\common\library\ProcuremenSchema;
  8. use app\common\library\ProcuremenStatus;
  9. use app\common\library\ProcuremenSupplierScore;
  10. use app\common\library\ProcuremenTime;
  11. use PHPMailer\PHPMailer\PHPMailer;
  12. use think\Config;
  13. use think\Cache;
  14. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  15. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  16. use PhpOffice\PhpSpreadsheet\Style\Border;
  17. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  18. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  19. use think\Db;
  20. use think\Log;
  21. class Procuremen extends Backend
  22. {
  23. /**
  24. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  25. */
  26. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,b.czlyq,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  27. /**
  28. * Procuremen模型对象
  29. * @var \app\admin\model\Procuremen
  30. */
  31. protected $model = null;
  32. /**
  33. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  34. */
  35. protected $notifyDryRunPreview = [];
  36. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  37. protected $procuremenRedisCache = null;
  38. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  39. protected $pickHiddenScydgySetCache = null;
  40. /** 邮件发送日志表结构已就绪缓存键 */
  41. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  42. /**
  43. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  44. * @var array
  45. */
  46. protected $noNeedRight = [
  47. 'pickreview', 'review', 'reviewcompanies',
  48. // 方法内用 hasProcuremenPerm 校验(兼容 auditsubmit / auditissue)
  49. 'auditmanualpick',
  50. // 与 rfqlist 同权,方法内校验
  51. 'rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqissuesuppliers', 'rfqissue', 'rfqissuesendmail', 'rfqquotes',
  52. 'rfqappendsuppliers', 'rfqsupplieroptions', 'rfqsalesmanoptions', 'rfqappendsalesmen',
  53. ];
  54. public function _initialize()
  55. {
  56. parent::_initialize();
  57. $this->model = new \app\admin\model\Procuremen;
  58. $this->maybeMigrateLegacyWflowStatusText();
  59. $this->assignProcuremenAuthConfig();
  60. try {
  61. ProcuremenSchema::ensureAll();
  62. } catch (\Throwable $e) {
  63. }
  64. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  65. $this->ensurePurchaseEmailSendLogTableOnce();
  66. }
  67. }
  68. /**
  69. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  70. */
  71. protected function maybeMigrateLegacyWflowStatusText(): void
  72. {
  73. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  74. if (is_file($flagFile)) {
  75. return;
  76. }
  77. $map = [
  78. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  79. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  80. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  81. '3' => ProcuremenStatus::WFLOW_APPROVED,
  82. ];
  83. try {
  84. foreach ($map as $num => $text) {
  85. Db::table('purchase_order')
  86. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  87. ->update(['wflow_status' => $text]);
  88. }
  89. @file_put_contents($flagFile, date('c'));
  90. } catch (\Throwable $e) {
  91. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  92. }
  93. }
  94. /**
  95. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  96. *
  97. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  98. */
  99. protected function hasProcuremenPerm(array $actions): bool
  100. {
  101. foreach ($actions as $action) {
  102. $action = strtolower(trim((string)$action));
  103. if ($action === '') {
  104. continue;
  105. }
  106. if (strpos($action, 'procuremen/') !== 0) {
  107. $action = 'procuremen/' . $action;
  108. }
  109. if ($this->auth->check($action)) {
  110. return true;
  111. }
  112. }
  113. $suffixes = [];
  114. foreach ($actions as $action) {
  115. $action = strtolower(trim((string)$action));
  116. $action = preg_replace('#^procuremen/#', '', $action);
  117. if ($action !== '') {
  118. $suffixes[$action] = true;
  119. }
  120. }
  121. if ($suffixes === []) {
  122. return false;
  123. }
  124. try {
  125. foreach ($this->auth->getRuleList() as $rule) {
  126. $rule = strtolower((string)$rule);
  127. if (strpos($rule, 'procuremen/') !== 0) {
  128. continue;
  129. }
  130. foreach (array_keys($suffixes) as $suffix) {
  131. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  132. return true;
  133. }
  134. }
  135. }
  136. } catch (\Throwable $e) {
  137. }
  138. return false;
  139. }
  140. /**
  141. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  142. *
  143. * @param string[] $actions
  144. */
  145. protected function hasProcuremenPermStrict(array $actions): bool
  146. {
  147. foreach ($actions as $action) {
  148. $action = strtolower(trim((string)$action));
  149. if ($action === '') {
  150. continue;
  151. }
  152. if (strpos($action, 'procuremen/') !== 0) {
  153. $action = 'procuremen/' . $action;
  154. }
  155. if ($this->auth->check($action)) {
  156. return true;
  157. }
  158. }
  159. return false;
  160. }
  161. /**
  162. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  163. *
  164. * @param string[] $titles
  165. */
  166. protected function authHasAssignedRuleTitle(array $titles): bool
  167. {
  168. $titles = array_values(array_filter(array_map('trim', $titles)));
  169. if ($titles === []) {
  170. return false;
  171. }
  172. try {
  173. $ids = $this->auth->getRuleIds();
  174. if (in_array('*', $ids, true)) {
  175. return true;
  176. }
  177. if ($ids === []) {
  178. return false;
  179. }
  180. $rows = Db::name('auth_rule')
  181. ->where('status', 'normal')
  182. ->whereIn('id', $ids)
  183. ->column('title');
  184. foreach ($rows as $title) {
  185. $t = trim((string)$title);
  186. if ($t !== '' && in_array($t, $titles, true)) {
  187. return true;
  188. }
  189. }
  190. } catch (\Throwable $e) {
  191. }
  192. return false;
  193. }
  194. protected function procuremenCanPickDelete(): bool
  195. {
  196. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  197. return true;
  198. }
  199. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  200. }
  201. protected function procuremenCanComplete(): bool
  202. {
  203. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  204. return true;
  205. }
  206. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  207. }
  208. protected function procuremenCanDispatch(): bool
  209. {
  210. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  211. }
  212. /**
  213. * 前端按钮显隐(Config.procuremenAuth)
  214. */
  215. protected function assignProcuremenAuthConfig(): void
  216. {
  217. $authMap = [
  218. 'pickreview' => $this->procuremenCanDispatch(),
  219. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  220. 'pickdelete' => $this->procuremenCanPickDelete(),
  221. 'completedirectly' => $this->procuremenCanComplete(),
  222. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  223. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  224. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  225. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  226. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  227. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  228. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  229. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  230. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  231. 'details' => $this->hasProcuremenPerm(['details']),
  232. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  233. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  234. 'export_month_quote' => $this->hasProcuremenPerm(['export_month_quote', 'exportMonthQuote', 'export_month_outward', 'exportMonthOutward']),
  235. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  236. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  237. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  238. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  239. 'auditmanualpick' => $this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue']),
  240. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  241. 'add' => $this->hasProcuremenPerm(['add']),
  242. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  243. // 查询询价三个操作按钮:各自独立,不再因有 rfqlist 就全部放开
  244. 'rfqissue' => $this->hasProcuremenPerm(['rfqissue']),
  245. 'rfqquotes' => $this->hasProcuremenPerm(['rfqquotes']),
  246. 'rfqnotifysalesman' => $this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen']),
  247. 'rfqnotifysalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman']),
  248. // 询价附属接口:有「询价」按钮权限即可(无需再单独勾选)
  249. 'rfqissuesuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers']),
  250. 'rfqissuesendmail' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail']),
  251. 'rfqappendsuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers']),
  252. 'rfqsupplieroptions' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions']),
  253. 'rfqsalesmanoptions' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen']),
  254. 'rfqappendsalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen']),
  255. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  256. ];
  257. $this->assignconfig('procuremenAuth', $authMap);
  258. }
  259. /**
  260. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  261. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  262. * 列表 Tab 写入 hash(mproc_tab),避免邮件客户端拆坏多 query 参数;浏览器端再补全 tab=
  263. *
  264. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  265. * @param string $listTab rfq|draft|submitted|done|rfq_submitted,空则仅靠服务端按状态推断
  266. */
  267. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId, $listTab = '')
  268. {
  269. static $mprocCfgLoaded = false;
  270. if (!$mprocCfgLoaded) {
  271. $mprocCfgLoaded = true;
  272. if (is_file(APP_PATH . 'extra/mproc.php')) {
  273. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  274. }
  275. }
  276. $eid = (int)$purchaseOrderDetailId;
  277. $base = $this->resolveMprocMobilePublicBaseUrl();
  278. if ($base === '') {
  279. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  280. }
  281. $path = trim((string)Config::get('mproc.mobile_index_path'));
  282. if ($path === '') {
  283. $path = '/index.php/index/index/index';
  284. } else {
  285. $path = '/' . ltrim($path, '/');
  286. }
  287. $tab = trim((string)$listTab);
  288. if (!in_array($tab, ['rfq', 'rfq_submitted', 'draft', 'submitted', 'done'], true)) {
  289. $tab = '';
  290. }
  291. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份 Tab
  292. if ($eid > 0) {
  293. $hash = 'mproc_fe=' . $eid;
  294. if ($tab !== '') {
  295. $hash .= '&mproc_tab=' . $tab;
  296. }
  297. return $base . $path . '?focus_eid=' . $eid . '#' . $hash;
  298. }
  299. return $base . $path . '?main_tab=orders' . ($tab !== '' ? ('&tab=' . $tab) : '');
  300. }
  301. /**
  302. * 业务员手机端「订单询价」直达链接(默认待询价)
  303. *
  304. * @param int $scydgyId 手工询价 scydgy_id(负数)
  305. * @param string $status pending|quoted
  306. */
  307. protected function buildMprocMobileRfqAddUrl($scydgyId = 0, $status = 'pending')
  308. {
  309. static $mprocCfgLoaded = false;
  310. if (!$mprocCfgLoaded) {
  311. $mprocCfgLoaded = true;
  312. if (is_file(APP_PATH . 'extra/mproc.php')) {
  313. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  314. }
  315. }
  316. $base = $this->resolveMprocMobilePublicBaseUrl();
  317. if ($base === '') {
  318. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  319. }
  320. $indexPath = trim((string)Config::get('mproc.mobile_index_path'));
  321. if ($indexPath === '') {
  322. $indexPath = '/index.php/index/index/index';
  323. } else {
  324. $indexPath = '/' . ltrim($indexPath, '/');
  325. }
  326. $path = preg_replace('#/index$#', '/rfqadd', rtrim($indexPath, '/'));
  327. if ($path === null || $path === '' || substr($path, -6) === '/index') {
  328. $path = '/index.php/index/index/rfqadd';
  329. }
  330. $status = trim((string)$status) === 'quoted' ? 'quoted' : 'pending';
  331. $sid = (int)$scydgyId;
  332. $q = 'status=' . $status;
  333. $hash = '';
  334. if ($sid < 0) {
  335. $q .= '&focus_sid=' . $sid;
  336. $hash = '#mproc_fs=' . $sid;
  337. }
  338. return $base . $path . '?' . $q . $hash;
  339. }
  340. /**
  341. * 邮件/短信外链:须为带点的公网域名
  342. */
  343. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  344. {
  345. $u = trim((string)$baseUrl);
  346. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  347. return false;
  348. }
  349. $host = parse_url($u, PHP_URL_HOST);
  350. if (!is_string($host) || $host === '') {
  351. return false;
  352. }
  353. if (strcasecmp($host, 'localhost') === 0) {
  354. return false;
  355. }
  356. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  357. return false;
  358. }
  359. if (strpos($host, '.') === false) {
  360. return false;
  361. }
  362. return true;
  363. }
  364. /**
  365. * 解析用于协助邮件/短信的手机端站点根
  366. */
  367. protected function resolveMprocMobilePublicBaseUrl()
  368. {
  369. $candidates = [];
  370. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  371. $candidates[] = trim((string)Config::get('site.indexurl'));
  372. $cdn = trim((string)Config::get('site.cdnurl'));
  373. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  374. $candidates[] = rtrim($cdn, '/');
  375. }
  376. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  377. $candidates[] = $reqBase;
  378. foreach ($candidates as $c) {
  379. if ($c === '') {
  380. continue;
  381. }
  382. $c = rtrim($c, '/');
  383. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  384. return $c;
  385. }
  386. }
  387. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  388. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  389. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  390. return $reqBase;
  391. }
  392. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  393. return '';
  394. }
  395. /**
  396. * 获取 Redis 中 procuremen_redis
  397. */
  398. protected function ProcuremenRedis(): array
  399. {
  400. if ($this->procuremenRedisCache !== null) {
  401. return $this->procuremenRedisCache;
  402. }
  403. try {
  404. $redis = redis();
  405. $raw = $redis->get('procuremen_redis');
  406. if ($raw === false || $raw === '') {
  407. $this->procuremenRedisCache = [];
  408. return $this->procuremenRedisCache;
  409. }
  410. $decoded = json_decode($raw, true);
  411. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  412. $this->procuremenRedisCache = [];
  413. return $this->procuremenRedisCache;
  414. }
  415. $this->procuremenRedisCache = $decoded['data'];
  416. // 整包已解码时顺带补齐侧栏小键,避免下次首屏再扫库
  417. if ($this->loadProcuremenSidebarYmList() === []) {
  418. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($this->procuremenRedisCache));
  419. }
  420. return $this->procuremenRedisCache;
  421. } catch (\Throwable $e) {
  422. $this->procuremenRedisCache = [];
  423. return $this->procuremenRedisCache;
  424. }
  425. }
  426. /**
  427. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  428. *
  429. * @return array<int, array<string, mixed>>
  430. */
  431. protected function procuremenFetchErpPoolFromDb(): array
  432. {
  433. try {
  434. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  435. $endTime = date('Y-m-d 23:59:59');
  436. $list = Db::table('scydgy')
  437. ->alias('a')
  438. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  439. ->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, b.czlyq, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  440. ->where([
  441. 'a.bwjg' => 1,
  442. 'a.iEndBz' => 0,
  443. 'a.iType' => 0,
  444. 'a.iStatus' => 10,
  445. ])
  446. ->where('a.dStamp', '>=', $startTime)
  447. ->where('a.dStamp', '<=', $endTime)
  448. ->order('a.dStamp', 'desc')
  449. ->select();
  450. if (!is_array($list)) {
  451. return [];
  452. }
  453. try {
  454. $redis = redis();
  455. $payload = [
  456. 'code' => 200,
  457. 'msg' => 'success',
  458. 'data' => $list,
  459. ];
  460. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  461. $this->procuremenRedisCache = $list;
  462. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($list));
  463. $this->clearPickMonthPoolCaches();
  464. $this->warmPickMonthPoolCachesFromPool($list);
  465. } catch (\Throwable $e) {
  466. }
  467. return $list;
  468. } catch (\Throwable $e) {
  469. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  470. return [];
  471. }
  472. }
  473. /**
  474. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  475. *
  476. * @return array<int, array<string, mixed>>
  477. */
  478. protected function procuremenEnsureRedisPool(): array
  479. {
  480. $pool = $this->ProcuremenRedis();
  481. if (is_array($pool) && $pool !== []) {
  482. return $pool;
  483. }
  484. static $warmed = false;
  485. if ($warmed) {
  486. return is_array($pool) ? $pool : [];
  487. }
  488. $warmed = true;
  489. return $this->procuremenFetchErpPoolFromDb();
  490. }
  491. /**
  492. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  493. *
  494. * @param array<string, mixed> $row
  495. */
  496. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  497. {
  498. $t = $this->procuremenRowListSortTime($row, $primary);
  499. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  500. return null;
  501. }
  502. $mo = (int)$m[2];
  503. if ($mo < 1 || $mo > 12) {
  504. return null;
  505. }
  506. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  507. }
  508. /**
  509. * @param array<int, array{year:string, months:array}> $sidebar
  510. * @return array<int, array{year:string, months:array}>
  511. */
  512. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  513. {
  514. $ym = trim($ym);
  515. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  516. return $sidebar;
  517. }
  518. foreach ($sidebar as $block) {
  519. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  520. continue;
  521. }
  522. foreach ($block['months'] as $item) {
  523. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  524. return $sidebar;
  525. }
  526. }
  527. }
  528. $y = substr($ym, 0, 4);
  529. $mo = (int)substr($ym, 5, 2);
  530. $sidebar[] = [
  531. 'year' => $y,
  532. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  533. ];
  534. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  535. }
  536. /**
  537. * @param array<int, array{year:string, months:array}> $sidebar
  538. * @return string[]
  539. */
  540. protected function flattenProcuremenSidebarYms(array $sidebar): array
  541. {
  542. $yms = [];
  543. foreach ($sidebar as $block) {
  544. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  545. continue;
  546. }
  547. foreach ($block['months'] as $item) {
  548. if (!is_array($item)) {
  549. continue;
  550. }
  551. $ym = trim((string)($item['ym'] ?? ''));
  552. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  553. $yms[$ym] = true;
  554. }
  555. }
  556. }
  557. return array_keys($yms);
  558. }
  559. /**
  560. * 左侧菜单(协助初选)
  561. * 优先 Redis 月份小键;为空时用轻量 DISTINCT 查库补齐(避免只显示空当月、漏掉有数据的月份)。
  562. */
  563. protected function GetIndexYearMonths()
  564. {
  565. $ymList = $this->ensureProcuremenPickSidebarYmList();
  566. if ($ymList === []) {
  567. $def = date('Y-m');
  568. $ymList = [preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m')];
  569. }
  570. return $this->buildYearMonthSidebar($ymList);
  571. }
  572. /**
  573. * 初选侧栏月份:以轻量 DISTINCT 查库为准(有数据才显示),并写回 Redis 小键。
  574. *
  575. * @return string[]
  576. */
  577. protected function ensureProcuremenPickSidebarYmList(bool $forceRefresh = false): array
  578. {
  579. static $memo = null;
  580. if (!$forceRefresh && is_array($memo)) {
  581. return $memo;
  582. }
  583. $fromDb = $this->queryProcuremenPickSidebarYmListLight();
  584. if ($fromDb !== []) {
  585. $this->saveProcuremenSidebarYmList($fromDb);
  586. $memo = $fromDb;
  587. return $memo;
  588. }
  589. // 库侧暂无初选数据时,再回退 Redis / 当月,避免侧栏空白
  590. $cached = $this->loadProcuremenSidebarYmList();
  591. if ($cached !== []) {
  592. $memo = $cached;
  593. return $memo;
  594. }
  595. $memo = [date('Y-m')];
  596. return $memo;
  597. }
  598. /**
  599. * @return string[] 形如 2026-07
  600. */
  601. protected function loadProcuremenSidebarYmList(): array
  602. {
  603. try {
  604. $raw = redis()->get('procuremen_redis_yms');
  605. if ($raw === false || $raw === null || $raw === '') {
  606. return [];
  607. }
  608. $decoded = json_decode((string)$raw, true);
  609. if (!is_array($decoded)) {
  610. return [];
  611. }
  612. $out = [];
  613. foreach ($decoded as $ym) {
  614. $ym = trim((string)$ym);
  615. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  616. $out[$ym] = true;
  617. }
  618. }
  619. return array_keys($out);
  620. } catch (\Throwable $e) {
  621. return [];
  622. }
  623. }
  624. /**
  625. * @param string[] $ymList
  626. */
  627. protected function saveProcuremenSidebarYmList(array $ymList): void
  628. {
  629. $out = [];
  630. foreach ($ymList as $ym) {
  631. $ym = trim((string)$ym);
  632. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  633. $out[$ym] = true;
  634. }
  635. }
  636. if ($out === []) {
  637. return;
  638. }
  639. try {
  640. redis()->set('procuremen_redis_yms', json_encode(array_keys($out), JSON_UNESCAPED_UNICODE));
  641. } catch (\Throwable $e) {
  642. }
  643. }
  644. /**
  645. * @param array<int, array<string, mixed>> $pool
  646. * @return string[]
  647. */
  648. protected function extractYearMonthsFromPoolRows(array $pool): array
  649. {
  650. $ymSet = [];
  651. foreach ($pool as $r) {
  652. if (!is_array($r)) {
  653. continue;
  654. }
  655. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  656. continue;
  657. }
  658. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  659. if ($ym !== null) {
  660. $ymSet[$ym] = true;
  661. }
  662. }
  663. return array_keys($ymSet);
  664. }
  665. /**
  666. * 轻量查询初选侧栏月份(只取 DISTINCT 年月,不拉整包工序)
  667. *
  668. * @return string[]
  669. */
  670. protected function queryProcuremenPickSidebarYmListLight(): array
  671. {
  672. try {
  673. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  674. $endTime = date('Y-m-d 23:59:59');
  675. $sql = 'SELECT DISTINCT DATE_FORMAT('
  676. . 'IF(b.dputrecord IS NOT NULL AND TRIM(CAST(b.dputrecord AS CHAR(32))) <> \'\''
  677. . ' AND TRIM(CAST(b.dputrecord AS CHAR(32))) NOT LIKE \'0000-00-00%\','
  678. . ' b.dputrecord, a.dStamp), \'%Y-%m\') AS ym'
  679. . ' FROM scydgy a'
  680. . ' INNER JOIN mcyd b ON b.ICYDID = a.ICYDID AND b.iStatus >= 10'
  681. . ' WHERE a.bwjg = 1 AND a.iEndBz = 0 AND a.iType = 0 AND a.iStatus = 10'
  682. . ' AND a.dStamp >= ? AND a.dStamp <= ?';
  683. $rows = Db::query($sql, [$startTime, $endTime]);
  684. if (!is_array($rows)) {
  685. return [];
  686. }
  687. $out = [];
  688. foreach ($rows as $r) {
  689. $ym = trim((string)($r['ym'] ?? ''));
  690. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  691. $out[$ym] = true;
  692. }
  693. }
  694. return array_keys($out);
  695. } catch (\Throwable $e) {
  696. Log::write('初选侧栏月份轻量查询失败:' . $e->getMessage(), 'warning');
  697. return [];
  698. }
  699. }
  700. /**
  701. * @return string[] 含当月在内的近 N 个自然月
  702. */
  703. protected function buildRecentCalendarYmList(int $months = 12): array
  704. {
  705. $months = max(1, min(24, $months));
  706. $out = [];
  707. $base = strtotime(date('Y-m-01'));
  708. for ($i = 0; $i < $months; $i++) {
  709. $out[] = date('Y-m', strtotime('-' . $i . ' month', $base));
  710. }
  711. return $out;
  712. }
  713. /**
  714. * 初选按月工序池:优先月缓存;未命中则直接按月查 ERP。
  715. * 禁止为列表去解近一年整包 Redis(解包/连接异常会造成长时间转圈)。
  716. *
  717. * @return array<int, array<string, mixed>>
  718. */
  719. protected function loadPickPoolForYm(string $ym): array
  720. {
  721. $ym = trim($ym);
  722. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  723. return [];
  724. }
  725. $hit = $this->readPickMonthPoolCache($ym);
  726. if ($hit !== null) {
  727. return $hit;
  728. }
  729. return $this->queryPickPoolForYmFromDb($ym);
  730. }
  731. /**
  732. * @return array<int, array<string, mixed>>|null null=无有效缓存(含旧版空数组误缓存)
  733. */
  734. protected function readPickMonthPoolCache(string $ym): ?array
  735. {
  736. try {
  737. $raw = redis()->get('procuremen_pick_pool:' . $ym);
  738. if ($raw === false || $raw === null || $raw === '') {
  739. return null;
  740. }
  741. $decoded = json_decode((string)$raw, true);
  742. if (!is_array($decoded)) {
  743. return null;
  744. }
  745. // 新格式:{ok:1, rows:[...]},空月也算有效(已从整包确认)
  746. if (isset($decoded['ok']) && (int)$decoded['ok'] === 1 && isset($decoded['rows']) && is_array($decoded['rows'])) {
  747. return $decoded['rows'];
  748. }
  749. // 旧格式:仅非空行列表可命中;[] 多半是错误 SQL 写入,视为未命中
  750. if ($decoded === []) {
  751. try {
  752. redis()->del('procuremen_pick_pool:' . $ym);
  753. } catch (\Throwable $e) {
  754. }
  755. return null;
  756. }
  757. if (isset($decoded[0]) && is_array($decoded[0])) {
  758. return $decoded;
  759. }
  760. return null;
  761. } catch (\Throwable $e) {
  762. return null;
  763. }
  764. }
  765. /**
  766. * @param array<int, array<string, mixed>> $rows
  767. */
  768. protected function writePickMonthPoolCache(string $ym, array $rows): void
  769. {
  770. try {
  771. redis()->setex(
  772. 'procuremen_pick_pool:' . $ym,
  773. 600,
  774. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  775. );
  776. } catch (\Throwable $e) {
  777. }
  778. }
  779. /**
  780. * @param array<int, array<string, mixed>> $pool
  781. * @return array<int, array<string, mixed>>
  782. */
  783. protected function filterPoolRowsByYm(array $pool, string $ym): array
  784. {
  785. $out = [];
  786. foreach ($pool as $r) {
  787. if (!is_array($r)) {
  788. continue;
  789. }
  790. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  791. continue;
  792. }
  793. if ($this->procuremenRowYearMonth($r, 'dputrecord') === $ym) {
  794. $out[] = $r;
  795. }
  796. }
  797. return $out;
  798. }
  799. /**
  800. * 按 dStamp 取当月附近数据,再用列表规则(dputrecord 优先)精确到 ym
  801. *
  802. * @return array<int, array<string, mixed>>
  803. */
  804. protected function queryPickPoolForYmFromDb(string $ym): array
  805. {
  806. $monthStart = $ym . '-01 00:00:00';
  807. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  808. // 略放大窗口,避免 dStamp 与 dputrecord 跨月导致漏数;最终仍按 ym 精确过滤
  809. $queryStart = date('Y-m-d 00:00:00', strtotime($monthStart . ' -7 days'));
  810. $queryEnd = date('Y-m-d 23:59:59', strtotime($monthEnd . ' +7 days'));
  811. try {
  812. $list = Db::table('scydgy')
  813. ->alias('a')
  814. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  815. ->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, b.czlyq, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  816. ->where([
  817. 'a.bwjg' => 1,
  818. 'a.iEndBz' => 0,
  819. 'a.iType' => 0,
  820. 'a.iStatus' => 10,
  821. ])
  822. ->where('a.dStamp', '>=', $queryStart)
  823. ->where('a.dStamp', '<=', $queryEnd)
  824. ->order('a.dStamp', 'desc')
  825. ->select();
  826. } catch (\Throwable $e) {
  827. Log::write('初选按月取数失败 ym=' . $ym . ':' . $e->getMessage(), 'error');
  828. return [];
  829. }
  830. if (!is_array($list)) {
  831. $list = [];
  832. }
  833. $out = $this->filterPoolRowsByYm($list, $ym);
  834. // 新格式缓存(含空月),避免重复打库;读侧只认 ok=1
  835. $this->writePickMonthPoolCache($ym, $out);
  836. try {
  837. $yms = $this->loadProcuremenSidebarYmList();
  838. if ($out !== [] && ($yms === [] || !in_array($ym, $yms, true))) {
  839. $yms[] = $ym;
  840. $this->saveProcuremenSidebarYmList($yms);
  841. }
  842. } catch (\Throwable $e) {
  843. }
  844. return $out;
  845. }
  846. /**
  847. * 整包写入后拆成按月小缓存,供初选列表秒开
  848. *
  849. * @param array<int, array<string, mixed>> $pool
  850. */
  851. protected function warmPickMonthPoolCachesFromPool(array $pool): void
  852. {
  853. if ($pool === []) {
  854. return;
  855. }
  856. $byYm = [];
  857. foreach ($pool as $r) {
  858. if (!is_array($r)) {
  859. continue;
  860. }
  861. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  862. continue;
  863. }
  864. $rowYm = $this->procuremenRowYearMonth($r, 'dputrecord');
  865. if ($rowYm === null) {
  866. continue;
  867. }
  868. $byYm[$rowYm][] = $r;
  869. }
  870. if ($byYm === []) {
  871. return;
  872. }
  873. try {
  874. $redis = redis();
  875. foreach ($byYm as $rowYm => $rows) {
  876. $redis->setex(
  877. 'procuremen_pick_pool:' . $rowYm,
  878. 600,
  879. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  880. );
  881. }
  882. try {
  883. $redis->del('procuremen_pick_hidden_scydgy_v1');
  884. } catch (\Throwable $e) {
  885. }
  886. } catch (\Throwable $e) {
  887. }
  888. }
  889. /**
  890. * 刷新整包后清理近月缓存,避免脏读
  891. */
  892. protected function clearPickMonthPoolCaches(int $months = 24): void
  893. {
  894. try {
  895. $redis = redis();
  896. foreach ($this->buildRecentCalendarYmList($months) as $ym) {
  897. try {
  898. $redis->del('procuremen_pick_pool:' . $ym);
  899. } catch (\Throwable $e) {
  900. }
  901. }
  902. } catch (\Throwable $e) {
  903. }
  904. $this->invalidatePickHiddenScydgyCache();
  905. }
  906. /**
  907. * 下发/完结后清隐藏集缓存,避免初选列表最多 90 秒仍显示已下发行
  908. */
  909. protected function invalidatePickHiddenScydgyCache(): void
  910. {
  911. $this->pickHiddenScydgySetCache = null;
  912. try {
  913. redis()->del('procuremen_pick_hidden_scydgy_v1');
  914. } catch (\Throwable $e) {
  915. }
  916. }
  917. /** 列表/首屏读完鉴权后尽早释放 session,避免多 iframe 串行卡死 */
  918. protected function procuremenReleaseSessionLock(): void
  919. {
  920. if (session_status() === PHP_SESSION_ACTIVE) {
  921. @session_write_close();
  922. }
  923. }
  924. /**
  925. * @param string[] $ymList 形如 2026-06
  926. * @return array<int, array{year:string, months:array}>
  927. */
  928. protected function buildYearMonthSidebar(array $ymList): array
  929. {
  930. rsort($ymList, SORT_STRING);
  931. $byYear = [];
  932. foreach ($ymList as $ym) {
  933. $y = substr($ym, 0, 4);
  934. $mo = (int)substr($ym, 5, 2);
  935. if (!isset($byYear[$y])) {
  936. $byYear[$y] = [];
  937. }
  938. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  939. }
  940. krsort($byYear, SORT_NUMERIC);
  941. foreach ($byYear as $y => $items) {
  942. usort($byYear[$y], function ($a, $b) {
  943. return strcmp($b['ym'], $a['ym']);
  944. });
  945. }
  946. $sidebar = [];
  947. foreach ($byYear as $y => $months) {
  948. $sidebar[] = ['year' => $y, 'months' => $months];
  949. }
  950. return $sidebar;
  951. }
  952. /**
  953. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  954. */
  955. protected function GetIssuedOrderYearMonths(string $stage): array
  956. {
  957. $ymSet = [];
  958. try {
  959. $query = Db::table('purchase_order');
  960. $this->applyPurchaseOrderNotDeletedWhere($query);
  961. if ($stage === 'audit') {
  962. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  963. } elseif ($stage === 'confirm') {
  964. $this->applyPurchaseOrderConfirmStageWhere($query);
  965. } else {
  966. return $this->GetIndexYearMonths();
  967. }
  968. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  969. if (is_array($rows)) {
  970. foreach ($rows as $r) {
  971. if (!is_array($r)) {
  972. continue;
  973. }
  974. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  975. if ($ym !== null) {
  976. $ymSet[$ym] = true;
  977. }
  978. }
  979. }
  980. } catch (\Throwable $e) {
  981. $ymSet = [];
  982. }
  983. $ymList = array_keys($ymSet);
  984. if ($ymList === []) {
  985. $def = $this->resolveProcuremenDefaultYm($stage);
  986. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  987. }
  988. return $this->buildYearMonthSidebar($ymList);
  989. }
  990. /**
  991. * 列表默认月份:已下发类取最近有数据的月份;初选也取最近有数据月份(避免跨月后落到空当月)
  992. */
  993. protected function resolveProcuremenDefaultYm(string $stage): string
  994. {
  995. if ($stage === 'pick') {
  996. $yms = $this->ensureProcuremenPickSidebarYmList();
  997. if ($yms !== []) {
  998. rsort($yms, SORT_STRING);
  999. return $yms[0];
  1000. }
  1001. return date('Y-m');
  1002. }
  1003. try {
  1004. $query = Db::table('purchase_order');
  1005. $this->applyPurchaseOrderNotDeletedWhere($query);
  1006. if ($stage === 'audit') {
  1007. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1008. } elseif ($stage === 'confirm') {
  1009. $this->applyPurchaseOrderConfirmStageWhere($query);
  1010. } else {
  1011. return date('Y-m');
  1012. }
  1013. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  1014. if ($latest === null || $latest === '') {
  1015. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  1016. }
  1017. $t = $this->formatProcuremenDetailTime($latest);
  1018. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  1019. return $m[1] . '-' . $m[2];
  1020. }
  1021. } catch (\Throwable $e) {
  1022. }
  1023. return date('Y-m');
  1024. }
  1025. protected function applyPurchaseOrderNotDeletedWhere($query): void
  1026. {
  1027. $query->whereRaw(
  1028. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  1029. );
  1030. }
  1031. /**
  1032. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  1033. */
  1034. protected function applyPurchaseOrderConfirmStageWhere($query): void
  1035. {
  1036. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  1037. $quoted = [];
  1038. foreach ($vals as $v) {
  1039. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  1040. }
  1041. if ($quoted === []) {
  1042. $query->whereRaw('1 = 0');
  1043. return;
  1044. }
  1045. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  1046. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  1047. }
  1048. /**
  1049. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  1050. *
  1051. * @param array<string, mixed> $row
  1052. * @return array<string, mixed>
  1053. */
  1054. protected function normalizePurchaseOrderListTimeRow(array $row): array
  1055. {
  1056. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  1057. $pick = trim((string)($row['pick_time'] ?? ''));
  1058. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  1059. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  1060. $t = trim((string)($row[$key] ?? ''));
  1061. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1062. $row['pick_time'] = $t;
  1063. break;
  1064. }
  1065. }
  1066. }
  1067. return $row;
  1068. }
  1069. /**
  1070. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  1071. */
  1072. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  1073. {
  1074. if (!in_array($stage, ['audit', 'confirm'], true)) {
  1075. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1076. }
  1077. if ($pool === []) {
  1078. $def = $this->resolveProcuremenDefaultYm($stage);
  1079. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  1080. }
  1081. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  1082. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1083. return false;
  1084. }
  1085. $monthStart = $ym . '-01 00:00:00';
  1086. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1087. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  1088. return $probe !== [];
  1089. };
  1090. if ($tryYm($requestedYm)) {
  1091. return $requestedYm;
  1092. }
  1093. $fallback = $this->resolveProcuremenDefaultYm($stage);
  1094. if ($tryYm($fallback)) {
  1095. return $fallback;
  1096. }
  1097. $bestYm = '';
  1098. $bestTime = '';
  1099. foreach ($pool as $row) {
  1100. if (!is_array($row)) {
  1101. continue;
  1102. }
  1103. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  1104. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  1105. continue;
  1106. }
  1107. $ymRow = $m[1];
  1108. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  1109. $bestTime = $t;
  1110. $bestYm = $ymRow;
  1111. }
  1112. }
  1113. if ($bestYm !== '') {
  1114. return $bestYm;
  1115. }
  1116. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1117. }
  1118. protected function isPurchaseOrderDetailVoid(array $row): bool
  1119. {
  1120. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  1121. return true;
  1122. }
  1123. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  1124. }
  1125. /**
  1126. * 仅当前有效下发明细(排除废弃归档)
  1127. */
  1128. protected function applyActivePurchaseOrderDetailWhere($query): void
  1129. {
  1130. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1131. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  1132. }
  1133. /**
  1134. * @param array<string, mixed> $detailRow
  1135. */
  1136. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  1137. {
  1138. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  1139. return false;
  1140. }
  1141. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  1142. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  1143. }
  1144. /**
  1145. * 废弃退回初选:下发明细标记归档,不物理删除
  1146. *
  1147. * @param array<int, int|string> $scydgyIds
  1148. */
  1149. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  1150. {
  1151. $ids = [];
  1152. foreach ($scydgyIds as $sid) {
  1153. $n = (int)$sid;
  1154. if ($this->isValidScydgyRowId($n) || $n < 0) {
  1155. $ids[$n] = true;
  1156. }
  1157. }
  1158. if ($ids === []) {
  1159. return;
  1160. }
  1161. $void = ProcuremenStatus::POD_VOID;
  1162. Db::table('purchase_order_detail')
  1163. ->where('scydgy_id', 'in', array_keys($ids))
  1164. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1165. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  1166. ->update([
  1167. 'status' => $void,
  1168. 'status_name' => $void,
  1169. ]);
  1170. }
  1171. /**
  1172. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  1173. */
  1174. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  1175. {
  1176. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  1177. $norm = function (string $col) use ($p): string {
  1178. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  1179. };
  1180. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  1181. $parts = [];
  1182. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  1183. if ($key === 'createtime') {
  1184. $parts[] = $createtime;
  1185. } else {
  1186. $parts[] = $norm($key);
  1187. }
  1188. }
  1189. return 'COALESCE(' . implode(', ', $parts) . ')';
  1190. }
  1191. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  1192. {
  1193. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  1194. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  1195. }
  1196. /**
  1197. * @return array<int, array<string, mixed>>
  1198. */
  1199. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  1200. {
  1201. $this->ensurePurchaseOrderCzlyqColumn();
  1202. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1203. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  1204. try {
  1205. $query = Db::table('purchase_order')->field($fields);
  1206. $this->applyPurchaseOrderNotDeletedWhere($query);
  1207. if ($stage === 'audit') {
  1208. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1209. } elseif ($stage === 'confirm') {
  1210. $this->applyPurchaseOrderConfirmStageWhere($query);
  1211. } else {
  1212. return [];
  1213. }
  1214. $query->order('pick_time', 'desc')->order('id', 'desc');
  1215. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  1216. $monthStart = $ym . '-01 00:00:00';
  1217. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1218. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  1219. }
  1220. $rows = $query->select();
  1221. } catch (\Throwable $e) {
  1222. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  1223. $rows = [];
  1224. }
  1225. return is_array($rows) ? $rows : [];
  1226. }
  1227. /**
  1228. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  1229. */
  1230. protected function resolveProcuremenListStage(): string
  1231. {
  1232. $tab = trim((string)$this->request->request('wff_tab', ''));
  1233. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  1234. return $tab;
  1235. }
  1236. $action = strtolower((string)$this->request->action());
  1237. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  1238. return $action;
  1239. }
  1240. return 'pick';
  1241. }
  1242. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  1243. {
  1244. $this->procuremenReleaseSessionLock();
  1245. $rootTrue = rtrim((string)$this->request->root(true), '/');
  1246. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  1247. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  1248. $indexPhpRoot = $rootTrue . '/index.php';
  1249. }
  1250. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  1251. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  1252. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  1253. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  1254. $this->view->assign('defaultYm', $defaultYm);
  1255. $this->view->assign('sidebarYearMonths', $sidebar);
  1256. $this->view->assign('procuremenStage', $stage);
  1257. $this->view->assign('procuremenPageTitle', $pageTitle);
  1258. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  1259. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  1260. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  1261. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  1262. $this->assignconfig('procuremenFilterOptions', $this->buildProcuremenFilterOptions($stage));
  1263. }
  1264. /**
  1265. * 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
  1266. *
  1267. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1268. */
  1269. protected function buildProcuremenFilterOptions(string $stage): array
  1270. {
  1271. $buckets = [
  1272. 'czlyq' => [],
  1273. 'CCLBMMC' => [],
  1274. 'cywyxm' => [],
  1275. 'CGYMC' => [],
  1276. ];
  1277. $maxPerField = 300;
  1278. try {
  1279. if ($stage === 'pick') {
  1280. // 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
  1281. return $buckets;
  1282. }
  1283. if (in_array($stage, ['audit', 'confirm'], true)) {
  1284. $this->ensurePurchaseOrderCzlyqColumn();
  1285. foreach (array_keys($buckets) as $field) {
  1286. try {
  1287. $query = Db::table('purchase_order')->field($field);
  1288. $this->applyPurchaseOrderNotDeletedWhere($query);
  1289. if ($stage === 'audit') {
  1290. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1291. } else {
  1292. $this->applyPurchaseOrderConfirmStageWhere($query);
  1293. }
  1294. $query->where($field, '<>', '')->whereNotNull($field);
  1295. $vals = $query->distinct(true)->limit($maxPerField)->column($field);
  1296. if (!is_array($vals)) {
  1297. continue;
  1298. }
  1299. foreach ($vals as $v) {
  1300. $v = trim((string)$v);
  1301. if ($v !== '') {
  1302. $buckets[$field][$v] = $v;
  1303. }
  1304. }
  1305. } catch (\Throwable $e) {
  1306. // 单字段失败不影响其它
  1307. }
  1308. }
  1309. }
  1310. } catch (\Throwable $e) {
  1311. Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
  1312. }
  1313. foreach ($buckets as &$set) {
  1314. if ($set !== []) {
  1315. ksort($set, SORT_STRING);
  1316. }
  1317. }
  1318. unset($set);
  1319. return $buckets;
  1320. }
  1321. /**
  1322. * filter JSON 是否含有效条件
  1323. *
  1324. * @param array<string, mixed> $filterArr
  1325. */
  1326. protected function procuremenFilterArrHasValue(array $filterArr): bool
  1327. {
  1328. foreach ($filterArr as $v) {
  1329. if (is_array($v)) {
  1330. if (array_filter($v, function ($x) {
  1331. return $x !== '' && $x !== null;
  1332. })) {
  1333. return true;
  1334. }
  1335. } elseif ($v !== '' && $v !== null) {
  1336. return true;
  1337. }
  1338. }
  1339. return false;
  1340. }
  1341. /**
  1342. * 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
  1343. *
  1344. * @param array<string, mixed> $filterArr
  1345. * @param array<string, mixed> $opArr
  1346. */
  1347. protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
  1348. {
  1349. if ($search !== '') {
  1350. return false;
  1351. }
  1352. foreach ($filterArr as $fk => $fv) {
  1353. if (is_array($fv)) {
  1354. continue;
  1355. }
  1356. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  1357. continue;
  1358. }
  1359. if ($fv === null) {
  1360. continue;
  1361. }
  1362. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  1363. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  1364. if ($sym === '' || $sym === '=') {
  1365. continue;
  1366. }
  1367. return false;
  1368. }
  1369. return true;
  1370. }
  1371. /**
  1372. * 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
  1373. *
  1374. * @param array<int, mixed> $rows
  1375. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1376. */
  1377. protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
  1378. {
  1379. $buckets = [
  1380. 'czlyq' => [],
  1381. 'CCLBMMC' => [],
  1382. 'cywyxm' => [],
  1383. 'CGYMC' => [],
  1384. ];
  1385. foreach ($rows as $r) {
  1386. if (!is_array($r)) {
  1387. continue;
  1388. }
  1389. foreach ($buckets as $field => &$set) {
  1390. if (count($set) >= $maxPerField) {
  1391. continue;
  1392. }
  1393. $v = trim((string)($r[$field] ?? ''));
  1394. if ($v !== '') {
  1395. $set[$v] = $v;
  1396. }
  1397. }
  1398. unset($set);
  1399. $full = true;
  1400. foreach ($buckets as $set) {
  1401. if (count($set) < $maxPerField) {
  1402. $full = false;
  1403. break;
  1404. }
  1405. }
  1406. if ($full) {
  1407. break;
  1408. }
  1409. }
  1410. foreach ($buckets as &$set) {
  1411. if ($set !== []) {
  1412. // 保证 json 编码为对象(避免 list 下标 0,1,2… 被前端当选项)
  1413. $normalized = [];
  1414. foreach ($set as $k => $v) {
  1415. $s = trim((string)(is_scalar($v) ? $v : $k));
  1416. if ($s === '') {
  1417. continue;
  1418. }
  1419. $normalized[$s] = $s;
  1420. }
  1421. ksort($normalized, SORT_STRING);
  1422. $set = $normalized;
  1423. }
  1424. }
  1425. unset($set);
  1426. return $buckets;
  1427. }
  1428. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  1429. public function pick()
  1430. {
  1431. $this->request->filter(['strip_tags', 'trim']);
  1432. if (!$this->request->isAjax()) {
  1433. $this->assignProcuremenListPage('pick', '协助下发');
  1434. return $this->view->fetch('procuremen/index');
  1435. }
  1436. return $this->index();
  1437. }
  1438. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  1439. public function audit()
  1440. {
  1441. $this->request->filter(['strip_tags', 'trim']);
  1442. if (!$this->request->isAjax()) {
  1443. $this->assignProcuremenListPage('audit', '确认供应商');
  1444. return $this->view->fetch('procuremen/index');
  1445. }
  1446. return $this->index();
  1447. }
  1448. /** 采购确认(定标) */
  1449. public function confirm()
  1450. {
  1451. $this->request->filter(['strip_tags', 'trim']);
  1452. if (!$this->request->isAjax()) {
  1453. $this->assignProcuremenListPage('confirm', '采购确认');
  1454. return $this->view->fetch('procuremen/index');
  1455. }
  1456. return $this->index();
  1457. }
  1458. /**
  1459. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  1460. */
  1461. public function index()
  1462. {
  1463. $this->request->filter(['strip_tags', 'trim']);
  1464. if (!$this->request->isAjax()) {
  1465. $this->assignProcuremenListPage('pick', '协助下发');
  1466. return $this->view->fetch('procuremen/index');
  1467. }
  1468. if ($this->request->request('keyField')) {
  1469. return $this->selectpage();
  1470. }
  1471. $this->procuremenReleaseSessionLock();
  1472. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  1473. $limit = max(10, min(500, (int)$limit));
  1474. $ym = $this->request->request('ym', '');
  1475. $ym = is_string($ym) ? trim($ym) : '';
  1476. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  1477. $wffTab = $this->resolveProcuremenListStage();
  1478. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1479. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  1480. ? $this->resolveProcuremenDefaultYm($wffTab)
  1481. : date('Y-m');
  1482. }
  1483. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1484. $ym = date('Y-m');
  1485. }
  1486. $monthStart = $ym . '-01 00:00:00';
  1487. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1488. $search = trim((string)$this->request->get('search', ''));
  1489. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  1490. $opArr = (array)json_decode($this->request->get('op', ''), true);
  1491. if (!is_array($filterArr)) {
  1492. $filterArr = [];
  1493. }
  1494. if (!is_array($opArr)) {
  1495. $opArr = [];
  1496. }
  1497. // 开标状态为计算字段,不能进池内等值筛选;单独抽出后在合并后再滤
  1498. $bidOpenStatusFilter = '';
  1499. foreach (['bid_open_status_text', 'a.bid_open_status_text'] as $bidFk) {
  1500. if (!array_key_exists($bidFk, $filterArr)) {
  1501. continue;
  1502. }
  1503. $bidOpenStatusFilter = trim((string)$filterArr[$bidFk]);
  1504. unset($filterArr[$bidFk], $opArr[$bidFk]);
  1505. }
  1506. // 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
  1507. $applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
  1508. $hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
  1509. try {
  1510. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  1511. if ($wffTab === 'audit') {
  1512. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  1513. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  1514. );
  1515. } elseif ($wffTab === 'confirm') {
  1516. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  1517. if ($dbRows === []) {
  1518. try {
  1519. $dbRows = Db::table('purchase_order')
  1520. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1521. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  1522. ->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%\')')
  1523. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  1524. ->order('pick_time', 'desc')->order('id', 'desc')
  1525. ->select();
  1526. } catch (\Throwable $e) {
  1527. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  1528. $dbRows = [];
  1529. }
  1530. }
  1531. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  1532. if ($pool === []) {
  1533. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1534. }
  1535. } else {
  1536. // 初选:按月直查 ERP(不解整包 Redis,避免长时间转圈)
  1537. if ($applyMonthRange) {
  1538. $pool = $this->loadPickPoolForYm($ym);
  1539. } else {
  1540. $pool = $this->procuremenEnsureRedisPool();
  1541. }
  1542. if (!is_array($pool)) {
  1543. $pool = [];
  1544. }
  1545. // 只针对本页候选 ID 查隐藏集,避免全表扫 purchase_order_detail
  1546. $hideSet = $this->loadPickHiddenScydgySetForIds($this->extractScydgyIdsFromPool($pool));
  1547. if ($pool !== [] && $hideSet !== []) {
  1548. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1549. if (!is_array($r)) {
  1550. return false;
  1551. }
  1552. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1553. return $id <= 0 || !isset($hideSet[$id]);
  1554. }));
  1555. }
  1556. // 手工新增(YW / scydgy_id<0)只走「新增询价/查询询价」,不进初选表格
  1557. if ($pool === []) {
  1558. return json([
  1559. 'total' => 0,
  1560. 'rows' => [],
  1561. 'activeYm' => $ym,
  1562. 'filterOptions' => (
  1563. (int)$offset === 0
  1564. && !$hasActiveSearch
  1565. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1566. )
  1567. ? $this->extractProcuremenFilterOptionsFromRows([])
  1568. : new \stdClass(),
  1569. ]);
  1570. }
  1571. }
  1572. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  1573. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  1574. $monthStart = $ym . '-01 00:00:00';
  1575. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1576. }
  1577. $filtered = $this->filterProcuremenIndexPool(
  1578. $pool,
  1579. $monthStart,
  1580. $monthEnd,
  1581. $applyMonthRange,
  1582. $search,
  1583. $filterArr,
  1584. $opArr,
  1585. $listTimePrimary
  1586. );
  1587. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1588. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1589. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1590. }
  1591. if ($wffTab === 'audit' && $bidOpenStatusFilter !== '') {
  1592. $filtered = $this->filterProcuremenPoolByBidOpenStatus($filtered, $bidOpenStatusFilter);
  1593. }
  1594. $sortField = 'ID';
  1595. if (is_string($sort) && $sort !== '') {
  1596. $parts = explode(',', $sort);
  1597. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1598. if ($sortField === '') {
  1599. $sortField = 'ID';
  1600. }
  1601. }
  1602. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1603. $nFiltered = count($filtered);
  1604. if ($nFiltered > 1) {
  1605. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1606. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1607. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1608. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1609. if ($ta === $tb) {
  1610. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1611. }
  1612. if ($ta === '') {
  1613. return 1;
  1614. }
  1615. if ($tb === '') {
  1616. return -1;
  1617. }
  1618. return strcmp($ta, $tb) * $ord;
  1619. });
  1620. } elseif ($sortField === 'ID') {
  1621. $sortKeys = [];
  1622. foreach ($filtered as $i => $row) {
  1623. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1624. }
  1625. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1626. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1627. } elseif ($sortField === 'CCYDH') {
  1628. usort($filtered, function ($a, $b) use ($ord) {
  1629. $sa = trim((string)($a['CCYDH'] ?? ''));
  1630. $sb = trim((string)($b['CCYDH'] ?? ''));
  1631. if ($sa === $sb) {
  1632. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1633. }
  1634. if ($sa === '') {
  1635. return 1;
  1636. }
  1637. if ($sb === '') {
  1638. return -1;
  1639. }
  1640. return strcmp($sa, $sb) * $ord;
  1641. });
  1642. } else {
  1643. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1644. $va = $a[$sortField] ?? null;
  1645. $vb = $b[$sortField] ?? null;
  1646. $sa = (string)$va;
  1647. $sb = (string)$vb;
  1648. if ($sa === $sb) {
  1649. return 0;
  1650. }
  1651. return strcmp($sa, $sb) * $ord;
  1652. });
  1653. }
  1654. }
  1655. $offset = max(0, (int)$offset);
  1656. $limit = max(1, (int)$limit);
  1657. $rows = array_slice($filtered, $offset, $limit);
  1658. foreach ($rows as &$rw) {
  1659. if (!is_array($rw)) {
  1660. continue;
  1661. }
  1662. $rid = (int)($rw['ID'] ?? 0);
  1663. $rw['_iss_out'] = ($wffTab !== 'pick');
  1664. }
  1665. unset($rw);
  1666. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1667. $idList = [];
  1668. foreach ($rows as $rw) {
  1669. if (!is_array($rw)) {
  1670. continue;
  1671. }
  1672. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1673. foreach ($rw['_order_merge_rows'] as $mr) {
  1674. $mid = (int)($mr['ID'] ?? 0);
  1675. if ($this->isValidScydgyRowId($mid)) {
  1676. $idList[$mid] = true;
  1677. }
  1678. }
  1679. }
  1680. $id = (int)($rw['ID'] ?? 0);
  1681. if ($this->isValidScydgyRowId($id)) {
  1682. $idList[$id] = true;
  1683. }
  1684. }
  1685. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1686. foreach ($rows as &$rw) {
  1687. if (!is_array($rw)) {
  1688. continue;
  1689. }
  1690. $mergeIds = [];
  1691. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1692. foreach ($rw['_order_merge_rows'] as $mr) {
  1693. $mid = (int)($mr['ID'] ?? 0);
  1694. if ($this->isValidScydgyRowId($mid)) {
  1695. $mergeIds[$mid] = true;
  1696. }
  1697. }
  1698. }
  1699. $rid = (int)($rw['ID'] ?? 0);
  1700. if ($this->isValidScydgyRowId($rid)) {
  1701. $mergeIds[$rid] = true;
  1702. }
  1703. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1704. $rw['po_detail_count'] = $s['cnt'];
  1705. $rw['po_amount_fill_cnt'] = $s['amt'];
  1706. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1707. }
  1708. unset($rw);
  1709. }
  1710. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1711. $idList = [];
  1712. foreach ($rows as $rw) {
  1713. if (!is_array($rw)) {
  1714. continue;
  1715. }
  1716. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1717. foreach ($rw['_order_merge_rows'] as $mr) {
  1718. $mid = (int)($mr['ID'] ?? 0);
  1719. if ($this->isValidScydgyRowId($mid)) {
  1720. $idList[$mid] = true;
  1721. }
  1722. }
  1723. }
  1724. $id = (int)($rw['ID'] ?? 0);
  1725. if ($this->isValidScydgyRowId($id)) {
  1726. $idList[$id] = true;
  1727. }
  1728. }
  1729. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1730. $bidOpenSet = [];
  1731. $manualPickSet = [];
  1732. if ($wffTab === 'audit') {
  1733. $ccydhList = [];
  1734. foreach ($rows as $rw0) {
  1735. if (!is_array($rw0)) {
  1736. continue;
  1737. }
  1738. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1739. if ($c0 !== '') {
  1740. $ccydhList[] = $c0;
  1741. }
  1742. }
  1743. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1744. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  1745. }
  1746. foreach ($rows as &$rw) {
  1747. if (!is_array($rw)) {
  1748. continue;
  1749. }
  1750. $mergeIds = [];
  1751. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1752. foreach ($rw['_order_merge_rows'] as $mr) {
  1753. $mid = (int)($mr['ID'] ?? 0);
  1754. if ($this->isValidScydgyRowId($mid)) {
  1755. $mergeIds[$mid] = true;
  1756. }
  1757. }
  1758. }
  1759. $rid = (int)($rw['ID'] ?? 0);
  1760. if ($this->isValidScydgyRowId($rid)) {
  1761. $mergeIds[$rid] = true;
  1762. }
  1763. $buckets = [];
  1764. foreach (array_keys($mergeIds) as $mid) {
  1765. if (isset($quoteBucket[$mid])) {
  1766. $buckets[] = $quoteBucket[$mid];
  1767. }
  1768. }
  1769. $supplierText = $buckets !== []
  1770. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1771. : '';
  1772. if ($wffTab === 'confirm') {
  1773. $picked = trim((string)($rw['pick_company_name'] ?? $rw['picked_supplier_name'] ?? ''));
  1774. if ($picked === '') {
  1775. // 兜底:从合并工序行取
  1776. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1777. foreach ($rw['_order_merge_rows'] as $mr) {
  1778. if (!is_array($mr)) {
  1779. continue;
  1780. }
  1781. $pn = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  1782. if ($pn !== '') {
  1783. $picked = $pn;
  1784. break;
  1785. }
  1786. }
  1787. }
  1788. }
  1789. $rw['picked_supplier_name'] = $picked;
  1790. } else {
  1791. $rw['notify_supplier_text'] = $supplierText;
  1792. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1793. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1794. $manualPicked = ($ccydh !== '' && isset($manualPickSet[$ccydh]));
  1795. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1796. $rw['manual_picked'] = $manualPicked ? 1 : 0;
  1797. if ($verified) {
  1798. $rw['bid_open_status_text'] = '已开标';
  1799. } elseif ($manualPicked) {
  1800. $rw['bid_open_status_text'] = '已指定供应商';
  1801. } else {
  1802. $rw['bid_open_status_text'] = '待开标';
  1803. }
  1804. }
  1805. }
  1806. unset($rw);
  1807. }
  1808. if (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
  1809. $this->enrichProcuremenListMilestoneTimes($rows);
  1810. $this->syncCollapsedOrderQtyPriceForList($rows);
  1811. }
  1812. if ($wffTab === 'all' && count($rows) > 0) {
  1813. $this->mergePurchaseOrder($rows);
  1814. }
  1815. if ($wffTab === 'pick' && count($rows) > 0) {
  1816. $this->mergePurchaseOrder($rows);
  1817. }
  1818. foreach ($rows as &$rwClean) {
  1819. if (is_array($rwClean)) {
  1820. unset($rwClean['_order_merge_rows']);
  1821. if (array_key_exists('NGZL', $rwClean)) {
  1822. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1823. }
  1824. }
  1825. }
  1826. unset($rwClean);
  1827. return json([
  1828. 'total' => count($filtered),
  1829. 'rows' => $rows,
  1830. 'activeYm' => $ym,
  1831. // 初选:把有数据的月份带回,替换「空月份日历」侧栏
  1832. 'sidebarYms' => ($wffTab === 'pick' && (int)$offset === 0)
  1833. ? $this->ensureProcuremenPickSidebarYmList()
  1834. : [],
  1835. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1836. 'filterOptions' => (
  1837. (int)$offset === 0
  1838. && !$hasActiveSearch
  1839. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1840. )
  1841. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1842. : new \stdClass(),
  1843. ]);
  1844. } catch (\Throwable $e) {
  1845. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1846. return json([
  1847. 'total' => 0,
  1848. 'rows' => [],
  1849. ]);
  1850. }
  1851. }
  1852. /**
  1853. * @param array<int, array<string, mixed>> $pool
  1854. * @return int[]
  1855. */
  1856. protected function extractScydgyIdsFromPool(array $pool): array
  1857. {
  1858. $ids = [];
  1859. foreach ($pool as $r) {
  1860. if (!is_array($r)) {
  1861. continue;
  1862. }
  1863. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1864. if ($id > 0) {
  1865. $ids[$id] = $id;
  1866. }
  1867. }
  1868. return array_values($ids);
  1869. }
  1870. /**
  1871. * 仅查询指定工序 ID 是否已下发/进入后续流程(初选列表加速)
  1872. *
  1873. * @param int[] $scydgyIds
  1874. * @return array<int, true>
  1875. */
  1876. protected function loadPickHiddenScydgySetForIds(array $scydgyIds): array
  1877. {
  1878. $hideSet = [];
  1879. $scydgyIds = array_values(array_filter(array_map('intval', $scydgyIds), function ($id) {
  1880. return $id > 0;
  1881. }));
  1882. if ($scydgyIds === []) {
  1883. return $hideSet;
  1884. }
  1885. // 分批,避免 whereIn 过长
  1886. foreach (array_chunk($scydgyIds, 500) as $chunk) {
  1887. try {
  1888. $poIds = Db::table('purchase_order')
  1889. ->where('scydgy_id', 'in', $chunk)
  1890. ->where(function ($q) {
  1891. $q->whereIn('wflow_status', array_merge(
  1892. ProcuremenStatus::wflowPendingConfirmValues(),
  1893. ProcuremenStatus::wflowPendingApprovalValues()
  1894. ))
  1895. ->whereOr(function ($q1) {
  1896. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1897. })
  1898. ->whereOr(function ($q2) {
  1899. $q2->whereNotNull('pick_time')
  1900. ->where('pick_time', '<>', '')
  1901. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1902. })
  1903. ->whereOr(function ($q3) {
  1904. $q3->whereNotNull('mod_rq')
  1905. ->where('mod_rq', '<>', '')
  1906. ->where('mod_rq', 'not like', '0000-00-00%');
  1907. });
  1908. })
  1909. ->column('scydgy_id');
  1910. if (is_array($poIds)) {
  1911. foreach ($poIds as $pid) {
  1912. $k = (int)$pid;
  1913. if ($k !== 0) {
  1914. $hideSet[$k] = true;
  1915. }
  1916. }
  1917. }
  1918. } catch (\Throwable $e) {
  1919. }
  1920. try {
  1921. $detIdsQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $chunk);
  1922. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1923. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1924. if (is_array($detIds)) {
  1925. foreach ($detIds as $pid) {
  1926. $k = (int)$pid;
  1927. if ($this->isValidScydgyRowId($k)) {
  1928. $hideSet[$k] = true;
  1929. }
  1930. }
  1931. }
  1932. } catch (\Throwable $e) {
  1933. }
  1934. }
  1935. return $hideSet;
  1936. }
  1937. /**
  1938. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1939. *
  1940. * @return array<int, true>
  1941. */
  1942. protected function loadPickHiddenScydgySet(): array
  1943. {
  1944. if ($this->pickHiddenScydgySetCache !== null) {
  1945. return $this->pickHiddenScydgySetCache;
  1946. }
  1947. $cacheKey = 'procuremen_pick_hidden_scydgy_v1';
  1948. try {
  1949. $raw = redis()->get($cacheKey);
  1950. if ($raw !== false && $raw !== null && $raw !== '') {
  1951. $ids = json_decode((string)$raw, true);
  1952. if (is_array($ids)) {
  1953. $hideSet = [];
  1954. foreach ($ids as $pid) {
  1955. $k = (int)$pid;
  1956. if ($k !== 0) {
  1957. $hideSet[$k] = true;
  1958. }
  1959. }
  1960. $this->pickHiddenScydgySetCache = $hideSet;
  1961. return $hideSet;
  1962. }
  1963. }
  1964. } catch (\Throwable $e) {
  1965. }
  1966. $hideSet = [];
  1967. try {
  1968. $poIds = Db::table('purchase_order')
  1969. ->where(function ($q) {
  1970. $q->whereIn('wflow_status', array_merge(
  1971. ProcuremenStatus::wflowPendingConfirmValues(),
  1972. ProcuremenStatus::wflowPendingApprovalValues()
  1973. ))
  1974. ->whereOr(function ($q1) {
  1975. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1976. })
  1977. ->whereOr(function ($q2) {
  1978. $q2->whereNotNull('pick_time')
  1979. ->where('pick_time', '<>', '')
  1980. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1981. })
  1982. ->whereOr(function ($q3) {
  1983. $q3->whereNotNull('mod_rq')
  1984. ->where('mod_rq', '<>', '')
  1985. ->where('mod_rq', 'not like', '0000-00-00%');
  1986. });
  1987. })
  1988. ->column('scydgy_id');
  1989. if (is_array($poIds)) {
  1990. foreach ($poIds as $pid) {
  1991. $k = (int)$pid;
  1992. if ($k !== 0) {
  1993. $hideSet[$k] = true;
  1994. }
  1995. }
  1996. }
  1997. } catch (\Throwable $e) {
  1998. }
  1999. try {
  2000. $detIdsQuery = Db::table('purchase_order_detail');
  2001. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  2002. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  2003. if (is_array($detIds)) {
  2004. foreach ($detIds as $pid) {
  2005. $k = (int)$pid;
  2006. if ($this->isValidScydgyRowId($k)) {
  2007. $hideSet[$k] = true;
  2008. }
  2009. }
  2010. }
  2011. } catch (\Throwable $e) {
  2012. }
  2013. $this->pickHiddenScydgySetCache = $hideSet;
  2014. try {
  2015. redis()->setex($cacheKey, 90, json_encode(array_map('intval', array_keys($hideSet))));
  2016. } catch (\Throwable $e) {
  2017. }
  2018. return $hideSet;
  2019. }
  2020. /**
  2021. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  2022. *
  2023. * @return array<int, array<string, mixed>>
  2024. */
  2025. protected function loadPickManualOrderRows(): array
  2026. {
  2027. try {
  2028. $dbRows = Db::table('purchase_order')
  2029. ->where('scydgy_id', '<', 0)
  2030. ->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%\')')
  2031. ->order('scydgy_id', 'asc')
  2032. ->select();
  2033. } catch (\Throwable $e) {
  2034. try {
  2035. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  2036. } catch (\Throwable $e2) {
  2037. return [];
  2038. }
  2039. }
  2040. if (!is_array($dbRows) || $dbRows === []) {
  2041. return [];
  2042. }
  2043. $detailSidSet = [];
  2044. try {
  2045. $negIds = [];
  2046. foreach ($dbRows as $dbRow) {
  2047. if (!is_array($dbRow)) {
  2048. continue;
  2049. }
  2050. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2051. if ($sid < 0) {
  2052. $negIds[$sid] = true;
  2053. }
  2054. }
  2055. if ($negIds !== []) {
  2056. $detQuery = Db::table('purchase_order_detail')
  2057. ->where('scydgy_id', 'in', array_keys($negIds));
  2058. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  2059. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  2060. if (is_array($detRows)) {
  2061. foreach ($detRows as $did) {
  2062. $detailSidSet[(int)$did] = true;
  2063. }
  2064. }
  2065. }
  2066. } catch (\Throwable $e) {
  2067. }
  2068. $pool = [];
  2069. foreach ($dbRows as $dbRow) {
  2070. if (!is_array($dbRow)) {
  2071. continue;
  2072. }
  2073. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2074. if ($sid >= 0) {
  2075. continue;
  2076. }
  2077. // 已进入确认/审批的不进初选;仅废弃明细残留的仍算可下发
  2078. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  2079. continue;
  2080. }
  2081. // 仅排除已完结;空 status / 「进行中」/ 0 均保留(新建手工单)
  2082. if (ProcuremenStatus::isPoCompleted($dbRow['status'] ?? '')) {
  2083. continue;
  2084. }
  2085. if (isset($detailSidSet[$sid])) {
  2086. continue;
  2087. }
  2088. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  2089. $r['_is_manual'] = 1;
  2090. $pool[] = $r;
  2091. }
  2092. return $pool;
  2093. }
  2094. /**
  2095. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  2096. */
  2097. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  2098. {
  2099. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  2100. foreach ($keys as $k) {
  2101. $t = trim((string)($row[$k] ?? ''));
  2102. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2103. return $t;
  2104. }
  2105. }
  2106. return '';
  2107. }
  2108. /**
  2109. * 分配手工新增工序行 ID(负数递减)
  2110. * 调用方须在命名锁内执行,避免并发重复
  2111. */
  2112. protected function allocateManualScydgyId(): int
  2113. {
  2114. try {
  2115. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  2116. $min = (int)$min;
  2117. return $min < 0 ? $min - 1 : -1;
  2118. } catch (\Throwable $e) {
  2119. return -1;
  2120. }
  2121. }
  2122. /**
  2123. * 手工新增订单号:YW + 年月日 + 当日序号(如 YW20260618001)
  2124. * 调用方须在命名锁内执行,避免并发重复
  2125. */
  2126. protected function allocateManualOrderCcydh(): string
  2127. {
  2128. $prefix = 'YW' . date('Ymd');
  2129. $maxSeq = 0;
  2130. try {
  2131. $rows = Db::table('purchase_order')
  2132. ->where('CCYDH', 'like', $prefix . '%')
  2133. ->column('CCYDH');
  2134. if (is_array($rows)) {
  2135. foreach ($rows as $ccydh) {
  2136. $ccydh = trim((string)$ccydh);
  2137. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3,})$/', $ccydh, $m)) {
  2138. $maxSeq = max($maxSeq, (int)$m[1]);
  2139. }
  2140. }
  2141. }
  2142. } catch (\Throwable $e) {
  2143. }
  2144. $next = $maxSeq + 1;
  2145. $width = $next > 999 ? strlen((string)$next) : 3;
  2146. return $prefix . str_pad((string)$next, $width, '0', STR_PAD_LEFT);
  2147. }
  2148. /**
  2149. * MySQL 命名锁(跨连接防并发撞号)
  2150. */
  2151. protected function acquireProcuremenNamedLock(string $name, int $timeoutSec = 10): bool
  2152. {
  2153. $name = trim($name);
  2154. if ($name === '') {
  2155. return false;
  2156. }
  2157. try {
  2158. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2159. $rows = Db::query('SELECT GET_LOCK(\'' . $nameSql . '\', ' . max(1, $timeoutSec) . ') AS locked');
  2160. if (!is_array($rows) || $rows === []) {
  2161. return false;
  2162. }
  2163. $v = $rows[0]['locked'] ?? $rows[0]['LOCKED'] ?? null;
  2164. return (int)$v === 1;
  2165. } catch (\Throwable $e) {
  2166. return false;
  2167. }
  2168. }
  2169. protected function releaseProcuremenNamedLock(string $name): void
  2170. {
  2171. $name = trim($name);
  2172. if ($name === '') {
  2173. return;
  2174. }
  2175. try {
  2176. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2177. Db::query('SELECT RELEASE_LOCK(\'' . $nameSql . '\')');
  2178. } catch (\Throwable $e) {
  2179. }
  2180. }
  2181. /**
  2182. * purchase_order.mod_rq 是否有有效软删除时间
  2183. */
  2184. protected function isPurchaseOrderSoftDeleted($modRq): bool
  2185. {
  2186. $t = trim((string)$modRq);
  2187. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  2188. }
  2189. /**
  2190. * 列表行 → purchase_order 写入字段
  2191. *
  2192. * @return array<string, mixed>
  2193. */
  2194. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  2195. {
  2196. return [
  2197. 'scydgy_id' => $scydgyId,
  2198. 'CCYDH' => $row['CCYDH'] ?? null,
  2199. 'CYJMC' => $row['CYJMC'] ?? null,
  2200. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2201. 'CDXMC' => $row['CDXMC'] ?? null,
  2202. 'CGYBH' => $row['CGYBH'] ?? null,
  2203. 'CGYMC' => $row['CGYMC'] ?? null,
  2204. 'CDW' => $row['CDW'] ?? null,
  2205. 'czlyq' => $row['czlyq'] ?? null,
  2206. 'NGZL' => $row['NGZL'] ?? null,
  2207. 'CDF' => $row['CDF'] ?? null,
  2208. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2209. 'MBZ' => $row['MBZ'] ?? null,
  2210. 'bwjg' => $row['bwjg'] ?? null,
  2211. 'iStatus' => $row['iStatus'] ?? null,
  2212. 'dStamp' => $row['dStamp'] ?? null,
  2213. 'dputrecord' => $row['dputrecord'] ?? null,
  2214. 'cywyxm' => $row['cywyxm'] ?? null,
  2215. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2216. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2217. ];
  2218. }
  2219. /**
  2220. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  2221. *
  2222. * @return array{po:?array<string,mixed>, hidden:bool}
  2223. */
  2224. protected function resolvePickRowPoContext(int $sid): array
  2225. {
  2226. $po = null;
  2227. try {
  2228. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2229. if (is_array($found)) {
  2230. $po = $found;
  2231. }
  2232. } catch (\Throwable $e) {
  2233. }
  2234. $hideSet = $this->loadPickHiddenScydgySet();
  2235. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  2236. }
  2237. /**
  2238. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  2239. */
  2240. protected function assertPickRowCanDelete(int $sid, array $row): void
  2241. {
  2242. $ctx = $this->resolvePickRowPoContext($sid);
  2243. $po = $ctx['po'];
  2244. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2245. return;
  2246. }
  2247. if (is_array($po)) {
  2248. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2249. throw new \InvalidArgumentException('该工序已完结,无法删除');
  2250. }
  2251. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2252. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  2253. }
  2254. }
  2255. if ($ctx['hidden']) {
  2256. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2257. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  2258. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  2259. }
  2260. }
  2261. /**
  2262. * 初选直接完结前校验
  2263. */
  2264. protected function assertPickRowCanComplete(int $sid, array $row): void
  2265. {
  2266. $ctx = $this->resolvePickRowPoContext($sid);
  2267. $po = $ctx['po'];
  2268. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2269. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  2270. }
  2271. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2272. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  2273. }
  2274. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  2275. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  2276. }
  2277. }
  2278. /**
  2279. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  2280. */
  2281. protected function softDeleteProcuremenPickRow(array $row): void
  2282. {
  2283. $sid = $this->extractScydgyRowId($row);
  2284. if (!$this->isValidScydgyRowId($sid)) {
  2285. throw new \InvalidArgumentException('无效的行主键');
  2286. }
  2287. $this->assertPickRowCanDelete($sid, $row);
  2288. $po = $this->resolvePickRowPoContext($sid)['po'];
  2289. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2290. return;
  2291. }
  2292. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2293. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  2294. }
  2295. $now = date('Y-m-d H:i:s');
  2296. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2297. if (is_array($exists)) {
  2298. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  2299. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  2300. } else {
  2301. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  2302. $data['mod_rq'] = $now;
  2303. $data['createtime'] = $now;
  2304. Db::table('purchase_order')->insert($data);
  2305. $poIdLog = (int)Db::getLastInsID();
  2306. }
  2307. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  2308. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  2309. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  2310. if ($gymcLog !== '') {
  2311. $logTail .= ' / ' . $gymcLog;
  2312. }
  2313. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  2314. }
  2315. /**
  2316. * 手工新增协助工序(写入 purchase_order)
  2317. *
  2318. * @param array<string, mixed> $params
  2319. * @return int scydgy_id
  2320. */
  2321. protected function saveManualPickOrder(array $params): int
  2322. {
  2323. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  2324. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  2325. $ccydhIn = trim((string)($params['CCYDH'] ?? ''));
  2326. $lockName = 'procuremen_manual_order_alloc';
  2327. if (!$this->acquireProcuremenNamedLock($lockName, 10)) {
  2328. throw new \RuntimeException('系统繁忙,请稍后重试');
  2329. }
  2330. try {
  2331. $ccydh = $ccydhIn !== '' ? $ccydhIn : $this->allocateManualOrderCcydh();
  2332. $now = date('Y-m-d H:i:s');
  2333. $sid = $this->allocateManualScydgyId();
  2334. $this->ensurePurchaseOrderNotifySalesmanColumn();
  2335. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  2336. // 选择供应商 / 通知业务员:支持多选,落库用顿号拼接
  2337. $supplierName = $this->joinRfqMultiSelectValues($params['cGzzxMc'] ?? ($params['pick_company_name'] ?? ''));
  2338. $notifySalesman = $this->joinRfqMultiSelectValues($params['notify_salesman'] ?? '');
  2339. $data = [
  2340. 'scydgy_id' => $sid,
  2341. 'CCYDH' => $ccydh,
  2342. 'CYJMC' => $cyjmc,
  2343. 'CGYMC' => $cgymc,
  2344. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  2345. 'CDW' => trim((string)($params['CDW'] ?? '')),
  2346. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  2347. 'CDF' => trim((string)($params['CDF'] ?? '')),
  2348. 'cGzzxMc' => $supplierName,
  2349. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  2350. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  2351. 'notify_salesman' => $notifySalesman,
  2352. 'rfq_salesman_notified' => 0,
  2353. 'rfq_salesman_notify_time' => null,
  2354. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  2355. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  2356. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  2357. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  2358. 'createtime' => $now,
  2359. 'dStamp' => $now,
  2360. 'dputrecord' => $now,
  2361. ];
  2362. Db::table('purchase_order')->insert($data);
  2363. $poId = (int)Db::getLastInsID();
  2364. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  2365. return $sid;
  2366. } finally {
  2367. $this->releaseProcuremenNamedLock($lockName);
  2368. }
  2369. }
  2370. protected function formatProcuremenRowLabel(array $row): string
  2371. {
  2372. $dh = trim((string)($row['CCYDH'] ?? ''));
  2373. $gymc = trim((string)($row['CGYMC'] ?? ''));
  2374. if ($dh !== '' && $gymc !== '') {
  2375. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  2376. }
  2377. if ($dh !== '') {
  2378. return '订单「' . $dh . '」';
  2379. }
  2380. if ($gymc !== '') {
  2381. return '工序「' . $gymc . '」';
  2382. }
  2383. $id = $this->extractScydgyRowId($row);
  2384. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  2385. }
  2386. /**
  2387. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  2388. */
  2389. protected function extractScydgyRowId(array $row): int
  2390. {
  2391. // 优先 scydgy_id,避免明细行 ID(自增主键)被误当成工序主键;手工单为负数
  2392. if (array_key_exists('scydgy_id', $row) && $row['scydgy_id'] !== null && $row['scydgy_id'] !== '') {
  2393. return (int)$row['scydgy_id'];
  2394. }
  2395. if (array_key_exists('SCYDGY_ID', $row) && $row['SCYDGY_ID'] !== null && $row['SCYDGY_ID'] !== '') {
  2396. return (int)$row['SCYDGY_ID'];
  2397. }
  2398. return (int)($row['ID'] ?? $row['id'] ?? 0);
  2399. }
  2400. protected function isValidScydgyRowId(int $id): bool
  2401. {
  2402. return ProcuremenGuard::isValidScydgyId($id);
  2403. }
  2404. protected function isManualScydgyRowId(int $id): bool
  2405. {
  2406. return $id < 0;
  2407. }
  2408. /**
  2409. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  2410. *
  2411. * @param int[] $scydgyIds
  2412. * @return array<int, string[]>
  2413. */
  2414. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  2415. {
  2416. $out = [];
  2417. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2418. if ($scydgyIds === []) {
  2419. return $out;
  2420. }
  2421. try {
  2422. $rows = Db::table('purchase_order_detail')
  2423. ->where('scydgy_id', 'in', $scydgyIds)
  2424. ->field('scydgy_id,company_name')
  2425. ->order('company_name', 'asc')
  2426. ->select();
  2427. } catch (\Throwable $e) {
  2428. $rows = [];
  2429. }
  2430. if (!is_array($rows)) {
  2431. return $out;
  2432. }
  2433. foreach ($rows as $r) {
  2434. if (!is_array($r)) {
  2435. continue;
  2436. }
  2437. $sid = (int)($r['scydgy_id'] ?? 0);
  2438. $cn = trim((string)($r['company_name'] ?? ''));
  2439. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2440. continue;
  2441. }
  2442. if (!isset($out[$sid])) {
  2443. $out[$sid] = [];
  2444. }
  2445. if (!in_array($cn, $out[$sid], true)) {
  2446. $out[$sid][] = $cn;
  2447. }
  2448. }
  2449. return $out;
  2450. }
  2451. /**
  2452. * 列表展示通知供应商(完整列表,前端单行省略展开)
  2453. *
  2454. * @param string[] $names
  2455. */
  2456. protected function formatNotifySupplierDisplay(array $names): string
  2457. {
  2458. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  2459. return trim((string)$n);
  2460. }, $names))));
  2461. if ($names === []) {
  2462. return '';
  2463. }
  2464. sort($names, SORT_STRING);
  2465. return implode("\n", $names);
  2466. }
  2467. /**
  2468. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  2469. *
  2470. * @param int[] $scydgyIds
  2471. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  2472. */
  2473. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  2474. {
  2475. $out = [];
  2476. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2477. if ($scydgyIds === []) {
  2478. return $out;
  2479. }
  2480. try {
  2481. $rows = Db::table('purchase_order_detail')
  2482. ->where('scydgy_id', 'in', $scydgyIds)
  2483. ->field('scydgy_id,company_name,amount')
  2484. ->select();
  2485. } catch (\Throwable $e) {
  2486. $rows = [];
  2487. }
  2488. if (!is_array($rows)) {
  2489. return $out;
  2490. }
  2491. foreach ($rows as $r) {
  2492. if (!is_array($r)) {
  2493. continue;
  2494. }
  2495. $sid = (int)($r['scydgy_id'] ?? 0);
  2496. $cn = trim((string)($r['company_name'] ?? ''));
  2497. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2498. continue;
  2499. }
  2500. if (!isset($out[$sid])) {
  2501. $out[$sid] = ['all' => [], 'quoted' => []];
  2502. }
  2503. $out[$sid]['all'][$cn] = true;
  2504. $am = trim((string)($r['amount'] ?? ''));
  2505. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2506. $out[$sid]['quoted'][$cn] = true;
  2507. }
  2508. }
  2509. return $out;
  2510. }
  2511. /**
  2512. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  2513. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  2514. */
  2515. protected function mergeQuotedSupplierBuckets(array $buckets): array
  2516. {
  2517. $merged = ['all' => [], 'quoted' => []];
  2518. foreach ($buckets as $b) {
  2519. if (!is_array($b)) {
  2520. continue;
  2521. }
  2522. foreach ($b['all'] ?? [] as $cn => $_) {
  2523. $merged['all'][$cn] = true;
  2524. }
  2525. foreach ($b['quoted'] ?? [] as $cn => $_) {
  2526. $merged['quoted'][$cn] = true;
  2527. }
  2528. }
  2529. return $merged;
  2530. }
  2531. /**
  2532. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  2533. */
  2534. protected function formatQuotedSupplierLines(array $bucket): string
  2535. {
  2536. $all = array_keys($bucket['all'] ?? []);
  2537. if ($all === []) {
  2538. return '';
  2539. }
  2540. sort($all, SORT_STRING);
  2541. $lines = [];
  2542. foreach ($all as $cn) {
  2543. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  2544. $lines[] = $cn . '(' . $status . ')';
  2545. }
  2546. return implode("\n", $lines);
  2547. }
  2548. /**
  2549. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  2550. */
  2551. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  2552. {
  2553. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2554. $this->view->engine->layout(false);
  2555. try {
  2556. $bodyHtml = $this->view->fetch($view);
  2557. $this->view->assign('dialogBody', $bodyHtml);
  2558. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  2559. return $this->view->fetch('procuremen/dialog_lite_shell');
  2560. } finally {
  2561. if ($restoreLayout) {
  2562. $this->view->engine->layout($restoreLayout);
  2563. }
  2564. }
  2565. }
  2566. /**
  2567. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  2568. */
  2569. protected function resolveBundleSysRq(array $bundle): string
  2570. {
  2571. foreach ($bundle['pos'] ?? [] as $po) {
  2572. if (!is_array($po)) {
  2573. continue;
  2574. }
  2575. $sr = trim((string)($po['sys_rq'] ?? ''));
  2576. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  2577. return $sr;
  2578. }
  2579. }
  2580. return '';
  2581. }
  2582. /**
  2583. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  2584. */
  2585. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  2586. {
  2587. $raw = trim((string)$sysRq);
  2588. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  2589. return true;
  2590. }
  2591. $ts = strtotime(str_replace('T', ' ', $raw));
  2592. if ($ts === false || $ts <= 0) {
  2593. return true;
  2594. }
  2595. return time() >= $ts;
  2596. }
  2597. /**
  2598. * 开标前校验:必须已过报价截止时间
  2599. *
  2600. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2601. */
  2602. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  2603. {
  2604. $sysRq = $this->resolveBundleSysRq($bundle);
  2605. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  2606. $this->error('未到招标截止日期');
  2607. }
  2608. }
  2609. /**
  2610. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  2611. *
  2612. * @param array<string, mixed> $d
  2613. * @param string $deliveryYmd
  2614. */
  2615. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  2616. {
  2617. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  2618. return max(0, (int)$d['lead_days']);
  2619. }
  2620. if ($deliveryYmd === '') {
  2621. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  2622. }
  2623. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  2624. return null;
  2625. }
  2626. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2627. $t2 = strtotime($m[1] . ' 00:00:00');
  2628. if ($t1 === false || $t2 === false) {
  2629. return null;
  2630. }
  2631. return max(0, (int)round(($t2 - $t1) / 86400));
  2632. }
  2633. /**
  2634. * @param int|null $days
  2635. */
  2636. protected function formatProcuremenLeadDaysText($days): string
  2637. {
  2638. if ($days === null || $days === '') {
  2639. return '未填写';
  2640. }
  2641. if (!is_numeric($days)) {
  2642. return '未填写';
  2643. }
  2644. return ((int)$days) . '天';
  2645. }
  2646. /**
  2647. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2648. *
  2649. * @param array<string, mixed> $line
  2650. */
  2651. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2652. {
  2653. $amountFilled = !empty($line['amount_filled']);
  2654. $deliveryFilled = !empty($line['delivery_filled']);
  2655. $leadFilled = !empty($line['lead_days_filled']);
  2656. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2657. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2658. $line['amount_show'] = '';
  2659. if (array_key_exists('amount_text', $line)) {
  2660. $line['amount_text'] = $line['unit_price_text'];
  2661. }
  2662. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2663. $line['delivery_show'] = $deliveryText;
  2664. if (array_key_exists('delivery_text', $line)) {
  2665. $line['delivery_text'] = $deliveryText;
  2666. }
  2667. $line['delivery_ymd'] = '';
  2668. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2669. $line['lead_days_show'] = $leadText;
  2670. $line['lead_days_text'] = $leadText;
  2671. $line['lead_days'] = '';
  2672. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2673. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2674. $line['subtotal_num'] = null;
  2675. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2676. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2677. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2678. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2679. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2680. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2681. $line['amount_filled'] = false;
  2682. $line['delivery_filled'] = false;
  2683. $line['lead_days_filled'] = false;
  2684. $line['is_quoted'] = false;
  2685. if (array_key_exists('quote_label', $line)) {
  2686. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2687. }
  2688. }
  2689. protected function ensurePurchaseOrderBidOpenTable(): void
  2690. {
  2691. static $ready = false;
  2692. if ($ready) {
  2693. return;
  2694. }
  2695. $cacheKey = 'procuremen_bid_open_table_ok_v1';
  2696. try {
  2697. if (Cache::get($cacheKey)) {
  2698. $ready = true;
  2699. return;
  2700. }
  2701. } catch (\Throwable $e) {
  2702. }
  2703. try {
  2704. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2705. $ready = true;
  2706. try {
  2707. Cache::set($cacheKey, 1, 86400);
  2708. } catch (\Throwable $e) {
  2709. }
  2710. } catch (\Throwable $e) {
  2711. Db::execute(
  2712. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2713. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2714. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2715. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2716. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2717. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2718. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2719. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2720. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2721. `createtime` datetime DEFAULT NULL,
  2722. PRIMARY KEY (`id`),
  2723. UNIQUE KEY `uk_ccydh` (`ccydh`)
  2724. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2725. );
  2726. $ready = true;
  2727. try {
  2728. Cache::set($cacheKey, 1, 86400);
  2729. } catch (\Throwable $e2) {
  2730. }
  2731. }
  2732. }
  2733. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  2734. {
  2735. $ccydh = trim($ccydh);
  2736. if ($ccydh === '') {
  2737. return false;
  2738. }
  2739. $this->ensurePurchaseOrderBidOpenTable();
  2740. try {
  2741. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2742. return is_array($row);
  2743. } catch (\Throwable $e) {
  2744. return false;
  2745. }
  2746. }
  2747. /**
  2748. * 批量查询订单是否已开标验证
  2749. *
  2750. * @param array<int, string> $ccydhs
  2751. * @return array<string, bool> ccydh => true
  2752. */
  2753. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  2754. {
  2755. $set = [];
  2756. $list = [];
  2757. foreach ($ccydhs as $c) {
  2758. $c = trim((string)$c);
  2759. if ($c !== '') {
  2760. $list[$c] = true;
  2761. }
  2762. }
  2763. if ($list === []) {
  2764. return $set;
  2765. }
  2766. $this->ensurePurchaseOrderBidOpenTable();
  2767. try {
  2768. $rows = Db::table('purchase_order_bid_open')
  2769. ->where('ccydh', 'in', array_keys($list))
  2770. ->field('ccydh')
  2771. ->select();
  2772. foreach ($rows as $row) {
  2773. if (!is_array($row)) {
  2774. continue;
  2775. }
  2776. $c = trim((string)($row['ccydh'] ?? ''));
  2777. if ($c !== '') {
  2778. $set[$c] = true;
  2779. }
  2780. }
  2781. } catch (\Throwable $e) {
  2782. return [];
  2783. }
  2784. return $set;
  2785. }
  2786. /**
  2787. * 批量查询订单是否已指定供应商(免开标)
  2788. *
  2789. * @param array<int, string> $ccydhs
  2790. * @return array<string, bool> ccydh => true
  2791. */
  2792. protected function loadProcuremenManualPickedCcydhSet(array $ccydhs): array
  2793. {
  2794. $set = [];
  2795. $list = [];
  2796. foreach ($ccydhs as $c) {
  2797. $c = trim((string)$c);
  2798. if ($c !== '') {
  2799. $list[$c] = true;
  2800. }
  2801. }
  2802. if ($list === []) {
  2803. return $set;
  2804. }
  2805. $this->ensurePurchaseOrderManualPickColumns();
  2806. try {
  2807. $rows = Db::table('purchase_order')
  2808. ->where('CCYDH', 'in', array_keys($list))
  2809. ->where('manual_pick', 1)
  2810. ->field('CCYDH')
  2811. ->select();
  2812. foreach ($rows as $row) {
  2813. if (!is_array($row)) {
  2814. continue;
  2815. }
  2816. $c = trim((string)($row['CCYDH'] ?? ''));
  2817. if ($c !== '') {
  2818. $set[$c] = true;
  2819. }
  2820. }
  2821. } catch (\Throwable $e) {
  2822. return [];
  2823. }
  2824. return $set;
  2825. }
  2826. /**
  2827. * 确认供应商列表:按开标状态筛选(已开标 / 已指定供应商 / 待开标)
  2828. *
  2829. * @param array<int, array<string, mixed>> $pool
  2830. * @return array<int, array<string, mixed>>
  2831. */
  2832. protected function filterProcuremenPoolByBidOpenStatus(array $pool, string $status): array
  2833. {
  2834. $status = trim($status);
  2835. if ($status === '' || !in_array($status, ['待开标', '已开标', '已指定供应商'], true)) {
  2836. return $pool;
  2837. }
  2838. $ccydhList = [];
  2839. foreach ($pool as $rw) {
  2840. if (!is_array($rw)) {
  2841. continue;
  2842. }
  2843. $c = trim((string)($rw['CCYDH'] ?? ''));
  2844. if ($c !== '') {
  2845. $ccydhList[] = $c;
  2846. }
  2847. }
  2848. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  2849. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  2850. $out = [];
  2851. foreach ($pool as $rw) {
  2852. if (!is_array($rw)) {
  2853. continue;
  2854. }
  2855. $c = trim((string)($rw['CCYDH'] ?? ''));
  2856. if ($c !== '' && isset($bidOpenSet[$c])) {
  2857. $t = '已开标';
  2858. } elseif ($c !== '' && isset($manualPickSet[$c])) {
  2859. $t = '已指定供应商';
  2860. } else {
  2861. $t = '待开标';
  2862. }
  2863. if ($t === $status) {
  2864. $out[] = $rw;
  2865. }
  2866. }
  2867. return $out;
  2868. }
  2869. /**
  2870. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  2871. *
  2872. * @param array<string, mixed> $group
  2873. */
  2874. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  2875. {
  2876. if ($quoteVisible) {
  2877. $group['remark_quote_pending'] = 0;
  2878. return;
  2879. }
  2880. $group['remark'] = '';
  2881. $group['remark_quote_pending'] = 0;
  2882. }
  2883. /**
  2884. * @param array{ccydh?:string} $bundle
  2885. */
  2886. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  2887. {
  2888. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  2889. }
  2890. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  2891. {
  2892. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  2893. return true;
  2894. }
  2895. return $this->isProcuremenManualPickedForBundle($bundle);
  2896. }
  2897. /**
  2898. * 确保 purchase_order 自选供应商字段
  2899. */
  2900. protected function ensurePurchaseOrderManualPickColumns(): void
  2901. {
  2902. static $done = false;
  2903. if ($done) {
  2904. return;
  2905. }
  2906. $done = true;
  2907. $adds = [
  2908. 'manual_pick' => "ADD COLUMN `manual_pick` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=自选供应商(免开标)' AFTER `pick_company_name`",
  2909. 'manual_pick_reason' => "ADD COLUMN `manual_pick_reason` varchar(500) NOT NULL DEFAULT '' COMMENT '自选供应商选择说明' AFTER `manual_pick`",
  2910. ];
  2911. foreach ($adds as $col => $ddl) {
  2912. try {
  2913. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  2914. if (!is_array($cols) || $cols === []) {
  2915. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  2916. }
  2917. } catch (\Throwable $e) {
  2918. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  2919. }
  2920. }
  2921. }
  2922. /**
  2923. * 是否已自选供应商(免开标查看报价)
  2924. *
  2925. * @param array{pos?:array} $bundle
  2926. */
  2927. protected function isProcuremenManualPickedForBundle(array $bundle): bool
  2928. {
  2929. $this->ensurePurchaseOrderManualPickColumns();
  2930. foreach ($bundle['pos'] ?? [] as $poRow) {
  2931. if (!is_array($poRow)) {
  2932. continue;
  2933. }
  2934. if ((int)($poRow['manual_pick'] ?? 0) === 1) {
  2935. return true;
  2936. }
  2937. }
  2938. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2939. if ($ccydh === '') {
  2940. return false;
  2941. }
  2942. try {
  2943. $v = Db::table('purchase_order')->where('CCYDH', $ccydh)->where('manual_pick', 1)->value('id');
  2944. return $v !== null && $v !== false && (int)$v > 0;
  2945. } catch (\Throwable $e) {
  2946. return false;
  2947. }
  2948. }
  2949. /**
  2950. * @param array{pos?:array} $bundle
  2951. * @return array{company:string,reason:string}
  2952. */
  2953. protected function resolveProcuremenManualPickInfo(array $bundle): array
  2954. {
  2955. $this->ensurePurchaseOrderManualPickColumns();
  2956. foreach ($bundle['pos'] ?? [] as $poRow) {
  2957. if (!is_array($poRow)) {
  2958. continue;
  2959. }
  2960. if ((int)($poRow['manual_pick'] ?? 0) !== 1) {
  2961. continue;
  2962. }
  2963. $cn = trim((string)($poRow['pick_company_name'] ?? ''));
  2964. $reason = trim((string)($poRow['manual_pick_reason'] ?? ''));
  2965. return ['company' => $cn, 'reason' => $reason];
  2966. }
  2967. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2968. if ($ccydh === '') {
  2969. return ['company' => '', 'reason' => ''];
  2970. }
  2971. try {
  2972. $row = Db::table('purchase_order')
  2973. ->where('CCYDH', $ccydh)
  2974. ->where('manual_pick', 1)
  2975. ->field('pick_company_name,manual_pick_reason')
  2976. ->order('id', 'asc')
  2977. ->find();
  2978. } catch (\Throwable $e) {
  2979. $row = null;
  2980. }
  2981. if (!is_array($row)) {
  2982. return ['company' => '', 'reason' => ''];
  2983. }
  2984. return [
  2985. 'company' => trim((string)($row['pick_company_name'] ?? '')),
  2986. 'reason' => trim((string)($row['manual_pick_reason'] ?? '')),
  2987. ];
  2988. }
  2989. protected function loadBidOpenAdminUser(int $adminId): ?array
  2990. {
  2991. if ($adminId <= 0) {
  2992. return null;
  2993. }
  2994. try {
  2995. $row = Db::name('admin')->where('id', $adminId)->find();
  2996. } catch (\Throwable $e) {
  2997. return null;
  2998. }
  2999. if (!is_array($row)) {
  3000. return null;
  3001. }
  3002. $status = strtolower(trim((string)($row['status'] ?? '')));
  3003. if ($status !== '' && $status !== 'normal') {
  3004. return null;
  3005. }
  3006. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  3007. return null;
  3008. }
  3009. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  3010. if (!preg_match('/^1\d{10}$/', $phone)) {
  3011. return null;
  3012. }
  3013. $name = trim((string)($row['nickname'] ?? ''));
  3014. if ($name === '') {
  3015. $name = trim((string)($row['username'] ?? ''));
  3016. }
  3017. return [
  3018. 'id' => (int)$row['id'],
  3019. 'username' => trim((string)($row['username'] ?? '')),
  3020. 'nickname' => $name,
  3021. 'mobile' => $phone,
  3022. ];
  3023. }
  3024. /**
  3025. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  3026. */
  3027. protected function bidOpenVerifierAuthGroupRootId(): int
  3028. {
  3029. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  3030. return $id > 0 ? $id : 10;
  3031. }
  3032. /**
  3033. * @return int[]
  3034. */
  3035. protected function loadBidOpenVerifierAuthGroupIds(): array
  3036. {
  3037. static $memo = [];
  3038. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  3039. if (isset($memo[$rootId])) {
  3040. return $memo[$rootId];
  3041. }
  3042. try {
  3043. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  3044. } catch (\Throwable $e) {
  3045. $memo[$rootId] = [$rootId];
  3046. return $memo[$rootId];
  3047. }
  3048. if (!is_array($groups) || $groups === []) {
  3049. $memo[$rootId] = [$rootId];
  3050. return $memo[$rootId];
  3051. }
  3052. $groupList = [];
  3053. foreach ($groups as $g) {
  3054. if (is_array($g)) {
  3055. $groupList[] = $g;
  3056. }
  3057. }
  3058. if ($groupList === []) {
  3059. $memo[$rootId] = [$rootId];
  3060. return $memo[$rootId];
  3061. }
  3062. $tree = \fast\Tree::instance();
  3063. $tree->init($groupList);
  3064. $ids = $tree->getChildrenIds($rootId, true);
  3065. if (!is_array($ids) || $ids === []) {
  3066. $memo[$rootId] = [$rootId];
  3067. return $memo[$rootId];
  3068. }
  3069. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  3070. return $memo[$rootId];
  3071. }
  3072. protected function isBidOpenVerifierAdmin(int $adminId): bool
  3073. {
  3074. if ($adminId <= 0) {
  3075. return false;
  3076. }
  3077. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3078. if ($groupIds === []) {
  3079. return false;
  3080. }
  3081. try {
  3082. return (bool)Db::name('auth_group_access')
  3083. ->where('uid', $adminId)
  3084. ->where('group_id', 'in', $groupIds)
  3085. ->count();
  3086. } catch (\Throwable $e) {
  3087. return false;
  3088. }
  3089. }
  3090. /**
  3091. * @return array<int, array<string, mixed>>
  3092. */
  3093. protected function listBidOpenVerifierCandidates(): array
  3094. {
  3095. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3096. if ($groupIds === []) {
  3097. return [];
  3098. }
  3099. try {
  3100. $adminIds = Db::name('auth_group_access')
  3101. ->where('group_id', 'in', $groupIds)
  3102. ->column('uid');
  3103. } catch (\Throwable $e) {
  3104. $adminIds = [];
  3105. }
  3106. $adminIds = is_array($adminIds)
  3107. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  3108. : [];
  3109. if ($adminIds === []) {
  3110. return [];
  3111. }
  3112. try {
  3113. $rows = Db::name('admin')
  3114. ->where('status', 'normal')
  3115. ->where('id', 'in', $adminIds)
  3116. ->where('mobile', '<>', '')
  3117. ->order('id', 'asc')
  3118. ->select();
  3119. } catch (\Throwable $e) {
  3120. return [];
  3121. }
  3122. if (!is_array($rows)) {
  3123. return [];
  3124. }
  3125. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  3126. $out = [];
  3127. foreach ($rows as $row) {
  3128. if (!is_array($row)) {
  3129. continue;
  3130. }
  3131. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  3132. if ($one === null) {
  3133. continue;
  3134. }
  3135. $out[] = [
  3136. 'id' => $one['id'],
  3137. 'username' => $one['username'],
  3138. 'nickname' => $one['nickname'],
  3139. 'group_name' => $groupNameMap[$one['id']] ?? '',
  3140. 'mobile' => mask_phone($one['mobile']),
  3141. 'mobile_plain' => (string)$one['mobile'],
  3142. ];
  3143. }
  3144. return $out;
  3145. }
  3146. /**
  3147. * @param int[] $adminIds
  3148. * @return array<int, string>
  3149. */
  3150. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  3151. {
  3152. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  3153. if ($adminIds === []) {
  3154. return [];
  3155. }
  3156. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3157. try {
  3158. $rows = Db::name('auth_group_access')
  3159. ->alias('aga')
  3160. ->join('auth_group ag', 'aga.group_id = ag.id')
  3161. ->where('aga.uid', 'in', $adminIds)
  3162. ->where('aga.group_id', 'in', $groupIds)
  3163. ->field('aga.uid,ag.name')
  3164. ->order('aga.uid', 'asc')
  3165. ->order('aga.group_id', 'asc')
  3166. ->select();
  3167. } catch (\Throwable $e) {
  3168. return [];
  3169. }
  3170. if (!is_array($rows)) {
  3171. return [];
  3172. }
  3173. $out = [];
  3174. foreach ($rows as $row) {
  3175. if (!is_array($row)) {
  3176. continue;
  3177. }
  3178. $uid = (int)($row['uid'] ?? 0);
  3179. $name = trim((string)($row['name'] ?? ''));
  3180. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  3181. continue;
  3182. }
  3183. $out[$uid] = $name;
  3184. }
  3185. return $out;
  3186. }
  3187. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  3188. {
  3189. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  3190. }
  3191. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  3192. {
  3193. return 'procuremen_bidopen_wait_' . $adminId;
  3194. }
  3195. protected function renderBidOpenVerifySms(string $code): string
  3196. {
  3197. $tpl = '';
  3198. try {
  3199. $row = $this->loadNotifyTemplateRow('bid_open');
  3200. if (is_array($row)) {
  3201. $tpl = trim((string)($row['content'] ?? ''));
  3202. }
  3203. } catch (\Throwable $e) {
  3204. $tpl = '';
  3205. }
  3206. if ($tpl === '') {
  3207. $tpl = '【可集达】您的短信验证码是{code}';
  3208. }
  3209. return str_replace('{code}', $code, $tpl);
  3210. }
  3211. protected function sendBidOpenVerifySms(string $phone, string $code): void
  3212. {
  3213. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  3214. }
  3215. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  3216. {
  3217. $code = trim($code);
  3218. if (!preg_match('/^\d{6}$/', $code)) {
  3219. return false;
  3220. }
  3221. $mock = Config::get('mproc.mock_sms_code');
  3222. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3223. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3224. return true;
  3225. }
  3226. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3227. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3228. return false;
  3229. }
  3230. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3231. return true;
  3232. }
  3233. /**
  3234. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3235. */
  3236. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  3237. {
  3238. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3239. if ($ccydh === '') {
  3240. throw new \InvalidArgumentException('订单号无效');
  3241. }
  3242. $this->ensurePurchaseOrderBidOpenTable();
  3243. list($operatorId, $operatorName) = $this->GetUseName();
  3244. $now = date('Y-m-d H:i:s');
  3245. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3246. $payload = [
  3247. 'ccydh' => $ccydh,
  3248. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  3249. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  3250. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  3251. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  3252. 'operator_id' => (int)$operatorId,
  3253. 'operator_name' => trim((string)$operatorName),
  3254. 'createtime' => $now,
  3255. ];
  3256. if (is_array($exists)) {
  3257. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  3258. } else {
  3259. Db::table('purchase_order_bid_open')->insert($payload);
  3260. }
  3261. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  3262. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  3263. $labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
  3264. (int)$payload['verifier1_id'],
  3265. (int)$payload['verifier2_id'],
  3266. ]);
  3267. if (isset($labelMap[(int)$payload['verifier1_id']]) && (int)$payload['verifier1_id'] > 0) {
  3268. $name1 = $labelMap[(int)$payload['verifier1_id']];
  3269. }
  3270. if (isset($labelMap[(int)$payload['verifier2_id']]) && (int)$payload['verifier2_id'] > 0) {
  3271. $name2 = $labelMap[(int)$payload['verifier2_id']];
  3272. }
  3273. $logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
  3274. $seenSid = [];
  3275. foreach ($bundle['pos'] ?? [] as $poRow) {
  3276. if (!is_array($poRow)) {
  3277. continue;
  3278. }
  3279. $sid = (int)($poRow['scydgy_id'] ?? 0);
  3280. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  3281. continue;
  3282. }
  3283. $seenSid[$sid] = true;
  3284. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  3285. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  3286. }
  3287. if ($seenSid === []) {
  3288. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  3289. if ($this->isValidScydgyRowId($anchor)) {
  3290. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  3291. }
  3292. }
  3293. // 开标通过后计算并写入供应商服务评分
  3294. try {
  3295. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  3296. ProcuremenSupplierScore::saveForOrder($ccydh, $quoteGroups, date('Y-m', strtotime($now) ?: time()));
  3297. } catch (\Throwable $e) {
  3298. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  3299. }
  3300. }
  3301. /**
  3302. * 报价行展示字段默认值(模板安全访问)
  3303. *
  3304. * @param array<string, mixed> $line
  3305. * @return array<string, mixed>
  3306. */
  3307. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  3308. {
  3309. if (!array_key_exists('amount_quote_pending', $line)) {
  3310. $line['amount_quote_pending'] = 0;
  3311. }
  3312. if (!array_key_exists('delivery_quote_pending', $line)) {
  3313. $line['delivery_quote_pending'] = 0;
  3314. }
  3315. if (!array_key_exists('quote_before_deadline', $line)) {
  3316. $line['quote_before_deadline'] = 0;
  3317. }
  3318. if (!array_key_exists('amount_filled', $line)) {
  3319. $line['amount_filled'] = 0;
  3320. }
  3321. if (!array_key_exists('delivery_filled', $line)) {
  3322. $line['delivery_filled'] = 0;
  3323. }
  3324. if (!array_key_exists('lead_days_filled', $line)) {
  3325. $line['lead_days_filled'] = 0;
  3326. }
  3327. if (!array_key_exists('lead_days_quote_pending', $line)) {
  3328. $line['lead_days_quote_pending'] = 0;
  3329. }
  3330. if (!array_key_exists('lead_days_show', $line)) {
  3331. $line['lead_days_show'] = '未填写';
  3332. }
  3333. if (!array_key_exists('lead_days_text', $line)) {
  3334. $line['lead_days_text'] = $line['lead_days_show'];
  3335. }
  3336. return $line;
  3337. }
  3338. /**
  3339. * 审核弹窗:按供应商汇总报价明细
  3340. *
  3341. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3342. * @return array<int, array<string, mixed>>
  3343. */
  3344. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  3345. {
  3346. $sids = [];
  3347. foreach ($bundle['pos'] ?? [] as $po) {
  3348. if (!is_array($po)) {
  3349. continue;
  3350. }
  3351. $sid = (int)($po['scydgy_id'] ?? 0);
  3352. if ($this->isValidScydgyRowId($sid)) {
  3353. $sids[$sid] = true;
  3354. }
  3355. }
  3356. if ($sids === []) {
  3357. return [];
  3358. }
  3359. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3360. $gymcMap = [];
  3361. $qtyBySid = [];
  3362. $orderedSids = [];
  3363. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3364. if (!is_array($mr)) {
  3365. continue;
  3366. }
  3367. $gid = $this->extractScydgyRowId($mr);
  3368. if ($this->isValidScydgyRowId($gid)) {
  3369. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3370. $orderedSids[] = $gid;
  3371. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3372. if ($qty === '') {
  3373. $qty = trim((string)($mr['NGZL'] ?? ''));
  3374. }
  3375. $qtyBySid[$gid] = $qty;
  3376. }
  3377. }
  3378. foreach ($bundle['pos'] ?? [] as $po) {
  3379. if (!is_array($po)) {
  3380. continue;
  3381. }
  3382. $gid = (int)($po['scydgy_id'] ?? 0);
  3383. if ($this->isValidScydgyRowId($gid)) {
  3384. $nm = trim((string)($po['CGYMC'] ?? ''));
  3385. if ($nm !== '') {
  3386. $gymcMap[$gid] = $nm;
  3387. }
  3388. if (!in_array($gid, $orderedSids, true)) {
  3389. $orderedSids[] = $gid;
  3390. }
  3391. }
  3392. }
  3393. try {
  3394. $detailsQuery = Db::table('purchase_order_detail')
  3395. ->where('scydgy_id', 'in', array_keys($sids));
  3396. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3397. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  3398. } catch (\Throwable $e) {
  3399. try {
  3400. $detailsQuery = Db::table('purchase_order_detail')
  3401. ->where('scydgy_id', 'in', array_keys($sids));
  3402. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3403. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  3404. } catch (\Throwable $e2) {
  3405. $details = [];
  3406. }
  3407. }
  3408. if (!is_array($details)) {
  3409. $details = [];
  3410. }
  3411. $byCompany = [];
  3412. foreach ($details as $d) {
  3413. if (!is_array($d)) {
  3414. continue;
  3415. }
  3416. $cn = trim((string)($d['company_name'] ?? ''));
  3417. if ($cn === '') {
  3418. continue;
  3419. }
  3420. if (!isset($byCompany[$cn])) {
  3421. $ph = trim((string)($d['phone'] ?? ''));
  3422. $username = trim((string)($d['username'] ?? ''));
  3423. if ($username === '') {
  3424. $username = $this->resolveCustomerContactName($ph, $cn);
  3425. }
  3426. $byCompany[$cn] = [
  3427. 'name' => $cn,
  3428. 'email' => trim((string)($d['email'] ?? '')),
  3429. 'phone' => $ph,
  3430. 'username' => $username,
  3431. 'remark' => '',
  3432. 'has_quote' => false,
  3433. 'lines_map' => [],
  3434. ];
  3435. }
  3436. if ($byCompany[$cn]['remark'] === '') {
  3437. $rm = '';
  3438. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3439. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3440. $rm = trim((string)$d[$rk]);
  3441. break;
  3442. }
  3443. }
  3444. if ($rm !== '') {
  3445. $byCompany[$cn]['remark'] = $rm;
  3446. }
  3447. }
  3448. $sid = (int)($d['scydgy_id'] ?? 0);
  3449. $am = trim((string)($d['amount'] ?? ''));
  3450. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3451. if ($gymc === '') {
  3452. $gymc = '工序';
  3453. }
  3454. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3455. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3456. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3457. $deliveryShow = $deliveryRaw;
  3458. }
  3459. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3460. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3461. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3462. $subtotal = null;
  3463. if ($amountNum !== null) {
  3464. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3465. }
  3466. $unitPriceText = $amountFilled
  3467. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3468. : '未填写';
  3469. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3470. $leadFilled = ($leadDays !== null);
  3471. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3472. $lineRow = [
  3473. 'cgymc' => $gymc,
  3474. 'amount' => $am,
  3475. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  3476. 'amount_filled' => $amountFilled,
  3477. 'unit_price_text' => $unitPriceText,
  3478. 'delivery' => $deliveryRaw,
  3479. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  3480. 'delivery_filled' => $deliveryFilled,
  3481. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  3482. 'lead_days' => $leadFilled ? $leadDays : '',
  3483. 'lead_days_filled'=> $leadFilled,
  3484. 'lead_days_show' => $leadText,
  3485. 'lead_days_text' => $leadText,
  3486. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3487. 'subtotal_num' => $subtotal,
  3488. 'status_name' => trim((string)($d['status_name'] ?? '')),
  3489. 'is_quoted' => $amountFilled,
  3490. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  3491. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3492. ];
  3493. if (!$quoteVisible) {
  3494. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  3495. }
  3496. // 按工序 id 暂存,下面再按上方工序表顺序输出
  3497. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  3498. }
  3499. foreach ($byCompany as $cn => $g) {
  3500. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  3501. $lines = [];
  3502. $usedSids = [];
  3503. foreach ($orderedSids as $sid) {
  3504. if (!isset($linesMap[$sid])) {
  3505. continue;
  3506. }
  3507. $lines[] = $linesMap[$sid];
  3508. $usedSids[$sid] = true;
  3509. }
  3510. foreach ($linesMap as $sid => $ln) {
  3511. if (isset($usedSids[$sid])) {
  3512. continue;
  3513. }
  3514. $lines[] = $ln;
  3515. }
  3516. $total = count($lines);
  3517. $quoted = 0;
  3518. $groupTotal = 0.0;
  3519. $groupHasTotal = false;
  3520. if ($quoteVisible) {
  3521. foreach ($lines as $ln) {
  3522. $am = trim((string)($ln['amount'] ?? ''));
  3523. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  3524. $quoted++;
  3525. }
  3526. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3527. $groupTotal += (float)$ln['subtotal_num'];
  3528. $groupHasTotal = true;
  3529. }
  3530. }
  3531. }
  3532. unset($byCompany[$cn]['lines_map']);
  3533. $byCompany[$cn]['lines'] = $lines;
  3534. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  3535. $byCompany[$cn]['line_count'] = $total;
  3536. $byCompany[$cn]['has_total'] = $total > 0;
  3537. $byCompany[$cn]['has_remark'] = $total > 0;
  3538. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  3539. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3540. // 工序行 + 备注行 + 总计行
  3541. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  3542. }
  3543. $groups = array_values($byCompany);
  3544. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3545. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  3546. }
  3547. /**
  3548. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  3549. *
  3550. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3551. * @return array<int, array<string, mixed>>
  3552. */
  3553. protected function loadConfirmSupplierPickGroups(array $bundle): array
  3554. {
  3555. $sids = [];
  3556. $poIdMap = [];
  3557. foreach ($bundle['pos'] ?? [] as $po) {
  3558. if (!is_array($po)) {
  3559. continue;
  3560. }
  3561. $sid = (int)($po['scydgy_id'] ?? 0);
  3562. if ($this->isValidScydgyRowId($sid)) {
  3563. $sids[$sid] = true;
  3564. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  3565. }
  3566. }
  3567. if ($sids === []) {
  3568. return [];
  3569. }
  3570. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3571. $gymcMap = [];
  3572. $qtyBySid = [];
  3573. $orderedSids = [];
  3574. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3575. if (!is_array($mr)) {
  3576. continue;
  3577. }
  3578. $gid = $this->extractScydgyRowId($mr);
  3579. if ($this->isValidScydgyRowId($gid)) {
  3580. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3581. $orderedSids[] = $gid;
  3582. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3583. if ($qty === '') {
  3584. $qty = trim((string)($mr['NGZL'] ?? ''));
  3585. }
  3586. $qtyBySid[$gid] = $qty;
  3587. }
  3588. }
  3589. foreach ($bundle['pos'] ?? [] as $po) {
  3590. if (!is_array($po)) {
  3591. continue;
  3592. }
  3593. $gid = (int)($po['scydgy_id'] ?? 0);
  3594. if ($this->isValidScydgyRowId($gid)) {
  3595. $nm = trim((string)($po['CGYMC'] ?? ''));
  3596. if ($nm !== '') {
  3597. $gymcMap[$gid] = $nm;
  3598. }
  3599. }
  3600. }
  3601. try {
  3602. $details = Db::table('purchase_order_detail')
  3603. ->where('scydgy_id', 'in', array_keys($sids))
  3604. ->order('company_name', 'asc')
  3605. ->order('id', 'asc')
  3606. ->select();
  3607. } catch (\Throwable $e) {
  3608. try {
  3609. $details = Db::table('purchase_order_detail')
  3610. ->where('scydgy_id', 'in', array_keys($sids))
  3611. ->order('company_name', 'asc')
  3612. ->order('ID', 'asc')
  3613. ->select();
  3614. } catch (\Throwable $e2) {
  3615. $details = [];
  3616. }
  3617. }
  3618. if (!is_array($details)) {
  3619. $details = [];
  3620. }
  3621. $byCompany = [];
  3622. foreach ($details as $d) {
  3623. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3624. continue;
  3625. }
  3626. $cn = trim((string)($d['company_name'] ?? ''));
  3627. if ($cn === '') {
  3628. continue;
  3629. }
  3630. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  3631. $sid = (int)($d['scydgy_id'] ?? 0);
  3632. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  3633. continue;
  3634. }
  3635. if (!isset($byCompany[$cn])) {
  3636. $ph = trim((string)($d['phone'] ?? ''));
  3637. $username = trim((string)($d['username'] ?? ''));
  3638. if ($username === '') {
  3639. $username = $this->resolveCustomerContactName($ph, $cn);
  3640. }
  3641. $byCompany[$cn] = [
  3642. 'name' => $cn,
  3643. 'email' => trim((string)($d['email'] ?? '')),
  3644. 'phone' => $ph,
  3645. 'username' => $username,
  3646. 'remark' => '',
  3647. 'pick_lines' => [],
  3648. 'detail_picks' => [],
  3649. ];
  3650. }
  3651. if ($byCompany[$cn]['remark'] === '') {
  3652. $rm = '';
  3653. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3654. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3655. $rm = trim((string)$d[$rk]);
  3656. break;
  3657. }
  3658. }
  3659. if ($rm !== '') {
  3660. $byCompany[$cn]['remark'] = $rm;
  3661. }
  3662. }
  3663. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3664. if ($gymc === '') {
  3665. $gymc = '工序';
  3666. }
  3667. $am = trim((string)($d['amount'] ?? ''));
  3668. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3669. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3670. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3671. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3672. $deliveryShow = $deliveryRaw;
  3673. }
  3674. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3675. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3676. $subtotal = null;
  3677. if ($amountNum !== null) {
  3678. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3679. }
  3680. $unitPriceText = $amountFilled
  3681. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3682. : '未填写';
  3683. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3684. $leadFilled = ($leadDays !== null);
  3685. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3686. $pickLine = [
  3687. 'cgymc' => $gymc,
  3688. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  3689. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  3690. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  3691. 'amount_filled' => $amountFilled,
  3692. 'delivery_filled' => $deliveryFilled,
  3693. 'unit_price_text' => $unitPriceText,
  3694. 'lead_days' => $leadFilled ? $leadDays : '',
  3695. 'lead_days_filled'=> $leadFilled,
  3696. 'lead_days_show' => $leadText,
  3697. 'lead_days_text' => $leadText,
  3698. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3699. 'subtotal_num' => $subtotal,
  3700. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3701. 'is_quoted' => $amountFilled,
  3702. ];
  3703. if (!$quoteVisible) {
  3704. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  3705. }
  3706. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  3707. $byCompany[$cn]['detail_picks'][$sid] = [
  3708. 'scydgy_id' => $sid,
  3709. 'detail_id' => $detailId,
  3710. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  3711. 'cgymc' => $gymc,
  3712. ];
  3713. }
  3714. $out = [];
  3715. foreach ($byCompany as $g) {
  3716. $pickLinesMap = $g['pick_lines'] ?? [];
  3717. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  3718. continue;
  3719. }
  3720. $pickLines = [];
  3721. $usedLineSids = [];
  3722. foreach ($orderedSids as $sid) {
  3723. if (!isset($pickLinesMap[$sid])) {
  3724. continue;
  3725. }
  3726. $pickLines[] = $pickLinesMap[$sid];
  3727. $usedLineSids[$sid] = true;
  3728. }
  3729. foreach ($pickLinesMap as $sid => $ln) {
  3730. if (isset($usedLineSids[$sid])) {
  3731. continue;
  3732. }
  3733. $pickLines[] = $ln;
  3734. }
  3735. $groupTotal = 0.0;
  3736. $groupHasTotal = false;
  3737. if ($quoteVisible) {
  3738. foreach ($pickLines as $ln) {
  3739. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3740. $groupTotal += (float)$ln['subtotal_num'];
  3741. $groupHasTotal = true;
  3742. }
  3743. }
  3744. }
  3745. $lineCount = count($pickLines);
  3746. $g['pick_lines'] = $pickLines;
  3747. $g['line_count'] = $lineCount;
  3748. $g['has_total'] = $lineCount > 0;
  3749. $g['has_remark'] = $lineCount > 0;
  3750. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  3751. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3752. // 工序行 + 备注行 + 总计行
  3753. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  3754. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  3755. $detailPicks = [];
  3756. $usedPickSids = [];
  3757. foreach ($orderedSids as $sid) {
  3758. if (!isset($detailPicksMap[$sid])) {
  3759. continue;
  3760. }
  3761. $detailPicks[] = $detailPicksMap[$sid];
  3762. $usedPickSids[$sid] = true;
  3763. }
  3764. foreach ($detailPicksMap as $sid => $dp) {
  3765. if (isset($usedPickSids[$sid])) {
  3766. continue;
  3767. }
  3768. $detailPicks[] = $dp;
  3769. }
  3770. $g['detail_picks'] = $detailPicks;
  3771. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  3772. unset($g['detail_picks']);
  3773. $out[] = $g;
  3774. }
  3775. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3776. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  3777. }
  3778. /**
  3779. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  3780. * @return array<int, int[]> scydgy_id => detail_id[]
  3781. */
  3782. protected function mapDetailIdsByScydgyId(array $details): array
  3783. {
  3784. $out = [];
  3785. foreach ($details as $d) {
  3786. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3787. continue;
  3788. }
  3789. $sid = (int)($d['scydgy_id'] ?? 0);
  3790. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  3791. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  3792. continue;
  3793. }
  3794. if (!isset($out[$sid])) {
  3795. $out[$sid] = [];
  3796. }
  3797. $out[$sid][] = $pk;
  3798. }
  3799. foreach ($out as $sid => $ids) {
  3800. $out[$sid] = array_values(array_unique($ids));
  3801. }
  3802. return $out;
  3803. }
  3804. /**
  3805. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  3806. *
  3807. * @param array<string, mixed> $dbRow
  3808. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  3809. */
  3810. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  3811. {
  3812. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  3813. $r = [
  3814. 'ID' => $sid,
  3815. 'scydgy_id' => $sid,
  3816. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  3817. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  3818. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  3819. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  3820. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  3821. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  3822. 'CDW' => $dbRow['CDW'] ?? '',
  3823. 'czlyq' => $dbRow['czlyq'] ?? '',
  3824. 'NGZL' => $dbRow['NGZL'] ?? '',
  3825. 'CDF' => $dbRow['CDF'] ?? '',
  3826. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  3827. 'MBZ' => $dbRow['MBZ'] ?? '',
  3828. 'bwjg' => $dbRow['bwjg'] ?? '',
  3829. 'iStatus' => $dbRow['iStatus'] ?? '',
  3830. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  3831. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  3832. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  3833. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  3834. 'dStamp' => $dbRow['dStamp'] ?? '',
  3835. 'pick_time' => $dbRow['pick_time'] ?? '',
  3836. ];
  3837. $r['This_quantity'] = $this->resolveProcuremenThisQuantity($r);
  3838. $r['ceilingPrice'] = $this->resolveProcuremenCeilingPrice($r);
  3839. if ($sid > 0 && isset($dStampMap[$sid])) {
  3840. $t = trim((string)$dStampMap[$sid]);
  3841. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  3842. $r['dStamp'] = $dStampMap[$sid];
  3843. }
  3844. }
  3845. $dsOut = trim((string)($r['dStamp'] ?? ''));
  3846. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  3847. $ct = $dbRow['createtime'];
  3848. if (is_numeric($ct) && (int)$ct > 946684800) {
  3849. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  3850. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  3851. $r['dStamp'] = trim($ct);
  3852. }
  3853. }
  3854. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  3855. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  3856. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  3857. $fallback = trim((string)($r['dStamp'] ?? ''));
  3858. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  3859. $r['dputrecord'] = $fallback;
  3860. }
  3861. }
  3862. if (array_key_exists('id', $dbRow)) {
  3863. $r['purchase_order_id'] = (int)$dbRow['id'];
  3864. }
  3865. if ($sid < 0) {
  3866. $r['_is_manual'] = 1;
  3867. }
  3868. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  3869. $pickOut = trim((string)($r['pick_time'] ?? ''));
  3870. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  3871. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  3872. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  3873. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  3874. $r['pick_time'] = $pickFallback;
  3875. break;
  3876. }
  3877. }
  3878. }
  3879. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  3880. if ($pickNm !== '') {
  3881. $r['pick_company_name'] = $pickNm;
  3882. $r['picked_supplier_name'] = $pickNm;
  3883. }
  3884. return $r;
  3885. }
  3886. /**
  3887. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  3888. *
  3889. * @return array<int, array<string, mixed>>
  3890. */
  3891. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  3892. {
  3893. $pool = [];
  3894. if (!is_array($dbRows) || $dbRows === []) {
  3895. return $pool;
  3896. }
  3897. $dStampMap = [];
  3898. $sidList = [];
  3899. foreach ($dbRows as $tmpRow) {
  3900. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  3901. $sid = (int)$tmpRow['scydgy_id'];
  3902. if ($sid > 0) {
  3903. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  3904. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3905. $sidList[$sid] = true;
  3906. }
  3907. }
  3908. }
  3909. }
  3910. if ($sidList !== []) {
  3911. try {
  3912. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  3913. } catch (\Throwable $e) {
  3914. $dStampMap = [];
  3915. }
  3916. }
  3917. foreach ($dbRows as $dbRow) {
  3918. if (!is_array($dbRow)) {
  3919. continue;
  3920. }
  3921. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  3922. }
  3923. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  3924. $needCcydh = [];
  3925. foreach ($pool as $row) {
  3926. if (!is_array($row)) {
  3927. continue;
  3928. }
  3929. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3930. continue;
  3931. }
  3932. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3933. if ($ccydh !== '') {
  3934. $needCcydh[$ccydh] = true;
  3935. }
  3936. }
  3937. if ($needCcydh !== []) {
  3938. $czMap = [];
  3939. try {
  3940. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  3941. } catch (\Throwable $e) {
  3942. $czMap = [];
  3943. }
  3944. if (is_array($czMap) && $czMap !== []) {
  3945. foreach ($pool as &$row) {
  3946. if (!is_array($row)) {
  3947. continue;
  3948. }
  3949. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3950. continue;
  3951. }
  3952. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3953. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  3954. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  3955. }
  3956. }
  3957. unset($row);
  3958. }
  3959. }
  3960. return $pool;
  3961. }
  3962. /**
  3963. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  3964. *
  3965. * @param int[] $scydgyIds
  3966. * @return array<int, array<string, mixed>>
  3967. */
  3968. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  3969. {
  3970. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3971. if ($scydgyIds === []) {
  3972. return [];
  3973. }
  3974. try {
  3975. $list = Db::table('purchase_order_detail')
  3976. ->where('scydgy_id', 'in', $scydgyIds)
  3977. ->field('scydgy_id,company_name,amount,delivery')
  3978. ->select();
  3979. } catch (\Throwable $e) {
  3980. $list = [];
  3981. }
  3982. return is_array($list) ? $list : [];
  3983. }
  3984. /**
  3985. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  3986. *
  3987. * @param int[] $scydgyIds
  3988. * @param array<int, array<string, mixed>> $allRows
  3989. * @return array{cnt:int, amt:int, deliv:int}
  3990. */
  3991. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  3992. {
  3993. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3994. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3995. if ($scydgyIds === [] || $allRows === []) {
  3996. return $out;
  3997. }
  3998. $idSet = array_flip($scydgyIds);
  3999. $all = [];
  4000. $withAmt = [];
  4001. $withDeliv = [];
  4002. foreach ($allRows as $r) {
  4003. if (!is_array($r)) {
  4004. continue;
  4005. }
  4006. $sid = (int)($r['scydgy_id'] ?? 0);
  4007. if (!isset($idSet[$sid])) {
  4008. continue;
  4009. }
  4010. $cn = trim((string)($r['company_name'] ?? ''));
  4011. if ($cn === '') {
  4012. continue;
  4013. }
  4014. $all[$cn] = true;
  4015. $am = $r['amount'] ?? null;
  4016. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  4017. $withAmt[$cn] = true;
  4018. }
  4019. $dv = $r['delivery'] ?? null;
  4020. if ($dv !== null && trim((string)$dv) !== '') {
  4021. $withDeliv[$cn] = true;
  4022. }
  4023. }
  4024. return [
  4025. 'cnt' => count($all),
  4026. 'amt' => count($withAmt),
  4027. 'deliv' => count($withDeliv),
  4028. ];
  4029. }
  4030. /**
  4031. * 本次数量:优先 This_quantity,空则回退工作量 NGZL(与下发/确认/审批弹窗一致)
  4032. *
  4033. * @param array<string, mixed> $row
  4034. */
  4035. protected function resolveProcuremenThisQuantity(array $row): string
  4036. {
  4037. $q = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  4038. if ($q !== '') {
  4039. return $q;
  4040. }
  4041. $ngzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  4042. if (!is_scalar($ngzl)) {
  4043. return '';
  4044. }
  4045. $s = trim((string)$ngzl);
  4046. if ($s === '') {
  4047. return '';
  4048. }
  4049. if (is_numeric($s) && (float)$s === 0.0) {
  4050. return '';
  4051. }
  4052. return $s;
  4053. }
  4054. /**
  4055. * @param array<string, mixed> $row
  4056. */
  4057. protected function resolveProcuremenCeilingPrice(array $row): string
  4058. {
  4059. return trim((string)($row['ceilingPrice'] ?? $row['ceiling_price'] ?? ''));
  4060. }
  4061. /**
  4062. * 多工序数量/限价拼接:跳过空值,避免出现「、10」「304、」
  4063. *
  4064. * @param array<int, mixed> $parts
  4065. */
  4066. protected function joinProcuremenNonEmpty(array $parts, string $sep = '、'): string
  4067. {
  4068. $out = [];
  4069. foreach ($parts as $p) {
  4070. $s = trim((string)$p);
  4071. if ($s !== '') {
  4072. $out[] = $s;
  4073. }
  4074. }
  4075. return $out === [] ? '' : implode($sep, $out);
  4076. }
  4077. /**
  4078. * 确认/审批列表:合并行按各工序同步本次数量、最高限价(顿号间隔)
  4079. *
  4080. * @param array<int, array<string, mixed>> $rows
  4081. */
  4082. protected function syncCollapsedOrderQtyPriceForList(array &$rows): void
  4083. {
  4084. if ($rows === []) {
  4085. return;
  4086. }
  4087. $idList = [];
  4088. foreach ($rows as $rw) {
  4089. if (!is_array($rw)) {
  4090. continue;
  4091. }
  4092. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4093. foreach ($rw['_order_merge_rows'] as $mr) {
  4094. if (!is_array($mr)) {
  4095. continue;
  4096. }
  4097. $mid = (int)($mr['ID'] ?? 0);
  4098. if ($this->isValidScydgyRowId($mid)) {
  4099. $idList[$mid] = true;
  4100. }
  4101. }
  4102. }
  4103. $id = (int)($rw['ID'] ?? 0);
  4104. if ($this->isValidScydgyRowId($id)) {
  4105. $idList[$id] = true;
  4106. }
  4107. }
  4108. if ($idList === []) {
  4109. return;
  4110. }
  4111. try {
  4112. $list = Db::table('purchase_order')
  4113. ->where('scydgy_id', 'in', array_keys($idList))
  4114. ->field('scydgy_id,This_quantity,ceilingPrice,NGZL,pick_company_name')
  4115. ->select();
  4116. } catch (\Throwable $e) {
  4117. return;
  4118. }
  4119. if (!is_array($list)) {
  4120. return;
  4121. }
  4122. $byId = [];
  4123. foreach ($list as $dbRow) {
  4124. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4125. continue;
  4126. }
  4127. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4128. }
  4129. foreach ($rows as &$rw) {
  4130. if (!is_array($rw)) {
  4131. continue;
  4132. }
  4133. $mergeRows = [];
  4134. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4135. $mergeRows = $rw['_order_merge_rows'];
  4136. } else {
  4137. $mergeRows = [$rw];
  4138. }
  4139. $qtyList = [];
  4140. $priceList = [];
  4141. $picked = '';
  4142. foreach ($mergeRows as $mr) {
  4143. if (!is_array($mr)) {
  4144. continue;
  4145. }
  4146. $sid = (int)($mr['ID'] ?? 0);
  4147. $db = ($sid !== 0 && isset($byId[$sid])) ? $byId[$sid] : null;
  4148. $src = $mr;
  4149. if (is_array($db)) {
  4150. $qDb = trim((string)($db['This_quantity'] ?? $db['this_quantity'] ?? ''));
  4151. $pDb = trim((string)($db['ceilingPrice'] ?? $db['ceiling_price'] ?? ''));
  4152. $ngzlDb = $db['NGZL'] ?? $db['ngzl'] ?? null;
  4153. if ($qDb !== '') {
  4154. $src['This_quantity'] = $qDb;
  4155. }
  4156. if ($pDb !== '') {
  4157. $src['ceilingPrice'] = $pDb;
  4158. }
  4159. if ($ngzlDb !== null && trim((string)$ngzlDb) !== '') {
  4160. $src['NGZL'] = $ngzlDb;
  4161. }
  4162. if ($picked === '') {
  4163. $picked = trim((string)($db['pick_company_name'] ?? ''));
  4164. }
  4165. }
  4166. if ($picked === '') {
  4167. $picked = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  4168. }
  4169. $qtyList[] = $this->resolveProcuremenThisQuantity($src);
  4170. $priceList[] = $this->resolveProcuremenCeilingPrice($src);
  4171. }
  4172. $rw['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  4173. $rw['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  4174. if ($picked !== '') {
  4175. $rw['pick_company_name'] = $picked;
  4176. $rw['picked_supplier_name'] = $picked;
  4177. }
  4178. }
  4179. unset($rw);
  4180. }
  4181. /**
  4182. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  4183. *
  4184. * @param int[] $scydgyIds
  4185. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  4186. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  4187. */
  4188. protected function OrderDetailSummary(array $scydgyIds)
  4189. {
  4190. $out = [];
  4191. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4192. if ($scydgyIds === []) {
  4193. return $out;
  4194. }
  4195. $list = [];
  4196. try {
  4197. $list = Db::table('purchase_order_detail')
  4198. ->where('scydgy_id', 'in', $scydgyIds)
  4199. ->field('id,scydgy_id,amount,delivery')
  4200. ->select();
  4201. } catch (\Throwable $e) {
  4202. $list = [];
  4203. }
  4204. if (!is_array($list)) {
  4205. return $out;
  4206. }
  4207. foreach ($list as $r) {
  4208. if (!is_array($r)) {
  4209. continue;
  4210. }
  4211. $ids = (int)($r['scydgy_id'] ?? 0);
  4212. if (!$this->isValidScydgyRowId($ids)) {
  4213. continue;
  4214. }
  4215. if (!isset($out[$ids])) {
  4216. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4217. }
  4218. $out[$ids]['cnt']++;
  4219. $am = $r['amount'] ?? null;
  4220. if ($am !== null && $am !== '') {
  4221. if (!(is_string($am) && trim($am) === '')) {
  4222. $out[$ids]['amt']++;
  4223. }
  4224. }
  4225. $dv = $r['delivery'] ?? null;
  4226. if ($dv !== null && trim((string)$dv) !== '') {
  4227. $out[$ids]['deliv']++;
  4228. }
  4229. }
  4230. return $out;
  4231. }
  4232. /**
  4233. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  4234. *
  4235. * @return array
  4236. */
  4237. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  4238. {
  4239. $strContains = function ($haystack, $needle) {
  4240. if ($needle === '') {
  4241. return false;
  4242. }
  4243. $haystack = (string)$haystack;
  4244. if (function_exists('mb_stripos')) {
  4245. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  4246. }
  4247. return stripos($haystack, $needle) !== false;
  4248. };
  4249. $stripAlias = function ($f) {
  4250. return preg_replace('/^[ab]\./i', '', (string)$f);
  4251. };
  4252. $searchColNames = [];
  4253. foreach (explode(',', $this->searchFields) as $colRaw) {
  4254. $c = $stripAlias(trim($colRaw));
  4255. if ($c !== '') {
  4256. $searchColNames[] = $c;
  4257. }
  4258. }
  4259. // 等值条件先行(表头下拉),减少后续日期解析量
  4260. $eqFilters = [];
  4261. $otherFilters = [];
  4262. foreach ($filterArr as $fk => $fv) {
  4263. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  4264. continue;
  4265. }
  4266. if (is_array($fv)) {
  4267. continue;
  4268. }
  4269. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  4270. continue;
  4271. }
  4272. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  4273. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  4274. $field = $stripAlias($fk);
  4275. if ($sym === '=' || $sym === '') {
  4276. $eqFilters[$field] = trim((string)$fv);
  4277. } else {
  4278. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  4279. }
  4280. }
  4281. $ymTarget = '';
  4282. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  4283. $ymTarget = $ymM[1];
  4284. }
  4285. $filtered = [];
  4286. foreach ($pool as $r) {
  4287. if (!is_array($r)) {
  4288. continue;
  4289. }
  4290. foreach ($eqFilters as $field => $fv) {
  4291. if (trim((string)($r[$field] ?? '')) !== $fv) {
  4292. continue 2;
  4293. }
  4294. }
  4295. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  4296. // 初选池不应含手工单;若混入则直接剔除
  4297. if ($isManual) {
  4298. continue;
  4299. }
  4300. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  4301. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  4302. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  4303. continue;
  4304. }
  4305. if ($applyMonthRange) {
  4306. $mo = (int)$m[2];
  4307. if ($mo < 1 || $mo > 12) {
  4308. continue;
  4309. }
  4310. if ($ymTarget !== '') {
  4311. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4312. if ($ymRow !== $ymTarget) {
  4313. continue;
  4314. }
  4315. } else {
  4316. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4317. $rowMonthStart = $ymRow . '-01 00:00:00';
  4318. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  4319. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  4320. continue;
  4321. }
  4322. }
  4323. }
  4324. if ($search !== '') {
  4325. $hitSearch = false;
  4326. foreach ($searchColNames as $c) {
  4327. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  4328. if ($cell !== '' && $strContains($cell, $search)) {
  4329. $hitSearch = true;
  4330. break;
  4331. }
  4332. }
  4333. if (!$hitSearch) {
  4334. continue;
  4335. }
  4336. }
  4337. foreach ($otherFilters as $item) {
  4338. $fv = $item['fv'];
  4339. $sym = $item['sym'];
  4340. $field = $item['field'];
  4341. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  4342. $cellStr = trim((string)$cell);
  4343. switch ($sym) {
  4344. case '<>':
  4345. if ((string)$cell === (string)$fv) {
  4346. continue 3;
  4347. }
  4348. break;
  4349. case 'LIKE':
  4350. case 'NOT LIKE':
  4351. $needle = trim((string)$fv);
  4352. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  4353. if ($sym === 'LIKE' && !$hit) {
  4354. continue 3;
  4355. }
  4356. if ($sym === 'NOT LIKE' && $hit) {
  4357. continue 3;
  4358. }
  4359. break;
  4360. case 'BETWEEN':
  4361. case 'RANGE':
  4362. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  4363. if (count($parts) < 2) {
  4364. $parts = is_string($fv) ? explode(',', $fv) : [];
  4365. }
  4366. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  4367. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  4368. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  4369. continue 3;
  4370. }
  4371. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  4372. continue 3;
  4373. }
  4374. break;
  4375. case '>':
  4376. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  4377. continue 3;
  4378. }
  4379. break;
  4380. case '>=':
  4381. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  4382. continue 3;
  4383. }
  4384. break;
  4385. case '<':
  4386. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  4387. continue 3;
  4388. }
  4389. break;
  4390. case '<=':
  4391. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  4392. continue 3;
  4393. }
  4394. break;
  4395. default:
  4396. if ((string)$cell !== (string)$fv) {
  4397. continue 3;
  4398. }
  4399. break;
  4400. }
  4401. }
  4402. $filtered[] = $r;
  4403. }
  4404. return $filtered;
  4405. }
  4406. /**
  4407. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  4408. */
  4409. public function snapshotToProcure()
  4410. {
  4411. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4412. $this->error(__('Invalid parameters'));
  4413. }
  4414. $row = json_decode($this->request->post('row_json', ''), true);
  4415. if (!is_array($row)) {
  4416. $this->error(__('Invalid parameters'));
  4417. }
  4418. try {
  4419. $ids = $this->extractScydgyRowId($row);
  4420. if (!$this->isValidScydgyRowId($ids)) {
  4421. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4422. }
  4423. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4424. $data = [
  4425. 'scydgy_id' => $ids,
  4426. 'CCYDH' => $row['CCYDH'] ?? null,
  4427. 'CYJMC' => $row['CYJMC'] ?? null,
  4428. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4429. 'CDXMC' => $row['CDXMC'] ?? null,
  4430. 'CGYBH' => $row['CGYBH'] ?? null,
  4431. 'CGYMC' => $row['CGYMC'] ?? null,
  4432. 'CDW' => $row['CDW'] ?? null,
  4433. 'czlyq' => $row['czlyq'] ?? null,
  4434. 'NGZL' => $row['NGZL'] ?? null,
  4435. 'CDF' => $row['CDF'] ?? null,
  4436. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4437. 'MBZ' => $row['MBZ'] ?? null,
  4438. 'bwjg' => $row['bwjg'] ?? null,
  4439. 'iStatus' => $row['iStatus'] ?? null,
  4440. 'dStamp' => $row['dStamp'] ?? null,
  4441. 'dputrecord' => $row['dputrecord'] ?? null,
  4442. 'cywyxm' => $row['cywyxm'] ?? null,
  4443. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4444. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4445. ];
  4446. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  4447. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  4448. $mbzSnap = trim((string)($data['MBZ'] ?? ''));
  4449. if (!$exists && $qtySnap === '' && $priceSnap === '' && $mbzSnap === '') {
  4450. $this->success('操作成功');
  4451. return;
  4452. }
  4453. if ($exists) {
  4454. $upd = $data;
  4455. unset($upd['scydgy_id'], $upd['status']);
  4456. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4457. } else {
  4458. // 新增:不写 status(空/走库默认);仅写创建时间
  4459. $data['createtime'] = date('Y-m-d H:i:s');
  4460. Db::table('purchase_order')->insert($data);
  4461. }
  4462. } catch (\Throwable $e) {
  4463. $this->error($e->getMessage());
  4464. }
  4465. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  4466. $this->success('操作成功');
  4467. }
  4468. /**
  4469. * 未发列表
  4470. * 「完结」或「仅保存本次数量/最高限价/备注」:有则改、无则插
  4471. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  4472. */
  4473. public function completeDirectly()
  4474. {
  4475. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4476. $this->error(__('参数错误'));
  4477. }
  4478. if (!$this->procuremenCanComplete()) {
  4479. $this->error(__('You have no permission'));
  4480. }
  4481. $row = json_decode($this->request->post('row_json', ''), true);
  4482. if (!is_array($row)) {
  4483. $this->error(__('Invalid parameters'));
  4484. }
  4485. $finishRaw = $this->request->post('finish', '1');
  4486. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  4487. $poIdLog = null;
  4488. try {
  4489. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  4490. $ids = $this->extractScydgyRowId($row);
  4491. if (!$this->isValidScydgyRowId($ids)) {
  4492. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4493. }
  4494. if ($asComplete) {
  4495. $this->assertPickRowCanComplete($ids, $row);
  4496. }
  4497. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4498. $data = [
  4499. 'scydgy_id' => $ids,
  4500. 'CCYDH' => $row['CCYDH'] ?? null,
  4501. 'CYJMC' => $row['CYJMC'] ?? null,
  4502. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4503. 'CDXMC' => $row['CDXMC'] ?? null,
  4504. 'CGYBH' => $row['CGYBH'] ?? null,
  4505. 'CGYMC' => $row['CGYMC'] ?? null,
  4506. 'CDW' => $row['CDW'] ?? null,
  4507. 'czlyq' => $row['czlyq'] ?? null,
  4508. 'NGZL' => $row['NGZL'] ?? null,
  4509. 'CDF' => $row['CDF'] ?? null,
  4510. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4511. 'MBZ' => $row['MBZ'] ?? null,
  4512. 'bwjg' => $row['bwjg'] ?? null,
  4513. 'iStatus' => $row['iStatus'] ?? null,
  4514. 'dStamp' => $row['dStamp'] ?? null,
  4515. 'dputrecord' => $row['dputrecord'] ?? null,
  4516. 'cywyxm' => $row['cywyxm'] ?? null,
  4517. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4518. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4519. ];
  4520. if ($asComplete) {
  4521. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  4522. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  4523. }
  4524. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  4525. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  4526. $mbzCd = trim((string)($data['MBZ'] ?? ''));
  4527. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '' && $mbzCd === '') {
  4528. $this->success('操作成功');
  4529. return;
  4530. }
  4531. if ($exists) {
  4532. $upd = $data;
  4533. unset($upd['scydgy_id']);
  4534. if (!$asComplete) {
  4535. unset($upd['status']);
  4536. }
  4537. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4538. } else {
  4539. // 新增:不写 status;完结时 $data 已含 status=1
  4540. $data['createtime'] = date('Y-m-d H:i:s');
  4541. Db::table('purchase_order')->insert($data);
  4542. }
  4543. } catch (\Throwable $e) {
  4544. $this->error($e->getMessage());
  4545. }
  4546. try {
  4547. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4548. if (is_array($rpo)) {
  4549. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4550. $poIdLog = $tid > 0 ? $tid : null;
  4551. }
  4552. } catch (\Throwable $e) {
  4553. $poIdLog = null;
  4554. }
  4555. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  4556. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  4557. if ($asComplete) {
  4558. $this->addOrderLog(
  4559. $ids,
  4560. 'mark_complete',
  4561. '点击「完结」,已标记为已完结',
  4562. $poIdLog
  4563. );
  4564. try {
  4565. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  4566. if ($pdfPublicPath === '') {
  4567. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  4568. }
  4569. } catch (\Throwable $e) {
  4570. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  4571. }
  4572. } else {
  4573. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  4574. $mbz = isset($data['MBZ']) ? trim((string)$data['MBZ']) : '';
  4575. $qtyPart = '本次数量「' . ($q !== '' ? $q : '') . '」';
  4576. $pricePart = '最高限价「' . ($p !== '' ? $p : '') . '」';
  4577. $mbzPart = '备注「' . ($mbz !== '' ? $mbz : '') . '」';
  4578. $detail = ($gymc !== '' ? ($gymc . $qtyPart) : $qtyPart) . ',' . $pricePart . ',' . $mbzPart;
  4579. $this->addOrderLog(
  4580. $ids,
  4581. 'save_qty_price',
  4582. '保存本次数量、最高限价、备注:' . $detail,
  4583. $poIdLog
  4584. );
  4585. }
  4586. $this->pickHiddenScydgySetCache = null;
  4587. $this->success("操作成功");
  4588. }
  4589. /**
  4590. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价、备注(若表中有对应列)
  4591. *
  4592. * @param array<int, array> $rows 引用传递当前页行
  4593. */
  4594. protected function mergePurchaseOrder(array &$rows)
  4595. {
  4596. if ($rows === []) {
  4597. return;
  4598. }
  4599. $ids = [];
  4600. foreach ($rows as $rw) {
  4601. if (!is_array($rw)) {
  4602. continue;
  4603. }
  4604. $id = (int)($rw['ID'] ?? 0);
  4605. // 含手工新增负数 scydgy_id,避免限价/数量不同步
  4606. if ($this->isValidScydgyRowId($id)) {
  4607. $ids[$id] = true;
  4608. }
  4609. }
  4610. $idList = array_keys($ids);
  4611. if ($idList === []) {
  4612. return;
  4613. }
  4614. try {
  4615. $list = Db::table('purchase_order')
  4616. ->where('scydgy_id', 'in', $idList)
  4617. ->field('scydgy_id,This_quantity,ceilingPrice,MBZ')
  4618. ->select();
  4619. } catch (\Throwable $e) {
  4620. return;
  4621. }
  4622. if (!is_array($list)) {
  4623. return;
  4624. }
  4625. $byId = [];
  4626. foreach ($list as $dbRow) {
  4627. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4628. continue;
  4629. }
  4630. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4631. }
  4632. foreach ($rows as &$rw) {
  4633. if (!is_array($rw)) {
  4634. continue;
  4635. }
  4636. $sid = (int)($rw['ID'] ?? 0);
  4637. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  4638. continue;
  4639. }
  4640. $db = $byId[$sid];
  4641. // 有 purchase_order 记录时同步数量/限价/备注(含清空后的空串,避免刷新后又冒出来)
  4642. if (array_key_exists('This_quantity', $db)) {
  4643. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  4644. }
  4645. if (array_key_exists('ceilingPrice', $db)) {
  4646. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  4647. } elseif (array_key_exists('ceiling_price', $db)) {
  4648. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  4649. }
  4650. if (array_key_exists('MBZ', $db)) {
  4651. $rw['MBZ'] = $db['MBZ'] === null ? '' : $db['MBZ'];
  4652. }
  4653. }
  4654. unset($rw);
  4655. }
  4656. /**
  4657. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  4658. */
  4659. public function purchaseConfirmPick()
  4660. {
  4661. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4662. $this->error(__('Invalid parameters'));
  4663. }
  4664. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  4665. $this->error(__('You have no permission'));
  4666. }
  4667. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  4668. if ($batchRaw !== '') {
  4669. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  4670. return;
  4671. }
  4672. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  4673. $sid = (int)$scydgyId;
  4674. if (!$this->isValidScydgyRowId($sid)) {
  4675. $this->error('参数无效');
  4676. }
  4677. $parseIdList = function ($raw) {
  4678. if (is_array($raw)) {
  4679. $arr = $raw;
  4680. } else {
  4681. $decoded = json_decode((string)$raw, true);
  4682. $arr = is_array($decoded) ? $decoded : [];
  4683. }
  4684. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  4685. };
  4686. $selectedRaw = $this->request->post('selected_ids', null);
  4687. if ($selectedRaw === null || $selectedRaw === '') {
  4688. $legacy = (int)$this->request->post('selected_id', 0);
  4689. $selectedIds = $legacy > 0 ? [$legacy] : [];
  4690. } else {
  4691. $selectedIds = $parseIdList($selectedRaw);
  4692. }
  4693. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  4694. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  4695. try {
  4696. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  4697. } catch (\InvalidArgumentException $e) {
  4698. $this->error($e->getMessage());
  4699. } catch (\Throwable $e) {
  4700. $this->error($e->getMessage());
  4701. }
  4702. $this->pickHiddenScydgySetCache = null;
  4703. $this->success('操作成功', '', $result);
  4704. }
  4705. /**
  4706. * 整单采购确认(多道工序一次提交)
  4707. */
  4708. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  4709. {
  4710. $decoded = json_decode($batchRaw, true);
  4711. if (!is_array($decoded) || $decoded === []) {
  4712. $this->error('提交数据无效');
  4713. }
  4714. $picks = [];
  4715. foreach ($decoded as $item) {
  4716. if (!is_array($item)) {
  4717. continue;
  4718. }
  4719. $sid = (int)($item['scydgy_id'] ?? 0);
  4720. if (!$this->isValidScydgyRowId($sid)) {
  4721. continue;
  4722. }
  4723. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  4724. if (!is_array($sel)) {
  4725. $sel = [(int)$sel];
  4726. }
  4727. $unsel = $item['unselected_ids'] ?? [];
  4728. if (!is_array($unsel)) {
  4729. $unsel = json_decode((string)$unsel, true);
  4730. $unsel = is_array($unsel) ? $unsel : [];
  4731. }
  4732. $picks[] = [
  4733. 'scydgy_id' => $sid,
  4734. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  4735. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  4736. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  4737. ];
  4738. }
  4739. if ($picks === []) {
  4740. $this->error('提交数据无效');
  4741. }
  4742. Db::startTrans();
  4743. $results = [];
  4744. try {
  4745. foreach ($picks as $pick) {
  4746. $results[] = $this->runPurchaseConfirmPick(
  4747. (int)$pick['scydgy_id'],
  4748. $pick['selected_ids'],
  4749. $pick['unselected_ids'],
  4750. (int)$pick['purchase_order_id'],
  4751. false,
  4752. false
  4753. );
  4754. }
  4755. Db::commit();
  4756. } catch (\Throwable $e) {
  4757. Db::rollback();
  4758. $msg = $e->getMessage();
  4759. $this->error($msg !== '' ? $msg : '提交失败');
  4760. }
  4761. try {
  4762. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  4763. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  4764. } catch (\Throwable $e) {
  4765. Log::write('采购确认通知批量发送异常: ' . $e->getMessage(), 'error');
  4766. }
  4767. $this->pickHiddenScydgySetCache = null;
  4768. $this->success('操作成功', '', ['batch' => $results]);
  4769. }
  4770. /**
  4771. * @return array<string, mixed>
  4772. */
  4773. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  4774. {
  4775. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  4776. ProcuremenGuard::assertWflowPendingApproval($poRow);
  4777. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  4778. $scydgyId = (string)$sid;
  4779. if ($selectedIds === []) {
  4780. throw new \InvalidArgumentException('请至少勾选一条明细');
  4781. }
  4782. $inter = array_intersect($selectedIds, $unselectedIds);
  4783. if ($inter !== []) {
  4784. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  4785. }
  4786. $allIds = $this->purchaseOrderDetail($sid);
  4787. if ($allIds === []) {
  4788. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  4789. }
  4790. foreach ($selectedIds as $id) {
  4791. if (!in_array($id, $allIds, true)) {
  4792. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  4793. }
  4794. }
  4795. foreach ($unselectedIds as $id) {
  4796. if (!in_array($id, $allIds, true)) {
  4797. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  4798. }
  4799. }
  4800. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  4801. sort($union, SORT_NUMERIC);
  4802. $expect = $allIds;
  4803. sort($expect, SORT_NUMERIC);
  4804. if ($union !== $expect) {
  4805. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  4806. }
  4807. if ($manageTransaction) {
  4808. Db::startTrans();
  4809. }
  4810. try {
  4811. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  4812. $aff = 0;
  4813. try {
  4814. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4815. } catch (\Throwable $e) {
  4816. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4817. }
  4818. if ($aff < 1) {
  4819. throw new \Exception('更新选中状态失败');
  4820. }
  4821. $poPayload = [
  4822. // 审核通过后进入「待入库评分」;合格/不合格后才置已完结
  4823. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  4824. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  4825. ];
  4826. if ($purchaseOrderId > 0) {
  4827. $poAff = (int)Db::table('purchase_order')
  4828. ->where('id', $purchaseOrderId)
  4829. ->where('scydgy_id', $sid)
  4830. ->update($poPayload);
  4831. if ($poAff < 1) {
  4832. throw new \Exception('主表订单不存在或与工序行不匹配');
  4833. }
  4834. } else {
  4835. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  4836. if ($poAff < 1) {
  4837. throw new \Exception('未找到');
  4838. }
  4839. }
  4840. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  4841. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  4842. if ($manageTransaction) {
  4843. Db::commit();
  4844. }
  4845. } catch (\Throwable $e) {
  4846. if ($manageTransaction) {
  4847. Db::rollback();
  4848. }
  4849. throw $e;
  4850. }
  4851. $poIdFinal = $purchaseOrderId;
  4852. if ($poIdFinal <= 0) {
  4853. try {
  4854. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4855. if (is_array($rpo)) {
  4856. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4857. }
  4858. } catch (\Throwable $e) {
  4859. $poIdFinal = 0;
  4860. }
  4861. }
  4862. $pickNames = [];
  4863. foreach ($selectedIds as $pid) {
  4864. $dr = $this->purchaseOrderDetai($sid, $pid);
  4865. $nm = trim((string)($dr['company_name'] ?? ''));
  4866. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  4867. }
  4868. $this->addOrderLog(
  4869. $sid,
  4870. 'purchase_confirm',
  4871. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  4872. $poIdFinal > 0 ? $poIdFinal : null
  4873. );
  4874. if ($sendNotifications) {
  4875. try {
  4876. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  4877. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  4878. 'scydgy_id' => $sid,
  4879. 'selected_ids' => $selectedIds,
  4880. 'unselected_ids' => $unselectedIds,
  4881. 'purchase_order_id' => $purchaseOrderId,
  4882. ]]);
  4883. } catch (\Throwable $e) {
  4884. Log::write('采购确认通知发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  4885. }
  4886. }
  4887. Log::write(sprintf(
  4888. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  4889. $scydgyId,
  4890. $purchaseOrderId,
  4891. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  4892. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  4893. ), 'notice');
  4894. $pdfPublicPath = '';
  4895. try {
  4896. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  4897. } catch (\Throwable $e) {
  4898. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  4899. }
  4900. return [
  4901. 'scydgy_id' => $scydgyId,
  4902. 'purchase_order_id' => $purchaseOrderId,
  4903. 'selected_ids' => $selectedIds,
  4904. 'unselected_ids' => $unselectedIds,
  4905. 'purchase_confirm_pdf' => $pdfPublicPath,
  4906. ];
  4907. }
  4908. /**
  4909. * 审批通过短信:按本次涉及的工序汇总 process_lines
  4910. *
  4911. * @param int[]|string[] $scydgyIds
  4912. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4913. */
  4914. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  4915. {
  4916. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4917. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4918. if ($scydgyIds === []) {
  4919. return $empty;
  4920. }
  4921. $pos = [];
  4922. try {
  4923. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  4924. } catch (\Throwable $e) {
  4925. $rows = [];
  4926. }
  4927. if (is_array($rows)) {
  4928. foreach ($rows as $po) {
  4929. if (is_array($po)) {
  4930. $pos[] = $po;
  4931. }
  4932. }
  4933. }
  4934. if ($pos === []) {
  4935. return $empty;
  4936. }
  4937. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  4938. return [
  4939. 'ccydh' => $ccydh,
  4940. 'pos' => $pos,
  4941. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4942. ];
  4943. }
  4944. /**
  4945. * 审批通过/未通过:短信 + 邮件(同一供应商只发一条;邮件含平台链接)
  4946. *
  4947. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  4948. * @param array<int, array<string, mixed>> $picks
  4949. */
  4950. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  4951. {
  4952. if ($picks === []) {
  4953. return;
  4954. }
  4955. $this->ensureConfirmResultEmailTemplates();
  4956. $fallbackDetailId = 0;
  4957. $winners = [];
  4958. $losers = [];
  4959. foreach ($picks as $pick) {
  4960. if (!is_array($pick)) {
  4961. continue;
  4962. }
  4963. $sid = (int)($pick['scydgy_id'] ?? 0);
  4964. if (!$this->isValidScydgyRowId($sid)) {
  4965. continue;
  4966. }
  4967. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  4968. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  4969. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  4970. $fallbackDetailId = (int)$selectedIds[0];
  4971. }
  4972. foreach ($selectedIds as $pid) {
  4973. $dr = $this->purchaseOrderDetai($sid, $pid);
  4974. if (!is_array($dr)) {
  4975. continue;
  4976. }
  4977. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  4978. }
  4979. foreach ($unselectedIds as $pid) {
  4980. $dr = $this->purchaseOrderDetai($sid, $pid);
  4981. if (!is_array($dr)) {
  4982. continue;
  4983. }
  4984. $key = $this->notifySupplierDedupeKey($dr);
  4985. if (!isset($winners[$key])) {
  4986. $losers[$key] = $dr;
  4987. }
  4988. }
  4989. }
  4990. if ($winners === [] && $losers === []) {
  4991. return;
  4992. }
  4993. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  4994. $poIdLog = 0;
  4995. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  4996. if (isset($pos[0]) && is_array($pos[0])) {
  4997. $poIdLog = (int)($pos[0]['id'] ?? 0);
  4998. }
  4999. $sendSmsSafe = function ($phone, $content) {
  5000. $phone = trim((string)$phone);
  5001. if ($phone === '') {
  5002. return;
  5003. }
  5004. try {
  5005. $this->smsbao($phone, $content);
  5006. } catch (\Throwable $e) {
  5007. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  5008. }
  5009. };
  5010. $sendConfirmEmailSafe = function (array $dr, string $emailScene) use ($confirmNotifyVars, $poIdLog) {
  5011. $cname = trim((string)($dr['company_name'] ?? ''));
  5012. $ph = trim((string)($dr['phone'] ?? ''));
  5013. $toEmail = trim((string)($dr['email'] ?? ''));
  5014. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5015. Log::write('采购确认邮件跳过:无有效邮箱 company=' . $cname, 'error');
  5016. return;
  5017. }
  5018. $detailId = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5019. if ($detailId <= 0) {
  5020. $detailId = (int)($confirmNotifyVars['_fallback_detail_id'] ?? 0);
  5021. }
  5022. try {
  5023. $platformUrl = $this->buildMprocMobileOrderUrl($detailId);
  5024. } catch (\Throwable $e) {
  5025. Log::write('采购确认邮件链接失败: ' . $e->getMessage(), 'error');
  5026. $platformUrl = '';
  5027. }
  5028. $vars = array_merge($confirmNotifyVars, [
  5029. 'company_name' => $cname,
  5030. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5031. 'phone' => $ph,
  5032. 'email' => $toEmail,
  5033. 'platform_url' => $platformUrl,
  5034. ]);
  5035. unset($vars['_fallback_detail_id']);
  5036. try {
  5037. $mailPlain = $this->renderNotifyTemplate($emailScene, $vars);
  5038. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  5039. $mailSubject = $this->resolveProcuremenEmailSubject($emailScene);
  5040. $mailConfig = $this->loadMailerConfig();
  5041. $this->issueSendSupplierEmail([
  5042. 'company_name' => $cname,
  5043. 'email' => $toEmail,
  5044. 'mail_plain' => $mailPlain,
  5045. 'mail_body' => $mailBody,
  5046. 'notify_vars' => $vars,
  5047. 'sms_content' => '',
  5048. 'detail_links' => $platformUrl !== '' ? [['url' => $platformUrl, 'cgymc' => '']] : [],
  5049. 'email_log_scene' => 'confirm_result',
  5050. 'email_log_scydgy_id' => (int)($dr['scydgy_id'] ?? 0),
  5051. 'email_log_purchase_order_id' => $poIdLog,
  5052. ], $mailConfig, $mailSubject);
  5053. } catch (\Throwable $e) {
  5054. Log::write('采购确认邮件失败 company=' . $cname . ' email=' . $toEmail . ' ' . $e->getMessage(), 'error');
  5055. }
  5056. };
  5057. $confirmNotifyVars['_fallback_detail_id'] = $fallbackDetailId;
  5058. foreach ($winners as $dr) {
  5059. $cname = trim((string)($dr['company_name'] ?? ''));
  5060. $ph = trim((string)($dr['phone'] ?? ''));
  5061. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  5062. 'company_name' => $cname,
  5063. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5064. 'phone' => $ph,
  5065. ]));
  5066. $sendSmsSafe($ph, $sms);
  5067. $sendConfirmEmailSafe($dr, 'confirm_ok_email');
  5068. }
  5069. foreach ($losers as $dr) {
  5070. $cname = trim((string)($dr['company_name'] ?? ''));
  5071. $ph = trim((string)($dr['phone'] ?? ''));
  5072. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  5073. 'company_name' => $cname,
  5074. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5075. 'phone' => $ph,
  5076. ]));
  5077. $sendSmsSafe($ph, $sms);
  5078. $sendConfirmEmailSafe($dr, 'confirm_fail_email');
  5079. }
  5080. }
  5081. /**
  5082. * 短信去重键:优先手机号,否则公司名
  5083. */
  5084. protected function notifySupplierDedupeKey(array $detailRow): string
  5085. {
  5086. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  5087. if ($ph !== '') {
  5088. return 'p:' . $ph;
  5089. }
  5090. $cn = trim((string)($detailRow['company_name'] ?? ''));
  5091. return 'c:' . $cn;
  5092. }
  5093. /**
  5094. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  5095. *
  5096. * @param int[] $detailIds
  5097. */
  5098. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  5099. {
  5100. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  5101. if ($detailIds === []) {
  5102. return;
  5103. }
  5104. $payload = ['status_name' => $statusName];
  5105. try {
  5106. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  5107. } catch (\Throwable $e) {
  5108. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  5109. }
  5110. }
  5111. /**
  5112. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  5113. */
  5114. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  5115. {
  5116. try {
  5117. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  5118. } catch (\Throwable $e) {
  5119. return;
  5120. }
  5121. if (!is_array($rows)) {
  5122. return;
  5123. }
  5124. foreach ($rows as $dr) {
  5125. if (!is_array($dr)) {
  5126. continue;
  5127. }
  5128. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5129. if ($id <= 0) {
  5130. continue;
  5131. }
  5132. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  5133. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  5134. try {
  5135. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  5136. } catch (\Throwable $e) {
  5137. }
  5138. }
  5139. }
  5140. /**
  5141. * @param array<string, mixed> $detailRow
  5142. */
  5143. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  5144. {
  5145. $am = $detailRow['amount'] ?? null;
  5146. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  5147. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  5148. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  5149. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  5150. }
  5151. /**
  5152. * @return int[]
  5153. */
  5154. protected function purchaseOrderDetail(int $scydgyId): array
  5155. {
  5156. if (!$this->isValidScydgyRowId($scydgyId)) {
  5157. return [];
  5158. }
  5159. try {
  5160. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  5161. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  5162. $list = $listQuery->select();
  5163. } catch (\Throwable $e) {
  5164. return [];
  5165. }
  5166. if (!is_array($list)) {
  5167. return [];
  5168. }
  5169. $ids = [];
  5170. foreach ($list as $r) {
  5171. if (!is_array($r)) {
  5172. continue;
  5173. }
  5174. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  5175. if ($pk > 0) {
  5176. $ids[] = $pk;
  5177. }
  5178. }
  5179. return array_values(array_unique($ids));
  5180. }
  5181. /**
  5182. * 获取当前登录用户信息 [id, 展示名]
  5183. * admin_name 一律记「名称」(昵称),无昵称再回退账号
  5184. */
  5185. protected function GetUseName(): array
  5186. {
  5187. $id = 0;
  5188. $name = '';
  5189. try {
  5190. if ($this->auth && $this->auth->isLogin()) {
  5191. $u = $this->auth->getUserInfo();
  5192. if (is_array($u)) {
  5193. $id = (int)($u['id'] ?? 0);
  5194. $name = trim((string)($u['nickname'] ?? ''));
  5195. // 会话昵称缺失或等于登录账号时,再查库取正式昵称
  5196. $sessionUser = trim((string)($u['username'] ?? ''));
  5197. if ($id > 0 && ($name === '' || ($sessionUser !== '' && strcasecmp($name, $sessionUser) === 0))) {
  5198. try {
  5199. $row = Db::name('admin')->where('id', $id)->field('nickname,username')->find();
  5200. if (is_array($row)) {
  5201. $nick = trim((string)($row['nickname'] ?? ''));
  5202. if ($nick !== '') {
  5203. $name = $nick;
  5204. } elseif ($name === '') {
  5205. $name = trim((string)($row['username'] ?? ''));
  5206. }
  5207. }
  5208. } catch (\Throwable $e) {
  5209. }
  5210. }
  5211. if ($name === '') {
  5212. $name = $sessionUser;
  5213. }
  5214. }
  5215. }
  5216. } catch (\Throwable $e) {
  5217. }
  5218. if ($name === '') {
  5219. $name = '未知用户';
  5220. }
  5221. return [$id, $name];
  5222. }
  5223. /**
  5224. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  5225. */
  5226. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  5227. {
  5228. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  5229. }
  5230. /**
  5231. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  5232. *
  5233. * @param array<int, array<string, mixed>> $rows
  5234. */
  5235. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  5236. {
  5237. $sidList = [];
  5238. foreach ($rows as $rw) {
  5239. if (!is_array($rw)) {
  5240. continue;
  5241. }
  5242. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5243. foreach ($rw['_order_merge_rows'] as $mr) {
  5244. $mid = (int)($mr['ID'] ?? 0);
  5245. if ($this->isValidScydgyRowId($mid)) {
  5246. $sidList[$mid] = true;
  5247. }
  5248. }
  5249. }
  5250. $id = (int)($rw['ID'] ?? 0);
  5251. if ($this->isValidScydgyRowId($id)) {
  5252. $sidList[$id] = true;
  5253. }
  5254. }
  5255. $sids = array_keys($sidList);
  5256. $issueBySid = [];
  5257. $confirmBySid = [];
  5258. $approveBySid = [];
  5259. if ($sids !== []) {
  5260. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  5261. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  5262. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  5263. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  5264. try {
  5265. $logs = Db::table('purchase_order_oper_log')
  5266. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  5267. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  5268. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  5269. ->order('id', 'asc')
  5270. ->select();
  5271. } catch (\Throwable $e) {
  5272. $logs = [];
  5273. }
  5274. if (is_array($logs)) {
  5275. $issueSet = array_fill_keys($issueActs, true);
  5276. $confirmSet = array_fill_keys($confirmActs, true);
  5277. $approveSet = array_fill_keys($approveActs, true);
  5278. foreach ($logs as $lg) {
  5279. if (!is_array($lg)) {
  5280. continue;
  5281. }
  5282. $lg = ProcuremenOperLog::normalizeRow($lg);
  5283. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  5284. if ($sid === 0) {
  5285. continue;
  5286. }
  5287. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  5288. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  5289. if ($t === '') {
  5290. continue;
  5291. }
  5292. if (isset($issueSet[$action])) {
  5293. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  5294. $issueBySid[$sid] = $t;
  5295. }
  5296. }
  5297. if (isset($confirmSet[$action])) {
  5298. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  5299. $confirmBySid[$sid] = $t;
  5300. }
  5301. }
  5302. if (isset($approveSet[$action])) {
  5303. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  5304. $approveBySid[$sid] = $t;
  5305. }
  5306. }
  5307. }
  5308. }
  5309. }
  5310. foreach ($rows as &$rw) {
  5311. if (!is_array($rw)) {
  5312. continue;
  5313. }
  5314. $mergeSids = [];
  5315. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5316. foreach ($rw['_order_merge_rows'] as $mr) {
  5317. $mid = (int)($mr['ID'] ?? 0);
  5318. if ($this->isValidScydgyRowId($mid)) {
  5319. $mergeSids[] = $mid;
  5320. }
  5321. }
  5322. }
  5323. $rid = (int)($rw['ID'] ?? 0);
  5324. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  5325. $mergeSids[] = $rid;
  5326. }
  5327. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  5328. $issue = $pick;
  5329. $confirm = '';
  5330. $approve = '';
  5331. foreach ($mergeSids as $sid) {
  5332. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  5333. $issue = $issueBySid[$sid];
  5334. }
  5335. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  5336. $confirm = $confirmBySid[$sid];
  5337. }
  5338. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  5339. $approve = $approveBySid[$sid];
  5340. }
  5341. }
  5342. if ($issue === '' && $pick !== '') {
  5343. $issue = $pick;
  5344. }
  5345. $rw['issue_time'] = $issue;
  5346. $rw['confirm_time'] = $confirm;
  5347. $rw['approve_time'] = $approve;
  5348. }
  5349. unset($rw);
  5350. }
  5351. /**
  5352. * 按主键取一条
  5353. */
  5354. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  5355. {
  5356. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  5357. return [];
  5358. }
  5359. try {
  5360. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  5361. if (is_array($one)) {
  5362. return $one;
  5363. }
  5364. } catch (\Throwable $e) {
  5365. }
  5366. try {
  5367. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  5368. if (is_array($one)) {
  5369. return $one;
  5370. }
  5371. } catch (\Throwable $e) {
  5372. }
  5373. return [];
  5374. }
  5375. /**
  5376. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  5377. */
  5378. protected function formatProcuremenDetailTime($v): string
  5379. {
  5380. if ($v === null || $v === '') {
  5381. return '';
  5382. }
  5383. if (is_numeric($v) && (int)$v > 946684800) {
  5384. return date('Y-m-d H:i:s', (int)$v);
  5385. }
  5386. return ProcuremenTime::formatDisplayDateTime($v);
  5387. }
  5388. /**
  5389. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  5390. */
  5391. protected function formatDeliveryYmd($v): string
  5392. {
  5393. if ($v === null || $v === '') {
  5394. return '';
  5395. }
  5396. $s = trim((string)$v);
  5397. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  5398. return '';
  5399. }
  5400. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5401. return $m[1];
  5402. }
  5403. $ts = strtotime($s);
  5404. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  5405. }
  5406. /**
  5407. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  5408. */
  5409. protected function detailRowSupplierOperated(array $r): bool
  5410. {
  5411. $am = $r['amount'] ?? null;
  5412. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5413. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5414. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5415. return $okAmt || $okDel;
  5416. }
  5417. /**
  5418. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  5419. */
  5420. protected function resolveDetailSupplierOperTime(array $r): string
  5421. {
  5422. if (!$this->detailRowSupplierOperated($r)) {
  5423. return '';
  5424. }
  5425. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  5426. if ($t !== '') {
  5427. return $t;
  5428. }
  5429. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  5430. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  5431. continue;
  5432. }
  5433. $t = $this->formatProcuremenDetailTime($r[$col]);
  5434. if ($t !== '') {
  5435. return $t;
  5436. }
  5437. }
  5438. return '';
  5439. }
  5440. /**
  5441. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  5442. */
  5443. protected function detailRowSupplierAccepted(array $r): bool
  5444. {
  5445. $am = $r['amount'] ?? null;
  5446. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5447. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5448. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5449. return $okAmt && $okDel;
  5450. }
  5451. /**
  5452. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  5453. */
  5454. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  5455. {
  5456. if ($detailCount > 0) {
  5457. return true;
  5458. }
  5459. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  5460. return true;
  5461. }
  5462. $pickTime = trim((string)($main['pick_time'] ?? ''));
  5463. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  5464. return true;
  5465. }
  5466. return false;
  5467. }
  5468. /**
  5469. * 下发时间:优先 pick_time,其次首条下发明细时间
  5470. */
  5471. protected function resolveProcuremenIssueTime(array $main, array $details): string
  5472. {
  5473. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  5474. if ($issueTime !== '') {
  5475. return $issueTime;
  5476. }
  5477. foreach ($details as $dr) {
  5478. if (!is_array($dr)) {
  5479. continue;
  5480. }
  5481. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5482. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  5483. $issueTime = $t;
  5484. }
  5485. }
  5486. if ($issueTime !== '') {
  5487. return $issueTime;
  5488. }
  5489. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5490. }
  5491. /**
  5492. * 直接点「完结」时间:优先操作记录 mark_complete
  5493. */
  5494. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  5495. {
  5496. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  5497. }
  5498. /**
  5499. * 操作记录时间(取指定 action 最近一条)
  5500. *
  5501. * @param string|array<int, string> $actions
  5502. */
  5503. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  5504. {
  5505. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  5506. }
  5507. /**
  5508. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  5509. *
  5510. * @param array $main purchase_order 一行
  5511. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  5512. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  5513. */
  5514. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  5515. {
  5516. $issueCnt = count($details);
  5517. $acceptCnt = 0;
  5518. $pickedName = '';
  5519. $pickedTime = '';
  5520. foreach ($details as $dr) {
  5521. if (!is_array($dr)) {
  5522. continue;
  5523. }
  5524. if ($this->detailRowSupplierAccepted($dr)) {
  5525. $acceptCnt++;
  5526. }
  5527. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5528. if ($pickedName === '') {
  5529. $pickedName = trim((string)($dr['company_name'] ?? ''));
  5530. }
  5531. if ($pickedTime === '') {
  5532. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  5533. if ($pickedTime === '') {
  5534. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5535. }
  5536. }
  5537. }
  5538. }
  5539. $hasMain = $main !== [];
  5540. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  5541. if ($poTime === '') {
  5542. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  5543. }
  5544. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  5545. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  5546. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  5547. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  5548. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  5549. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  5550. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  5551. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  5552. $inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
  5553. $inboundResult = '';
  5554. if ($scydgyId > 0) {
  5555. try {
  5556. $inRow = Db::table('purchase_order_inbound_score')
  5557. ->where('scydgy_id', $scydgyId)
  5558. ->field('result,updatetime,createtime')
  5559. ->find();
  5560. } catch (\Throwable $e) {
  5561. $inRow = null;
  5562. }
  5563. if (is_array($inRow) && $inRow !== []) {
  5564. $inboundResult = trim((string)($inRow['result'] ?? ''));
  5565. if ($inboundScoreTime === '') {
  5566. $inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
  5567. }
  5568. }
  5569. }
  5570. $inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
  5571. $supplierTime = '';
  5572. if ($acceptCnt > 0) {
  5573. foreach ($details as $dr) {
  5574. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  5575. continue;
  5576. }
  5577. $t = $this->resolveDetailSupplierOperTime($dr);
  5578. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  5579. $supplierTime = $t;
  5580. }
  5581. }
  5582. }
  5583. $directComplete = ($mainCompleted && !$issued);
  5584. $doneTime = '';
  5585. if ($mainCompleted) {
  5586. if ($directComplete) {
  5587. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  5588. }
  5589. if ($doneTime === '' && $inboundScoreTime !== '') {
  5590. $doneTime = $inboundScoreTime;
  5591. }
  5592. if ($doneTime === '') {
  5593. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5594. }
  5595. if ($doneTime === '') {
  5596. foreach ($details as $dr) {
  5597. if (!is_array($dr)) {
  5598. continue;
  5599. }
  5600. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  5601. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  5602. $doneTime = $t;
  5603. }
  5604. }
  5605. }
  5606. if ($doneTime === '') {
  5607. $doneTime = $poTime;
  5608. }
  5609. // 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
  5610. if ($doneTime === '' && $confirmApproveTime !== '') {
  5611. $doneTime = $confirmApproveTime;
  5612. }
  5613. }
  5614. if ($directComplete) {
  5615. // 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
  5616. $step1Done = $hasMain;
  5617. $step2Done = false;
  5618. $step3Done = false;
  5619. $step4Done = false;
  5620. $step5Done = false;
  5621. $stepInboundDone = $inboundScored;
  5622. $step6Done = $mainCompleted && $inboundScored;
  5623. } else {
  5624. $step1Done = $issued;
  5625. $step2Done = $issued;
  5626. $step3Done = $acceptCnt > 0;
  5627. $step4Done = $wflowPendingApproval;
  5628. if (!$step4Done) {
  5629. foreach ($details as $dr) {
  5630. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5631. $step4Done = true;
  5632. break;
  5633. }
  5634. }
  5635. }
  5636. $step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
  5637. $stepInboundDone = $inboundScored;
  5638. // 未确认合格/不合格时,「已完结」保持未点亮(灰色)
  5639. $step6Done = $mainCompleted && $inboundScored;
  5640. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  5641. if ($mainCompleted && $issued) {
  5642. $step3Done = true;
  5643. $step4Done = true;
  5644. $step5Done = true;
  5645. // 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
  5646. if ($supplierTime === '') {
  5647. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5648. if ($fillT !== '') {
  5649. $supplierTime = $fillT;
  5650. }
  5651. }
  5652. if ($pickedTime === '') {
  5653. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5654. if ($fillT !== '') {
  5655. $pickedTime = $fillT;
  5656. }
  5657. }
  5658. if ($auditSelectTime === '') {
  5659. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5660. if ($fillT !== '') {
  5661. $auditSelectTime = $fillT;
  5662. }
  5663. }
  5664. if ($confirmApproveTime === '') {
  5665. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5666. if ($fillT !== '') {
  5667. $confirmApproveTime = $fillT;
  5668. }
  5669. }
  5670. }
  5671. }
  5672. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  5673. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  5674. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  5675. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  5676. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  5677. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  5678. $inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
  5679. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  5680. $deadlineLines = [];
  5681. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  5682. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  5683. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  5684. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  5685. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  5686. }
  5687. }
  5688. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  5689. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  5690. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  5691. if ($deliveryDisp === '') {
  5692. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  5693. }
  5694. if ($deliveryDisp !== '') {
  5695. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  5696. }
  5697. }
  5698. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  5699. $deadlineText = implode("\n", $deadlineLines);
  5700. $prefixOperTime = static function (string $t): string {
  5701. $t = trim($t);
  5702. if ($t === '' || $t === '—') {
  5703. return $t;
  5704. }
  5705. if (strpos($t, '操作时间') === 0) {
  5706. return $t;
  5707. }
  5708. return '操作时间:' . $t;
  5709. };
  5710. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  5711. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  5712. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
  5713. $stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5714. $step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5715. $steps = [
  5716. [
  5717. 'title' => '未发',
  5718. 'subtitle' => '',
  5719. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  5720. 'done' => $step1Done,
  5721. ],
  5722. [
  5723. 'title' => '下发',
  5724. 'subtitle' => $deadlineText,
  5725. 'time' => $prefixOperTime($step2Time),
  5726. 'done' => $step2Done,
  5727. ],
  5728. [
  5729. 'title' => '供应商接单',
  5730. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  5731. 'time' => '',
  5732. 'done' => $step3Done,
  5733. ],
  5734. [
  5735. 'title' => '待确认',
  5736. 'subtitle' => $step4Done
  5737. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  5738. : ($issued ? '待选供应商' : ''),
  5739. 'time' => $prefixOperTime($step4Time),
  5740. 'done' => $step4Done,
  5741. ],
  5742. [
  5743. 'title' => '待审批',
  5744. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  5745. 'time' => $prefixOperTime($step5Time),
  5746. 'done' => $step5Done,
  5747. ],
  5748. [
  5749. 'title' => '是否合格',
  5750. 'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
  5751. 'time' => $prefixOperTime($stepInboundTime),
  5752. 'done' => $stepInboundDone,
  5753. ],
  5754. [
  5755. 'title' => '已完结',
  5756. 'subtitle' => '',
  5757. 'time' => $prefixOperTime($step6Time),
  5758. 'done' => $step6Done,
  5759. ],
  5760. ];
  5761. $currentIdx = count($steps) - 1;
  5762. if ($directComplete) {
  5763. // 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
  5764. if (!$step6Done) {
  5765. foreach ($steps as $i => $s) {
  5766. if (($s['title'] ?? '') === '是否合格') {
  5767. $currentIdx = $i;
  5768. break;
  5769. }
  5770. }
  5771. }
  5772. } else {
  5773. foreach ($steps as $i => $s) {
  5774. if (!$s['done']) {
  5775. $currentIdx = $i;
  5776. break;
  5777. }
  5778. }
  5779. }
  5780. $nSteps = count($steps);
  5781. foreach ($steps as $idx => &$s) {
  5782. $s['current'] = ($idx === $currentIdx);
  5783. if ($idx === 0) {
  5784. $s['pdf_left_bg'] = '';
  5785. } else {
  5786. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  5787. }
  5788. if ($idx >= $nSteps - 1) {
  5789. $s['pdf_right_bg'] = '';
  5790. } else {
  5791. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  5792. }
  5793. }
  5794. unset($s);
  5795. $labelMap = [
  5796. 'CCYDH' => '订单号',
  5797. 'CYJMC' => '印件名称',
  5798. 'CCLBMMC' => '承揽部门',
  5799. 'CGYMC' => '工序名称',
  5800. 'CDW' => '单位',
  5801. 'czlyq' => '类型',
  5802. 'NGZL' => '工作量',
  5803. 'CDF' => '单价',
  5804. 'cGzzxMc' => '工作中心',
  5805. 'MBZ' => '备注',
  5806. 'This_quantity' => '本次数量',
  5807. 'ceilingPrice' => '最高限价',
  5808. ];
  5809. $orderSummary = [];
  5810. foreach ($labelMap as $key => $lab) {
  5811. if (!array_key_exists($key, $main)) {
  5812. continue;
  5813. }
  5814. $val = $main[$key];
  5815. if ($val === null) {
  5816. $val = '';
  5817. } elseif (!is_scalar($val)) {
  5818. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  5819. } else {
  5820. $val = (string)$val;
  5821. }
  5822. $orderSummary[] = ['label' => $lab, 'value' => $val];
  5823. }
  5824. $orderSummary[] = [
  5825. 'label' => '是否合格',
  5826. 'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
  5827. ];
  5828. $orderSummaryGrid = [];
  5829. $n = count($orderSummary);
  5830. for ($i = 0; $i < $n; $i += 2) {
  5831. $left = $orderSummary[$i];
  5832. $hasRight = ($i + 1) < $n;
  5833. $orderSummaryGrid[] = [
  5834. 'l1' => $left['label'],
  5835. 'v1' => $left['value'],
  5836. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  5837. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  5838. ];
  5839. }
  5840. return [
  5841. 'steps' => $steps,
  5842. 'orderSummary' => $orderSummary,
  5843. 'orderSummaryGrid' => $orderSummaryGrid,
  5844. 'inbound_result' => $inboundResult,
  5845. 'inbound_score_time'=> $inboundScoreTime,
  5846. 'detailRows' => $details,
  5847. ];
  5848. }
  5849. /**
  5850. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  5851. *
  5852. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  5853. */
  5854. protected function prepareProcuremenDetailsView(string $ids): array
  5855. {
  5856. $main = [];
  5857. try {
  5858. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5859. $main = is_array($one) ? $one : [];
  5860. } catch (\Throwable $e) {
  5861. $main = [];
  5862. }
  5863. $details = [];
  5864. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  5865. if ($mergeRows === []) {
  5866. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  5867. if ($mergeRows === [] && $main !== []) {
  5868. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  5869. }
  5870. }
  5871. $detailSidList = [];
  5872. $anchorSid = (int)$ids;
  5873. if ($anchorSid !== 0) {
  5874. $detailSidList[$anchorSid] = true;
  5875. }
  5876. foreach ($mergeRows as $mr) {
  5877. if (!is_array($mr)) {
  5878. continue;
  5879. }
  5880. $sid = $this->extractScydgyRowId($mr);
  5881. if ($sid !== 0) {
  5882. $detailSidList[$sid] = true;
  5883. }
  5884. }
  5885. try {
  5886. if ($detailSidList !== []) {
  5887. $details = Db::table('purchase_order_detail')
  5888. ->where('scydgy_id', 'in', array_keys($detailSidList))
  5889. ->order('id', 'asc')
  5890. ->select();
  5891. }
  5892. } catch (\Throwable $e) {
  5893. $details = [];
  5894. }
  5895. if (!is_array($details)) {
  5896. $details = [];
  5897. }
  5898. foreach ($details as &$r) {
  5899. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  5900. $r['id'] = $r['ID'];
  5901. }
  5902. if (isset($r['createtime'])) {
  5903. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  5904. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  5905. } else {
  5906. $r['createtime_text'] = (string)$r['createtime'];
  5907. }
  5908. } else {
  5909. $r['createtime_text'] = '';
  5910. }
  5911. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  5912. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  5913. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  5914. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  5915. if (is_array($r)) {
  5916. $r = $this->maskSupplierContactFields($r);
  5917. }
  5918. }
  5919. unset($r);
  5920. $activeDetails = [];
  5921. foreach ($details as $r) {
  5922. if (is_array($r) && empty($r['is_void'])) {
  5923. $activeDetails[] = $r;
  5924. }
  5925. }
  5926. $operLogs = [];
  5927. try {
  5928. $operSidList = array_keys($detailSidList);
  5929. if ($operSidList === [] && (int)$ids !== 0) {
  5930. $operSidList = [(int)$ids];
  5931. }
  5932. if ($operSidList !== []) {
  5933. $operLogs = Db::table('purchase_order_oper_log')
  5934. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  5935. ->order('id', 'asc')
  5936. ->select();
  5937. }
  5938. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  5939. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  5940. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  5941. if ($poId > 0) {
  5942. $operLogs = Db::table('purchase_order_oper_log')
  5943. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  5944. ->order('id', 'asc')
  5945. ->select();
  5946. }
  5947. }
  5948. } catch (\Throwable $e) {
  5949. $operLogs = [];
  5950. }
  5951. if (!is_array($operLogs)) {
  5952. $operLogs = [];
  5953. }
  5954. $operLogsRaw = $operLogs;
  5955. $processNameBySid = [];
  5956. foreach ($mergeRows as $mr) {
  5957. if (!is_array($mr)) {
  5958. continue;
  5959. }
  5960. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  5961. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5962. if ($psid !== 0 && $gymc !== '') {
  5963. $processNameBySid[$psid] = $gymc;
  5964. }
  5965. }
  5966. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  5967. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
  5968. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  5969. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  5970. if ($ccydh === '') {
  5971. foreach ($details as $r) {
  5972. if (!is_array($r)) {
  5973. continue;
  5974. }
  5975. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  5976. if ($ccydh !== '') {
  5977. break;
  5978. }
  5979. }
  5980. }
  5981. $this->view->assign('ccydh', $ccydh);
  5982. $this->view->assign('steps', $bundle['steps']);
  5983. $this->view->assign('orderSummary', $bundle['orderSummary']);
  5984. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  5985. $this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
  5986. $this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
  5987. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  5988. $this->view->assign('processCount', count($mergeRows));
  5989. $this->view->assign('detailRows', $details);
  5990. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  5991. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  5992. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  5993. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  5994. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  5995. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  5996. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  5997. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  5998. $this->view->assign('operLogs', $operLogs);
  5999. $sg = $quoteView['supplier_groups'] ?? [];
  6000. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
  6001. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  6002. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
  6003. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
  6004. return [
  6005. 'ok' => $main !== [] || $details !== [],
  6006. 'ccydh' => $ccydh,
  6007. 'steps' => $bundle['steps'],
  6008. ];
  6009. }
  6010. /**
  6011. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  6012. */
  6013. public function details()
  6014. {
  6015. $ids = $this->request->param('ids', $this->request->param('id', ''));
  6016. if (is_array($ids)) {
  6017. $ids = isset($ids[0]) ? $ids[0] : '';
  6018. }
  6019. $ids = trim((string)$ids);
  6020. if ($ids === '') {
  6021. $this->error(__('Invalid parameters'));
  6022. }
  6023. $this->assertManualOrderDetailsViewable((int)$ids);
  6024. // 已完结:打开详情时按最新进度/操作记录重存存证 PDF(含质量/交货评分)
  6025. $sid = (int)$ids;
  6026. if ($this->isValidScydgyRowId($sid)) {
  6027. try {
  6028. $poCheck = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  6029. if (is_array($poCheck) && ProcuremenStatus::isPoCompleted($poCheck['status'] ?? '')) {
  6030. $this->refreshCompletedOrderArchivePdf($sid, true);
  6031. }
  6032. } catch (\Throwable $e) {
  6033. Log::write('详情页刷新完结存证PDF失败 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'notice');
  6034. }
  6035. }
  6036. $this->prepareProcuremenDetailsView($ids);
  6037. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  6038. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  6039. $this->view->engine->layout(false);
  6040. try {
  6041. return $this->view->fetch('procuremen/details_dialog_shell');
  6042. } finally {
  6043. if ($restoreLayout) {
  6044. $this->view->engine->layout($restoreLayout);
  6045. }
  6046. }
  6047. }
  6048. /**
  6049. * 已完结订单重生成存证 PDF(与详情页一致,含质量/交货评分与「已完结」节点)
  6050. *
  6051. * @param bool $requireCompleted true 时仅已完结才重生成;false 强制按当前详情重存
  6052. * @return string 本地 web 路径或 OSS URL,失败为空串
  6053. */
  6054. protected function refreshCompletedOrderArchivePdf(int $scydgyId, bool $requireCompleted = true): string
  6055. {
  6056. if (!$this->isValidScydgyRowId($scydgyId)) {
  6057. return '';
  6058. }
  6059. try {
  6060. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6061. } catch (\Throwable $e) {
  6062. $po = null;
  6063. }
  6064. if (!is_array($po) || $po === []) {
  6065. return '';
  6066. }
  6067. if ($requireCompleted && !ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6068. return trim((string)($po['pdf_url'] ?? ''));
  6069. }
  6070. $poId = (int)($po['id'] ?? 0);
  6071. return $this->savePurchaseConfirmDetailPdf($scydgyId, $poId);
  6072. }
  6073. /**
  6074. * CLI / 手机端评分完结后调用:无后台登录态重生成存证 PDF
  6075. */
  6076. public static function regenerateArchivePdfWithoutAuth(int $scydgyId, bool $requireCompleted = true): string
  6077. {
  6078. if ((int)$scydgyId === 0) {
  6079. return '';
  6080. }
  6081. try {
  6082. $ctl = new class extends Procuremen {
  6083. public function _initialize()
  6084. {
  6085. $this->request = \think\Request::instance();
  6086. $tpl = \think\Config::get('template');
  6087. if (!is_array($tpl)) {
  6088. $tpl = [];
  6089. }
  6090. // CLI / 跨模块调用时无 admin 视图目录
  6091. $tpl['view_path'] = APP_PATH . 'admin' . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR;
  6092. $this->view = new \think\View($tpl, \think\Config::get('view_replace_str'));
  6093. $this->model = new \app\admin\model\Procuremen();
  6094. try {
  6095. ProcuremenSchema::ensureAll();
  6096. } catch (\Throwable $e) {
  6097. }
  6098. }
  6099. public function runRegen(int $sid, bool $requireCompleted): string
  6100. {
  6101. return $this->refreshCompletedOrderArchivePdf($sid, $requireCompleted);
  6102. }
  6103. };
  6104. return $ctl->runRegen($scydgyId, $requireCompleted);
  6105. } catch (\Throwable $e) {
  6106. Log::write('regenerateArchivePdfWithoutAuth 失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'error');
  6107. return '';
  6108. }
  6109. }
  6110. /**
  6111. * 解析合并审核工序行(订单号须一致,且均未协助)
  6112. *
  6113. * @return array<int, array<string, mixed>>
  6114. */
  6115. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  6116. {
  6117. $primary = json_decode($rowJson, true);
  6118. if (!is_array($primary)) {
  6119. $this->error(__('Invalid parameters'));
  6120. }
  6121. $merge = json_decode($mergeRowsJson, true);
  6122. if (!is_array($merge) || $merge === []) {
  6123. $merge = [$primary];
  6124. }
  6125. $seen = [];
  6126. $out = [];
  6127. foreach ($merge as $r) {
  6128. if (!is_array($r)) {
  6129. continue;
  6130. }
  6131. $id = $this->extractScydgyRowId($r);
  6132. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  6133. continue;
  6134. }
  6135. $seen[$id] = true;
  6136. $out[] = $r;
  6137. }
  6138. if ($out === []) {
  6139. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  6140. }
  6141. $ccydh = null;
  6142. foreach ($out as $r) {
  6143. $dh = trim((string)($r['CCYDH'] ?? ''));
  6144. if ($ccydh === null) {
  6145. $ccydh = $dh;
  6146. } elseif ($dh !== $ccydh) {
  6147. $this->error('合并审核要求所选行的订单号一致');
  6148. }
  6149. }
  6150. $ids = [];
  6151. foreach ($out as $r) {
  6152. $id = $this->extractScydgyRowId($r);
  6153. if ($this->isValidScydgyRowId($id)) {
  6154. $ids[$id] = true;
  6155. }
  6156. }
  6157. $poBySid = [];
  6158. $detCntBySid = [];
  6159. if ($ids !== []) {
  6160. $idList = array_keys($ids);
  6161. try {
  6162. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  6163. if (is_array($poList)) {
  6164. foreach ($poList as $po) {
  6165. if (!is_array($po)) {
  6166. continue;
  6167. }
  6168. $sid = (int)($po['scydgy_id'] ?? 0);
  6169. if ($this->isValidScydgyRowId($sid)) {
  6170. $poBySid[$sid] = $po;
  6171. }
  6172. }
  6173. }
  6174. } catch (\Throwable $e) {
  6175. }
  6176. try {
  6177. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  6178. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  6179. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  6180. if (is_array($detRows)) {
  6181. foreach ($detRows as $dr) {
  6182. if (!is_array($dr)) {
  6183. continue;
  6184. }
  6185. $sid = (int)($dr['scydgy_id'] ?? 0);
  6186. if ($this->isValidScydgyRowId($sid)) {
  6187. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  6188. }
  6189. }
  6190. }
  6191. } catch (\Throwable $e) {
  6192. }
  6193. }
  6194. foreach ($out as $r) {
  6195. $id = $this->extractScydgyRowId($r);
  6196. if (!$this->isValidScydgyRowId($id)) {
  6197. continue;
  6198. }
  6199. $po = $poBySid[$id] ?? null;
  6200. if (!is_array($po)) {
  6201. continue;
  6202. }
  6203. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6204. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6205. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  6206. }
  6207. $detCnt = (int)($detCntBySid[$id] ?? 0);
  6208. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  6209. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6210. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  6211. }
  6212. }
  6213. return $out;
  6214. }
  6215. /**
  6216. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  6217. */
  6218. protected function maskSupplierContactFields(array $item): array
  6219. {
  6220. if (array_key_exists('email', $item)) {
  6221. $item['email'] = mask_email((string)$item['email']);
  6222. }
  6223. if (array_key_exists('phone', $item)) {
  6224. $item['phone'] = mask_phone((string)$item['phone']);
  6225. }
  6226. return $item;
  6227. }
  6228. /**
  6229. * @param array<int, array<string, mixed>> $list
  6230. * @return array<int, array<string, mixed>>
  6231. */
  6232. protected function maskSupplierContactList(array $list): array
  6233. {
  6234. $out = [];
  6235. foreach ($list as $item) {
  6236. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  6237. }
  6238. return $out;
  6239. }
  6240. /**
  6241. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  6242. *
  6243. * @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
  6244. * @return array<string, string>|null
  6245. */
  6246. protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
  6247. {
  6248. if (!is_array($row)) {
  6249. return null;
  6250. }
  6251. $norm = [];
  6252. foreach ($row as $k => $v) {
  6253. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  6254. }
  6255. $row = $norm;
  6256. $st = $row['status'] ?? '';
  6257. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  6258. return null;
  6259. }
  6260. $companyName = '';
  6261. foreach (['company_name', 'name'] as $nk) {
  6262. if (!empty($row[$nk])) {
  6263. $companyName = trim((string)$row[$nk]);
  6264. break;
  6265. }
  6266. }
  6267. if ($companyName === '') {
  6268. return null;
  6269. }
  6270. $username = '';
  6271. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  6272. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  6273. $username = trim((string)$row[$uk]);
  6274. break;
  6275. }
  6276. }
  6277. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  6278. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  6279. if ($phone === '' && isset($row['account'])) {
  6280. $phone = trim((string)$row['account']);
  6281. }
  6282. if ($phone === '' && isset($row['mobile'])) {
  6283. $phone = trim((string)$row['mobile']);
  6284. }
  6285. if ($requireContactChannels && $email === '' && $phone === '') {
  6286. return null;
  6287. }
  6288. $category = '';
  6289. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6290. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6291. $category = trim((string)$row[$ck]);
  6292. break;
  6293. }
  6294. }
  6295. return [
  6296. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  6297. 'name' => $companyName,
  6298. 'company_name' => $companyName,
  6299. 'username' => $username,
  6300. 'email' => $email,
  6301. 'phone' => $phone,
  6302. 'category' => $category,
  6303. 'company_type' => $category,
  6304. ];
  6305. }
  6306. /**
  6307. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  6308. */
  6309. protected function resolveCustomerContactById(string $id): ?array
  6310. {
  6311. $id = trim($id);
  6312. if ($id === '' || !ctype_digit($id)) {
  6313. return null;
  6314. }
  6315. try {
  6316. $row = Db::table('customer')->where('id', (int)$id)->find();
  6317. } catch (\Throwable $e) {
  6318. return null;
  6319. }
  6320. return $this->buildCustomerContactPayloadFromRow($row);
  6321. }
  6322. /**
  6323. * 按供应商名称解析联系信息(兼容旧提交数据)
  6324. *
  6325. * @param bool $requireContactChannels true 时须有邮箱或手机
  6326. */
  6327. protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
  6328. {
  6329. $name = trim($name);
  6330. if ($name === '') {
  6331. return null;
  6332. }
  6333. try {
  6334. // customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
  6335. $row = Db::table('customer')
  6336. ->where('company_name', $name)
  6337. ->order('id', 'desc')
  6338. ->find();
  6339. } catch (\Throwable $e) {
  6340. return null;
  6341. }
  6342. return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
  6343. }
  6344. /**
  6345. * 规范化下发/确认时勾选的供应商
  6346. *
  6347. * @param array<int, mixed> $companies
  6348. * @return array<int, array<string, string>>
  6349. */
  6350. protected function normalizePickCompanies(array $companies): array
  6351. {
  6352. $out = [];
  6353. foreach ($companies as $c) {
  6354. if (!is_array($c)) {
  6355. continue;
  6356. }
  6357. $resolved = null;
  6358. $cid = trim((string)($c['id'] ?? ''));
  6359. if ($cid !== '') {
  6360. $resolved = $this->resolveCustomerContactById($cid);
  6361. }
  6362. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  6363. if ($resolved === null && $name !== '') {
  6364. $resolved = $this->resolveCustomerContactByCompanyName($name);
  6365. }
  6366. if ($resolved === null) {
  6367. continue;
  6368. }
  6369. $out[] = $resolved;
  6370. }
  6371. return $out;
  6372. }
  6373. /**
  6374. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  6375. *
  6376. * @param array<int, array<string, mixed>> $pool
  6377. * @return array<int, array<string, mixed>>
  6378. */
  6379. protected function collapseProcuremenPoolByOrder(array $pool): array
  6380. {
  6381. if ($pool === []) {
  6382. return [];
  6383. }
  6384. $groups = [];
  6385. foreach ($pool as $row) {
  6386. if (!is_array($row)) {
  6387. continue;
  6388. }
  6389. $dh = trim((string)($row['CCYDH'] ?? ''));
  6390. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  6391. if (!isset($groups[$key])) {
  6392. $groups[$key] = [];
  6393. }
  6394. $groups[$key][] = $row;
  6395. }
  6396. $out = [];
  6397. foreach ($groups as $ccydh => $rows) {
  6398. if ($rows === []) {
  6399. continue;
  6400. }
  6401. usort($rows, function ($a, $b) {
  6402. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  6403. });
  6404. $head = $rows[0];
  6405. $gymcList = [];
  6406. foreach ($rows as $r) {
  6407. $g = trim((string)($r['CGYMC'] ?? ''));
  6408. if ($g !== '' && !in_array($g, $gymcList, true)) {
  6409. $gymcList[] = $g;
  6410. }
  6411. }
  6412. $merged = $head;
  6413. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  6414. $merged['process_count'] = count($rows);
  6415. $merged['_order_merge_rows'] = $rows;
  6416. $qtyList = [];
  6417. $priceList = [];
  6418. foreach ($rows as $r) {
  6419. if (!is_array($r)) {
  6420. continue;
  6421. }
  6422. $qtyList[] = $this->resolveProcuremenThisQuantity($r);
  6423. $priceList[] = $this->resolveProcuremenCeilingPrice($r);
  6424. }
  6425. if (count($rows) > 1) {
  6426. $merged['CGYMC'] = implode('、', $gymcList);
  6427. // 多工序:数量/限价按有值项顿号间隔(空值不占位)
  6428. $merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  6429. $merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  6430. } else {
  6431. $merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
  6432. $merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
  6433. }
  6434. // 已选供应商:取合并行中首个非空 pick_company_name
  6435. $pickedName = '';
  6436. foreach ($rows as $r) {
  6437. if (!is_array($r)) {
  6438. continue;
  6439. }
  6440. $pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
  6441. if ($pn !== '') {
  6442. $pickedName = $pn;
  6443. break;
  6444. }
  6445. }
  6446. if ($pickedName !== '') {
  6447. $merged['pick_company_name'] = $pickedName;
  6448. $merged['picked_supplier_name'] = $pickedName;
  6449. }
  6450. $mergedPickTime = '';
  6451. foreach ($rows as $r) {
  6452. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  6453. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  6454. $mergedPickTime = $t;
  6455. }
  6456. }
  6457. if ($mergedPickTime !== '') {
  6458. $merged['pick_time'] = $mergedPickTime;
  6459. }
  6460. $out[] = $merged;
  6461. }
  6462. usort($out, function ($a, $b) {
  6463. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  6464. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  6465. if ($ta === $tb) {
  6466. $ida = (int)($a['purchase_order_id'] ?? 0);
  6467. $idb = (int)($b['purchase_order_id'] ?? 0);
  6468. if ($ida !== $idb) {
  6469. return $idb <=> $ida;
  6470. }
  6471. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  6472. }
  6473. if ($ta === '') {
  6474. return 1;
  6475. }
  6476. if ($tb === '') {
  6477. return -1;
  6478. }
  6479. return strcmp($tb, $ta);
  6480. });
  6481. return $out;
  6482. }
  6483. /**
  6484. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  6485. *
  6486. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6487. */
  6488. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  6489. {
  6490. $scydgyId = trim($scydgyId);
  6491. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6492. if ($scydgyId === '') {
  6493. return $empty;
  6494. }
  6495. try {
  6496. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6497. } catch (\Throwable $e) {
  6498. $anchor = null;
  6499. }
  6500. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  6501. return $empty;
  6502. }
  6503. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6504. if ($ccydh === '') {
  6505. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  6506. }
  6507. try {
  6508. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  6509. } catch (\Throwable $e) {
  6510. $pos = [$anchor];
  6511. }
  6512. if (!is_array($pos) || $pos === []) {
  6513. $pos = [$anchor];
  6514. }
  6515. return [
  6516. 'ccydh' => $ccydh,
  6517. 'pos' => $pos,
  6518. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6519. ];
  6520. }
  6521. /**
  6522. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  6523. */
  6524. protected function purchaseOrderRowInConfirmStage(array $po): bool
  6525. {
  6526. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6527. return false;
  6528. }
  6529. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  6530. return false;
  6531. }
  6532. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  6533. return true;
  6534. }
  6535. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  6536. $sid = (int)($po['scydgy_id'] ?? 0);
  6537. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  6538. }
  6539. return false;
  6540. }
  6541. /**
  6542. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  6543. *
  6544. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6545. */
  6546. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  6547. {
  6548. $scydgyId = trim($scydgyId);
  6549. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6550. if ($scydgyId === '') {
  6551. return $empty;
  6552. }
  6553. try {
  6554. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6555. } catch (\Throwable $e) {
  6556. $anchor = null;
  6557. }
  6558. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  6559. return $empty;
  6560. }
  6561. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6562. if ($ccydh === '') {
  6563. return [
  6564. 'ccydh' => '',
  6565. 'pos' => [$anchor],
  6566. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  6567. ];
  6568. }
  6569. try {
  6570. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  6571. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  6572. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  6573. } catch (\Throwable $e) {
  6574. $pos = [$anchor];
  6575. }
  6576. if (!is_array($pos) || $pos === []) {
  6577. $pos = [$anchor];
  6578. }
  6579. $pos = array_values(array_filter($pos, function ($po) {
  6580. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  6581. }));
  6582. if ($pos === []) {
  6583. $pos = [$anchor];
  6584. }
  6585. return [
  6586. 'ccydh' => $ccydh,
  6587. 'pos' => $pos,
  6588. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6589. ];
  6590. }
  6591. /**
  6592. * @param array<int, array<string, mixed>> $purchaseOrders
  6593. * @return array<int, array<string, mixed>>
  6594. */
  6595. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  6596. {
  6597. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  6598. $byId = [];
  6599. foreach ($pool as $r) {
  6600. if (!is_array($r)) {
  6601. continue;
  6602. }
  6603. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  6604. if ($this->isValidScydgyRowId($sid)) {
  6605. $byId[$sid] = $r;
  6606. }
  6607. }
  6608. $out = [];
  6609. foreach ($purchaseOrders as $po) {
  6610. if (!is_array($po)) {
  6611. continue;
  6612. }
  6613. $sid = (int)($po['scydgy_id'] ?? 0);
  6614. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  6615. $out[] = $byId[$sid];
  6616. }
  6617. }
  6618. return $out;
  6619. }
  6620. /**
  6621. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  6622. *
  6623. * @return array<int, array<string, mixed>>
  6624. */
  6625. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  6626. {
  6627. $scydgyId = trim($scydgyId);
  6628. if ($scydgyId === '') {
  6629. return [];
  6630. }
  6631. try {
  6632. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6633. } catch (\Throwable $e) {
  6634. $anchor = null;
  6635. }
  6636. if (!is_array($anchor)) {
  6637. return [];
  6638. }
  6639. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  6640. return [];
  6641. }
  6642. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6643. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  6644. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  6645. try {
  6646. $q = Db::table('purchase_order');
  6647. if ($ccydh !== '') {
  6648. $q->where('CCYDH', $ccydh);
  6649. } else {
  6650. $q->where('scydgy_id', $scydgyId);
  6651. }
  6652. if ($isValidPick) {
  6653. $q->where('pick_time', $pickTime);
  6654. }
  6655. $pos = $q->order('scydgy_id', 'asc')->select();
  6656. } catch (\Throwable $e) {
  6657. $pos = [$anchor];
  6658. }
  6659. if (!is_array($pos) || $pos === []) {
  6660. $pos = [$anchor];
  6661. }
  6662. $pos = array_values(array_filter($pos, function ($po) {
  6663. if (!is_array($po)) {
  6664. return false;
  6665. }
  6666. $mr = $po['mod_rq'] ?? null;
  6667. if ($mr === null || $mr === '') {
  6668. return true;
  6669. }
  6670. $mrs = trim((string)$mr);
  6671. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  6672. }));
  6673. if ($pos === []) {
  6674. $pos = [$anchor];
  6675. }
  6676. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  6677. if ($rows === []) {
  6678. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  6679. }
  6680. return $rows;
  6681. }
  6682. /**
  6683. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  6684. *
  6685. * @param array<int, array<string, mixed>> $mergeRows
  6686. * @return array<int, array<string, mixed>>
  6687. */
  6688. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  6689. {
  6690. $list = array_values($mergeRows);
  6691. $n = count($list);
  6692. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  6693. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  6694. $mergeSame = $n > 1 && $orderKey0 !== '';
  6695. if ($mergeSame) {
  6696. foreach ($list as $rr) {
  6697. if (!is_array($rr)) {
  6698. $mergeSame = false;
  6699. break;
  6700. }
  6701. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  6702. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  6703. $mergeSame = false;
  6704. break;
  6705. }
  6706. }
  6707. }
  6708. $out = [];
  6709. foreach ($list as $idx => $r) {
  6710. if (!is_array($r)) {
  6711. continue;
  6712. }
  6713. $qty = $this->resolveProcuremenThisQuantity($r);
  6714. $price = $this->resolveProcuremenCeilingPrice($r);
  6715. $sid = $this->extractScydgyRowId($r);
  6716. $out[] = [
  6717. 'seq' => $idx + 1,
  6718. 'scydgy_id' => $sid,
  6719. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6720. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6721. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6722. 'CDW' => trim((string)($r['CDW'] ?? '')),
  6723. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  6724. 'NGZL' => $r['NGZL'] ?? '',
  6725. 'This_quantity' => $qty,
  6726. 'ceilingPrice' => $price,
  6727. 'CDF' => trim((string)($r['CDF'] ?? '')),
  6728. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  6729. 'show_order_cells' => !$mergeSame || $idx === 0,
  6730. 'order_rowspan' => $mergeSame ? $n : 1,
  6731. ];
  6732. }
  6733. return $out;
  6734. }
  6735. /**
  6736. * 解析金额/数量(去千分位等非数字字符)
  6737. */
  6738. protected function parseProcuremenMoneyNumber($value): ?float
  6739. {
  6740. if ($value === null || $value === '') {
  6741. return null;
  6742. }
  6743. if (is_numeric($value)) {
  6744. return (float)$value;
  6745. }
  6746. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  6747. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  6748. }
  6749. protected function formatProcuremenMoneyDisplay(?float $amount): string
  6750. {
  6751. if ($amount === null) {
  6752. return '';
  6753. }
  6754. // 保留小数(最多 5 位),去掉末尾无意义的 0,避免 0.25 被显示成 0
  6755. $s = rtrim(rtrim(sprintf('%.5F', (float)$amount), '0'), '.');
  6756. return $s === '' ? '0' : $s;
  6757. }
  6758. /**
  6759. * 列表/详情展示:工作量为 0 时显示空
  6760. */
  6761. protected function formatProcuremenWorkloadDisplay($value): string
  6762. {
  6763. if ($value === null || $value === '') {
  6764. return '';
  6765. }
  6766. $s = trim((string)$value);
  6767. if ($s === '') {
  6768. return '';
  6769. }
  6770. if (is_numeric($s) && (float)$s == 0) {
  6771. return '';
  6772. }
  6773. return $s;
  6774. }
  6775. /**
  6776. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  6777. */
  6778. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  6779. {
  6780. foreach ($details as $d) {
  6781. if (!is_array($d)) {
  6782. continue;
  6783. }
  6784. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  6785. $cn = trim((string)($d['company_name'] ?? ''));
  6786. if ($cn !== '') {
  6787. return $cn;
  6788. }
  6789. }
  6790. }
  6791. return trim((string)($main['pick_company_name'] ?? ''));
  6792. }
  6793. /**
  6794. * 详情报价小计:单价 × 本工序本次数量
  6795. */
  6796. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  6797. {
  6798. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  6799. if ($unit === null) {
  6800. return null;
  6801. }
  6802. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  6803. if ($qty === null || $qty <= 0) {
  6804. return null;
  6805. }
  6806. return $unit * $qty;
  6807. }
  6808. /**
  6809. * 详情页:工序小计 + 供应商分组报价与总计
  6810. *
  6811. * @param array<int, array<string, mixed>> $mergeRows
  6812. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  6813. * @return array{
  6814. * process_rows: array,
  6815. * supplier_groups: array,
  6816. * order_total_text: string,
  6817. * order_total_has: bool,
  6818. * selected_company: string
  6819. * }
  6820. */
  6821. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  6822. {
  6823. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  6824. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  6825. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
  6826. || ((int)($main['manual_pick'] ?? 0) === 1);
  6827. $qtyBySid = [];
  6828. $gymcBySid = [];
  6829. $orderedSids = [];
  6830. foreach ($mergeRows as $mr) {
  6831. if (!is_array($mr)) {
  6832. continue;
  6833. }
  6834. $sid = $this->extractScydgyRowId($mr);
  6835. if ($this->isValidScydgyRowId($sid)) {
  6836. $orderedSids[] = $sid;
  6837. }
  6838. $qty = trim((string)($mr['This_quantity'] ?? ''));
  6839. if ($qty === '') {
  6840. $qty = trim((string)($mr['NGZL'] ?? ''));
  6841. }
  6842. $qtyBySid[$sid] = $qty;
  6843. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  6844. }
  6845. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  6846. $detailByCompanySid = [];
  6847. foreach ($details as $d) {
  6848. if (!is_array($d)) {
  6849. continue;
  6850. }
  6851. $cn = trim((string)($d['company_name'] ?? ''));
  6852. $sid = (int)($d['scydgy_id'] ?? 0);
  6853. if ($cn === '' || $sid === 0) {
  6854. continue;
  6855. }
  6856. if (!isset($detailByCompanySid[$cn])) {
  6857. $detailByCompanySid[$cn] = [];
  6858. }
  6859. $detailByCompanySid[$cn][$sid] = $d;
  6860. }
  6861. $supplierGroups = [];
  6862. foreach ($detailByCompanySid as $cn => $bySid) {
  6863. $lines = [];
  6864. $groupTotal = 0.0;
  6865. $groupHas = false;
  6866. $groupVoid = true;
  6867. $usedSids = [];
  6868. $appendLine = function (int $sid, array $d) use (
  6869. &$lines,
  6870. &$groupTotal,
  6871. &$groupHas,
  6872. &$groupVoid,
  6873. $qtyBySid,
  6874. $gymcBySid,
  6875. $quoteVisible
  6876. ) {
  6877. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  6878. if (!$isVoid) {
  6879. $groupVoid = false;
  6880. }
  6881. $qtyStr = $qtyBySid[$sid] ?? '';
  6882. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  6883. $am = trim((string)($d['amount'] ?? ''));
  6884. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  6885. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  6886. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  6887. $sub = null;
  6888. if (!$isVoid && $amountNum !== null) {
  6889. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  6890. }
  6891. $ct = $this->resolveDetailSupplierOperTime($d);
  6892. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  6893. $leadFilled = ($leadDays !== null);
  6894. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  6895. $line = [
  6896. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  6897. 'amount' => $am,
  6898. 'unit_price_text' => $amountFilled
  6899. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  6900. : '未填写',
  6901. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  6902. 'delivery_ymd' => $deliveryYmd,
  6903. 'amount_filled' => $amountFilled,
  6904. 'delivery_filled' => $deliveryFilled,
  6905. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  6906. 'lead_days' => $leadFilled ? $leadDays : '',
  6907. 'lead_days_filled'=> $leadFilled,
  6908. 'lead_days_show' => $leadText,
  6909. 'lead_days_text' => $leadText,
  6910. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  6911. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  6912. 'is_void' => $isVoid,
  6913. 'oper_time_text' => $ct,
  6914. ];
  6915. if (!$quoteVisible && !$isVoid) {
  6916. $this->maskSupplierQuoteLineBeforeDeadline($line);
  6917. } elseif ($sub !== null) {
  6918. $groupTotal += $sub;
  6919. $groupHas = true;
  6920. }
  6921. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  6922. };
  6923. foreach ($orderedSids as $sid) {
  6924. if (!isset($bySid[$sid])) {
  6925. continue;
  6926. }
  6927. $usedSids[$sid] = true;
  6928. $appendLine($sid, $bySid[$sid]);
  6929. }
  6930. foreach ($bySid as $sid => $d) {
  6931. if (isset($usedSids[$sid])) {
  6932. continue;
  6933. }
  6934. $appendLine((int)$sid, $d);
  6935. }
  6936. $firstDetail = null;
  6937. foreach ($bySid as $d) {
  6938. if (is_array($d)) {
  6939. $firstDetail = $d;
  6940. break;
  6941. }
  6942. }
  6943. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  6944. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  6945. if ($username === '' && $ph !== '') {
  6946. $username = $this->resolveCustomerContactName($ph, $cn);
  6947. }
  6948. $remark = '';
  6949. foreach ($bySid as $d) {
  6950. if (!is_array($d)) {
  6951. continue;
  6952. }
  6953. $rm = '';
  6954. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  6955. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  6956. $rm = trim((string)$d[$rk]);
  6957. break;
  6958. }
  6959. }
  6960. if ($rm !== '') {
  6961. $remark = $rm;
  6962. break;
  6963. }
  6964. }
  6965. $lineCount = count($lines);
  6966. $hasRemark = $lineCount > 0;
  6967. $supplierGroup = [
  6968. 'company_name' => $cn,
  6969. 'username' => $username,
  6970. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  6971. 'phone' => $ph,
  6972. 'remark' => $remark,
  6973. 'has_remark' => $hasRemark,
  6974. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  6975. 'is_void' => $groupVoid,
  6976. 'lines' => $lines,
  6977. 'line_count' => $lineCount,
  6978. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  6979. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  6980. 'has_total' => $lineCount > 0,
  6981. ];
  6982. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  6983. $supplierGroups[] = $supplierGroup;
  6984. }
  6985. usort($supplierGroups, function ($a, $b) {
  6986. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  6987. return ($a['is_void'] ?? false) ? 1 : -1;
  6988. }
  6989. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  6990. return ($a['is_selected'] ?? false) ? -1 : 1;
  6991. }
  6992. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  6993. });
  6994. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  6995. return [
  6996. 'process_rows' => $processRows,
  6997. 'supplier_groups' => $supplierGroups,
  6998. 'order_total_text' => '',
  6999. 'order_total_has' => false,
  7000. 'selected_company' => $selectedCompany,
  7001. ];
  7002. }
  7003. /**
  7004. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  7005. */
  7006. protected function buildProcessLinesPlain(array $mergeRows): string
  7007. {
  7008. $lines = [];
  7009. $i = 1;
  7010. foreach ($mergeRows as $r) {
  7011. if (!is_array($r)) {
  7012. continue;
  7013. }
  7014. $gymc = trim((string)($r['CGYMC'] ?? ''));
  7015. $dw = trim((string)($r['CDW'] ?? ''));
  7016. $gzl = trim((string)($r['NGZL'] ?? ''));
  7017. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  7018. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  7019. if ($dw !== '') {
  7020. $parts[] = '单位:' . $dw;
  7021. }
  7022. if ($gzl !== '') {
  7023. $parts[] = '工作量:' . $gzl;
  7024. }
  7025. if ($qty !== '') {
  7026. $parts[] = '本次数量:' . $qty;
  7027. }
  7028. $lines[] = implode(' ', $parts);
  7029. $i++;
  7030. }
  7031. return implode("\n", $lines);
  7032. }
  7033. /**
  7034. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  7035. *
  7036. * @return array<string, string>
  7037. */
  7038. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  7039. {
  7040. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  7041. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  7042. }
  7043. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  7044. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  7045. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  7046. $cyjmc = '';
  7047. foreach ($mergeRows as $mr) {
  7048. if (!is_array($mr)) {
  7049. continue;
  7050. }
  7051. if ($ccydh === '') {
  7052. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  7053. }
  7054. if ($cyjmc === '') {
  7055. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  7056. }
  7057. }
  7058. if ($pos !== []) {
  7059. $firstPo = $pos[0];
  7060. if (is_array($firstPo)) {
  7061. if ($ccydh === '') {
  7062. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  7063. }
  7064. if ($cyjmc === '') {
  7065. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  7066. }
  7067. }
  7068. }
  7069. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  7070. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  7071. if (is_array($any)) {
  7072. if ($ccydh === '') {
  7073. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  7074. }
  7075. if ($cyjmc === '') {
  7076. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  7077. }
  7078. }
  7079. }
  7080. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  7081. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  7082. $cgymc = '';
  7083. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  7084. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  7085. }
  7086. return [
  7087. 'ccydh' => $ccydh,
  7088. 'cyjmc' => $cyjmc,
  7089. 'cgymc' => $cgymc,
  7090. 'process_lines' => $processLines,
  7091. 'process_lines_html' => '',
  7092. ];
  7093. }
  7094. /**
  7095. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  7096. */
  7097. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  7098. {
  7099. $lines = [];
  7100. if ($ccydh !== '') {
  7101. $lines[] = '订单号:' . $ccydh;
  7102. }
  7103. if ($cyjmc !== '') {
  7104. $lines[] = '印件名称:' . $cyjmc;
  7105. }
  7106. if ($processPlain !== '') {
  7107. $lines[] = $processPlain;
  7108. }
  7109. return implode("\n", $lines);
  7110. }
  7111. /**
  7112. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  7113. *
  7114. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  7115. */
  7116. protected function buildPlatformLinksPlain(array $detailLinks): string
  7117. {
  7118. $lines = [];
  7119. $i = 1;
  7120. foreach ($detailLinks as $lk) {
  7121. if (!is_array($lk)) {
  7122. continue;
  7123. }
  7124. $url = trim((string)($lk['url'] ?? ''));
  7125. if ($url === '') {
  7126. continue;
  7127. }
  7128. $label = trim((string)($lk['cgymc'] ?? ''));
  7129. if ($label === '') {
  7130. $label = '工序' . $i;
  7131. }
  7132. $lines[] = $label . ':' . $url;
  7133. $i++;
  7134. }
  7135. return implode("\n", $lines);
  7136. }
  7137. /**
  7138. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  7139. *
  7140. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  7141. */
  7142. protected function buildPlatformLinksHtml(array $detailLinks): string
  7143. {
  7144. $parts = [];
  7145. $i = 1;
  7146. foreach ($detailLinks as $lk) {
  7147. if (!is_array($lk)) {
  7148. continue;
  7149. }
  7150. $url = trim((string)($lk['url'] ?? ''));
  7151. if ($url === '') {
  7152. continue;
  7153. }
  7154. $label = trim((string)($lk['cgymc'] ?? ''));
  7155. if ($label === '') {
  7156. $label = '工序' . $i;
  7157. }
  7158. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  7159. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  7160. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  7161. $i++;
  7162. }
  7163. return implode("<br>\n", $parts);
  7164. }
  7165. /**
  7166. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  7167. *
  7168. * @return array<string, mixed>
  7169. */
  7170. protected function loadMailerConfig(): array
  7171. {
  7172. try {
  7173. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  7174. } catch (\Throwable $e) {
  7175. $cfg = [];
  7176. }
  7177. return is_array($cfg) ? $cfg : [];
  7178. }
  7179. protected function loadNotifyTemplateRow(string $scene): ?array
  7180. {
  7181. try {
  7182. $row = Db::table('purchase_sms_template')
  7183. ->where('scene', $scene)
  7184. ->where(function ($q) {
  7185. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  7186. })
  7187. ->order('id', 'asc')
  7188. ->find();
  7189. } catch (\Throwable $e) {
  7190. return null;
  7191. }
  7192. if (!is_array($row) || $row === []) {
  7193. return null;
  7194. }
  7195. return [
  7196. 'title' => trim((string)($row['title'] ?? '')),
  7197. 'content' => trim((string)($row['content'] ?? '')),
  7198. ];
  7199. }
  7200. /**
  7201. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  7202. */
  7203. protected function buildProcessLinesHtml(array $mergeRows): string
  7204. {
  7205. if (count($mergeRows) <= 1) {
  7206. $r = $mergeRows[0] ?? [];
  7207. if (!is_array($r)) {
  7208. return '';
  7209. }
  7210. $gymc = trim((string)($r['CGYMC'] ?? ''));
  7211. $dw = trim((string)($r['CDW'] ?? ''));
  7212. $gzl = trim((string)($r['NGZL'] ?? ''));
  7213. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  7214. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  7215. if ($dw !== '') {
  7216. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  7217. }
  7218. if ($gzl !== '') {
  7219. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  7220. }
  7221. if ($qty !== '') {
  7222. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  7223. }
  7224. return $html;
  7225. }
  7226. $rows = '';
  7227. $i = 1;
  7228. foreach ($mergeRows as $r) {
  7229. if (!is_array($r)) {
  7230. continue;
  7231. }
  7232. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  7233. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  7234. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  7235. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  7236. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  7237. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  7238. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  7239. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  7240. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  7241. $i++;
  7242. }
  7243. if ($rows === '') {
  7244. return '';
  7245. }
  7246. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  7247. . '<thead><tr style="background:#f5f5f5;">'
  7248. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  7249. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  7250. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  7251. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  7252. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  7253. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  7254. }
  7255. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  7256. {
  7257. $sysRq = trim($sysRq);
  7258. if ($sysRq === '') {
  7259. if ($required) {
  7260. $this->error('请选择招标截止日期');
  7261. }
  7262. return '';
  7263. }
  7264. $ts = strtotime($sysRq);
  7265. if ($ts === false || $ts <= 0) {
  7266. $this->error('招标截止日期格式无效');
  7267. }
  7268. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  7269. if (!$allowPast) {
  7270. $ymd = date('Y-m-d', $ts);
  7271. if ($ymd < date('Y-m-d')) {
  7272. $this->error('招标截止日期不能早于今天');
  7273. }
  7274. if ($ts <= time()) {
  7275. $this->error('招标截止时间不能早于当前时间');
  7276. }
  7277. }
  7278. return date('Y-m-d H:i:s', $ts);
  7279. }
  7280. /**
  7281. * 确保 purchase_order.czlyq(类型)存在
  7282. */
  7283. protected function ensurePurchaseOrderCzlyqColumn(): void
  7284. {
  7285. static $done = false;
  7286. if ($done) {
  7287. return;
  7288. }
  7289. $done = true;
  7290. try {
  7291. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  7292. if (empty($cols)) {
  7293. Db::execute(
  7294. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  7295. );
  7296. }
  7297. } catch (\Throwable $e) {
  7298. // ignore
  7299. }
  7300. }
  7301. /**
  7302. * 确保 purchase_order.delivery_deadline 存在
  7303. */
  7304. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  7305. {
  7306. static $done = false;
  7307. if ($done) {
  7308. return;
  7309. }
  7310. $done = true;
  7311. try {
  7312. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  7313. if (empty($cols)) {
  7314. Db::execute(
  7315. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  7316. );
  7317. }
  7318. } catch (\Throwable $e) {
  7319. // ignore
  7320. }
  7321. }
  7322. /**
  7323. * 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
  7324. */
  7325. protected function ensurePurchaseOrderScoreRuleIdColumn(): void
  7326. {
  7327. static $done = false;
  7328. if ($done) {
  7329. return;
  7330. }
  7331. $done = true;
  7332. // 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
  7333. $adds = [
  7334. 'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
  7335. 'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
  7336. 'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
  7337. 'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
  7338. 'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
  7339. ];
  7340. $changed = false;
  7341. foreach ($adds as $col => $ddl) {
  7342. try {
  7343. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  7344. if (!is_array($cols) || $cols === []) {
  7345. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  7346. $changed = true;
  7347. }
  7348. } catch (\Throwable $e) {
  7349. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  7350. }
  7351. }
  7352. if ($changed) {
  7353. $this->clearPurchaseOrderTableFieldsCache();
  7354. }
  7355. }
  7356. /**
  7357. * ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
  7358. */
  7359. protected function clearPurchaseOrderTableFieldsCache(): void
  7360. {
  7361. try {
  7362. $db = (string)Config::get('database.database');
  7363. $key = $db . '.purchase_order';
  7364. $ref = new \ReflectionProperty(\think\db\Query::class, 'info');
  7365. $ref->setAccessible(true);
  7366. $info = $ref->getValue();
  7367. if (is_array($info) && isset($info[$key])) {
  7368. unset($info[$key]);
  7369. $ref->setValue(null, $info);
  7370. }
  7371. } catch (\Throwable $e) {
  7372. }
  7373. try {
  7374. $db = (string)Config::get('database.database');
  7375. $schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
  7376. if (is_file($schemaFile)) {
  7377. @unlink($schemaFile);
  7378. }
  7379. } catch (\Throwable $e) {
  7380. }
  7381. }
  7382. /**
  7383. * @return array<string, bool>
  7384. */
  7385. protected function loadPurchaseOrderColumnSet(): array
  7386. {
  7387. static $set = null;
  7388. if (is_array($set)) {
  7389. return $set;
  7390. }
  7391. $set = [];
  7392. try {
  7393. $cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
  7394. } catch (\Throwable $e) {
  7395. return $set;
  7396. }
  7397. if (!is_array($cols)) {
  7398. return $set;
  7399. }
  7400. foreach ($cols as $c) {
  7401. if (!is_array($c)) {
  7402. continue;
  7403. }
  7404. $f = (string)($c['Field'] ?? $c['field'] ?? '');
  7405. if ($f !== '') {
  7406. $set[$f] = true;
  7407. }
  7408. }
  7409. return $set;
  7410. }
  7411. /**
  7412. * 解析交货截止日期(仅年月日)
  7413. */
  7414. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  7415. {
  7416. $raw = trim($raw);
  7417. if ($raw === '') {
  7418. if ($required) {
  7419. $this->error('请选择交货截止日期');
  7420. }
  7421. return '';
  7422. }
  7423. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  7424. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  7425. } else {
  7426. $ts = strtotime(str_replace('/', '-', $raw));
  7427. if ($ts === false || $ts <= 0) {
  7428. $this->error('交货截止日期格式无效');
  7429. }
  7430. $ymd = date('Y-m-d', $ts);
  7431. }
  7432. if ($ymd < date('Y-m-d')) {
  7433. $this->error('交货截止日期不能早于今天');
  7434. }
  7435. return $ymd;
  7436. }
  7437. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  7438. {
  7439. $s = trim((string)$value);
  7440. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  7441. return '';
  7442. }
  7443. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  7444. return $m[1];
  7445. }
  7446. $ts = strtotime(str_replace('/', '-', $s));
  7447. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  7448. }
  7449. /**
  7450. * @param array{pos?:array} $bundle
  7451. */
  7452. protected function resolveBundleDeliveryDeadline(array $bundle): string
  7453. {
  7454. foreach ($bundle['pos'] ?? [] as $po) {
  7455. if (!is_array($po)) {
  7456. continue;
  7457. }
  7458. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7459. if ($d !== '') {
  7460. return $d;
  7461. }
  7462. }
  7463. return '';
  7464. }
  7465. protected function formatProcuremenSysRqForInput($sysRq): string
  7466. {
  7467. $sr = trim((string)$sysRq);
  7468. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  7469. return '';
  7470. }
  7471. $ts = strtotime($sr);
  7472. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  7473. }
  7474. protected function formatProcuremenSysRqForDisplay($sysRq): string
  7475. {
  7476. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  7477. if ($sr === '') {
  7478. return '—';
  7479. }
  7480. $ts = strtotime($sr);
  7481. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  7482. }
  7483. /**
  7484. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  7485. *
  7486. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  7487. * @return array{ccydh?:string,pos:array,merge_rows:array}
  7488. */
  7489. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  7490. {
  7491. return $bundle;
  7492. }
  7493. /**
  7494. * 写入/更新 purchase_order(单道工序行)
  7495. *
  7496. * @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
  7497. */
  7498. protected function upsertPurchaseOrderFromRow(
  7499. array $row,
  7500. string $sysRqDb,
  7501. $wflowStatus = null,
  7502. ?string $pickTime = null,
  7503. ?array $exists = null,
  7504. ?string $deliveryDeadline = null,
  7505. $scoreRuleId = null
  7506. ): void {
  7507. $ids = $this->extractScydgyRowId($row);
  7508. if (!$this->isValidScydgyRowId($ids)) {
  7509. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  7510. }
  7511. if ($exists === null) {
  7512. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7513. }
  7514. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  7515. $this->ensurePurchaseOrderScoreRuleIdColumn();
  7516. $this->ensurePurchaseOrderCzlyqColumn();
  7517. $data = [
  7518. 'scydgy_id' => $ids,
  7519. 'CCYDH' => $row['CCYDH'] ?? null,
  7520. 'CYJMC' => $row['CYJMC'] ?? null,
  7521. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  7522. 'CDXMC' => $row['CDXMC'] ?? null,
  7523. 'CGYBH' => $row['CGYBH'] ?? null,
  7524. 'CGYMC' => $row['CGYMC'] ?? null,
  7525. 'CDW' => $row['CDW'] ?? null,
  7526. 'czlyq' => $row['czlyq'] ?? null,
  7527. 'NGZL' => $row['NGZL'] ?? null,
  7528. 'CDF' => $row['CDF'] ?? null,
  7529. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  7530. 'MBZ' => $row['MBZ'] ?? null,
  7531. 'bwjg' => $row['bwjg'] ?? null,
  7532. 'iStatus' => $row['iStatus'] ?? null,
  7533. 'dStamp' => $row['dStamp'] ?? null,
  7534. 'dputrecord' => $row['dputrecord'] ?? null,
  7535. 'cywyxm' => $row['cywyxm'] ?? null,
  7536. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  7537. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  7538. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7539. 'sys_rq' => $sysRqDb,
  7540. ];
  7541. // 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
  7542. $qtyUp = trim((string)($data['This_quantity'] ?? ''));
  7543. if ($qtyUp === '') {
  7544. $qtyFallback = $this->resolveProcuremenThisQuantity([
  7545. 'This_quantity' => '',
  7546. 'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
  7547. ]);
  7548. if ($qtyFallback !== '') {
  7549. $data['This_quantity'] = $qtyFallback;
  7550. }
  7551. }
  7552. if ($deliveryDeadline !== null) {
  7553. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  7554. }
  7555. // 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
  7556. $scoreRule = null;
  7557. if (is_array($scoreRuleId)) {
  7558. $scoreRule = $scoreRuleId;
  7559. $scoreRuleId = (int)($scoreRule['id'] ?? 0);
  7560. } else {
  7561. $scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
  7562. }
  7563. if ($scoreRuleId !== null && $scoreRuleId > 0) {
  7564. $poCols = $this->loadPurchaseOrderColumnSet();
  7565. if (!empty($poCols['score_rule_id'])) {
  7566. $data['score_rule_id'] = $scoreRuleId;
  7567. if (is_array($scoreRule)) {
  7568. if (!empty($poCols['score_rule_name'])) {
  7569. $data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
  7570. }
  7571. if (!empty($poCols['score_quality_weight'])) {
  7572. $data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
  7573. }
  7574. if (!empty($poCols['score_price_weight'])) {
  7575. $data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
  7576. }
  7577. if (!empty($poCols['score_lead_weight'])) {
  7578. $data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
  7579. }
  7580. }
  7581. }
  7582. }
  7583. if ($wflowStatus !== null && $wflowStatus !== '') {
  7584. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  7585. }
  7586. if ($pickTime !== null && $pickTime !== '') {
  7587. $data['pick_time'] = $pickTime;
  7588. $data['pick_company_name'] = '';
  7589. }
  7590. if ($exists) {
  7591. $upd = $data;
  7592. unset($upd['scydgy_id']);
  7593. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  7594. } else {
  7595. $data['createtime'] = date('Y-m-d H:i:s');
  7596. Db::table('purchase_order')->insert($data);
  7597. }
  7598. }
  7599. /**
  7600. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  7601. *
  7602. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  7603. */
  7604. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
  7605. {
  7606. $toDb = function ($value) {
  7607. if ($value === null) {
  7608. return null;
  7609. }
  7610. if (is_scalar($value)) {
  7611. return $value;
  7612. }
  7613. return json_encode($value, JSON_UNESCAPED_UNICODE);
  7614. };
  7615. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7616. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7617. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7618. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  7619. if ($username === '') {
  7620. $username = $this->resolveCustomerContactName($phone, $companyName);
  7621. }
  7622. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  7623. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  7624. }
  7625. if ($requirePhone && $phone === '') {
  7626. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  7627. }
  7628. $detailLinks = [];
  7629. foreach ($mergeRows as $row) {
  7630. if (!is_array($row)) {
  7631. continue;
  7632. }
  7633. $sid = $this->extractScydgyRowId($row);
  7634. $detailId = 0;
  7635. if ($skipExisting) {
  7636. try {
  7637. $existsQuery = Db::table('purchase_order_detail')
  7638. ->where('scydgy_id', $sid)
  7639. ->where('company_name', $companyName);
  7640. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  7641. $exists = $existsQuery->find();
  7642. } catch (\Throwable $e) {
  7643. $exists = null;
  7644. }
  7645. if (is_array($exists)) {
  7646. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  7647. }
  7648. }
  7649. if ($detailId <= 0) {
  7650. $one = [
  7651. 'scydgy_id' => $toDb($sid),
  7652. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  7653. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  7654. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  7655. 'username' => $username !== '' ? $username : null,
  7656. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  7657. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  7658. 'createtime' => date('Y-m-d H:i:s'),
  7659. 'status' => ProcuremenStatus::POD_UNPICKED,
  7660. 'status_name' => '未提交',
  7661. ];
  7662. Db::table('purchase_order_detail')->insert($one);
  7663. $detailId = (int)Db::getLastInsID();
  7664. }
  7665. $mprocUrl = '';
  7666. if ($buildMobileLinks && $detailId > 0) {
  7667. // 手工询价 → 待报价;协助下发 → 未提交
  7668. $listTab = ($sid < 0) ? 'rfq' : 'draft';
  7669. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId, $listTab);
  7670. }
  7671. $detailLinks[] = [
  7672. 'detail_id' => $detailId,
  7673. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  7674. 'url' => $mprocUrl,
  7675. ];
  7676. }
  7677. $this->invalidatePickHiddenScydgyCache();
  7678. return $detailLinks;
  7679. }
  7680. /**
  7681. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  7682. * @return array<string, mixed>
  7683. */
  7684. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks, string $emailTplScene = 'review_email'): array
  7685. {
  7686. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7687. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7688. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7689. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  7690. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  7691. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  7692. $isMerge = !empty($ctx['is_merge']);
  7693. $contactName = trim((string)($c['username'] ?? ''));
  7694. if ($contactName === '') {
  7695. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  7696. }
  7697. $notifyVars = [
  7698. 'company_name' => $companyName,
  7699. 'contact_name' => $contactName,
  7700. 'phone' => $phone,
  7701. 'email' => $toEmail,
  7702. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  7703. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  7704. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  7705. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  7706. 'deadline' => (string)($ctx['deadline'] ?? ''),
  7707. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  7708. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  7709. 'order_type' => (string)($ctx['order_type'] ?? ''),
  7710. 'score_weights' => (string)($ctx['score_weights'] ?? ''),
  7711. 'platform_url' => $platformUrl,
  7712. 'platform_links' => $platformLinksPlain,
  7713. 'platform_links_html' => $platformLinksHtml,
  7714. ];
  7715. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  7716. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  7717. $mailPlain = $this->renderNotifyTemplate($emailTplScene, $notifyVars);
  7718. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  7719. return [
  7720. 'company_name' => $companyName,
  7721. 'phone' => $phone,
  7722. 'email' => $toEmail,
  7723. 'sms_content' => $smsContent,
  7724. 'mail_plain' => $mailPlain,
  7725. 'mail_body' => $mailBody,
  7726. 'notify_vars' => $notifyVars,
  7727. 'detail_links' => $detailLinks,
  7728. ];
  7729. }
  7730. /**
  7731. * @param array<string, mixed> $chosen
  7732. * @param array<int, array<string, mixed>> $mergeRows
  7733. * @param array{ccydh:string, pos:array} $bundle
  7734. */
  7735. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue', string $emailTplScene = 'review_email'): void
  7736. {
  7737. if (!$sendSms && !$sendEmail) {
  7738. return;
  7739. }
  7740. $companyName = trim((string)($chosen['name'] ?? ''));
  7741. $phone = trim((string)($chosen['phone'] ?? ''));
  7742. $toEmail = trim((string)($chosen['email'] ?? ''));
  7743. if ($companyName === '') {
  7744. throw new \Exception('供应商名称无效');
  7745. }
  7746. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  7747. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  7748. }
  7749. if ($sendSms && $phone === '') {
  7750. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  7751. }
  7752. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  7753. $linkListTab = (strpos($emailTplScene, 'rfq_') === 0) ? 'rfq' : 'draft';
  7754. $sids = [];
  7755. foreach ($mergeRows as $mr) {
  7756. if (!is_array($mr)) {
  7757. continue;
  7758. }
  7759. $sid = $this->extractScydgyRowId($mr);
  7760. if ($this->isValidScydgyRowId($sid)) {
  7761. $sids[$sid] = true;
  7762. }
  7763. }
  7764. if ($sids === []) {
  7765. throw new \Exception('未找到工序行,无法发送通知');
  7766. }
  7767. $sysRqNotify = '';
  7768. $pos = $bundle['pos'] ?? [];
  7769. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7770. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  7771. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  7772. $ts = strtotime($sr);
  7773. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  7774. }
  7775. }
  7776. try {
  7777. $detailsQuery = Db::table('purchase_order_detail')
  7778. ->where('scydgy_id', 'in', array_keys($sids))
  7779. ->where('company_name', $companyName);
  7780. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7781. $details = $detailsQuery->order('id', 'asc')->select();
  7782. } catch (\Throwable $e) {
  7783. $details = [];
  7784. }
  7785. if (!is_array($details) || $details === []) {
  7786. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  7787. try {
  7788. $detailsQuery = Db::table('purchase_order_detail')
  7789. ->where('scydgy_id', 'in', array_keys($sids))
  7790. ->where('company_name', $companyName);
  7791. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7792. $details = $detailsQuery->order('id', 'asc')->select();
  7793. } catch (\Throwable $e) {
  7794. $details = [];
  7795. }
  7796. }
  7797. if (!is_array($details) || $details === []) {
  7798. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  7799. }
  7800. $detailLinks = [];
  7801. foreach ($details as $d) {
  7802. if (!is_array($d)) {
  7803. continue;
  7804. }
  7805. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  7806. if ($detailId <= 0) {
  7807. continue;
  7808. }
  7809. $sid = (int)($d['scydgy_id'] ?? 0);
  7810. $gymc = '';
  7811. foreach ($mergeRows as $mr) {
  7812. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  7813. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  7814. break;
  7815. }
  7816. }
  7817. $detailLinks[] = [
  7818. 'detail_id' => $detailId,
  7819. 'cgymc' => $gymc,
  7820. // 询价邮件 → 待报价;下发报价 → 未提交
  7821. 'url' => $this->buildMprocMobileOrderUrl(
  7822. $detailId,
  7823. ($linkListTab === 'rfq' || $sid < 0) ? 'rfq' : 'draft'
  7824. ),
  7825. ];
  7826. }
  7827. if ($detailLinks === []) {
  7828. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  7829. }
  7830. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  7831. $orderTypeCtx = $this->resolveIssueNotifyOrderTypeFromBundle($bundle);
  7832. $ctx['order_type'] = (string)($orderTypeCtx['order_type'] ?? '');
  7833. $ctx['score_weights'] = (string)($orderTypeCtx['score_weights'] ?? '');
  7834. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks, $emailTplScene);
  7835. $notifyBundle['email_log_scene'] = $emailLogScene;
  7836. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  7837. $poIdLog = 0;
  7838. $pos = $bundle['pos'] ?? [];
  7839. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7840. $poIdLog = (int)($pos[0]['id'] ?? 0);
  7841. }
  7842. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  7843. if ($sendEmail) {
  7844. $mailTplRow = $this->loadNotifyTemplateRow($emailTplScene);
  7845. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  7846. throw new \Exception($this->notifyTemplateMissingMessage($emailTplScene));
  7847. }
  7848. $mailSubject = $this->resolveProcuremenEmailSubject($emailTplScene);
  7849. $mailConfig = $this->loadMailerConfig();
  7850. if (!$this->isProcuremenNotifyDryRun()) {
  7851. if (empty($mailConfig['host'])) {
  7852. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  7853. }
  7854. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  7855. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  7856. }
  7857. }
  7858. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  7859. }
  7860. if ($sendSms) {
  7861. $this->issueSendSupplierSms($notifyBundle);
  7862. }
  7863. }
  7864. /**
  7865. * @param array<int, array<string, mixed>> $quoteGroups
  7866. * @return array<int, array<string, mixed>>
  7867. */
  7868. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  7869. {
  7870. $names = [];
  7871. if (is_string($companiesJson) && $companiesJson !== '') {
  7872. $decoded = json_decode($companiesJson, true);
  7873. if (is_array($decoded)) {
  7874. foreach ($decoded as $nm) {
  7875. $nm = trim((string)$nm);
  7876. if ($nm !== '') {
  7877. $names[] = $nm;
  7878. }
  7879. }
  7880. }
  7881. }
  7882. $names = array_values(array_unique($names));
  7883. if ($names === [] && $selectedCompany !== '') {
  7884. $names = [$selectedCompany];
  7885. }
  7886. if ($names === []) {
  7887. return $quoteGroups;
  7888. }
  7889. $targets = [];
  7890. foreach ($quoteGroups as $g) {
  7891. if (!is_array($g)) {
  7892. continue;
  7893. }
  7894. $cn = trim((string)($g['name'] ?? ''));
  7895. if ($cn !== '' && in_array($cn, $names, true)) {
  7896. $targets[] = $g;
  7897. }
  7898. }
  7899. return $targets;
  7900. }
  7901. /**
  7902. * @return array{pos:array, merge_rows:array, bundle:array}
  7903. */
  7904. protected function loadAuditResendBundle(string $scydgyId): array
  7905. {
  7906. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7907. $pos = $bundle['pos'];
  7908. $mergeRows = $bundle['merge_rows'];
  7909. if ($pos === [] || $mergeRows === []) {
  7910. $this->error('该订单不在待确认供应商状态');
  7911. }
  7912. $sysRqDb = '';
  7913. if (isset($pos[0]) && is_array($pos[0])) {
  7914. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  7915. }
  7916. foreach ($pos as $i => $poRow) {
  7917. if (is_array($pos[$i]) && $sysRqDb !== '') {
  7918. $pos[$i]['sys_rq'] = $sysRqDb;
  7919. }
  7920. }
  7921. $bundle['pos'] = $pos;
  7922. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  7923. }
  7924. /**
  7925. * @param array<int, array<string, mixed>> $targets
  7926. */
  7927. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  7928. {
  7929. if ($targets === []) {
  7930. $this->error('未找到可通知的供应商');
  7931. }
  7932. $notifyErrors = [];
  7933. try {
  7934. $this->notifyDryRunPreview = [];
  7935. foreach ($targets as $g) {
  7936. if (!is_array($g)) {
  7937. continue;
  7938. }
  7939. $cname = trim((string)($g['name'] ?? ''));
  7940. if ($cname === '') {
  7941. continue;
  7942. }
  7943. $chosen = [
  7944. 'name' => $cname,
  7945. 'company_name' => $cname,
  7946. 'email' => trim((string)($g['email'] ?? '')),
  7947. 'phone' => trim((string)($g['phone'] ?? '')),
  7948. 'username' => trim((string)($g['username'] ?? '')),
  7949. ];
  7950. try {
  7951. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  7952. } catch (\Throwable $e) {
  7953. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7954. }
  7955. }
  7956. } catch (\Throwable $e) {
  7957. $this->error('通知发送失败:' . $e->getMessage());
  7958. }
  7959. if ($notifyErrors !== []) {
  7960. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  7961. }
  7962. if ($this->isProcuremenNotifyDryRun()) {
  7963. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  7964. 'notify_dry_run' => true,
  7965. 'notify_preview' => $this->notifyDryRunPreview,
  7966. ]);
  7967. }
  7968. $nameLabels = [];
  7969. foreach ($targets as $g) {
  7970. if (!is_array($g)) {
  7971. continue;
  7972. }
  7973. $n = trim((string)($g['name'] ?? ''));
  7974. if ($n !== '') {
  7975. $nameLabels[] = $n;
  7976. }
  7977. }
  7978. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  7979. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  7980. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  7981. $seenLogSid = [];
  7982. foreach ($bundle['pos'] ?? [] as $poRow) {
  7983. if (!is_array($poRow)) {
  7984. continue;
  7985. }
  7986. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7987. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  7988. continue;
  7989. }
  7990. $seenLogSid[$sid] = true;
  7991. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7992. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7993. }
  7994. if ($seenLogSid === []) {
  7995. foreach ($mergeRows as $mr) {
  7996. if (!is_array($mr)) {
  7997. continue;
  7998. }
  7999. $sid = $this->extractScydgyRowId($mr);
  8000. if ($this->isValidScydgyRowId($sid)) {
  8001. $this->addOrderLog($sid, $logAction, $logMsg, null);
  8002. break;
  8003. }
  8004. }
  8005. }
  8006. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  8007. }
  8008. /**
  8009. * 协助下发 — 发送短信(一家供应商)
  8010. *
  8011. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  8012. */
  8013. protected function issueSendSupplierSms(array $bundle): void
  8014. {
  8015. $companyName = (string)($bundle['company_name'] ?? '');
  8016. $phone = (string)($bundle['phone'] ?? '');
  8017. $smsContent = (string)($bundle['sms_content'] ?? '');
  8018. $this->logIssueNotifyDebug('短信', [
  8019. 'company' => $companyName,
  8020. 'phone' => $phone,
  8021. 'sms_content' => $smsContent,
  8022. ]);
  8023. if ($this->isProcuremenNotifyDryRun()) {
  8024. $this->recordNotifyDryRunPreview([
  8025. 'scene' => 'issue_sms',
  8026. 'company_name' => $companyName,
  8027. 'phone' => $phone,
  8028. 'sms_content' => $smsContent,
  8029. ]);
  8030. return;
  8031. }
  8032. $this->smsbao($phone, $smsContent);
  8033. }
  8034. /**
  8035. * 协助下发 — 发送邮件(一家供应商)
  8036. *
  8037. * @param array<string, mixed> $bundle
  8038. * @param array<string, mixed> $mailConfig
  8039. */
  8040. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  8041. {
  8042. $companyName = (string)($bundle['company_name'] ?? '');
  8043. $toEmail = (string)($bundle['email'] ?? '');
  8044. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  8045. $mailBody = (string)($bundle['mail_body'] ?? '');
  8046. $this->logIssueNotifyDebug('邮件', [
  8047. 'company' => $companyName,
  8048. 'email' => $toEmail,
  8049. 'mail_subject' => $mailSubject,
  8050. 'mail_body' => $mailPlain,
  8051. ]);
  8052. if ($this->isProcuremenNotifyDryRun()) {
  8053. $this->recordNotifyDryRunPreview([
  8054. 'scene' => 'issue_email',
  8055. 'company_name' => $companyName,
  8056. 'email' => $toEmail,
  8057. 'mail_subject' => $mailSubject,
  8058. 'mail_body' => $mailPlain,
  8059. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  8060. 'notify_vars' => $bundle['notify_vars'] ?? [],
  8061. 'detail_links' => $bundle['detail_links'] ?? [],
  8062. ]);
  8063. return;
  8064. }
  8065. $mail = new PHPMailer(true);
  8066. $mail->isSMTP();
  8067. $mail->Host = $mailConfig['host'];
  8068. $mail->SMTPAuth = true;
  8069. $mail->Username = $mailConfig['addr'];
  8070. $mail->Password = $mailConfig['pass'];
  8071. $mail->SMTPSecure = $mailConfig['security'];
  8072. $mail->Port = $mailConfig['port'];
  8073. $mail->CharSet = $mailConfig['charset'];
  8074. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  8075. $mail->addAddress($toEmail, $companyName);
  8076. $mail->isHTML(true);
  8077. $mail->Subject = $mailSubject;
  8078. $mail->Body = $mailBody;
  8079. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  8080. $sendOk = true;
  8081. $failReason = '';
  8082. try {
  8083. $mail->send();
  8084. } catch (\Throwable $e) {
  8085. $sendOk = false;
  8086. $failReason = $e->getMessage();
  8087. $this->persistEmailSendLog([
  8088. 'from_email' => $fromEmail,
  8089. 'to_email' => $toEmail,
  8090. 'send_time' => date('Y-m-d H:i:s'),
  8091. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  8092. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  8093. 'company_name' => $companyName,
  8094. 'mail_subject' => $mailSubject,
  8095. 'status' => 0,
  8096. 'fail_reason' => $failReason,
  8097. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  8098. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  8099. ]);
  8100. throw $e;
  8101. }
  8102. $this->persistEmailSendLog([
  8103. 'from_email' => $fromEmail,
  8104. 'to_email' => $toEmail,
  8105. 'send_time' => date('Y-m-d H:i:s'),
  8106. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  8107. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  8108. 'company_name' => $companyName,
  8109. 'mail_subject' => $mailSubject,
  8110. 'status' => 1,
  8111. 'fail_reason' => '',
  8112. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  8113. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  8114. ]);
  8115. }
  8116. /**
  8117. * 下发通知:解析订单类型名称与评分比例文案
  8118. *
  8119. * @param array<string, mixed> $bundle
  8120. * @return array{order_type:string,score_weights:string}
  8121. */
  8122. protected function resolveIssueNotifyOrderTypeFromBundle(array $bundle): array
  8123. {
  8124. $orderType = '';
  8125. $scoreWeights = '';
  8126. $rule = null;
  8127. if (!empty($bundle['score_rule']) && is_array($bundle['score_rule'])) {
  8128. $rule = $bundle['score_rule'];
  8129. }
  8130. $pos = $bundle['pos'] ?? [];
  8131. $po0 = (is_array($pos) && isset($pos[0]) && is_array($pos[0])) ? $pos[0] : null;
  8132. if ($rule === null && is_array($po0)) {
  8133. $ruleId = (int)($po0['score_rule_id'] ?? 0);
  8134. if ($ruleId > 0) {
  8135. try {
  8136. $rule = ProcuremenSupplierScore::getRuleById($ruleId);
  8137. } catch (\Throwable $e) {
  8138. $rule = null;
  8139. }
  8140. }
  8141. if (!is_array($rule) || (int)($rule['id'] ?? 0) <= 0) {
  8142. $qw = (int)($po0['score_quality_weight'] ?? 0);
  8143. $pw = (int)($po0['score_price_weight'] ?? 0);
  8144. $lw = (int)($po0['score_lead_weight'] ?? 0);
  8145. if ($qw > 0 || $pw > 0 || $lw > 0) {
  8146. $rule = [
  8147. 'name' => trim((string)($po0['score_rule_name'] ?? '')),
  8148. 'quality_weight' => $qw,
  8149. 'price_weight' => $pw,
  8150. 'lead_weight' => $lw,
  8151. ];
  8152. }
  8153. }
  8154. }
  8155. if (is_array($rule)) {
  8156. $orderType = trim((string)($rule['name'] ?? ''));
  8157. $scoreWeights = $this->formatScoreRuleWeightsText($rule);
  8158. }
  8159. if ($orderType === '' && is_array($po0)) {
  8160. $orderType = trim((string)($po0['score_rule_name'] ?? ''));
  8161. }
  8162. return [
  8163. 'order_type' => $orderType,
  8164. 'score_weights' => $scoreWeights,
  8165. ];
  8166. }
  8167. /**
  8168. * 评分比例文案:质量30%、价格50%、交货20%
  8169. *
  8170. * @param array{quality_weight?:mixed,price_weight?:mixed,lead_weight?:mixed} $rule
  8171. */
  8172. protected function formatScoreRuleWeightsText(array $rule): string
  8173. {
  8174. $parts = [];
  8175. $qw = max(0, (float)($rule['quality_weight'] ?? 0));
  8176. $pw = max(0, (float)($rule['price_weight'] ?? 0));
  8177. $lw = max(0, (float)($rule['lead_weight'] ?? 0));
  8178. $fmt = static function ($n) {
  8179. $s = rtrim(rtrim(sprintf('%.2F', (float)$n), '0'), '.');
  8180. return $s === '' ? '0' : $s;
  8181. };
  8182. if ($qw > 0) {
  8183. $parts[] = '质量' . $fmt($qw) . '%';
  8184. }
  8185. if ($pw > 0) {
  8186. $parts[] = '价格' . $fmt($pw) . '%';
  8187. }
  8188. if ($lw > 0) {
  8189. $parts[] = '交货' . $fmt($lw) . '%';
  8190. }
  8191. return implode('、', $parts);
  8192. }
  8193. /**
  8194. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  8195. *
  8196. * @param array<int, array<string, mixed>> $mergeRows
  8197. * @return array<string, mixed>
  8198. */
  8199. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  8200. {
  8201. $head = $mergeRows[0] ?? [];
  8202. $isMerge = count($mergeRows) > 1;
  8203. return [
  8204. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  8205. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  8206. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  8207. 'is_merge' => $isMerge,
  8208. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  8209. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  8210. 'deadline' => $sysRqNotify,
  8211. 'order_type' => '',
  8212. 'score_weights' => '',
  8213. ];
  8214. }
  8215. /**
  8216. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  8217. *
  8218. * @param array<string, mixed> $data
  8219. */
  8220. protected function logIssueNotifyDebug(string $type, array $data): void
  8221. {
  8222. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  8223. return;
  8224. }
  8225. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  8226. }
  8227. protected function ensurePurchaseEmailSendLogTableOnce(): void
  8228. {
  8229. try {
  8230. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  8231. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  8232. return;
  8233. } catch (\Throwable $e) {
  8234. }
  8235. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  8236. if (is_file($sqlFile)) {
  8237. $sql = file_get_contents($sqlFile);
  8238. if (is_string($sql) && $sql !== '') {
  8239. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  8240. $stmt = trim($stmt);
  8241. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  8242. continue;
  8243. }
  8244. try {
  8245. Db::execute($stmt);
  8246. } catch (\Throwable $ignore) {
  8247. }
  8248. }
  8249. }
  8250. }
  8251. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  8252. }
  8253. /**
  8254. * @param array<string, mixed> $row
  8255. */
  8256. protected function persistEmailSendLog(array $row): void
  8257. {
  8258. try {
  8259. $this->ensurePurchaseEmailSendLogTableOnce();
  8260. } catch (\Throwable $e) {
  8261. return;
  8262. }
  8263. list($adminId, $adminName) = $this->GetUseName();
  8264. $cut = function ($s, $max) {
  8265. $s = (string)$s;
  8266. if (function_exists('mb_substr')) {
  8267. return mb_substr($s, 0, $max, 'UTF-8');
  8268. }
  8269. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  8270. };
  8271. $data = [
  8272. 'from_email' => $cut($row['from_email'] ?? '', 128),
  8273. 'to_email' => $cut($row['to_email'] ?? '', 128),
  8274. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  8275. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  8276. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  8277. 'company_name' => $cut($row['company_name'] ?? '', 128),
  8278. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  8279. 'status' => !empty($row['status']) ? 1 : 0,
  8280. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  8281. 'admin_id' => (int)$adminId,
  8282. 'admin_name' => $cut($adminName, 64),
  8283. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  8284. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  8285. 'createtime' => date('Y-m-d H:i:s'),
  8286. ];
  8287. try {
  8288. Db::table('purchase_email_send_log')->insert($data);
  8289. } catch (\Throwable $e) {
  8290. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  8291. }
  8292. }
  8293. protected function formatEmailLogSceneText(string $scene): string
  8294. {
  8295. $map = [
  8296. 'pick_issue' => '初选下发',
  8297. 'audit_resend' => '确认页重发',
  8298. 'rfq_salesman' => '询价通知业务员',
  8299. 'rfq_supplier' => '供应商询价通知',
  8300. ];
  8301. return $map[$scene] ?? $scene;
  8302. }
  8303. /**
  8304. * 邮件发送日志列表
  8305. */
  8306. public function emailLog()
  8307. {
  8308. $this->relationSearch = false;
  8309. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  8310. $this->request->filter(['strip_tags', 'trim']);
  8311. $bakModel = $this->model;
  8312. $this->model = new \app\admin\model\Purchaseemailsendlog;
  8313. if ($this->request->isAjax()) {
  8314. $this->ensurePurchaseEmailSendLogTableOnce();
  8315. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  8316. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  8317. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  8318. $list = $this->model
  8319. ->where($where)
  8320. ->order($sortField, $orderDir)
  8321. ->paginate($limit);
  8322. $rows = [];
  8323. foreach ($list->items() as $item) {
  8324. $row = is_array($item) ? $item : $item->toArray();
  8325. $scene = trim((string)($row['scene'] ?? ''));
  8326. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  8327. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  8328. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  8329. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  8330. $rows[] = $row;
  8331. }
  8332. $this->model = $bakModel;
  8333. return json(['total' => $list->total(), 'rows' => $rows]);
  8334. }
  8335. $this->model = $bakModel;
  8336. return $this->view->fetch('procuremen/emaillog');
  8337. }
  8338. /**
  8339. * 协助下发弹窗(选多家供应商并通知)
  8340. */
  8341. public function pickReview()
  8342. {
  8343. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  8344. $this->error(__('You have no permission'));
  8345. }
  8346. if ($this->request->isPost()) {
  8347. $this->error('请使用弹窗内「确认下发」提交');
  8348. }
  8349. $this->view->assign('pickMode', 1);
  8350. $this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
  8351. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  8352. }
  8353. /**
  8354. * 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
  8355. */
  8356. protected function ensurePurchaseOrderNotifySalesmanColumn(): void
  8357. {
  8358. static $done = false;
  8359. if ($done) {
  8360. return;
  8361. }
  8362. $done = true;
  8363. try {
  8364. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'notify_salesman'");
  8365. if (empty($cols)) {
  8366. Db::execute(
  8367. "ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
  8368. );
  8369. } else {
  8370. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  8371. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
  8372. Db::execute(
  8373. "ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
  8374. );
  8375. }
  8376. }
  8377. } catch (\Throwable $e) {
  8378. // ignore
  8379. }
  8380. }
  8381. /**
  8382. * 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
  8383. */
  8384. protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
  8385. {
  8386. static $done = false;
  8387. if ($done) {
  8388. return;
  8389. }
  8390. $done = true;
  8391. try {
  8392. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
  8393. if (empty($cols)) {
  8394. Db::execute(
  8395. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
  8396. );
  8397. }
  8398. } catch (\Throwable $e) {
  8399. // ignore
  8400. }
  8401. try {
  8402. $cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
  8403. if (empty($cols2)) {
  8404. Db::execute(
  8405. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
  8406. );
  8407. }
  8408. } catch (\Throwable $e) {
  8409. // ignore
  8410. }
  8411. }
  8412. /**
  8413. * 确保「采购确认通过/未通过」邮箱模版存在(正文同短信,末尾加平台链接)
  8414. */
  8415. protected function ensureConfirmResultEmailTemplates(): void
  8416. {
  8417. static $done = false;
  8418. if ($done) {
  8419. return;
  8420. }
  8421. $done = true;
  8422. $now = date('Y-m-d H:i:s');
  8423. $seeds = [
  8424. 'confirm_ok_email' => [
  8425. 'title' => '采购确认结果:已通过',
  8426. 'content' => "【可集达】您好,{company_name}:\n\n您参与的外发加工订单采购确认结果:已通过。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  8427. 'remark' => '审批通过-中标供应商邮箱通知;模版名称作邮件主题',
  8428. ],
  8429. 'confirm_fail_email' => [
  8430. 'title' => '采购确认结果:未通过',
  8431. 'content' => "【可集达】您好,{company_name}:\n\n您参与的外发加工订单采购确认结果:未通过。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  8432. 'remark' => '审批通过-未中标供应商邮箱通知;模版名称作邮件主题',
  8433. ],
  8434. ];
  8435. try {
  8436. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8437. } catch (\Throwable $e) {
  8438. return;
  8439. }
  8440. $colNames = [];
  8441. foreach ($cols as $c) {
  8442. if (!is_array($c)) {
  8443. continue;
  8444. }
  8445. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8446. if ($n !== '') {
  8447. $colNames[$n] = true;
  8448. }
  8449. }
  8450. foreach ($seeds as $scene => $seed) {
  8451. try {
  8452. $row = Db::table('purchase_sms_template')->where('scene', $scene)->find();
  8453. } catch (\Throwable $e) {
  8454. continue;
  8455. }
  8456. if (is_array($row) && $row !== []) {
  8457. continue;
  8458. }
  8459. $data = [
  8460. 'scene' => $scene,
  8461. 'title' => $seed['title'],
  8462. 'content' => $seed['content'],
  8463. 'remark' => $seed['remark'],
  8464. 'status' => 1,
  8465. ];
  8466. if (isset($colNames['updatetime'])) {
  8467. $data['updatetime'] = $now;
  8468. }
  8469. if (isset($colNames['createtime'])) {
  8470. $data['createtime'] = $now;
  8471. }
  8472. try {
  8473. Db::table('purchase_sms_template')->insert($data);
  8474. } catch (\Throwable $e) {
  8475. // ignore
  8476. }
  8477. }
  8478. }
  8479. /**
  8480. * 确保「供应商询价通知」邮箱模版存在(查询询价-询价/发邮件;可在短信模版配置中修改)
  8481. */
  8482. protected function ensureRfqSupplierEmailTemplate(): void
  8483. {
  8484. static $done = false;
  8485. if ($done) {
  8486. return;
  8487. }
  8488. $done = true;
  8489. $content = "您好,{company_name}:\n\n"
  8490. . "您有新的协助采购询价需求,请登录平台查看并处理。\n\n"
  8491. . "需求编号:{ccydh}\n"
  8492. . "印件名称:{cyjmc}\n"
  8493. . "{process_lines}\n\n"
  8494. . "请在 {deadline} 前完成回复。\n\n"
  8495. . "平台链接:{platform_url}\n";
  8496. try {
  8497. $row = Db::table('purchase_sms_template')
  8498. ->where('scene', 'rfq_supplier_email')
  8499. ->find();
  8500. } catch (\Throwable $e) {
  8501. return;
  8502. }
  8503. $now = date('Y-m-d H:i:s');
  8504. if (is_array($row) && $row !== []) {
  8505. return;
  8506. }
  8507. try {
  8508. $data = [
  8509. 'scene' => 'rfq_supplier_email',
  8510. 'title' => '供应商询价通知',
  8511. 'content' => $content,
  8512. 'remark' => '查询询价-询价/发邮件通知供应商;模版名称作邮件主题',
  8513. 'status' => 1,
  8514. ];
  8515. try {
  8516. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8517. } catch (\Throwable $e) {
  8518. $cols = [];
  8519. }
  8520. $colNames = [];
  8521. foreach ($cols as $c) {
  8522. if (!is_array($c)) {
  8523. continue;
  8524. }
  8525. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8526. if ($n !== '') {
  8527. $colNames[$n] = true;
  8528. }
  8529. }
  8530. if (isset($colNames['updatetime'])) {
  8531. $data['updatetime'] = $now;
  8532. }
  8533. if (isset($colNames['createtime'])) {
  8534. $data['createtime'] = $now;
  8535. }
  8536. Db::table('purchase_sms_template')->insert($data);
  8537. } catch (\Throwable $e) {
  8538. // ignore
  8539. }
  8540. }
  8541. /**
  8542. * 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
  8543. */
  8544. protected function ensureRfqSalesmanEmailTemplate(): void
  8545. {
  8546. static $done = false;
  8547. if ($done) {
  8548. return;
  8549. }
  8550. $done = true;
  8551. $content = "您好,{contact_name}:\n\n"
  8552. . "有新的协助采购询价需求,请知悉。\n"
  8553. . "印件名称:{cyjmc}\n"
  8554. . "工序名称:{cgymc}\n"
  8555. . "本次数量:{this_quantity}\n"
  8556. . "供应商报价:\n{supplier_quotes}\n"
  8557. . "平台链接:{platform_url}\n"
  8558. . "需求发起人:{cywyxm}\n";
  8559. try {
  8560. $row = Db::table('purchase_sms_template')
  8561. ->where('scene', 'rfq_salesman_email')
  8562. ->find();
  8563. } catch (\Throwable $e) {
  8564. return;
  8565. }
  8566. $now = date('Y-m-d H:i:s');
  8567. if (is_array($row) && $row !== []) {
  8568. $old = (string)($row['content'] ?? '');
  8569. // 无报价表格 / 无平台链接 / 链接不在「需求发起人」上方时,同步默认文案
  8570. $urlPos = strpos($old, '{platform_url}');
  8571. $cywyPos = strpos($old, '需求发起人');
  8572. $linkNotAboveStarter = ($urlPos === false)
  8573. || ($cywyPos !== false && $urlPos > $cywyPos);
  8574. $needMigrate = (strpos($old, '{supplier_quotes}') === false)
  8575. || (strpos($old, '供应商:{supplier_name}') !== false)
  8576. || $linkNotAboveStarter;
  8577. if ($needMigrate) {
  8578. $data = ['content' => $content];
  8579. if (trim((string)($row['title'] ?? '')) === '' || trim((string)($row['title'] ?? '')) === '询价通知') {
  8580. $data['title'] = '业务员询价通知';
  8581. }
  8582. try {
  8583. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
  8584. if (!empty($cols)) {
  8585. $data['updatetime'] = $now;
  8586. }
  8587. } catch (\Throwable $e) {
  8588. }
  8589. try {
  8590. Db::table('purchase_sms_template')
  8591. ->where('id', (int)($row['id'] ?? 0))
  8592. ->update($data);
  8593. } catch (\Throwable $e) {
  8594. }
  8595. }
  8596. return;
  8597. }
  8598. try {
  8599. $data = [
  8600. 'scene' => 'rfq_salesman_email',
  8601. 'title' => '业务员询价通知',
  8602. 'content' => $content,
  8603. 'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
  8604. 'status' => 1,
  8605. ];
  8606. try {
  8607. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8608. } catch (\Throwable $e) {
  8609. $cols = [];
  8610. }
  8611. $colNames = [];
  8612. foreach ($cols as $c) {
  8613. if (!is_array($c)) {
  8614. continue;
  8615. }
  8616. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8617. if ($n !== '') {
  8618. $colNames[$n] = true;
  8619. }
  8620. }
  8621. if (isset($colNames['updatetime'])) {
  8622. $data['updatetime'] = $now;
  8623. }
  8624. if (isset($colNames['createtime'])) {
  8625. $data['createtime'] = $now;
  8626. }
  8627. Db::table('purchase_sms_template')->insert($data);
  8628. } catch (\Throwable $e) {
  8629. // ignore
  8630. }
  8631. }
  8632. /**
  8633. * 通知业务员邮件:供应商报价明细行(仅名称+单价)
  8634. *
  8635. * @return array<int, array{name:string,amount:string}>
  8636. */
  8637. protected function loadRfqSalesmanSupplierQuoteRows(int $sid, string $supplierRaw = ''): array
  8638. {
  8639. $list = [];
  8640. $seen = [];
  8641. try {
  8642. $rows = Db::table('purchase_order_detail')
  8643. ->where('scydgy_id', $sid)
  8644. ->field('company_name,amount')
  8645. ->order('id', 'asc')
  8646. ->select();
  8647. if (is_array($rows)) {
  8648. foreach ($rows as $r) {
  8649. if (!is_array($r)) {
  8650. continue;
  8651. }
  8652. $cn = trim((string)($r['company_name'] ?? ''));
  8653. if ($cn === '' || isset($seen[$cn])) {
  8654. continue;
  8655. }
  8656. $seen[$cn] = true;
  8657. $amount = trim((string)($r['amount'] ?? ''));
  8658. $list[] = [
  8659. 'name' => $cn,
  8660. 'amount' => $amount !== '' ? $amount : '未报价',
  8661. ];
  8662. }
  8663. }
  8664. } catch (\Throwable $e) {
  8665. }
  8666. if ($list === [] && $supplierRaw !== '') {
  8667. foreach ($this->splitRfqSalesmanNames($supplierRaw) as $cn) {
  8668. if ($cn === '' || isset($seen[$cn])) {
  8669. continue;
  8670. }
  8671. $seen[$cn] = true;
  8672. $list[] = [
  8673. 'name' => $cn,
  8674. 'amount' => '未报价',
  8675. ];
  8676. }
  8677. }
  8678. return $list;
  8679. }
  8680. /**
  8681. * 通知业务员邮件:供应商报价 HTML 表格(名称+单价,不含时间)
  8682. */
  8683. protected function buildRfqSalesmanSupplierQuotesHtml(int $sid, string $supplierRaw = ''): string
  8684. {
  8685. $rows = $this->loadRfqSalesmanSupplierQuoteRows($sid, $supplierRaw);
  8686. if ($rows === []) {
  8687. return '<p style="margin:8px 0;color:#888;">暂无报价</p>';
  8688. }
  8689. $html = '<table cellpadding="0" cellspacing="0" border="1" '
  8690. . 'style="border-collapse:collapse;border-color:#ddd;width:100%;max-width:560px;font-size:14px;margin:8px 0;">'
  8691. . '<thead><tr style="background:#f5f5f5;">'
  8692. . '<th style="padding:8px 10px;text-align:center;width:56px;">序号</th>'
  8693. . '<th style="padding:8px 10px;text-align:left;">供应商名称</th>'
  8694. . '<th style="padding:8px 10px;text-align:center;width:100px;">单价</th>'
  8695. . '</tr></thead><tbody>';
  8696. foreach ($rows as $i => $row) {
  8697. $html .= '<tr>'
  8698. . '<td style="padding:8px 10px;text-align:center;">' . ($i + 1) . '</td>'
  8699. . '<td style="padding:8px 10px;">' . htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8') . '</td>'
  8700. . '<td style="padding:8px 10px;text-align:center;">' . htmlspecialchars($row['amount'], ENT_QUOTES, 'UTF-8') . '</td>'
  8701. . '</tr>';
  8702. }
  8703. $html .= '</tbody></table>';
  8704. return $html;
  8705. }
  8706. /**
  8707. * 询价多选字段:数组或字符串统一为顿号拼接
  8708. *
  8709. * @param mixed $raw
  8710. */
  8711. protected function joinRfqMultiSelectValues($raw): string
  8712. {
  8713. $parts = [];
  8714. if (is_array($raw)) {
  8715. foreach ($raw as $item) {
  8716. if (is_array($item)) {
  8717. continue;
  8718. }
  8719. $v = trim((string)$item);
  8720. if ($v !== '') {
  8721. $parts[] = $v;
  8722. }
  8723. }
  8724. } else {
  8725. $s = trim((string)$raw);
  8726. if ($s !== '') {
  8727. foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
  8728. $v = trim((string)$piece);
  8729. if ($v !== '') {
  8730. $parts[] = $v;
  8731. }
  8732. }
  8733. }
  8734. }
  8735. $parts = array_values(array_unique($parts));
  8736. return implode('、', $parts);
  8737. }
  8738. /**
  8739. * 新增询价:可选供应商名称(仅落库记录,不发通知)
  8740. *
  8741. * @return string[]
  8742. */
  8743. protected function loadRfqSupplierNameOptions(): array
  8744. {
  8745. $out = [];
  8746. try {
  8747. $rows = Db::table('customer')
  8748. ->where(function ($q) {
  8749. $q->where('status', 1)
  8750. ->whereOr('status', '1')
  8751. ->whereOr('status', '')
  8752. ->whereNull('status');
  8753. })
  8754. ->order('id', 'desc')
  8755. ->column('company_name');
  8756. } catch (\Throwable $e) {
  8757. return [];
  8758. }
  8759. if (!is_array($rows)) {
  8760. return [];
  8761. }
  8762. foreach ($rows as $name) {
  8763. $name = trim((string)$name);
  8764. if ($name === '' || isset($out[$name])) {
  8765. continue;
  8766. }
  8767. $out[$name] = $name;
  8768. }
  8769. return array_values($out);
  8770. }
  8771. /**
  8772. * 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
  8773. */
  8774. protected function rfqNotifySalesmanAuthGroupId(): int
  8775. {
  8776. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  8777. if ($id > 0) {
  8778. return $id;
  8779. }
  8780. try {
  8781. $found = Db::name('auth_group')
  8782. ->where('name', '业务员')
  8783. ->where('status', 'normal')
  8784. ->order('id', 'asc')
  8785. ->value('id');
  8786. $id = (int)$found;
  8787. } catch (\Throwable $e) {
  8788. $id = 0;
  8789. }
  8790. return $id > 0 ? $id : 12;
  8791. }
  8792. /**
  8793. * 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
  8794. *
  8795. * @return string[]
  8796. */
  8797. protected function loadRfqSalesmanNameOptions(): array
  8798. {
  8799. $out = [];
  8800. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8801. $name = trim((string)($row['name'] ?? ''));
  8802. if ($name !== '') {
  8803. $out[] = $name;
  8804. }
  8805. }
  8806. return $out;
  8807. }
  8808. /**
  8809. * 业务员角色组下管理员:姓名、邮箱、手机
  8810. *
  8811. * @return array<int, array{name:string,email:string,mobile:string}>
  8812. */
  8813. protected function loadRfqSalesmanContactOptions(): array
  8814. {
  8815. $out = [];
  8816. $seen = [];
  8817. $groupId = $this->rfqNotifySalesmanAuthGroupId();
  8818. if ($groupId <= 0) {
  8819. return [];
  8820. }
  8821. try {
  8822. $adminIds = Db::name('auth_group_access')
  8823. ->where('group_id', $groupId)
  8824. ->column('uid');
  8825. } catch (\Throwable $e) {
  8826. return [];
  8827. }
  8828. $adminIds = is_array($adminIds)
  8829. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  8830. : [];
  8831. if ($adminIds === []) {
  8832. return [];
  8833. }
  8834. try {
  8835. $rows = Db::name('admin')
  8836. ->where('status', 'normal')
  8837. ->where('id', 'in', $adminIds)
  8838. ->order('id', 'asc')
  8839. ->field('id,nickname,username,email,mobile')
  8840. ->select();
  8841. } catch (\Throwable $e) {
  8842. return [];
  8843. }
  8844. if (!is_array($rows)) {
  8845. return [];
  8846. }
  8847. foreach ($rows as $row) {
  8848. if (!is_array($row)) {
  8849. continue;
  8850. }
  8851. $name = trim((string)($row['nickname'] ?? ''));
  8852. if ($name === '') {
  8853. $name = trim((string)($row['username'] ?? ''));
  8854. }
  8855. if ($name === '' || isset($seen[$name])) {
  8856. continue;
  8857. }
  8858. $seen[$name] = true;
  8859. $out[] = [
  8860. 'name' => $name,
  8861. 'email' => trim((string)($row['email'] ?? '')),
  8862. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  8863. ];
  8864. }
  8865. return $out;
  8866. }
  8867. /**
  8868. * 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
  8869. *
  8870. * @return string[]
  8871. */
  8872. protected function loadRfqDeptNameOptions(): array
  8873. {
  8874. $out = [];
  8875. // ERP 承揽部门(主来源)
  8876. try {
  8877. $vals = Db::table('mcyd')
  8878. ->where('CCLBMMC', '<>', '')
  8879. ->whereNotNull('CCLBMMC')
  8880. ->distinct(true)
  8881. ->limit(300)
  8882. ->column('CCLBMMC');
  8883. } catch (\Throwable $e) {
  8884. $vals = [];
  8885. }
  8886. if (is_array($vals)) {
  8887. foreach ($vals as $v) {
  8888. $v = trim((string)$v);
  8889. if ($v === '' || isset($out[$v])) {
  8890. continue;
  8891. }
  8892. $out[$v] = $v;
  8893. }
  8894. }
  8895. // 手工询价历史部门补全
  8896. try {
  8897. $poVals = Db::table('purchase_order')
  8898. ->where('CCLBMMC', '<>', '')
  8899. ->whereNotNull('CCLBMMC')
  8900. ->distinct(true)
  8901. ->limit(200)
  8902. ->column('CCLBMMC');
  8903. } catch (\Throwable $e) {
  8904. $poVals = [];
  8905. }
  8906. if (is_array($poVals)) {
  8907. foreach ($poVals as $v) {
  8908. $v = trim((string)$v);
  8909. if ($v === '' || isset($out[$v])) {
  8910. continue;
  8911. }
  8912. $out[$v] = $v;
  8913. }
  8914. }
  8915. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  8916. if (!isset($out[$preset])) {
  8917. $out[$preset] = $preset;
  8918. }
  8919. }
  8920. $list = array_values($out);
  8921. // 常用部门靠前
  8922. usort($list, static function ($a, $b) {
  8923. $weight = [
  8924. '营销中心' => 1,
  8925. '业务部' => 2,
  8926. '市场部' => 3,
  8927. '外贸部' => 4,
  8928. '新华技术业务部' => 5,
  8929. ];
  8930. $wa = $weight[$a] ?? 100;
  8931. $wb = $weight[$b] ?? 100;
  8932. if ($wa !== $wb) {
  8933. return $wa <=> $wb;
  8934. }
  8935. return strcmp((string)$a, (string)$b);
  8936. });
  8937. return $list;
  8938. }
  8939. /**
  8940. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  8941. */
  8942. public function add()
  8943. {
  8944. if ($this->request->isPost()) {
  8945. $params = $this->request->post('row/a');
  8946. if (!is_array($params)) {
  8947. $this->error(__('Parameter %s can not be empty', ''));
  8948. }
  8949. [, $adminName] = $this->GetUseName();
  8950. $params['cywyxm'] = $adminName;
  8951. try {
  8952. $sid = $this->saveManualPickOrder($params);
  8953. } catch (\InvalidArgumentException $e) {
  8954. $this->error($e->getMessage());
  8955. } catch (\Throwable $e) {
  8956. $this->error($e->getMessage());
  8957. }
  8958. $this->success('新增成功', '', [
  8959. 'scydgy_id' => $sid,
  8960. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  8961. ]);
  8962. }
  8963. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8964. [, $adminName] = $this->GetUseName();
  8965. $this->view->assign('adminNickname', $adminName);
  8966. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  8967. $this->view->assign('defaultCclbmmc', '营销中心');
  8968. $this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
  8969. $this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
  8970. $this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
  8971. return $this->view->fetch();
  8972. }
  8973. /**
  8974. * 业务员新增进度查询(手工询价;有查询权限看全部,含手机端新增且未通知业务员的)
  8975. */
  8976. public function rfqlist()
  8977. {
  8978. $this->relationSearch = false;
  8979. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ';
  8980. $this->request->filter(['strip_tags', 'trim']);
  8981. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8982. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8983. $this->ensureRfqSalesmanEmailTemplate();
  8984. $this->ensureRfqSupplierEmailTemplate();
  8985. if ($this->request->isAjax()) {
  8986. try {
  8987. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  8988. $limit = max(10, min(500, (int)$limit));
  8989. $filterYm = trim((string)$this->request->param('filter_ym', ''));
  8990. if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
  8991. $filterYm = date('Y-m');
  8992. }
  8993. $applyFilters = function ($query) use ($where, $filterYm) {
  8994. $query->where('scydgy_id', '<', 0);
  8995. $this->applyPurchaseOrderNotDeletedWhere($query);
  8996. // 查询询价:有菜单权限即可看全部手工单(含手机端新增、尚未通知业务员的)
  8997. $this->applyRfqListMonthFilter($query, $filterYm);
  8998. if (!empty($where)) {
  8999. // 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
  9000. $safeWhere = [];
  9001. $skipFields = [
  9002. 'supplier_name' => true,
  9003. 'progress_text' => true,
  9004. 'createtime_text' => true,
  9005. 'notify_time_text' => true,
  9006. 'can_notify_salesman' => true,
  9007. 'has_issued' => true,
  9008. 'has_quoted' => true,
  9009. ];
  9010. foreach ((array)$where as $cond) {
  9011. if (!is_array($cond) || !isset($cond[0])) {
  9012. continue;
  9013. }
  9014. $field = (string)$cond[0];
  9015. $fieldBase = (string)preg_replace('/\|.*$/', '', $field);
  9016. $fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
  9017. if (isset($skipFields[$fieldBase])) {
  9018. continue;
  9019. }
  9020. if ($fieldBase === 'supplier_name') {
  9021. continue;
  9022. }
  9023. $safeWhere[] = $cond;
  9024. }
  9025. if ($safeWhere !== []) {
  9026. $query->where($safeWhere);
  9027. }
  9028. }
  9029. };
  9030. $countQuery = Db::table('purchase_order');
  9031. $applyFilters($countQuery);
  9032. $total = (int)$countQuery->count();
  9033. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  9034. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  9035. $listQuery = Db::table('purchase_order');
  9036. $applyFilters($listQuery);
  9037. $rows = $listQuery
  9038. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CGYMC,CDW,CDF,This_quantity,ceilingPrice,cGzzxMc,pick_company_name,cywyxm,notify_salesman,rfq_salesman_notified,rfq_salesman_notify_time,MBZ,createtime,dStamp,status,wflow_status')
  9039. ->order($sortField, $orderDir)
  9040. ->limit($offset, $limit)
  9041. ->select();
  9042. if (!is_array($rows)) {
  9043. $rows = [];
  9044. }
  9045. $sidList = [];
  9046. foreach ($rows as $r) {
  9047. if (!is_array($r)) {
  9048. continue;
  9049. }
  9050. $sid = (int)($r['scydgy_id'] ?? 0);
  9051. if ($sid < 0) {
  9052. $sidList[$sid] = true;
  9053. }
  9054. }
  9055. $issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
  9056. $quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
  9057. $out = [];
  9058. foreach ($rows as $r) {
  9059. if (!is_array($r)) {
  9060. continue;
  9061. }
  9062. $sid = (int)($r['scydgy_id'] ?? 0);
  9063. if ($sid >= 0) {
  9064. continue;
  9065. }
  9066. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  9067. if ($createdText === '') {
  9068. $createdText = trim((string)($r['dStamp'] ?? ''));
  9069. }
  9070. $notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
  9071. $supplier = trim((string)($r['cGzzxMc'] ?? ''));
  9072. if ($supplier === '') {
  9073. $supplier = trim((string)($r['pick_company_name'] ?? ''));
  9074. }
  9075. $hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
  9076. || isset($issuedSidSet[$sid]);
  9077. $hasQuoted = isset($quotedSidSet[$sid]);
  9078. $salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
  9079. $canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
  9080. $out[] = [
  9081. 'id' => (int)($r['id'] ?? 0),
  9082. 'scydgy_id' => $sid,
  9083. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  9084. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  9085. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  9086. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  9087. 'CDW' => trim((string)($r['CDW'] ?? '')),
  9088. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  9089. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  9090. 'CDF' => trim((string)($r['CDF'] ?? '')),
  9091. 'supplier_name' => $supplier,
  9092. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  9093. 'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
  9094. 'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
  9095. 'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
  9096. 'notify_time_text' => $notifyTimeText,
  9097. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  9098. 'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
  9099. 'has_issued' => $hasIssued ? 1 : 0,
  9100. 'has_quoted' => $hasQuoted ? 1 : 0,
  9101. 'can_notify_salesman' => $canNotifySalesman,
  9102. 'createtime' => $r['createtime'] ?? null,
  9103. 'createtime_text' => $createdText,
  9104. ];
  9105. }
  9106. return json(['total' => $total, 'rows' => $out]);
  9107. } catch (\Throwable $e) {
  9108. Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
  9109. return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
  9110. }
  9111. }
  9112. $sidebar = $this->loadRfqSidebarYearMonths();
  9113. $defaultYm = $this->resolveRfqListDefaultYm($sidebar);
  9114. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  9115. [, $adminName] = $this->GetUseName();
  9116. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  9117. $this->view->assign('adminNickname', $adminName);
  9118. $this->view->assign('defaultYm', $defaultYm);
  9119. $this->view->assign('sidebarYearMonths', $sidebar);
  9120. return $this->view->fetch('procuremen/rfqlist');
  9121. }
  9122. /**
  9123. * 列表默认月份:当月有数据用当月,否则取最近有数据的月份
  9124. *
  9125. * @param array<int, array{year:string, months:array}> $sidebar
  9126. */
  9127. protected function resolveRfqListDefaultYm(array $sidebar): string
  9128. {
  9129. $current = date('Y-m');
  9130. $yms = $this->flattenProcuremenSidebarYms($sidebar);
  9131. if (in_array($current, $yms, true)) {
  9132. return $current;
  9133. }
  9134. if ($yms !== []) {
  9135. rsort($yms, SORT_STRING);
  9136. return (string)$yms[0];
  9137. }
  9138. return $current;
  9139. }
  9140. /**
  9141. * 手工询价列表左侧月份(按 createtime / dStamp)
  9142. *
  9143. * @return array<int, array{year:string, months:array}>
  9144. */
  9145. protected function loadRfqSidebarYearMonths(): array
  9146. {
  9147. $ymSet = [];
  9148. try {
  9149. $q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
  9150. $this->applyPurchaseOrderNotDeletedWhere($q);
  9151. $rows = $q->field('createtime,dStamp')->limit(5000)->select();
  9152. } catch (\Throwable $e) {
  9153. $rows = [];
  9154. }
  9155. if (!is_array($rows)) {
  9156. $rows = [];
  9157. }
  9158. foreach ($rows as $r) {
  9159. if (!is_array($r)) {
  9160. continue;
  9161. }
  9162. $t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  9163. if ($t === '') {
  9164. $t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
  9165. }
  9166. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  9167. $ymSet[$m[1] . '-' . $m[2]] = true;
  9168. }
  9169. }
  9170. return $this->buildYearMonthSidebar(array_keys($ymSet));
  9171. }
  9172. /**
  9173. * 手工询价可见范围(用于详情/操作校验):
  9174. * 超管、具备「查询询价」权限、需求发起人、通知业务员 → 可见
  9175. * 列表页本身不再按发起人/通知过滤,避免手机端新增后后台看不到。
  9176. */
  9177. protected function applyManualRfqViewerWhere($query): void
  9178. {
  9179. if ($this->auth->isSuperAdmin() || $this->hasProcuremenPerm(['rfqlist'])) {
  9180. return;
  9181. }
  9182. [, $adminName] = $this->GetUseName();
  9183. $adminName = trim((string)$adminName);
  9184. if ($adminName === '') {
  9185. $query->whereRaw('1 = 0');
  9186. return;
  9187. }
  9188. // 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
  9189. $query->where(function ($q) use ($adminName) {
  9190. $q->where('cywyxm', $adminName)
  9191. ->whereOr('notify_salesman', $adminName)
  9192. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  9193. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  9194. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  9195. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  9196. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  9197. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  9198. });
  9199. }
  9200. /**
  9201. * 当前用户是否可查看/操作该手工询价单
  9202. */
  9203. protected function canViewManualRfqOrder(array $po): bool
  9204. {
  9205. if ($this->auth->isSuperAdmin()) {
  9206. return true;
  9207. }
  9208. // 有查询询价权限则可操作全部手工询价(询价/查看报价/通知业务员等)
  9209. if ($this->hasProcuremenPerm(['rfqlist'])) {
  9210. return true;
  9211. }
  9212. [, $adminName] = $this->GetUseName();
  9213. $adminName = trim((string)$adminName);
  9214. if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
  9215. return true;
  9216. }
  9217. if ($adminName !== '') {
  9218. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  9219. if ($n === $adminName) {
  9220. return true;
  9221. }
  9222. }
  9223. }
  9224. return false;
  9225. }
  9226. /**
  9227. * 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
  9228. */
  9229. protected function applyRfqListMonthFilter($query, string $ym): void
  9230. {
  9231. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  9232. $ym = date('Y-m');
  9233. }
  9234. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  9235. // 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
  9236. $query->whereRaw(
  9237. "("
  9238. . "CASE "
  9239. . "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  9240. . "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
  9241. . "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
  9242. . "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  9243. . "THEN TRIM(CAST(createtime AS CHAR(32))) "
  9244. . "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
  9245. . "END"
  9246. . ") LIKE '{$ymEsc}-%'"
  9247. );
  9248. }
  9249. /**
  9250. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  9251. */
  9252. public function rfqlistDetails()
  9253. {
  9254. return $this->details();
  9255. }
  9256. /**
  9257. * 查询询价 — 弹窗:可选通知业务员名单(勾选后确认通知)
  9258. */
  9259. public function rfqnotifysalesmen()
  9260. {
  9261. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman'])) {
  9262. $this->error(__('You have no permission'));
  9263. }
  9264. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9265. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  9266. $sid = (int)$this->request->param('scydgy_id', 0);
  9267. if ($sid >= 0) {
  9268. $this->error('仅支持手工新增询价单');
  9269. }
  9270. $po = $this->loadManualRfqOrderForNotify($sid);
  9271. $selectedMap = [];
  9272. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  9273. $selectedMap[$n] = true;
  9274. }
  9275. $list = [];
  9276. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  9277. $name = trim((string)($row['name'] ?? ''));
  9278. if ($name === '') {
  9279. continue;
  9280. }
  9281. $email = trim((string)($row['email'] ?? ''));
  9282. $mobile = trim((string)($row['mobile'] ?? ''));
  9283. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  9284. $list[] = [
  9285. 'name' => $name,
  9286. 'email' => $email,
  9287. 'mobile' => $mobile,
  9288. 'can_select' => $hasEmail ? 1 : 0,
  9289. 'checked' => (!empty($selectedMap[$name]) && $hasEmail) ? 1 : 0,
  9290. ];
  9291. }
  9292. $canNotify = $this->canRfqNotifySalesman($po);
  9293. $this->success('', null, [
  9294. 'scydgy_id' => $sid,
  9295. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9296. 'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
  9297. 'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
  9298. 'can_notify_salesman' => $canNotify ? 1 : 0,
  9299. 'list' => $list,
  9300. ]);
  9301. }
  9302. /**
  9303. * 查询询价 — 补加通知业务员可选名单
  9304. */
  9305. public function rfqsalesmanoptions()
  9306. {
  9307. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen'])) {
  9308. $this->error(__('You have no permission'));
  9309. }
  9310. $out = [];
  9311. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  9312. $email = trim((string)($row['email'] ?? ''));
  9313. $mobile = trim((string)($row['mobile'] ?? ''));
  9314. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  9315. $out[] = [
  9316. 'name' => (string)($row['name'] ?? ''),
  9317. 'email' => $email,
  9318. 'mobile' => $mobile,
  9319. 'can_select' => $hasEmail ? 1 : 0,
  9320. ];
  9321. }
  9322. $this->success('', null, ['list' => $out]);
  9323. }
  9324. /**
  9325. * 查询询价 — 补加通知业务员(合并更新 notify_salesman)
  9326. */
  9327. public function rfqappendsalesmen()
  9328. {
  9329. if (!$this->request->isPost()) {
  9330. $this->error(__('Invalid parameters'));
  9331. }
  9332. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen'])) {
  9333. $this->error(__('You have no permission'));
  9334. }
  9335. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9336. $sid = (int)$this->request->post('scydgy_id', 0);
  9337. if ($sid >= 0) {
  9338. $this->error('仅支持手工新增询价单');
  9339. }
  9340. $po = $this->loadManualRfqOrderForNotify($sid);
  9341. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9342. $this->error('订单已完结,无法添加业务员');
  9343. }
  9344. $raw = $this->request->post('salesmen/a', []);
  9345. if (!is_array($raw) || $raw === []) {
  9346. $salesmenJson = $this->request->post('salesmen_json', '');
  9347. if (is_string($salesmenJson) && $salesmenJson !== '') {
  9348. $decoded = json_decode($salesmenJson, true);
  9349. $raw = is_array($decoded) ? $decoded : [];
  9350. }
  9351. }
  9352. $addNames = [];
  9353. foreach ((array)$raw as $item) {
  9354. if (is_array($item)) {
  9355. $n = trim((string)($item['name'] ?? ''));
  9356. } else {
  9357. $n = trim((string)$item);
  9358. }
  9359. if ($n !== '') {
  9360. $addNames[] = $n;
  9361. }
  9362. }
  9363. $addNames = array_values(array_unique($addNames));
  9364. if ($addNames === []) {
  9365. $this->error('请选择要添加的业务员');
  9366. }
  9367. $allowedOptions = $this->loadRfqSalesmanContactOptions();
  9368. $allowedMap = [];
  9369. foreach ($allowedOptions as $opt) {
  9370. $n = trim((string)($opt['name'] ?? ''));
  9371. if ($n === '') {
  9372. continue;
  9373. }
  9374. $email = trim((string)($opt['email'] ?? ''));
  9375. $allowedMap[$n] = ($email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL));
  9376. }
  9377. foreach ($addNames as $n) {
  9378. if (!array_key_exists($n, $allowedMap)) {
  9379. $this->error('业务员不在可选名单中:' . $n);
  9380. }
  9381. if (!$allowedMap[$n]) {
  9382. $this->error('业务员未填写有效邮箱,无法添加:' . $n);
  9383. }
  9384. }
  9385. $existingRaw = trim((string)($po['notify_salesman'] ?? ''));
  9386. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9387. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9388. try {
  9389. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['notify_salesman' => $mergedStr]);
  9390. } catch (\Throwable $e) {
  9391. $this->error('保存失败:' . $e->getMessage());
  9392. }
  9393. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9394. $this->addOrderLog($sid, 'rfq_append_salesman', '添加通知业务员:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9395. $this->success('已添加业务员', null, [
  9396. 'scydgy_id' => $sid,
  9397. 'notify_salesman' => $mergedStr,
  9398. 'added_count' => count($addNames),
  9399. ]);
  9400. }
  9401. /**
  9402. * 查询询价 — 勾选业务员后邮箱通知(salesmen_json)
  9403. */
  9404. public function rfqnotifysalesman()
  9405. {
  9406. if (!$this->request->isPost()) {
  9407. $this->error(__('Invalid parameters'));
  9408. }
  9409. if (!$this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen'])) {
  9410. $this->error(__('You have no permission'));
  9411. }
  9412. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9413. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  9414. $sid = (int)$this->request->post('scydgy_id', 0);
  9415. if ($sid >= 0) {
  9416. $this->error('仅支持手工新增询价单');
  9417. }
  9418. $po = $this->loadManualRfqOrderForNotify($sid);
  9419. $this->assertRfqCanNotifySalesman($po);
  9420. $raw = $this->request->post('salesmen/a', []);
  9421. if (!is_array($raw) || $raw === []) {
  9422. $salesmenJson = $this->request->post('salesmen_json', '');
  9423. if (is_string($salesmenJson) && $salesmenJson !== '') {
  9424. $decoded = json_decode($salesmenJson, true);
  9425. $raw = is_array($decoded) ? $decoded : [];
  9426. }
  9427. }
  9428. // 兼容旧参数:notify_all / 单人 name
  9429. if ((!is_array($raw) || $raw === []) && (int)$this->request->post('notify_all', 0) === 1) {
  9430. $raw = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  9431. }
  9432. if ((!is_array($raw) || $raw === [])) {
  9433. $oneName = trim((string)$this->request->post('name', ''));
  9434. if ($oneName !== '') {
  9435. $raw = [$oneName];
  9436. }
  9437. }
  9438. $selectedNames = [];
  9439. foreach ((array)$raw as $item) {
  9440. if (is_array($item)) {
  9441. $n = trim((string)($item['name'] ?? ''));
  9442. } else {
  9443. $n = trim((string)$item);
  9444. }
  9445. if ($n !== '') {
  9446. $selectedNames[] = $n;
  9447. }
  9448. }
  9449. $selectedNames = array_values(array_unique($selectedNames));
  9450. if ($selectedNames === []) {
  9451. $this->error('请选择要通知的业务员');
  9452. }
  9453. $optionMap = [];
  9454. foreach ($this->loadRfqSalesmanContactOptions() as $opt) {
  9455. $n = trim((string)($opt['name'] ?? ''));
  9456. if ($n === '') {
  9457. continue;
  9458. }
  9459. $optionMap[$n] = $opt;
  9460. }
  9461. $targets = [];
  9462. foreach ($selectedNames as $n) {
  9463. if (!isset($optionMap[$n])) {
  9464. $this->error('业务员不在可选名单中:' . $n);
  9465. }
  9466. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  9467. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9468. $this->error('业务员未填写有效邮箱,无法通知:' . $n);
  9469. }
  9470. $resolved = $this->resolveRfqSalesmanContactRows([$n]);
  9471. $targets[] = $resolved[0] ?? [
  9472. 'admin_id' => 0,
  9473. 'name' => $n,
  9474. 'email' => $email,
  9475. ];
  9476. }
  9477. $mergedStr = $this->joinRfqMultiSelectValues($selectedNames);
  9478. try {
  9479. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  9480. 'notify_salesman' => $mergedStr,
  9481. ]);
  9482. } catch (\Throwable $e) {
  9483. $this->error('保存通知业务员失败:' . $e->getMessage());
  9484. }
  9485. $po['notify_salesman'] = $mergedStr;
  9486. $mailConfig = $this->loadMailerConfig();
  9487. if (empty($mailConfig['host'])) {
  9488. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9489. }
  9490. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9491. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9492. }
  9493. $this->ensureRfqSalesmanEmailTemplate();
  9494. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  9495. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  9496. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  9497. $cdw = trim((string)($po['CDW'] ?? ''));
  9498. $qty = trim((string)$this->resolveProcuremenThisQuantity($po));
  9499. $ceiling = trim((string)$this->resolveProcuremenCeilingPrice($po));
  9500. $mbz = trim((string)($po['MBZ'] ?? ''));
  9501. $cywyxm = trim((string)($po['cywyxm'] ?? ''));
  9502. $supplier = trim((string)($po['cGzzxMc'] ?? ''));
  9503. if ($supplier === '') {
  9504. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  9505. }
  9506. $supplierQuotesHtml = $this->buildRfqSalesmanSupplierQuotesHtml($sid, $supplier);
  9507. try {
  9508. $platformUrl = $this->buildMprocMobileRfqAddUrl($sid, 'pending');
  9509. } catch (\Throwable $e) {
  9510. $platformUrl = '';
  9511. }
  9512. try {
  9513. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
  9514. } catch (\Throwable $e) {
  9515. $this->error($e->getMessage());
  9516. }
  9517. $okNames = [];
  9518. $failMsgs = [];
  9519. foreach ($targets as $contact) {
  9520. $toEmail = trim((string)($contact['email'] ?? ''));
  9521. $toName = trim((string)($contact['name'] ?? ''));
  9522. $notifyVars = [
  9523. 'contact_name' => $toName,
  9524. 'salesman_name' => $toName,
  9525. 'company_name' => $toName,
  9526. 'email' => $toEmail,
  9527. 'ccydh' => $ccydh,
  9528. 'cyjmc' => $cyjmc,
  9529. 'cgymc' => $cgymc,
  9530. 'cdw' => $cdw,
  9531. 'this_quantity' => $qty,
  9532. 'ceilingPrice' => $ceiling,
  9533. 'MBZ' => $mbz,
  9534. 'supplier_name' => $supplier,
  9535. // 占位符,转 HTML 后再替换成表格,避免被 htmlspecialchars 转义
  9536. 'supplier_quotes' => '__RFQ_SUPPLIER_QUOTES_TABLE__',
  9537. 'cywyxm' => $cywyxm,
  9538. 'platform_url' => $platformUrl,
  9539. ];
  9540. try {
  9541. $mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
  9542. $mailSubject = $mailSubjectTpl;
  9543. foreach ($notifyVars as $k => $v) {
  9544. if ($k === 'supplier_quotes') {
  9545. continue;
  9546. }
  9547. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  9548. }
  9549. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  9550. $mailSubject = trim((string)$mailSubject);
  9551. if ($mailSubject === '') {
  9552. $mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  9553. }
  9554. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  9555. $mailBody = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', $supplierQuotesHtml, $mailBody);
  9556. $mailPlainForLog = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', strip_tags(str_replace(['</tr>', '</p>'], "\n", $supplierQuotesHtml)), $mailPlain);
  9557. $bundle = [
  9558. 'company_name' => $toName,
  9559. 'email' => $toEmail,
  9560. 'mail_plain' => $mailPlainForLog,
  9561. 'mail_body' => $mailBody,
  9562. 'ccydh' => $ccydh,
  9563. 'email_log_scene' => 'rfq_salesman',
  9564. 'email_log_scydgy_id' => $sid,
  9565. 'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
  9566. 'notify_vars' => $notifyVars,
  9567. ];
  9568. $this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
  9569. $okNames[] = $toName . '(' . $toEmail . ')';
  9570. } catch (\Throwable $e) {
  9571. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  9572. }
  9573. }
  9574. if ($okNames === []) {
  9575. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  9576. }
  9577. $now = date('Y-m-d H:i:s');
  9578. try {
  9579. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  9580. 'rfq_salesman_notified' => 1,
  9581. 'rfq_salesman_notify_time' => $now,
  9582. ]);
  9583. } catch (\Throwable $e) {
  9584. // ignore
  9585. }
  9586. $this->addOrderLog(
  9587. $sid,
  9588. 'rfq_notify_salesman',
  9589. '邮箱通知业务员:' . implode('、', $okNames),
  9590. (int)($po['id'] ?? 0)
  9591. );
  9592. $msg = '已通知 ' . count($okNames) . ' 人';
  9593. if ($failMsgs !== []) {
  9594. $msg .= ';部分失败:' . implode(';', $failMsgs);
  9595. }
  9596. $this->success($msg, null, [
  9597. 'scydgy_id' => $sid,
  9598. 'notify_salesman' => $mergedStr,
  9599. 'rfq_salesman_notified' => 1,
  9600. 'rfq_salesman_notify_time' => $now,
  9601. 'notify_time_text' => $now,
  9602. 'ok_count' => count($okNames),
  9603. 'fail_count' => count($failMsgs),
  9604. ]);
  9605. }
  9606. /**
  9607. * 查询询价 — 下发前:返回将通知的供应商表格数据
  9608. */
  9609. public function rfqissuesuppliers()
  9610. {
  9611. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers'])) {
  9612. $this->error(__('You have no permission'));
  9613. }
  9614. $sid = (int)$this->request->param('scydgy_id', 0);
  9615. if ($sid >= 0) {
  9616. $this->error('仅支持手工新增询价单');
  9617. }
  9618. $po = $this->loadManualRfqOrderForNotify($sid);
  9619. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9620. if ($supplierRaw === '') {
  9621. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9622. }
  9623. $names = $this->splitRfqSalesmanNames($supplierRaw);
  9624. // 已成功发过询价邮件的供应商(含历史 pick_issue 场景)
  9625. $notifiedMap = [];
  9626. try {
  9627. $this->ensurePurchaseEmailSendLogTableOnce();
  9628. $logRows = Db::table('purchase_email_send_log')
  9629. ->where('scydgy_id', $sid)
  9630. ->where('status', 1)
  9631. ->where('scene', 'in', ['rfq_supplier', 'pick_issue'])
  9632. ->field('company_name')
  9633. ->select();
  9634. if (is_array($logRows)) {
  9635. foreach ($logRows as $lr) {
  9636. if (!is_array($lr)) {
  9637. continue;
  9638. }
  9639. $cn = trim((string)($lr['company_name'] ?? ''));
  9640. if ($cn !== '') {
  9641. $notifiedMap[$cn] = true;
  9642. }
  9643. }
  9644. }
  9645. } catch (\Throwable $e) {
  9646. }
  9647. // 兼容:明细已生成(曾下发)也视为已通知
  9648. try {
  9649. $detRows = Db::table('purchase_order_detail')
  9650. ->where('scydgy_id', $sid)
  9651. ->field('company_name')
  9652. ->select();
  9653. if (is_array($detRows)) {
  9654. foreach ($detRows as $dr) {
  9655. if (!is_array($dr)) {
  9656. continue;
  9657. }
  9658. $cn = trim((string)($dr['company_name'] ?? ''));
  9659. if ($cn !== '') {
  9660. $notifiedMap[$cn] = true;
  9661. }
  9662. }
  9663. }
  9664. } catch (\Throwable $e) {
  9665. }
  9666. $list = [];
  9667. foreach ($names as $name) {
  9668. // 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
  9669. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9670. $email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
  9671. $phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
  9672. $username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
  9673. $okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
  9674. $notified = !empty($notifiedMap[$name]) ? 1 : 0;
  9675. $list[] = [
  9676. 'name' => $name,
  9677. 'username' => $username,
  9678. 'email' => $email,
  9679. 'phone' => $phone,
  9680. 'can_notify' => $okEmail ? 1 : 0,
  9681. 'found' => is_array($contact) ? 1 : 0,
  9682. 'notified' => $notified,
  9683. 'notify_status_text' => $notified ? '已通知' : '未通知',
  9684. ];
  9685. }
  9686. $this->success('', null, [
  9687. 'scydgy_id' => $sid,
  9688. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9689. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9690. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9691. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9692. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9693. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9694. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9695. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9696. 'list' => $list,
  9697. ]);
  9698. }
  9699. /**
  9700. * 查询询价 — 补加供应商可选名单
  9701. */
  9702. public function rfqsupplieroptions()
  9703. {
  9704. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
  9705. $this->error(__('You have no permission'));
  9706. }
  9707. $names = array_values($this->loadRfqSupplierNameOptions());
  9708. $out = [];
  9709. foreach ($names as $name) {
  9710. $out[] = ['name' => $name];
  9711. }
  9712. $this->success('', null, ['list' => $out]);
  9713. }
  9714. /**
  9715. * 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
  9716. */
  9717. public function rfqappendsuppliers()
  9718. {
  9719. if (!$this->request->isPost()) {
  9720. $this->error(__('Invalid parameters'));
  9721. }
  9722. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers'])) {
  9723. $this->error(__('You have no permission'));
  9724. }
  9725. $sid = (int)$this->request->post('scydgy_id', 0);
  9726. if ($sid >= 0) {
  9727. $this->error('仅支持手工新增询价单');
  9728. }
  9729. $po = $this->loadManualRfqOrderForNotify($sid);
  9730. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9731. $this->error('订单已完结,无法补加供应商');
  9732. }
  9733. $raw = $this->request->post('suppliers/a', []);
  9734. if (!is_array($raw) || $raw === []) {
  9735. $suppliersJson = $this->request->post('suppliers_json', '');
  9736. if (is_string($suppliersJson) && $suppliersJson !== '') {
  9737. $decoded = json_decode($suppliersJson, true);
  9738. $raw = is_array($decoded) ? $decoded : [];
  9739. }
  9740. }
  9741. $addNames = [];
  9742. foreach ((array)$raw as $item) {
  9743. if (is_array($item)) {
  9744. $n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
  9745. } else {
  9746. $n = trim((string)$item);
  9747. }
  9748. if ($n !== '') {
  9749. $addNames[] = $n;
  9750. }
  9751. }
  9752. $addNames = array_values(array_unique($addNames));
  9753. if ($addNames === []) {
  9754. $this->error('请选择要补加的供应商');
  9755. }
  9756. $existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9757. if ($existingRaw === '') {
  9758. $existingRaw = trim((string)($po['pick_company_name'] ?? ''));
  9759. }
  9760. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9761. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9762. try {
  9763. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
  9764. } catch (\Throwable $e) {
  9765. $this->error('保存失败:' . $e->getMessage());
  9766. }
  9767. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9768. $this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9769. $this->success('已补加供应商', null, [
  9770. 'scydgy_id' => $sid,
  9771. 'cGzzxMc' => $mergedStr,
  9772. 'added_count' => count($addNames),
  9773. ]);
  9774. }
  9775. /**
  9776. * 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
  9777. */
  9778. public function rfqissue()
  9779. {
  9780. if (!$this->request->isPost()) {
  9781. $this->error(__('Invalid parameters'));
  9782. }
  9783. if (!$this->hasProcuremenPerm(['rfqissue'])) {
  9784. $this->error(__('You have no permission'));
  9785. }
  9786. $this->ensureRfqSupplierEmailTemplate();
  9787. $sid = (int)$this->request->post('scydgy_id', 0);
  9788. if ($sid >= 0) {
  9789. $this->error('仅支持手工新增询价单');
  9790. }
  9791. $po = $this->loadManualRfqOrderForNotify($sid);
  9792. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9793. $this->error('订单已完结,无法下发');
  9794. }
  9795. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9796. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9797. $this->error('订单已进入后续流程,无法再下发');
  9798. }
  9799. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9800. if ($supplierRaw === '') {
  9801. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9802. }
  9803. $supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
  9804. if ($supplierNames === []) {
  9805. $this->error('请先在新增询价时选择供应商');
  9806. }
  9807. $companies = [];
  9808. $missing = [];
  9809. $noEmail = [];
  9810. foreach ($supplierNames as $name) {
  9811. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9812. if ($contact === null) {
  9813. $missing[] = $name;
  9814. continue;
  9815. }
  9816. $em = trim((string)($contact['email'] ?? ''));
  9817. if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
  9818. $noEmail[] = $name;
  9819. continue;
  9820. }
  9821. $companies[] = $contact;
  9822. }
  9823. if ($missing !== []) {
  9824. $this->error('未找到供应商档案:' . implode('、', $missing));
  9825. }
  9826. if ($noEmail !== []) {
  9827. $this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
  9828. }
  9829. if ($companies === []) {
  9830. $this->error('没有可通知的供应商');
  9831. }
  9832. $mailConfig = $this->loadMailerConfig();
  9833. if (empty($mailConfig['host'])) {
  9834. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9835. }
  9836. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9837. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9838. }
  9839. $mergeRow = $po;
  9840. $mergeRow['ID'] = $sid;
  9841. $mergeRow['id'] = $sid;
  9842. $mergeRows = [$mergeRow];
  9843. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9844. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9845. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9846. }
  9847. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9848. $issueTime = date('Y-m-d H:i:s');
  9849. $nameLabels = [];
  9850. foreach ($companies as $c) {
  9851. $nameLabels[] = trim((string)($c['name'] ?? ''));
  9852. }
  9853. $logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
  9854. Db::startTrans();
  9855. try {
  9856. $this->upsertPurchaseOrderFromRow(
  9857. $mergeRow,
  9858. $sysRqDb,
  9859. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9860. $issueTime,
  9861. $po,
  9862. null,
  9863. $scoreRule
  9864. );
  9865. foreach ($companies as $c) {
  9866. $this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
  9867. }
  9868. Db::commit();
  9869. } catch (\Throwable $e) {
  9870. Db::rollback();
  9871. $this->error($e->getMessage());
  9872. }
  9873. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9874. if ($poId <= 0) {
  9875. try {
  9876. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9877. } catch (\Throwable $e) {
  9878. $poId = 0;
  9879. }
  9880. }
  9881. $this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
  9882. $posNotify = [];
  9883. try {
  9884. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9885. if (is_array($fresh)) {
  9886. $fresh['sys_rq'] = $sysRqDb;
  9887. $posNotify = [$fresh];
  9888. }
  9889. } catch (\Throwable $e) {
  9890. $posNotify = [$po];
  9891. $posNotify[0]['sys_rq'] = $sysRqDb;
  9892. }
  9893. $notifyBundle = [
  9894. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9895. 'pos' => $posNotify,
  9896. 'merge_rows' => $mergeRows,
  9897. ];
  9898. $notifyErrors = [];
  9899. foreach ($companies as $c) {
  9900. $cname = trim((string)($c['name'] ?? ''));
  9901. try {
  9902. // 询价下发:仅邮箱通知供应商
  9903. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  9904. } catch (\Throwable $e) {
  9905. $notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
  9906. }
  9907. }
  9908. if ($notifyErrors !== []) {
  9909. $this->error('下发已保存,但邮件通知失败:' . implode(';', $notifyErrors));
  9910. }
  9911. $this->success('已询价并邮件通知供应商', null, [
  9912. 'scydgy_id' => $sid,
  9913. 'progress_text' => '待报价',
  9914. 'supplier_count' => count($companies),
  9915. ]);
  9916. }
  9917. /**
  9918. * 查询询价 — 弹窗内向单个供应商发送询价邮件
  9919. */
  9920. public function rfqissuesendmail()
  9921. {
  9922. if (!$this->request->isPost()) {
  9923. $this->error(__('Invalid parameters'));
  9924. }
  9925. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail'])) {
  9926. $this->error(__('You have no permission'));
  9927. }
  9928. $this->ensureRfqSupplierEmailTemplate();
  9929. $sid = (int)$this->request->post('scydgy_id', 0);
  9930. $companyName = trim((string)$this->request->post('company_name', ''));
  9931. if ($sid >= 0) {
  9932. $this->error('仅支持手工新增询价单');
  9933. }
  9934. if ($companyName === '') {
  9935. $this->error('请选择供应商');
  9936. }
  9937. $po = $this->loadManualRfqOrderForNotify($sid);
  9938. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9939. $this->error('订单已完结,无法发送');
  9940. }
  9941. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9942. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9943. $this->error('订单已进入后续流程,无法再发送');
  9944. }
  9945. $contact = $this->resolveCustomerContactByCompanyName($companyName, false);
  9946. if ($contact === null) {
  9947. $this->error('未找到供应商档案:' . $companyName);
  9948. }
  9949. $email = trim((string)($contact['email'] ?? ''));
  9950. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9951. $this->error('该供应商未填写有效邮箱');
  9952. }
  9953. $mailConfig = $this->loadMailerConfig();
  9954. if (empty($mailConfig['host'])) {
  9955. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9956. }
  9957. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9958. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9959. }
  9960. $mergeRow = $po;
  9961. $mergeRow['ID'] = $sid;
  9962. $mergeRow['id'] = $sid;
  9963. $mergeRows = [$mergeRow];
  9964. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9965. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9966. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9967. }
  9968. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9969. $issueTime = date('Y-m-d H:i:s');
  9970. Db::startTrans();
  9971. try {
  9972. $this->upsertPurchaseOrderFromRow(
  9973. $mergeRow,
  9974. $sysRqDb,
  9975. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9976. $issueTime,
  9977. $po,
  9978. null,
  9979. $scoreRule
  9980. );
  9981. $this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
  9982. Db::commit();
  9983. } catch (\Throwable $e) {
  9984. Db::rollback();
  9985. $this->error($e->getMessage());
  9986. }
  9987. $posNotify = [];
  9988. try {
  9989. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9990. if (is_array($fresh)) {
  9991. $fresh['sys_rq'] = $sysRqDb;
  9992. $posNotify = [$fresh];
  9993. }
  9994. } catch (\Throwable $e) {
  9995. $posNotify = [$po];
  9996. $posNotify[0]['sys_rq'] = $sysRqDb;
  9997. }
  9998. $notifyBundle = [
  9999. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  10000. 'pos' => $posNotify,
  10001. 'merge_rows' => $mergeRows,
  10002. ];
  10003. try {
  10004. $this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  10005. } catch (\Throwable $e) {
  10006. $this->error('明细已保存,但邮件发送失败:' . $e->getMessage());
  10007. }
  10008. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  10009. if ($poId <= 0) {
  10010. try {
  10011. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  10012. } catch (\Throwable $e) {
  10013. $poId = 0;
  10014. }
  10015. }
  10016. $this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
  10017. $this->success('已向「' . $companyName . '」发送询价邮件', null, [
  10018. 'scydgy_id' => $sid,
  10019. 'company_name' => $companyName,
  10020. ]);
  10021. }
  10022. /**
  10023. * 查询询价 — 查看各供应商报价(单价)
  10024. */
  10025. public function rfqquotes()
  10026. {
  10027. if (!$this->hasProcuremenPerm(['rfqquotes', 'rfqissue'])) {
  10028. $this->error(__('You have no permission'));
  10029. }
  10030. $sid = (int)$this->request->param('scydgy_id', 0);
  10031. if ($sid >= 0) {
  10032. $this->error('仅支持手工新增询价单');
  10033. }
  10034. $po = $this->loadManualRfqOrderForNotify($sid);
  10035. $rows = [];
  10036. try {
  10037. // 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
  10038. $q = Db::table('purchase_order_detail')
  10039. ->where('scydgy_id', $sid)
  10040. ->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
  10041. ->order('id', 'asc');
  10042. $this->applyActivePurchaseOrderDetailWhere($q);
  10043. $rows = $q->select();
  10044. } catch (\Throwable $e) {
  10045. try {
  10046. $q = Db::table('purchase_order_detail')
  10047. ->where('scydgy_id', $sid)
  10048. ->order('id', 'asc');
  10049. $this->applyActivePurchaseOrderDetailWhere($q);
  10050. $rows = $q->select();
  10051. } catch (\Throwable $e2) {
  10052. $rows = [];
  10053. }
  10054. }
  10055. if (!is_array($rows)) {
  10056. $rows = [];
  10057. }
  10058. $list = [];
  10059. foreach ($rows as $row) {
  10060. if (!is_array($row)) {
  10061. continue;
  10062. }
  10063. $amount = trim((string)($row['amount'] ?? ''));
  10064. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  10065. // 未报价不显示时间(createtime 是下发时间,不是报价时间)
  10066. $oper = '';
  10067. if ($isQuoted) {
  10068. $oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
  10069. if ($oper === '') {
  10070. $oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  10071. }
  10072. }
  10073. $list[] = [
  10074. 'id' => (int)($row['id'] ?? 0),
  10075. 'company_name' => trim((string)($row['company_name'] ?? '')),
  10076. 'amount' => $amount,
  10077. 'amount_text' => $isQuoted ? $amount : '',
  10078. 'is_quoted' => $isQuoted,
  10079. 'quote_label' => $isQuoted ? '已报价' : '未报价',
  10080. 'status_name' => trim((string)($row['status_name'] ?? '')),
  10081. 'oper_time' => $oper,
  10082. ];
  10083. }
  10084. $this->success('', null, [
  10085. 'scydgy_id' => $sid,
  10086. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  10087. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  10088. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  10089. 'CDW' => trim((string)($po['CDW'] ?? '')),
  10090. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  10091. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  10092. 'CDF' => trim((string)($po['CDF'] ?? '')),
  10093. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  10094. 'list' => $list,
  10095. ]);
  10096. }
  10097. /**
  10098. * 手工询价是否已下发(有下发明细或已进入待确认及之后)
  10099. */
  10100. protected function isRfqOrderIssued(array $po): bool
  10101. {
  10102. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  10103. return true;
  10104. }
  10105. $sid = (int)($po['scydgy_id'] ?? 0);
  10106. if ($sid >= 0) {
  10107. return false;
  10108. }
  10109. try {
  10110. $q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  10111. $this->applyActivePurchaseOrderDetailWhere($q);
  10112. return (int)$q->count() > 0;
  10113. } catch (\Throwable $e) {
  10114. return false;
  10115. }
  10116. }
  10117. /**
  10118. * 批量:已有下发明细的手工询价 scydgy_id
  10119. *
  10120. * @param int[] $scydgyIds
  10121. * @return array<int, bool>
  10122. */
  10123. protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
  10124. {
  10125. $set = [];
  10126. $ids = [];
  10127. foreach ($scydgyIds as $sid) {
  10128. $sid = (int)$sid;
  10129. if ($sid < 0) {
  10130. $ids[$sid] = true;
  10131. }
  10132. }
  10133. if ($ids === []) {
  10134. return $set;
  10135. }
  10136. try {
  10137. $q = Db::table('purchase_order_detail')
  10138. ->where('scydgy_id', 'in', array_keys($ids))
  10139. ->field('scydgy_id');
  10140. $this->applyActivePurchaseOrderDetailWhere($q);
  10141. $rows = $q->select();
  10142. } catch (\Throwable $e) {
  10143. return $set;
  10144. }
  10145. if (!is_array($rows)) {
  10146. return $set;
  10147. }
  10148. foreach ($rows as $row) {
  10149. if (!is_array($row)) {
  10150. continue;
  10151. }
  10152. $sid = (int)($row['scydgy_id'] ?? 0);
  10153. if ($sid < 0) {
  10154. $set[$sid] = true;
  10155. }
  10156. }
  10157. return $set;
  10158. }
  10159. /**
  10160. * 批量:已填单价(已报价)的手工询价 scydgy_id
  10161. *
  10162. * @param int[] $scydgyIds
  10163. * @return array<int, bool>
  10164. */
  10165. protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
  10166. {
  10167. $set = [];
  10168. $ids = [];
  10169. foreach ($scydgyIds as $sid) {
  10170. $sid = (int)$sid;
  10171. if ($sid < 0) {
  10172. $ids[$sid] = true;
  10173. }
  10174. }
  10175. if ($ids === []) {
  10176. return $set;
  10177. }
  10178. try {
  10179. $q = Db::table('purchase_order_detail')
  10180. ->where('scydgy_id', 'in', array_keys($ids))
  10181. ->field('scydgy_id,amount');
  10182. $this->applyActivePurchaseOrderDetailWhere($q);
  10183. $rows = $q->select();
  10184. } catch (\Throwable $e) {
  10185. return $set;
  10186. }
  10187. if (!is_array($rows)) {
  10188. return $set;
  10189. }
  10190. foreach ($rows as $row) {
  10191. if (!is_array($row)) {
  10192. continue;
  10193. }
  10194. $amount = trim((string)($row['amount'] ?? ''));
  10195. if ($amount === '' || $amount === '0' || $amount === '0.00') {
  10196. continue;
  10197. }
  10198. $sid = (int)($row['scydgy_id'] ?? 0);
  10199. if ($sid < 0) {
  10200. $set[$sid] = true;
  10201. }
  10202. }
  10203. return $set;
  10204. }
  10205. /**
  10206. * 已下发且至少一家供应商已报价,才允许通知业务员
  10207. */
  10208. protected function canRfqNotifySalesman(array $po): bool
  10209. {
  10210. if (!$this->isRfqOrderIssued($po)) {
  10211. return false;
  10212. }
  10213. $sid = (int)($po['scydgy_id'] ?? 0);
  10214. if ($sid >= 0) {
  10215. return false;
  10216. }
  10217. $quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
  10218. return isset($quoted[$sid]);
  10219. }
  10220. protected function assertRfqCanNotifySalesman(array $po): void
  10221. {
  10222. if (!$this->isRfqOrderIssued($po)) {
  10223. $this->error('请先询价并等待供应商报价后再通知业务员');
  10224. }
  10225. if (!$this->canRfqNotifySalesman($po)) {
  10226. $this->error('供应商尚未报价,暂不能通知业务员');
  10227. }
  10228. }
  10229. /**
  10230. * 加载手工询价单(含可见性校验)
  10231. *
  10232. * @return array<string, mixed>
  10233. */
  10234. protected function loadManualRfqOrderForNotify(int $scydgyId): array
  10235. {
  10236. try {
  10237. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10238. } catch (\Throwable $e) {
  10239. $po = null;
  10240. }
  10241. if (!is_array($po)) {
  10242. $this->error('订单不存在');
  10243. }
  10244. $modRq = trim((string)($po['mod_rq'] ?? ''));
  10245. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  10246. $this->error('订单不存在');
  10247. }
  10248. if ($this->auth->isSuperAdmin()) {
  10249. return $po;
  10250. }
  10251. if ($this->canViewManualRfqOrder($po)) {
  10252. return $po;
  10253. }
  10254. $this->error('无权操作该订单');
  10255. }
  10256. /**
  10257. * @return string[]
  10258. */
  10259. protected function splitRfqSalesmanNames(string $raw): array
  10260. {
  10261. $parts = [];
  10262. $raw = trim($raw);
  10263. if ($raw === '') {
  10264. return [];
  10265. }
  10266. foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
  10267. $v = trim((string)$piece);
  10268. if ($v !== '' && !in_array($v, $parts, true)) {
  10269. $parts[] = $v;
  10270. }
  10271. }
  10272. return $parts;
  10273. }
  10274. /**
  10275. * 按姓名匹配 fa_admin 邮箱
  10276. *
  10277. * @param string[] $names
  10278. * @return array<int, array{admin_id:int,name:string,email:string}>
  10279. */
  10280. protected function resolveRfqSalesmanContactRows(array $names): array
  10281. {
  10282. $out = [];
  10283. foreach ($names as $name) {
  10284. $name = trim((string)$name);
  10285. if ($name === '') {
  10286. continue;
  10287. }
  10288. $adminId = 0;
  10289. $email = '';
  10290. try {
  10291. $row = Db::name('admin')
  10292. ->where(function ($q) use ($name) {
  10293. $q->where('nickname', $name)->whereOr('username', $name);
  10294. })
  10295. ->where('status', 'normal')
  10296. ->order('id', 'asc')
  10297. ->field('id,nickname,username,email')
  10298. ->find();
  10299. } catch (\Throwable $e) {
  10300. $row = null;
  10301. }
  10302. if (is_array($row)) {
  10303. $adminId = (int)($row['id'] ?? 0);
  10304. $email = trim((string)($row['email'] ?? ''));
  10305. $disp = trim((string)($row['nickname'] ?? ''));
  10306. if ($disp === '') {
  10307. $disp = trim((string)($row['username'] ?? ''));
  10308. }
  10309. if ($disp !== '') {
  10310. $name = $disp;
  10311. }
  10312. }
  10313. $out[] = [
  10314. 'admin_id' => $adminId,
  10315. 'name' => $name,
  10316. 'email' => $email,
  10317. ];
  10318. }
  10319. return $out;
  10320. }
  10321. /**
  10322. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  10323. */
  10324. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  10325. {
  10326. if ($scydgyId >= 0) {
  10327. return;
  10328. }
  10329. try {
  10330. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10331. } catch (\Throwable $e) {
  10332. $po = null;
  10333. }
  10334. if (!is_array($po)) {
  10335. $this->error('订单不存在');
  10336. }
  10337. $modRq = trim((string)($po['mod_rq'] ?? ''));
  10338. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  10339. $this->error('订单不存在');
  10340. }
  10341. if ($this->auth->isSuperAdmin()) {
  10342. return;
  10343. }
  10344. [, $adminName] = $this->GetUseName();
  10345. $cywy = trim((string)($po['cywyxm'] ?? ''));
  10346. if ($cywy !== '' && $cywy === $adminName) {
  10347. return;
  10348. }
  10349. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  10350. try {
  10351. if ($this->auth->check($rule)) {
  10352. return;
  10353. }
  10354. } catch (\Throwable $e) {
  10355. }
  10356. }
  10357. $this->error('无权查看该订单');
  10358. }
  10359. /**
  10360. * 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
  10361. */
  10362. protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
  10363. {
  10364. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  10365. return ProcuremenStatus::PO_COMPLETED;
  10366. }
  10367. $sid = (int)($row['scydgy_id'] ?? 0);
  10368. if ($sid < 0) {
  10369. if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
  10370. return '已通知业务员';
  10371. }
  10372. if ($hasQuoted) {
  10373. return '供应商已报价';
  10374. }
  10375. if ($hasIssued
  10376. || ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
  10377. || ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
  10378. return '待报价';
  10379. }
  10380. try {
  10381. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  10382. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  10383. if ((int)$detCntQuery->count() > 0) {
  10384. return '待报价';
  10385. }
  10386. } catch (\Throwable $e) {
  10387. }
  10388. return '待询价';
  10389. }
  10390. if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
  10391. return '待入库评分';
  10392. }
  10393. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  10394. return '待采购确认';
  10395. }
  10396. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  10397. return '待确认供应商';
  10398. }
  10399. return '待协助下发';
  10400. }
  10401. /**
  10402. * 协助初选列表 — 批量软删除
  10403. */
  10404. public function pickDelete()
  10405. {
  10406. if (!$this->request->isPost() || !$this->request->isAjax()) {
  10407. $this->error(__('Invalid parameters'));
  10408. }
  10409. if (!$this->procuremenCanPickDelete()) {
  10410. $this->error(__('You have no permission'));
  10411. }
  10412. $rowsRaw = $this->request->post('rows_json', '[]');
  10413. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  10414. if (!is_array($rows) || $rows === []) {
  10415. $this->error('请至少勾选一条工序');
  10416. }
  10417. $done = 0;
  10418. Db::startTrans();
  10419. try {
  10420. foreach ($rows as $row) {
  10421. if (!is_array($row)) {
  10422. continue;
  10423. }
  10424. $this->softDeleteProcuremenPickRow($row);
  10425. $done++;
  10426. }
  10427. if ($done < 1) {
  10428. throw new \Exception('没有可删除的工序');
  10429. }
  10430. Db::commit();
  10431. } catch (\InvalidArgumentException $e) {
  10432. Db::rollback();
  10433. $this->error($e->getMessage());
  10434. } catch (\Throwable $e) {
  10435. Db::rollback();
  10436. $this->error($e->getMessage());
  10437. }
  10438. $this->pickHiddenScydgySetCache = null;
  10439. $this->success('已删除 ' . $done . ' 条工序');
  10440. }
  10441. /**
  10442. * 下发 — 手工新增工序(弹窗)
  10443. */
  10444. public function pickAdd()
  10445. {
  10446. if ($this->request->isPost()) {
  10447. $params = $this->request->post('row/a');
  10448. if (!is_array($params)) {
  10449. $this->error(__('Parameter %s can not be empty', ''));
  10450. }
  10451. try {
  10452. $sid = $this->saveManualPickOrder($params);
  10453. } catch (\InvalidArgumentException $e) {
  10454. $this->error($e->getMessage());
  10455. } catch (\Throwable $e) {
  10456. $this->error($e->getMessage());
  10457. }
  10458. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  10459. }
  10460. return $this->view->fetch('procuremen/pick_add');
  10461. }
  10462. /**
  10463. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  10464. */
  10465. public function pickSubmit()
  10466. {
  10467. if (!$this->request->isPost()) {
  10468. $this->error(__('Invalid parameters'));
  10469. }
  10470. // ---------- 接口订单数据 ----------
  10471. $rowJson = $this->request->post('row_json', '');
  10472. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  10473. $companiesJson = $this->request->post('companies_json', '[]');
  10474. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  10475. $companies = json_decode($companiesJson, true);
  10476. if (!is_array($companies)) {
  10477. $this->error('供应商数据无效');
  10478. }
  10479. $issueCompanies = $this->normalizePickCompanies($companies);
  10480. if ($issueCompanies === []) {
  10481. $this->error('请至少选择一家合作供应商');
  10482. }
  10483. $issueNameLabels = [];
  10484. foreach ($issueCompanies as $pc) {
  10485. $issueNameLabels[] = $pc['name'];
  10486. }
  10487. $issueNamesSummary = implode('、', $issueNameLabels);
  10488. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  10489. if ($sysRq === '') {
  10490. $this->error('请选择招标截止日期');
  10491. }
  10492. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  10493. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  10494. (string)$this->request->post('delivery_deadline', ''),
  10495. true
  10496. );
  10497. $scoreRuleId = (int)$this->request->post('score_rule_id', 0);
  10498. if ($scoreRuleId <= 0) {
  10499. $this->error('请选择订单类型');
  10500. }
  10501. $scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
  10502. if ((int)($scoreRule['id'] ?? 0) <= 0) {
  10503. $this->error('订单类型无效,请刷新后重选');
  10504. }
  10505. $scoreRuleId = (int)$scoreRule['id'];
  10506. $this->ensurePurchaseOrderScoreRuleIdColumn();
  10507. $isMerge = count($mergeRows) > 1;
  10508. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  10509. $logMsg = '下发' . $procPart
  10510. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  10511. $issueTime = date('Y-m-d H:i:s');
  10512. $logSidList = [];
  10513. foreach ($mergeRows as $row) {
  10514. if (!is_array($row)) {
  10515. continue;
  10516. }
  10517. $sid = $this->extractScydgyRowId($row);
  10518. if ($this->isValidScydgyRowId($sid)) {
  10519. $logSidList[$sid] = true;
  10520. }
  10521. }
  10522. if ($logSidList === []) {
  10523. $this->error('未找到有效工序,无法下发');
  10524. }
  10525. // 防连点/并发:同一批工序加命名锁,已下发则直接拒绝(避免重复短信邮件)
  10526. $sidKeys = array_keys($logSidList);
  10527. sort($sidKeys, SORT_NUMERIC);
  10528. $pickLockName = 'procuremen_pick_submit_' . md5(implode(',', $sidKeys));
  10529. if (!$this->acquireProcuremenNamedLock($pickLockName, 15)) {
  10530. $this->error('下发处理中,请勿重复点击');
  10531. }
  10532. $existingBySid = [];
  10533. try {
  10534. try {
  10535. $existingRows = Db::table('purchase_order')
  10536. ->where('scydgy_id', 'in', $sidKeys)
  10537. ->select();
  10538. if (is_array($existingRows)) {
  10539. foreach ($existingRows as $poRow) {
  10540. if (!is_array($poRow)) {
  10541. continue;
  10542. }
  10543. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10544. if ($this->isValidScydgyRowId($sid)) {
  10545. $existingBySid[$sid] = $poRow;
  10546. }
  10547. }
  10548. }
  10549. } catch (\Throwable $e) {
  10550. $existingBySid = [];
  10551. }
  10552. foreach ($sidKeys as $sid) {
  10553. $poRow = $existingBySid[$sid] ?? null;
  10554. if (!is_array($poRow)) {
  10555. continue;
  10556. }
  10557. if ($this->isPurchaseOrderSoftDeleted($poRow['mod_rq'] ?? null)) {
  10558. continue;
  10559. }
  10560. $label = $this->formatProcuremenRowLabel(['CCYDH' => $poRow['CCYDH'] ?? '', 'CGYMC' => $poRow['CGYMC'] ?? '']);
  10561. if (ProcuremenStatus::isPoCompleted($poRow['status'] ?? '')) {
  10562. $this->error(($label !== '' ? $label : ('工序#' . $sid)) . '已完结,无法再次下发');
  10563. }
  10564. if (!ProcuremenStatus::isWflowPendingIssue($poRow['wflow_status'] ?? '')) {
  10565. $this->error(($label !== '' ? $label : ('工序#' . $sid)) . '已下发或进入后续流程,请勿重复提交');
  10566. }
  10567. }
  10568. Db::startTrans();
  10569. try {
  10570. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  10571. foreach ($mergeRows as $row) {
  10572. if (!is_array($row)) {
  10573. continue;
  10574. }
  10575. $sid = $this->extractScydgyRowId($row);
  10576. $this->upsertPurchaseOrderFromRow(
  10577. $row,
  10578. $sysRqDb,
  10579. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  10580. $issueTime,
  10581. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  10582. $deliveryDeadlineDb,
  10583. $scoreRule
  10584. );
  10585. }
  10586. foreach ($issueCompanies as $c) {
  10587. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10588. }
  10589. Db::commit();
  10590. } catch (\Throwable $e) {
  10591. Db::rollback();
  10592. $this->error($e->getMessage());
  10593. }
  10594. } finally {
  10595. $this->releaseProcuremenNamedLock($pickLockName);
  10596. }
  10597. $poIdBySid = [];
  10598. if ($logSidList !== []) {
  10599. try {
  10600. $poIdBySid = Db::table('purchase_order')
  10601. ->where('scydgy_id', 'in', array_keys($logSidList))
  10602. ->column('id', 'scydgy_id');
  10603. } catch (\Throwable $e) {
  10604. $poIdBySid = [];
  10605. }
  10606. }
  10607. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  10608. if ($logSidList !== []) {
  10609. list($adminId, $adminName) = $this->GetUseName();
  10610. $logRows = [];
  10611. $seenLogSid = [];
  10612. foreach ($mergeRows as $row) {
  10613. if (!is_array($row)) {
  10614. continue;
  10615. }
  10616. $ids = $this->extractScydgyRowId($row);
  10617. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  10618. continue;
  10619. }
  10620. $seenLogSid[$ids] = true;
  10621. $poIdLog = null;
  10622. if (isset($poIdBySid[$ids])) {
  10623. $tid = (int)$poIdBySid[$ids];
  10624. $poIdLog = $tid > 0 ? $tid : null;
  10625. }
  10626. $logRows[] = ProcuremenOperLog::buildInsertRow(
  10627. $ids,
  10628. 'issue_submit',
  10629. $logMsg,
  10630. $poIdLog,
  10631. (int)$adminId,
  10632. (string)$adminName
  10633. );
  10634. }
  10635. if ($logRows !== []) {
  10636. try {
  10637. Db::table('purchase_order_oper_log')->insertAll($logRows);
  10638. } catch (\Throwable $e) {
  10639. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  10640. }
  10641. }
  10642. }
  10643. $notifyErrors = [];
  10644. $posNotify = [];
  10645. if ($logSidList !== []) {
  10646. try {
  10647. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  10648. } catch (\Throwable $e) {
  10649. $posNotify = [];
  10650. }
  10651. }
  10652. if (!is_array($posNotify)) {
  10653. $posNotify = [];
  10654. }
  10655. foreach ($posNotify as $i => $prow) {
  10656. if (is_array($posNotify[$i])) {
  10657. $posNotify[$i]['sys_rq'] = $sysRqDb;
  10658. }
  10659. }
  10660. $ccydhPick = '';
  10661. foreach ($mergeRows as $row) {
  10662. if (!is_array($row)) {
  10663. continue;
  10664. }
  10665. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  10666. if ($ccydhPick !== '') {
  10667. break;
  10668. }
  10669. }
  10670. $notifyBundleBase = [
  10671. 'ccydh' => $ccydhPick,
  10672. 'pos' => $posNotify,
  10673. 'merge_rows' => $mergeRows,
  10674. 'score_rule' => is_array($scoreRule) ? $scoreRule : null,
  10675. ];
  10676. try {
  10677. $this->notifyDryRunPreview = [];
  10678. foreach ($issueCompanies as $c) {
  10679. if (!is_array($c)) {
  10680. continue;
  10681. }
  10682. $cname = trim((string)($c['name'] ?? ''));
  10683. if ($cname === '') {
  10684. continue;
  10685. }
  10686. try {
  10687. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  10688. } catch (\Throwable $e) {
  10689. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10690. }
  10691. }
  10692. } catch (\Throwable $e) {
  10693. $this->error('通知发送失败:' . $e->getMessage());
  10694. }
  10695. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10696. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  10697. }
  10698. if ($this->isProcuremenNotifyDryRun()) {
  10699. $this->success('【演练模式】已保存并生成通知预览', '', [
  10700. 'notify_dry_run' => true,
  10701. 'notify_preview' => $this->notifyDryRunPreview,
  10702. ]);
  10703. }
  10704. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  10705. }
  10706. /**
  10707. * 确认供应商弹窗
  10708. */
  10709. public function auditIssue()
  10710. {
  10711. $ids = $this->request->param('ids', $this->request->param('id', ''));
  10712. if (is_array($ids)) {
  10713. $ids = isset($ids[0]) ? $ids[0] : '';
  10714. }
  10715. $ids = trim((string)$ids);
  10716. if ($ids === '') {
  10717. $this->error(__('Invalid parameters'));
  10718. }
  10719. if ($this->request->isPost()) {
  10720. $this->error('请使用弹窗内「确认」提交');
  10721. }
  10722. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10723. $pos = $bundle['pos'];
  10724. if ($pos === []) {
  10725. $this->error('该订单不在待确认供应商状态');
  10726. }
  10727. $po = $pos[0];
  10728. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10729. if ($quoteGroups === []) {
  10730. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  10731. }
  10732. $pickedName = '';
  10733. foreach ($pos as $poRow) {
  10734. if (!is_array($poRow)) {
  10735. continue;
  10736. }
  10737. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  10738. if ($pn !== '') {
  10739. $pickedName = $pn;
  10740. break;
  10741. }
  10742. }
  10743. $this->view->assign('po', $po);
  10744. $this->view->assign('scydgyId', $ids);
  10745. $this->view->assign('orderCcydh', $bundle['ccydh']);
  10746. $mergeRows = $bundle['merge_rows'];
  10747. $this->view->assign('processRows', $mergeRows);
  10748. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  10749. $this->view->assign('processCount', count($mergeRows));
  10750. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  10751. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  10752. $this->view->assign('pickedCompanyName', $pickedName);
  10753. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10754. if ($sysRqForView === '') {
  10755. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10756. }
  10757. $this->view->assign('sysRq', $sysRqForView);
  10758. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  10759. if ($deliveryDeadlineForView === '') {
  10760. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10761. }
  10762. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10763. $this->ensurePurchaseOrderManualPickColumns();
  10764. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
  10765. $manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
  10766. $manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
  10767. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  10768. if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
  10769. $pickedName = $manualPickInfo['company'];
  10770. $this->view->assign('pickedCompanyName', $pickedName);
  10771. }
  10772. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  10773. $this->view->assign('manualPicked', $manualPicked);
  10774. $this->view->assign('manualPickReason', $manualPickInfo['reason']);
  10775. $this->view->assign('quoteVisible', $quoteVisible);
  10776. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
  10777. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  10778. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
  10779. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
  10780. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  10781. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  10782. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  10783. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  10784. return $this->view->fetch('procuremen/audit_issue');
  10785. }
  10786. /**
  10787. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  10788. *
  10789. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10790. */
  10791. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  10792. {
  10793. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10794. return false;
  10795. }
  10796. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10797. return false;
  10798. }
  10799. return true;
  10800. }
  10801. /**
  10802. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  10803. *
  10804. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10805. */
  10806. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  10807. {
  10808. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10809. return false;
  10810. }
  10811. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10812. return false;
  10813. }
  10814. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  10815. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  10816. return true;
  10817. }
  10818. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  10819. }
  10820. /**
  10821. * 确认页 — 补加供应商弹窗
  10822. */
  10823. public function auditAppend()
  10824. {
  10825. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  10826. $this->error(__('You have no permission'));
  10827. }
  10828. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  10829. if (is_array($ids)) {
  10830. $ids = isset($ids[0]) ? $ids[0] : '';
  10831. }
  10832. $ids = trim((string)$ids);
  10833. if ($ids === '') {
  10834. $this->error(__('Invalid parameters'));
  10835. }
  10836. if ($this->request->isPost()) {
  10837. $this->error('请使用弹窗内「确认」提交');
  10838. }
  10839. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10840. if (($bundle['pos'] ?? []) === []) {
  10841. $this->error('该订单不在待确认供应商状态');
  10842. }
  10843. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10844. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10845. $this->error('已开标验证,不能再补加供应商');
  10846. }
  10847. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10848. $this->error('已指定供应商,不能再补加供应商');
  10849. }
  10850. $this->error('已经超过了招标截止日期,不可操作');
  10851. }
  10852. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10853. $existingNames = [];
  10854. foreach ($quoteGroups as $g) {
  10855. if (!is_array($g)) {
  10856. continue;
  10857. }
  10858. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  10859. if ($n !== '') {
  10860. $existingNames[$n] = true;
  10861. }
  10862. }
  10863. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  10864. $mergeRows = $bundle['merge_rows'] ?? [];
  10865. $this->view->assign('scydgyId', $ids);
  10866. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  10867. $this->view->assign('po', $po);
  10868. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  10869. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  10870. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  10871. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10872. if ($sysRqForView === '') {
  10873. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10874. }
  10875. $this->view->assign('sysRq', $sysRqForView);
  10876. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  10877. if ($deliveryDeadlineForView === '') {
  10878. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10879. }
  10880. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10881. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  10882. }
  10883. /**
  10884. * 确认页 — 补加供应商提交
  10885. */
  10886. public function auditAppendSubmit()
  10887. {
  10888. if (!$this->request->isPost()) {
  10889. $this->error(__('Invalid parameters'));
  10890. }
  10891. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  10892. $this->error(__('You have no permission'));
  10893. }
  10894. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  10895. if ($ids === '') {
  10896. $this->error(__('Invalid parameters'));
  10897. }
  10898. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10899. if (($bundle['pos'] ?? []) === []) {
  10900. $this->error('该订单不在待确认供应商状态');
  10901. }
  10902. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10903. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10904. $this->error('已开标验证,不能再补加供应商');
  10905. }
  10906. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10907. $this->error('已指定供应商,不能再补加供应商');
  10908. }
  10909. $this->error('已经超过了招标截止日期,不可操作');
  10910. }
  10911. $companiesJson = $this->request->post('companies_json', '[]');
  10912. $companies = json_decode((string)$companiesJson, true);
  10913. if (!is_array($companies)) {
  10914. $this->error('供应商数据无效');
  10915. }
  10916. $issueCompanies = $this->normalizePickCompanies($companies);
  10917. if ($issueCompanies === []) {
  10918. $this->error('请至少选择一家合作供应商');
  10919. }
  10920. $mergeRows = $bundle['merge_rows'] ?? [];
  10921. if (!is_array($mergeRows) || $mergeRows === []) {
  10922. $this->error('未找到工序行,无法补加');
  10923. }
  10924. $existingNames = [];
  10925. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  10926. if (!is_array($g)) {
  10927. continue;
  10928. }
  10929. $n = trim((string)($g['company_name'] ?? ''));
  10930. if ($n !== '') {
  10931. $existingNames[$n] = true;
  10932. }
  10933. }
  10934. $toAdd = [];
  10935. foreach ($issueCompanies as $c) {
  10936. if (!is_array($c)) {
  10937. continue;
  10938. }
  10939. $n = trim((string)($c['name'] ?? ''));
  10940. if ($n === '' || isset($existingNames[$n])) {
  10941. continue;
  10942. }
  10943. $toAdd[] = $c;
  10944. }
  10945. if ($toAdd === []) {
  10946. $this->error('所选供应商均已在本单中,请选择新的供应商');
  10947. }
  10948. $addedNames = [];
  10949. Db::startTrans();
  10950. try {
  10951. foreach ($toAdd as $c) {
  10952. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10953. $addedNames[] = trim((string)($c['name'] ?? ''));
  10954. }
  10955. Db::commit();
  10956. } catch (\Throwable $e) {
  10957. Db::rollback();
  10958. $this->error($e->getMessage());
  10959. }
  10960. $notifyErrors = [];
  10961. $notifyBundleBase = [
  10962. 'ccydh' => $bundle['ccydh'] ?? '',
  10963. 'pos' => $bundle['pos'] ?? [],
  10964. 'merge_rows' => $mergeRows,
  10965. ];
  10966. foreach ($toAdd as $c) {
  10967. if (!is_array($c)) {
  10968. continue;
  10969. }
  10970. $cname = trim((string)($c['name'] ?? ''));
  10971. if ($cname === '') {
  10972. continue;
  10973. }
  10974. try {
  10975. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  10976. } catch (\Throwable $e) {
  10977. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10978. }
  10979. }
  10980. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  10981. $seenLogSid = [];
  10982. foreach ($bundle['pos'] ?? [] as $poRow) {
  10983. if (!is_array($poRow)) {
  10984. continue;
  10985. }
  10986. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10987. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  10988. continue;
  10989. }
  10990. $seenLogSid[$sid] = true;
  10991. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10992. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10993. }
  10994. if ($seenLogSid === []) {
  10995. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  10996. if ($this->isValidScydgyRowId($logSid)) {
  10997. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  10998. }
  10999. }
  11000. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  11001. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  11002. }
  11003. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  11004. }
  11005. /**
  11006. * 开标双重验证 — 可选验证人列表
  11007. */
  11008. public function bidOpenUsers()
  11009. {
  11010. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  11011. $this->error('无权限');
  11012. }
  11013. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  11014. if ($scydgyId !== '') {
  11015. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11016. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  11017. $this->success('已完成开标验证', null, [
  11018. 'verified' => 1,
  11019. 'users' => [],
  11020. ]);
  11021. }
  11022. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  11023. $this->error('本单已指定供应商,无需再开标');
  11024. }
  11025. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  11026. }
  11027. $this->success('', null, [
  11028. 'verified' => 0,
  11029. 'users' => $this->listBidOpenVerifierCandidates(),
  11030. ]);
  11031. }
  11032. /**
  11033. * 开标双重验证 — 向指定管理员发送短信验证码
  11034. */
  11035. public function bidOpenSendCode()
  11036. {
  11037. if (!$this->request->isPost()) {
  11038. $this->error(__('Invalid parameters'));
  11039. }
  11040. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  11041. $this->error('无权限');
  11042. }
  11043. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11044. $adminId = (int)$this->request->post('admin_id', 0);
  11045. if ($scydgyId === '' || $adminId <= 0) {
  11046. $this->error('参数无效');
  11047. }
  11048. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11049. if ($bundle['pos'] === []) {
  11050. $this->error('该订单不在待确认供应商状态');
  11051. }
  11052. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  11053. $this->success('已完成开标验证,无需重复发送');
  11054. }
  11055. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  11056. $this->error('本单已指定供应商,无需再开标');
  11057. }
  11058. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  11059. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11060. if ($ccydh === '') {
  11061. $this->error('订单号无效');
  11062. }
  11063. $admin = $this->loadBidOpenAdminUser($adminId);
  11064. if ($admin === null) {
  11065. $this->error('验证人无效或未绑定手机号');
  11066. }
  11067. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  11068. $cd = max(30, min(120, $cd));
  11069. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  11070. $this->error('发送过于频繁,请稍后再试');
  11071. }
  11072. $code = (string)random_int(100000, 999999);
  11073. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  11074. $ttl = max(60, min(600, $ttl));
  11075. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  11076. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  11077. try {
  11078. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  11079. } catch (\Throwable $e) {
  11080. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  11081. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  11082. $this->error($e->getMessage());
  11083. }
  11084. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  11085. }
  11086. /**
  11087. * 开标双重验证 — 两人验证码校验并记录
  11088. */
  11089. public function bidOpenVerify()
  11090. {
  11091. if (!$this->request->isPost()) {
  11092. $this->error(__('Invalid parameters'));
  11093. }
  11094. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  11095. $this->error('无权限');
  11096. }
  11097. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11098. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  11099. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  11100. $code1 = trim((string)$this->request->post('code1', ''));
  11101. $code2 = trim((string)$this->request->post('code2', ''));
  11102. if ($scydgyId === '') {
  11103. $this->error('参数无效');
  11104. }
  11105. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  11106. $this->error('请选择两位验证人');
  11107. }
  11108. if ($verifier1Id === $verifier2Id) {
  11109. $this->error('两位验证人不能相同');
  11110. }
  11111. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  11112. $this->error('请输入6位短信验证码');
  11113. }
  11114. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11115. if ($bundle['pos'] === []) {
  11116. $this->error('该订单不在待确认供应商状态');
  11117. }
  11118. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11119. if ($ccydh === '') {
  11120. $this->error('订单号无效');
  11121. }
  11122. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  11123. $this->success('已完成开标验证');
  11124. }
  11125. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  11126. $this->error('本单已指定供应商,无需再开标');
  11127. }
  11128. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  11129. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  11130. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  11131. if ($verifier1 === null || $verifier2 === null) {
  11132. $this->error('验证人无效或未绑定手机号');
  11133. }
  11134. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  11135. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  11136. }
  11137. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  11138. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  11139. }
  11140. try {
  11141. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  11142. } catch (\Throwable $e) {
  11143. $this->error($e->getMessage());
  11144. }
  11145. $this->success('开标验证成功,可查看供应商报价与交货日期');
  11146. }
  11147. /**
  11148. * 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
  11149. */
  11150. public function auditManualPick()
  11151. {
  11152. if (!$this->request->isPost()) {
  11153. $this->error(__('Invalid parameters'));
  11154. }
  11155. if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
  11156. $this->error('无权限');
  11157. }
  11158. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11159. if ($scydgyId === '') {
  11160. $this->error('参数无效');
  11161. }
  11162. $companyName = trim((string)$this->request->post('selected_company', ''));
  11163. $reason = trim((string)$this->request->post('pick_reason', ''));
  11164. if ($companyName === '') {
  11165. $this->error('请选择一家供应商');
  11166. }
  11167. if ($reason === '') {
  11168. $this->error('请填写选择说明');
  11169. }
  11170. if (mb_strlen($reason) > 500) {
  11171. $this->error('选择说明不能超过500字');
  11172. }
  11173. $this->ensurePurchaseOrderManualPickColumns();
  11174. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11175. $pos = $bundle['pos'];
  11176. if ($pos === []) {
  11177. $this->error('该订单不在待确认供应商状态');
  11178. }
  11179. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  11180. $this->error('本单已开标验证,请直接在列表中选定供应商后确认');
  11181. }
  11182. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11183. if ($quoteGroups === []) {
  11184. $this->error('暂无供应商,请确认已完成协助初选通知');
  11185. }
  11186. $matched = null;
  11187. foreach ($quoteGroups as $g) {
  11188. if (!is_array($g)) {
  11189. continue;
  11190. }
  11191. if (trim((string)($g['name'] ?? '')) === $companyName) {
  11192. $matched = $g;
  11193. break;
  11194. }
  11195. }
  11196. if ($matched === null) {
  11197. $this->error('所选供应商不在本单报价列表中');
  11198. }
  11199. $logMsg = '指定供应商:已选定「' . $companyName . '」;说明:' . $reason;
  11200. Db::startTrans();
  11201. try {
  11202. foreach ($pos as $poRow) {
  11203. if (!is_array($poRow)) {
  11204. continue;
  11205. }
  11206. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11207. if (!$this->isValidScydgyRowId($sid)) {
  11208. continue;
  11209. }
  11210. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11211. 'pick_company_name' => $companyName,
  11212. 'manual_pick' => 1,
  11213. 'manual_pick_reason' => $reason,
  11214. ]);
  11215. }
  11216. Db::commit();
  11217. } catch (\Throwable $e) {
  11218. Db::rollback();
  11219. $this->error($e->getMessage());
  11220. }
  11221. foreach ($pos as $poRow) {
  11222. if (!is_array($poRow)) {
  11223. continue;
  11224. }
  11225. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11226. if (!$this->isValidScydgyRowId($sid)) {
  11227. continue;
  11228. }
  11229. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11230. $this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11231. }
  11232. // 自选后可见报价:按本单规则计算评分(与开标后一致)
  11233. try {
  11234. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11235. if ($ccydh !== '') {
  11236. // 重新加载以拿到未掩码报价参与计分
  11237. $bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11238. $groupsFresh = $this->loadAuditSupplierQuoteGroups($bundleFresh);
  11239. ProcuremenSupplierScore::saveForOrder($ccydh, $groupsFresh, date('Y-m'));
  11240. }
  11241. } catch (\Throwable $e) {
  11242. Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
  11243. }
  11244. $this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
  11245. }
  11246. /**
  11247. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  11248. */
  11249. public function auditSubmit()
  11250. {
  11251. if (!$this->request->isPost()) {
  11252. $this->error(__('Invalid parameters'));
  11253. }
  11254. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11255. if ($scydgyId === '') {
  11256. $this->error('参数无效');
  11257. }
  11258. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11259. $pos = $bundle['pos'];
  11260. $mergeRows = $bundle['merge_rows'];
  11261. if ($pos === [] || $mergeRows === []) {
  11262. $this->error('该订单不在待确认供应商状态');
  11263. }
  11264. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11265. if ($quoteGroups === []) {
  11266. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  11267. }
  11268. $companyName = trim((string)$this->request->post('selected_company', ''));
  11269. if ($companyName === '') {
  11270. $this->error('请选择一家供应商');
  11271. }
  11272. $matched = null;
  11273. foreach ($quoteGroups as $g) {
  11274. if (!is_array($g)) {
  11275. continue;
  11276. }
  11277. if (trim((string)($g['name'] ?? '')) === $companyName) {
  11278. $matched = $g;
  11279. break;
  11280. }
  11281. }
  11282. if ($matched === null) {
  11283. $this->error('所选供应商不在本单报价列表中');
  11284. }
  11285. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  11286. if ($sysRqDb === '') {
  11287. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  11288. } else {
  11289. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  11290. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  11291. }
  11292. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  11293. $this->error('未到招标截止日期,暂不可确认');
  11294. }
  11295. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
  11296. && !$this->isProcuremenManualPickedForBundle($bundle)
  11297. ) {
  11298. $this->error('请先完成开标双重验证或指定供应商后再确认');
  11299. }
  11300. $procCnt = count($mergeRows);
  11301. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  11302. $logMsg = '确认供应商' . $procPart . ':已选定「' . $companyName . '」';
  11303. Db::startTrans();
  11304. try {
  11305. foreach ($pos as $poRow) {
  11306. if (!is_array($poRow)) {
  11307. continue;
  11308. }
  11309. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11310. if (!$this->isValidScydgyRowId($sid)) {
  11311. continue;
  11312. }
  11313. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11314. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  11315. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11316. 'pick_company_name' => $companyName,
  11317. 'sys_rq' => $sysRqDb,
  11318. ]);
  11319. }
  11320. Db::commit();
  11321. } catch (\Throwable $e) {
  11322. Db::rollback();
  11323. $this->error($e->getMessage());
  11324. }
  11325. foreach ($pos as $poRow) {
  11326. if (!is_array($poRow)) {
  11327. continue;
  11328. }
  11329. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11330. if (!$this->isValidScydgyRowId($sid)) {
  11331. continue;
  11332. }
  11333. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11334. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11335. }
  11336. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  11337. }
  11338. /**
  11339. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  11340. */
  11341. public function auditResendSms()
  11342. {
  11343. if (!$this->request->isPost()) {
  11344. $this->error(__('Invalid parameters'));
  11345. }
  11346. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11347. if ($scydgyId === '') {
  11348. $this->error('参数无效');
  11349. }
  11350. $loaded = $this->loadAuditResendBundle($scydgyId);
  11351. $mergeRows = $loaded['merge_rows'];
  11352. $bundle = $loaded['bundle'];
  11353. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  11354. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11355. if ($quoteGroups === []) {
  11356. $this->error('暂无可通知的供应商');
  11357. }
  11358. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  11359. $companiesJson = (string)$this->request->post('companies_json', '');
  11360. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  11361. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  11362. }
  11363. /**
  11364. * 确认供应商 — 二次发送邮件(可选单家/批量)
  11365. */
  11366. public function auditResendEmail()
  11367. {
  11368. if (!$this->request->isPost()) {
  11369. $this->error(__('Invalid parameters'));
  11370. }
  11371. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11372. if ($scydgyId === '') {
  11373. $this->error('参数无效');
  11374. }
  11375. $loaded = $this->loadAuditResendBundle($scydgyId);
  11376. $mergeRows = $loaded['merge_rows'];
  11377. $bundle = $loaded['bundle'];
  11378. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  11379. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11380. if ($quoteGroups === []) {
  11381. $this->error('暂无可通知的供应商');
  11382. }
  11383. $companiesJson = (string)$this->request->post('companies_json', '');
  11384. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  11385. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  11386. if ($companiesJson === '' && $selectedCompany === '') {
  11387. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  11388. }
  11389. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  11390. }
  11391. /**
  11392. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  11393. *
  11394. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  11395. * @return array<int, true> 已处理的 scydgy_id 集合
  11396. */
  11397. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  11398. {
  11399. $pos = $bundle['pos'] ?? [];
  11400. if (!is_array($pos) || $pos === []) {
  11401. return [];
  11402. }
  11403. $sids = [];
  11404. $poIdBySid = [];
  11405. foreach ($pos as $poRow) {
  11406. if (!is_array($poRow)) {
  11407. continue;
  11408. }
  11409. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11410. if ($this->isValidScydgyRowId($sid)) {
  11411. $sids[$sid] = true;
  11412. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11413. if ($poId > 0) {
  11414. $poIdBySid[$sid] = $poId;
  11415. }
  11416. }
  11417. }
  11418. if ($sids === []) {
  11419. return [];
  11420. }
  11421. $logMsg = '重新下发';
  11422. $suffix = trim((string)$logSuffix, ',, ');
  11423. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  11424. $logMsg .= ':从历史存证退回协助初选';
  11425. } else {
  11426. $logMsg .= ':退回协助初选';
  11427. }
  11428. Db::table('purchase_order')
  11429. ->where('scydgy_id', 'in', array_keys($sids))
  11430. ->update([
  11431. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  11432. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11433. 'pick_company_name' => '',
  11434. 'pick_time' => null,
  11435. 'sys_rq' => null,
  11436. 'mod_rq' => null,
  11437. ]);
  11438. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  11439. foreach (array_keys($sids) as $sid) {
  11440. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  11441. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11442. }
  11443. return $sids;
  11444. }
  11445. /**
  11446. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  11447. *
  11448. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  11449. */
  11450. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  11451. {
  11452. $scydgyId = trim($scydgyId);
  11453. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11454. if ($scydgyId === '') {
  11455. return $empty;
  11456. }
  11457. try {
  11458. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  11459. } catch (\Throwable $e) {
  11460. $anchor = null;
  11461. }
  11462. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  11463. return $empty;
  11464. }
  11465. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  11466. if ($ccydh === '') {
  11467. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  11468. }
  11469. try {
  11470. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  11471. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  11472. $pos = $query->order('scydgy_id', 'asc')->select();
  11473. } catch (\Throwable $e) {
  11474. $pos = [$anchor];
  11475. }
  11476. if (!is_array($pos) || $pos === []) {
  11477. $pos = [$anchor];
  11478. }
  11479. return [
  11480. 'ccydh' => $ccydh,
  11481. 'pos' => $pos,
  11482. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  11483. ];
  11484. }
  11485. protected function purchaseOrderRowIsCompleted(array $po): bool
  11486. {
  11487. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11488. }
  11489. /**
  11490. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  11491. *
  11492. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  11493. */
  11494. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  11495. {
  11496. $scydgyId = trim($scydgyId);
  11497. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11498. if ($scydgyId === '') {
  11499. return $empty;
  11500. }
  11501. try {
  11502. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  11503. } catch (\Throwable $e) {
  11504. $anchor = null;
  11505. }
  11506. if (!is_array($anchor)) {
  11507. return $empty;
  11508. }
  11509. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  11510. if ($ccydh === '') {
  11511. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  11512. }
  11513. try {
  11514. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  11515. } catch (\Throwable $e) {
  11516. $pos = [$anchor];
  11517. }
  11518. if (!is_array($pos) || $pos === []) {
  11519. $pos = [$anchor];
  11520. }
  11521. return [
  11522. 'ccydh' => $ccydh,
  11523. 'pos' => $pos,
  11524. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  11525. ];
  11526. }
  11527. /**
  11528. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  11529. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  11530. */
  11531. public function auditAbandon()
  11532. {
  11533. if (!$this->request->isPost()) {
  11534. $this->error(__('Invalid parameters'));
  11535. }
  11536. $anchorIds = [];
  11537. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  11538. if ($batchRaw !== '') {
  11539. $decoded = json_decode($batchRaw, true);
  11540. if (is_array($decoded)) {
  11541. foreach ($decoded as $id) {
  11542. $s = trim((string)$id);
  11543. if ($s !== '') {
  11544. $anchorIds[] = $s;
  11545. }
  11546. }
  11547. }
  11548. }
  11549. if ($anchorIds === []) {
  11550. $single = trim((string)$this->request->post('scydgy_id', ''));
  11551. if ($single !== '') {
  11552. $anchorIds[] = $single;
  11553. }
  11554. }
  11555. if ($anchorIds === []) {
  11556. $this->error('请至少选择一条订单');
  11557. }
  11558. $processedCcydh = [];
  11559. $doneOrders = 0;
  11560. $allSids = [];
  11561. Db::startTrans();
  11562. try {
  11563. foreach ($anchorIds as $anchorId) {
  11564. $fromArchive = false;
  11565. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  11566. if (($bundle['pos'] ?? []) === []) {
  11567. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  11568. $fromArchive = ($bundle['pos'] ?? []) !== [];
  11569. }
  11570. if (($bundle['pos'] ?? []) === []) {
  11571. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  11572. $fromArchive = ($bundle['pos'] ?? []) !== [];
  11573. }
  11574. if (($bundle['pos'] ?? []) === []) {
  11575. continue;
  11576. }
  11577. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11578. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  11579. if (isset($processedCcydh[$dedupeKey])) {
  11580. continue;
  11581. }
  11582. $processedCcydh[$dedupeKey] = true;
  11583. $sids = $fromArchive
  11584. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回协助初选')
  11585. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  11586. if ($sids === []) {
  11587. continue;
  11588. }
  11589. $doneOrders++;
  11590. foreach (array_keys($sids) as $sid) {
  11591. $allSids[(int)$sid] = true;
  11592. }
  11593. }
  11594. if ($doneOrders < 1) {
  11595. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  11596. }
  11597. Db::commit();
  11598. } catch (\Throwable $e) {
  11599. Db::rollback();
  11600. $this->error($e->getMessage());
  11601. }
  11602. $this->pickHiddenScydgySetCache = null;
  11603. $msg = $doneOrders > 1
  11604. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  11605. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  11606. $this->success($msg);
  11607. }
  11608. /**
  11609. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  11610. */
  11611. public function archiveAbandon()
  11612. {
  11613. return $this->auditAbandon();
  11614. }
  11615. /**
  11616. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  11617. */
  11618. public function purchaseApprovalReject()
  11619. {
  11620. if (!$this->request->isPost() || !$this->request->isAjax()) {
  11621. $this->error(__('Invalid parameters'));
  11622. }
  11623. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  11624. $this->error(__('You have no permission'));
  11625. }
  11626. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  11627. $decoded = json_decode($batchRaw, true);
  11628. if (!is_array($decoded) || $decoded === []) {
  11629. $this->error('提交数据无效');
  11630. }
  11631. $done = 0;
  11632. Db::startTrans();
  11633. try {
  11634. foreach ($decoded as $item) {
  11635. if (!is_array($item)) {
  11636. continue;
  11637. }
  11638. $sid = (int)($item['scydgy_id'] ?? 0);
  11639. if (!$this->isValidScydgyRowId($sid)) {
  11640. continue;
  11641. }
  11642. $this->runPurchaseApprovalRejectForSid($sid);
  11643. $done++;
  11644. }
  11645. if ($done < 1) {
  11646. throw new \Exception('所选订单均不在待审批状态');
  11647. }
  11648. Db::commit();
  11649. } catch (\Throwable $e) {
  11650. Db::rollback();
  11651. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  11652. }
  11653. $this->pickHiddenScydgySetCache = null;
  11654. $this->success('已驳回并退回「协助审批下发」');
  11655. }
  11656. /**
  11657. * @throws \Exception
  11658. */
  11659. protected function runPurchaseApprovalRejectForSid(int $sid): void
  11660. {
  11661. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  11662. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  11663. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  11664. $allIds = $this->purchaseOrderDetail($sid);
  11665. if ($allIds === []) {
  11666. throw new \Exception('未找到下发明细');
  11667. }
  11668. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11669. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  11670. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11671. 'pick_company_name' => '',
  11672. ]);
  11673. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  11674. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  11675. $poId = 0;
  11676. try {
  11677. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  11678. if (is_array($po)) {
  11679. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11680. }
  11681. } catch (\Throwable $e) {
  11682. }
  11683. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  11684. }
  11685. /**
  11686. * 审核弹窗(旧入口,POST 已关闭)
  11687. */
  11688. public function review()
  11689. {
  11690. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  11691. $this->error(__('You have no permission'));
  11692. }
  11693. if ($this->request->isPost()) {
  11694. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  11695. }
  11696. $this->view->assign('pickMode', 0);
  11697. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  11698. }
  11699. /**
  11700. * 审核弹窗获取公司列表
  11701. */
  11702. public function reviewCompanies()
  11703. {
  11704. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  11705. $this->error(__('You have no permission'));
  11706. }
  11707. if (!$this->request->isAjax()) {
  11708. $this->error(__('Invalid parameters'));
  11709. }
  11710. $list = [];
  11711. try {
  11712. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  11713. $rows = Db::table('customer')
  11714. ->where(function ($q) {
  11715. $q->where('status', 1)
  11716. ->whereOr('status', '1')
  11717. ->whereOr('status', '')
  11718. ->whereNull('status');
  11719. })
  11720. ->order('id', 'desc')
  11721. ->select();
  11722. } catch (\Throwable $e) {
  11723. $this->success('', '', []);
  11724. return;
  11725. }
  11726. if (!is_array($rows)) {
  11727. $this->success('', '', []);
  11728. return;
  11729. }
  11730. $detailColCandidates = [
  11731. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  11732. 'company_detail', 'company_desc', 'address',
  11733. ];
  11734. foreach ($rows as $row) {
  11735. if (!is_array($row)) {
  11736. continue;
  11737. }
  11738. $norm = [];
  11739. foreach ($row as $k => $v) {
  11740. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  11741. }
  11742. $row = $norm;
  11743. $st = $row['status'] ?? '';
  11744. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  11745. continue;
  11746. }
  11747. $payload = $this->buildCustomerContactPayloadFromRow($row);
  11748. if ($payload === null) {
  11749. continue;
  11750. }
  11751. $detail = '';
  11752. foreach ($detailColCandidates as $dk) {
  11753. if (!isset($row[$dk])) {
  11754. continue;
  11755. }
  11756. $dv = trim((string)$row[$dk]);
  11757. if ($dv !== '') {
  11758. $detail = $dv;
  11759. break;
  11760. }
  11761. }
  11762. $payload['detail'] = $detail;
  11763. $list[] = $this->maskSupplierContactFields($payload);
  11764. }
  11765. $this->success('', '', $list);
  11766. }
  11767. /**
  11768. * 采购确认-下发明细弹窗:
  11769. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  11770. */
  11771. public function outward_detail()
  11772. {
  11773. $ids = $this->request->param('ids', $this->request->param('id', ''));
  11774. if (is_array($ids)) {
  11775. $ids = isset($ids[0]) ? $ids[0] : '';
  11776. }
  11777. $ids = trim((string)$ids);
  11778. if ($ids === '') {
  11779. $this->error(__('Invalid parameters'));
  11780. }
  11781. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  11782. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  11783. $wffTab = 'all';
  11784. }
  11785. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  11786. $purchaseOrderId = 0;
  11787. $po = null;
  11788. try {
  11789. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  11790. if (is_array($po)) {
  11791. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11792. }
  11793. } catch (\Throwable $e) {
  11794. $purchaseOrderId = 0;
  11795. $po = null;
  11796. }
  11797. if (!$isPurchaseConfirm && is_array($po)) {
  11798. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11799. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  11800. $isPurchaseConfirm = true;
  11801. }
  11802. }
  11803. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  11804. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11805. $confirmProcessCount = 1;
  11806. $confirmPickGroups = [];
  11807. $processDisplayRows = [];
  11808. $allDetailsBySid = [];
  11809. $requiredSidList = [];
  11810. $sidList = [$ids];
  11811. if ($isPurchaseConfirm) {
  11812. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  11813. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  11814. if ($mergeRows !== []) {
  11815. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  11816. }
  11817. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  11818. if ($confirmBundle['pos'] !== []) {
  11819. $sidList = [];
  11820. foreach ($confirmBundle['pos'] as $poRow) {
  11821. if (!is_array($poRow)) {
  11822. continue;
  11823. }
  11824. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11825. if (!$this->isValidScydgyRowId($sid)) {
  11826. continue;
  11827. }
  11828. $sidList[] = (string)$sid;
  11829. $requiredSidList[] = $sid;
  11830. }
  11831. }
  11832. if ($sidList === []) {
  11833. $sidList = [$ids];
  11834. $requiredSidList = [(int)$ids];
  11835. }
  11836. $confirmProcessCount = max(1, count($requiredSidList));
  11837. if (is_array($po) && $purchaseOrderId <= 0) {
  11838. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11839. }
  11840. }
  11841. $rows = [];
  11842. try {
  11843. if (count($sidList) === 1) {
  11844. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  11845. } else {
  11846. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  11847. }
  11848. } catch (\Throwable $e) {
  11849. $rows = [];
  11850. }
  11851. if ($isPurchaseConfirm) {
  11852. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  11853. }
  11854. foreach ($rows as &$r) {
  11855. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  11856. $r['id'] = $r['ID'];
  11857. }
  11858. if (isset($r['createtime'])) {
  11859. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  11860. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  11861. } else {
  11862. $r['createtime_text'] = (string)$r['createtime'];
  11863. }
  11864. } else {
  11865. $r['createtime_text'] = '';
  11866. }
  11867. if (is_array($r)) {
  11868. $r = $this->maskSupplierContactFields($r);
  11869. }
  11870. }
  11871. unset($r);
  11872. $pickedCompanyName = '';
  11873. $manualPicked = 0;
  11874. $manualPickReason = '';
  11875. $quoteVisible = 0;
  11876. $bidOpenVerified = 0;
  11877. if ($isPurchaseConfirm) {
  11878. // 确认包为空时,用当前主单兜底,避免指定说明读不到
  11879. if (($confirmBundle['ccydh'] ?? '') === '' && is_array($po)) {
  11880. $confirmBundle['ccydh'] = trim((string)($po['CCYDH'] ?? ''));
  11881. }
  11882. if (($confirmBundle['pos'] ?? []) === [] && is_array($po)) {
  11883. $confirmBundle['pos'] = [$po];
  11884. }
  11885. $manualPickInfo = $this->resolveProcuremenManualPickInfo($confirmBundle);
  11886. $manualPicked = $this->isProcuremenManualPickedForBundle($confirmBundle) ? 1 : 0;
  11887. $manualPickReason = (string)($manualPickInfo['reason'] ?? '');
  11888. if ($manualPickInfo['company'] !== '') {
  11889. $pickedCompanyName = $manualPickInfo['company'];
  11890. }
  11891. if ($pickedCompanyName === '') {
  11892. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  11893. if (!is_array($poRow)) {
  11894. continue;
  11895. }
  11896. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  11897. if ($pn !== '') {
  11898. $pickedCompanyName = $pn;
  11899. break;
  11900. }
  11901. }
  11902. }
  11903. // 再兜底:直接读当前主单字段
  11904. if (is_array($po) && (int)($po['manual_pick'] ?? 0) === 1) {
  11905. $manualPicked = 1;
  11906. if ($manualPickReason === '') {
  11907. $manualPickReason = trim((string)($po['manual_pick_reason'] ?? ''));
  11908. }
  11909. if ($pickedCompanyName === '') {
  11910. $pickedCompanyName = trim((string)($po['pick_company_name'] ?? ''));
  11911. }
  11912. }
  11913. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle) ? 1 : 0;
  11914. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  11915. }
  11916. $this->view->assign('rows', $rows ?: []);
  11917. $this->view->assign('rowCount', count($rows ?: []));
  11918. $this->view->assign('scydgyId', $ids);
  11919. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  11920. $this->view->assign('headTitle', $headTitle);
  11921. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  11922. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  11923. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  11924. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  11925. $this->view->assign('processDisplayRows', $processDisplayRows);
  11926. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  11927. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  11928. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  11929. $this->view->assign('manualPicked', $manualPicked);
  11930. $this->view->assign('manualPickReason', $manualPickReason);
  11931. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  11932. $this->view->assign('quoteVisible', $quoteVisible);
  11933. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
  11934. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  11935. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
  11936. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
  11937. $sysRqDisplay = '—';
  11938. if ($isPurchaseConfirm) {
  11939. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  11940. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  11941. );
  11942. }
  11943. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  11944. $this->view->assign('sysRq', $isPurchaseConfirm
  11945. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  11946. : '');
  11947. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  11948. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  11949. : '');
  11950. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  11951. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  11952. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  11953. if ($isPurchaseConfirm) {
  11954. return $this->view->fetch();
  11955. }
  11956. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  11957. $this->view->engine->layout(false);
  11958. try {
  11959. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  11960. $this->view->assign('dialogBody', $bodyHtml);
  11961. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  11962. } finally {
  11963. if ($restoreLayout) {
  11964. $this->view->engine->layout($restoreLayout);
  11965. }
  11966. }
  11967. }
  11968. /**
  11969. * 月度导出记录表(不存在时自动创建)
  11970. */
  11971. protected function ensurePurchaseMonthExportLogTable(): void
  11972. {
  11973. try {
  11974. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  11975. } catch (\Throwable $e) {
  11976. Db::execute(
  11977. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  11978. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  11979. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  11980. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  11981. `admin_name` varchar(64) NOT NULL DEFAULT '',
  11982. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  11983. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  11984. `createtime` int(10) unsigned DEFAULT NULL,
  11985. PRIMARY KEY (`id`),
  11986. KEY `idx_ym` (`ym`),
  11987. KEY `idx_ct` (`createtime`)
  11988. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  11989. );
  11990. }
  11991. }
  11992. /**
  11993. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  11994. *
  11995. * @param array<int, mixed> $dbRows
  11996. * @return array<int, array<string, mixed>>
  11997. */
  11998. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  11999. {
  12000. $keyword = trim((string)$this->request->get('search', ''));
  12001. if ($keyword === '') {
  12002. $keyword = trim((string)$this->request->request('search', ''));
  12003. }
  12004. $filter = $this->request->get('filter', '');
  12005. $op = $this->request->get('op', '');
  12006. if (is_string($filter) && $filter !== '') {
  12007. $filterArr = (array)json_decode($filter, true);
  12008. } else {
  12009. $filterArr = is_array($filter) ? $filter : [];
  12010. }
  12011. if (is_string($op) && $op !== '') {
  12012. $opArr = (array)json_decode($op, true);
  12013. } else {
  12014. $opArr = is_array($op) ? $op : [];
  12015. }
  12016. if ($keyword === '' && $filterArr === []) {
  12017. return array_values(array_filter($dbRows, 'is_array'));
  12018. }
  12019. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  12020. $out = [];
  12021. foreach ($dbRows as $row) {
  12022. if (!is_array($row)) {
  12023. continue;
  12024. }
  12025. if ($keyword !== '') {
  12026. $hit = false;
  12027. foreach ($searchFields as $f) {
  12028. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  12029. $hit = true;
  12030. break;
  12031. }
  12032. }
  12033. if (!$hit) {
  12034. continue;
  12035. }
  12036. }
  12037. $passFilter = true;
  12038. foreach ($filterArr as $field => $val) {
  12039. $field = (string)$field;
  12040. $val = trim((string)$val);
  12041. if ($field === '' || $val === '') {
  12042. continue;
  12043. }
  12044. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  12045. continue;
  12046. }
  12047. $cell = (string)($row[$field] ?? '');
  12048. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  12049. if ($mode === '=' || $mode === 'EQUAL') {
  12050. if (strcasecmp($cell, $val) !== 0) {
  12051. $passFilter = false;
  12052. break;
  12053. }
  12054. } elseif (mb_stripos($cell, $val) === false) {
  12055. $passFilter = false;
  12056. break;
  12057. }
  12058. }
  12059. if (!$passFilter) {
  12060. continue;
  12061. }
  12062. $out[] = $row;
  12063. }
  12064. return $out;
  12065. }
  12066. /**
  12067. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  12068. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  12069. */
  12070. public function export_month_outward()
  12071. {
  12072. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  12073. $this->error(__('You have no permission'));
  12074. }
  12075. $bundle = $this->prepareMonthOutwardExportBundle();
  12076. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  12077. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  12078. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  12079. $spreadsheet = new Spreadsheet();
  12080. $sheet = $spreadsheet->getActiveSheet();
  12081. $sheet->setTitle('外协加工明细');
  12082. $mon = (int)substr($ym, 5, 2);
  12083. $sheet->mergeCells('A1:H1');
  12084. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  12085. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  12086. $sheet->getStyle('A1')->getAlignment()
  12087. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12088. ->setVertical(Alignment::VERTICAL_CENTER);
  12089. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  12090. $col = 'A';
  12091. foreach ($headers as $h) {
  12092. $sheet->setCellValue($col . '2', $h);
  12093. $col++;
  12094. }
  12095. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  12096. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12097. $rowNum = 3;
  12098. $sumSubtotalCounts = 0;
  12099. $grandAmount = 0.0;
  12100. $globalSeq = 0;
  12101. if ($groups === []) {
  12102. $sheet->mergeCells('A3:H3');
  12103. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  12104. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12105. $rowNum = 4;
  12106. } else {
  12107. foreach ($groups as $items) {
  12108. if ($items === []) {
  12109. continue;
  12110. }
  12111. $groupLineCount = count($items);
  12112. $subAmount = 0.0;
  12113. foreach ($items as $line) {
  12114. $globalSeq++;
  12115. $dr = $line['detail'];
  12116. $amt = $this->procuremenExportAmount($dr);
  12117. $subAmount += $amt;
  12118. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  12119. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  12120. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  12121. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  12122. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  12123. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  12124. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  12125. $sheet->setCellValue('H' . $rowNum, $amt);
  12126. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  12127. $rowNum++;
  12128. }
  12129. $sumSubtotalCounts += $groupLineCount;
  12130. $grandAmount += $subAmount;
  12131. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  12132. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  12133. $sheet->getStyle('G' . $rowNum)->getAlignment()
  12134. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  12135. ->setVertical(Alignment::VERTICAL_CENTER);
  12136. $rowNum++;
  12137. }
  12138. }
  12139. $sheet->setCellValue('A' . $rowNum, '总计');
  12140. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  12141. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  12142. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  12143. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  12144. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  12145. $lastRow = $rowNum;
  12146. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  12147. 'borders' => [
  12148. 'allBorders' => [
  12149. 'borderStyle' => Border::BORDER_THIN,
  12150. 'color' => ['rgb' => '000000'],
  12151. ],
  12152. ],
  12153. ]);
  12154. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  12155. if ($lastRow >= 3) {
  12156. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12157. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12158. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12159. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12160. }
  12161. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  12162. $sheet->getColumnDimension('A')->setWidth(7);
  12163. $sheet->getColumnDimension('B')->setWidth(16);
  12164. $sheet->getColumnDimension('C')->setWidth(52);
  12165. $sheet->getColumnDimension('D')->setWidth(32);
  12166. $sheet->getColumnDimension('E')->setWidth(12);
  12167. $sheet->getColumnDimension('F')->setWidth(44);
  12168. $sheet->getColumnDimension('G')->setWidth(26);
  12169. $sheet->getColumnDimension('H')->setWidth(13);
  12170. $sheet->getRowDimension(1)->setRowHeight(28);
  12171. $ymCompact = str_replace('-', '', $ym);
  12172. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  12173. $filename = $fileBase . '.xlsx';
  12174. try {
  12175. $this->ensurePurchaseMonthExportLogTable();
  12176. list($adminId, $adminName) = $this->GetUseName();
  12177. Db::table('purchase_month_export_log')->insert([
  12178. 'ym' => $ym,
  12179. 'admin_id' => (int)$adminId,
  12180. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  12181. 'row_count' => count($exportLines),
  12182. 'total_amount' => round($grandAmount, 2),
  12183. 'createtime' => time(),
  12184. ]);
  12185. } catch (\Throwable $e) {
  12186. Log::write('month export log: ' . $e->getMessage(), 'error');
  12187. }
  12188. if (ob_get_length()) {
  12189. ob_end_clean();
  12190. }
  12191. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  12192. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  12193. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  12194. header('Cache-Control: max-age=0');
  12195. $writer = new Xlsx($spreadsheet);
  12196. $writer->save('php://output');
  12197. $spreadsheet->disconnectWorksheets();
  12198. unset($spreadsheet);
  12199. exit;
  12200. }
  12201. /**
  12202. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  12203. */
  12204. public function export_month_quote()
  12205. {
  12206. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  12207. $this->error(__('You have no permission'));
  12208. }
  12209. $bundle = $this->prepareMonthOutwardExportBundle();
  12210. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  12211. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  12212. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  12213. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  12214. $spreadsheet = new Spreadsheet();
  12215. $sheet = $spreadsheet->getActiveSheet();
  12216. $sheet->setTitle('供应商报价明细');
  12217. $mon = (int)substr($ym, 5, 2);
  12218. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  12219. $sheet->getColumnDimension('A')->setWidth(7);
  12220. $sheet->getColumnDimension('B')->setWidth(16);
  12221. $sheet->getColumnDimension('C')->setWidth(52);
  12222. $sheet->getColumnDimension('D')->setWidth(26);
  12223. $sheet->getColumnDimension('E')->setWidth(32);
  12224. $sheet->getColumnDimension('F')->setWidth(12);
  12225. $sheet->getColumnDimension('G')->setWidth(14);
  12226. $sheet->getColumnDimension('H')->setWidth(12);
  12227. if ($quoteLastRow < 1) {
  12228. $quoteLastRow = 3;
  12229. }
  12230. $ymCompact = str_replace('-', '', $ym);
  12231. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  12232. if (ob_get_length()) {
  12233. ob_end_clean();
  12234. }
  12235. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  12236. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  12237. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  12238. header('Cache-Control: max-age=0');
  12239. $writer = new Xlsx($spreadsheet);
  12240. $writer->save('php://output');
  12241. $spreadsheet->disconnectWorksheets();
  12242. unset($spreadsheet);
  12243. exit;
  12244. }
  12245. /**
  12246. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  12247. *
  12248. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  12249. */
  12250. protected function prepareMonthOutwardExportBundle(): array
  12251. {
  12252. $this->request->filter(['strip_tags', 'trim']);
  12253. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  12254. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  12255. $ym = date('Y-m');
  12256. }
  12257. $dbRows = [];
  12258. try {
  12259. $query = Db::table('purchase_order');
  12260. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  12261. $dbRows = $query->select();
  12262. } catch (\Throwable $e) {
  12263. $dbRows = [];
  12264. }
  12265. if (!is_array($dbRows)) {
  12266. $dbRows = [];
  12267. }
  12268. $completeTsMap = [];
  12269. $sidList = [];
  12270. foreach ($dbRows as $dbRow) {
  12271. if (!is_array($dbRow)) {
  12272. continue;
  12273. }
  12274. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  12275. if ($sid > 0) {
  12276. $sidList[$sid] = true;
  12277. }
  12278. }
  12279. if ($sidList !== []) {
  12280. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  12281. }
  12282. // 导出始终按「查看月份」取当月完结单;搜索只在当月内再缩小(勿跨月,否则会与列表不一致)
  12283. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  12284. if (!is_array($dbRow)) {
  12285. return false;
  12286. }
  12287. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  12288. if ($done['ts'] <= 0) {
  12289. return false;
  12290. }
  12291. return date('Y-m', $done['ts']) === $ym;
  12292. }));
  12293. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  12294. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  12295. $mainBySid = [];
  12296. foreach ($pool as $rw) {
  12297. if (!is_array($rw)) {
  12298. continue;
  12299. }
  12300. $rid = (int)($rw['ID'] ?? 0);
  12301. if ($rid > 0) {
  12302. $mainBySid[$rid] = $rw;
  12303. }
  12304. }
  12305. if ($mainBySid === []) {
  12306. $detailRows = [];
  12307. } else {
  12308. try {
  12309. $detailRows = Db::table('purchase_order_detail')
  12310. ->where('scydgy_id', 'in', array_keys($mainBySid))
  12311. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  12312. ->order('status', 'desc')
  12313. ->order('CCYDH', 'asc')
  12314. ->order('company_name', 'asc')
  12315. ->order('id', 'asc')
  12316. ->select();
  12317. } catch (\Throwable $e) {
  12318. try {
  12319. $detailRows = Db::table('purchase_order_detail')
  12320. ->where('scydgy_id', 'in', array_keys($mainBySid))
  12321. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  12322. ->order('status', 'desc')
  12323. ->order('CCYDH', 'asc')
  12324. ->order('company_name', 'asc')
  12325. ->order('ID', 'asc')
  12326. ->select();
  12327. } catch (\Throwable $e2) {
  12328. $detailRows = [];
  12329. }
  12330. }
  12331. }
  12332. if (!is_array($detailRows)) {
  12333. $detailRows = [];
  12334. }
  12335. $exportLines = [];
  12336. $detailSidSeen = [];
  12337. foreach ($detailRows as $dr) {
  12338. if (!is_array($dr)) {
  12339. continue;
  12340. }
  12341. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12342. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  12343. continue;
  12344. }
  12345. if (isset($detailSidSeen[$sid])) {
  12346. continue;
  12347. }
  12348. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  12349. continue;
  12350. }
  12351. $detailSidSeen[$sid] = true;
  12352. $m = $mainBySid[$sid];
  12353. $exportLines[] = [
  12354. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12355. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12356. 'company_name' => (string)($dr['company_name'] ?? ''),
  12357. 'CDF' => (string)($m['CDF'] ?? ''),
  12358. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12359. 'gx' => $this->procuremenExportGxText($m),
  12360. 'detail' => $dr,
  12361. ];
  12362. }
  12363. foreach ($detailRows as $dr) {
  12364. if (!is_array($dr)) {
  12365. continue;
  12366. }
  12367. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12368. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  12369. continue;
  12370. }
  12371. $detailSidSeen[$sid] = true;
  12372. $m = $mainBySid[$sid];
  12373. $exportLines[] = [
  12374. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12375. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12376. 'company_name' => (string)($dr['company_name'] ?? ''),
  12377. 'CDF' => (string)($m['CDF'] ?? ''),
  12378. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12379. 'gx' => $this->procuremenExportGxText($m),
  12380. 'detail' => $dr,
  12381. ];
  12382. }
  12383. foreach ($mainBySid as $sid => $m) {
  12384. if (isset($detailSidSeen[$sid])) {
  12385. continue;
  12386. }
  12387. $company = trim((string)($m['pick_company_name'] ?? ''));
  12388. $exportLines[] = [
  12389. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  12390. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  12391. 'company_name' => $company,
  12392. 'CDF' => (string)($m['CDF'] ?? ''),
  12393. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12394. 'gx' => $this->procuremenExportGxText($m),
  12395. 'detail' => [],
  12396. ];
  12397. }
  12398. $groups = [];
  12399. foreach ($exportLines as $line) {
  12400. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  12401. if (!isset($groups[$k])) {
  12402. $groups[$k] = [];
  12403. }
  12404. $groups[$k][] = $line;
  12405. }
  12406. ksort($groups, SORT_STRING);
  12407. return [
  12408. 'ym' => $ym,
  12409. 'mainBySid' => $mainBySid,
  12410. 'detailRows' => $detailRows,
  12411. 'exportLines' => $exportLines,
  12412. 'groups' => $groups,
  12413. ];
  12414. }
  12415. /**
  12416. * 导出用:工序列文案
  12417. */
  12418. protected function procuremenExportGxText(array $r)
  12419. {
  12420. $a = trim((string)($r['CDXMC'] ?? ''));
  12421. $b = trim((string)($r['CGYMC'] ?? ''));
  12422. if ($a !== '' && $b !== '') {
  12423. return $a . ':' . $b;
  12424. }
  12425. return $a !== '' ? $a : $b;
  12426. }
  12427. /**
  12428. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  12429. */
  12430. protected function procuremenExportAmount(array $r)
  12431. {
  12432. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  12433. if (!array_key_exists($k, $r)) {
  12434. continue;
  12435. }
  12436. $v = $r[$k];
  12437. if ($v === null || $v === '') {
  12438. continue;
  12439. }
  12440. if (is_numeric($v)) {
  12441. return (float)$v;
  12442. }
  12443. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  12444. if ($v !== '' && is_numeric($v)) {
  12445. return (float)$v;
  12446. }
  12447. }
  12448. return 0.0;
  12449. }
  12450. /**
  12451. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  12452. *
  12453. * @param array<int, array<string, mixed>> $detailRows
  12454. * @param array<int, array<string, mixed>> $mainBySid
  12455. * @return array<int, array<string, mixed>>
  12456. */
  12457. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  12458. {
  12459. $lines = [];
  12460. foreach ($detailRows as $dr) {
  12461. if (!is_array($dr)) {
  12462. continue;
  12463. }
  12464. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12465. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  12466. continue;
  12467. }
  12468. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  12469. continue;
  12470. }
  12471. $cn = trim((string)($dr['company_name'] ?? ''));
  12472. if ($cn === '') {
  12473. continue;
  12474. }
  12475. $m = $mainBySid[$sid];
  12476. $am = trim((string)($dr['amount'] ?? ''));
  12477. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  12478. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  12479. $amountText = $amountFilled
  12480. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  12481. : '未填写';
  12482. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  12483. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  12484. if ($deliveryShow === '' && $deliveryRaw !== '') {
  12485. $deliveryShow = $deliveryRaw;
  12486. }
  12487. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  12488. ? $deliveryShow
  12489. : '未填写';
  12490. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  12491. $lines[] = [
  12492. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12493. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12494. 'gx' => $this->procuremenExportGxText($m),
  12495. 'company_name' => $cn,
  12496. 'amount_text' => $amountText,
  12497. 'amount_num' => $amountFilled ? $amountNum : null,
  12498. 'delivery_text' => $deliveryText,
  12499. 'picked_text' => $picked ? '中标' : '未中标',
  12500. 'picked' => $picked,
  12501. ];
  12502. }
  12503. $winnerSupplierByOrder = [];
  12504. foreach ($lines as $line) {
  12505. $dh = trim((string)($line['CCYDH'] ?? ''));
  12506. $cn = trim((string)($line['company_name'] ?? ''));
  12507. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  12508. $winnerSupplierByOrder[$dh][$cn] = true;
  12509. }
  12510. }
  12511. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  12512. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  12513. if ($c !== 0) {
  12514. return $c;
  12515. }
  12516. $dh = trim((string)($a['CCYDH'] ?? ''));
  12517. $aCn = trim((string)($a['company_name'] ?? ''));
  12518. $bCn = trim((string)($b['company_name'] ?? ''));
  12519. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  12520. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  12521. if ($aSupplierWin !== $bSupplierWin) {
  12522. return $aSupplierWin ? -1 : 1;
  12523. }
  12524. $c = strcmp($aCn, $bCn);
  12525. if ($c !== 0) {
  12526. return $c;
  12527. }
  12528. if (!empty($a['picked']) !== !empty($b['picked'])) {
  12529. return !empty($a['picked']) ? -1 : 1;
  12530. }
  12531. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  12532. if ($c !== 0) {
  12533. return $c;
  12534. }
  12535. return 0;
  12536. });
  12537. return $lines;
  12538. }
  12539. /**
  12540. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  12541. *
  12542. * @param array<int, array<string, mixed>> $quoteLines
  12543. */
  12544. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  12545. {
  12546. $mon = (int)substr($ym, 5, 2);
  12547. $titleRow = $startRow;
  12548. $headerRow = $startRow + 1;
  12549. $dataStartRow = $startRow + 2;
  12550. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  12551. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  12552. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  12553. $sheet->getStyle('A' . $titleRow)->getAlignment()
  12554. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12555. ->setVertical(Alignment::VERTICAL_CENTER);
  12556. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  12557. $col = 'A';
  12558. foreach ($headers as $h) {
  12559. $sheet->setCellValue($col . $headerRow, $h);
  12560. $col++;
  12561. }
  12562. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  12563. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12564. $rowNum = $dataStartRow;
  12565. if ($quoteLines === []) {
  12566. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  12567. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  12568. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12569. $rowNum = $dataStartRow + 1;
  12570. } else {
  12571. $i = 0;
  12572. foreach ($quoteLines as $line) {
  12573. $i++;
  12574. $sheet->setCellValue('A' . $rowNum, $i);
  12575. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  12576. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  12577. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  12578. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  12579. if ($line['amount_num'] !== null) {
  12580. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  12581. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  12582. } else {
  12583. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  12584. }
  12585. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  12586. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  12587. if (!empty($line['picked'])) {
  12588. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  12589. }
  12590. $rowNum++;
  12591. }
  12592. }
  12593. $lastRow = $rowNum - 1;
  12594. if ($lastRow >= $headerRow) {
  12595. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  12596. 'borders' => [
  12597. 'allBorders' => [
  12598. 'borderStyle' => Border::BORDER_THIN,
  12599. 'color' => ['rgb' => '000000'],
  12600. ],
  12601. ],
  12602. ]);
  12603. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  12604. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12605. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12606. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12607. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  12608. if ($lastRow >= $dataStartRow) {
  12609. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  12610. }
  12611. }
  12612. return $lastRow;
  12613. }
  12614. /**
  12615. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  12616. */
  12617. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  12618. {
  12619. if ($lastRow < $dataStartRow || $headerRow < 1) {
  12620. return;
  12621. }
  12622. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  12623. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12624. ->setVertical(Alignment::VERTICAL_CENTER);
  12625. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  12626. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12627. ->setVertical(Alignment::VERTICAL_CENTER);
  12628. if ($lastCol > 'B') {
  12629. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  12630. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  12631. ->setVertical(Alignment::VERTICAL_CENTER);
  12632. }
  12633. }
  12634. /**
  12635. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  12636. */
  12637. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  12638. {
  12639. $s = trim($ccydh);
  12640. if ($s === '') {
  12641. return 'ORDER';
  12642. }
  12643. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  12644. $s = trim($s, '._-');
  12645. if ($s === '') {
  12646. return 'ORDER';
  12647. }
  12648. if (function_exists('mb_substr')) {
  12649. return mb_substr($s, 0, 80, 'UTF-8');
  12650. }
  12651. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  12652. }
  12653. /**
  12654. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  12655. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  12656. *
  12657. * @return array{objectKey: string, webPath: string}
  12658. */
  12659. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  12660. {
  12661. $sid = (int)$scydgyId;
  12662. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  12663. $y = date('Y');
  12664. $m = date('m');
  12665. $d = date('d');
  12666. $basename = $safeOrder . '_' . $sid . '.pdf';
  12667. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  12668. return [
  12669. 'objectKey' => $objectKey,
  12670. 'webPath' => '/' . $objectKey,
  12671. ];
  12672. }
  12673. /**
  12674. * 采购确认成功后 / 已完结刷新:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  12675. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  12676. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  12677. * 说明:审批通过时会先存一版;质量+交货评分使订单「已完结」后,详情页打开或评分保存完成时会再重存,以含最终步骤与操作记录。
  12678. *
  12679. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  12680. */
  12681. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  12682. {
  12683. if (!$this->isValidScydgyRowId($scydgyId)) {
  12684. return '';
  12685. }
  12686. $ids = trim((string)$scydgyId);
  12687. $prep = $this->prepareProcuremenDetailsView($ids);
  12688. if (!$prep['ok']) {
  12689. return '';
  12690. }
  12691. $ccydh = $prep['ccydh'];
  12692. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  12693. $objectKey = $paths['objectKey'];
  12694. $webPath = $paths['webPath'];
  12695. $cyjmc = '';
  12696. try {
  12697. $poMeta = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->field('CYJMC')->find();
  12698. if (is_array($poMeta)) {
  12699. $cyjmc = trim((string)($poMeta['CYJMC'] ?? ''));
  12700. }
  12701. } catch (\Throwable $e) {
  12702. $cyjmc = '';
  12703. }
  12704. $genTime = date('Y-m-d H:i:s');
  12705. $metaIds = '工序行ID ' . $ids . ' | 主表订单ID ' . (int)$purchaseOrderId;
  12706. $metaLeft = $metaIds . ($cyjmc !== '' ? ' | ' . $cyjmc : '');
  12707. // PDF 进度:去掉「未发」;节点用纯色圆点(不用图片,避免 mPDF 破图)
  12708. $pdfSteps = [];
  12709. $viewSteps = $prep['steps'] ?? [];
  12710. if (is_array($viewSteps)) {
  12711. foreach ($viewSteps as $st) {
  12712. if (!is_array($st)) {
  12713. continue;
  12714. }
  12715. if (trim((string)($st['title'] ?? '')) === '未发') {
  12716. continue;
  12717. }
  12718. $pdfSteps[] = $st;
  12719. }
  12720. }
  12721. $pdfStepW = count($pdfSteps) > 0 ? (round(100 / count($pdfSteps), 2) . '%') : '16.66%';
  12722. $nPdf = count($pdfSteps);
  12723. foreach ($pdfSteps as $idx => &$pst) {
  12724. if ($idx === 0) {
  12725. $pst['pdf_left_bg'] = '';
  12726. } else {
  12727. $pst['pdf_left_bg'] = !empty($pdfSteps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  12728. }
  12729. if ($idx >= $nPdf - 1) {
  12730. $pst['pdf_right_bg'] = '';
  12731. } else {
  12732. $pst['pdf_right_bg'] = !empty($pst['done']) ? '#1890ff' : '#e0e0e0';
  12733. }
  12734. }
  12735. unset($pst);
  12736. $this->view->assign([
  12737. 'pdf_export' => 1,
  12738. 'pdfMetaLine' => $metaLeft,
  12739. 'pdfMetaLeft' => $metaLeft,
  12740. 'pdfMetaIds' => $metaIds,
  12741. 'pdfMetaTitle' => $cyjmc,
  12742. 'pdfMetaTime' => 'PDF生成时间 ' . $genTime,
  12743. 'pdfSteps' => $pdfSteps,
  12744. 'pdfStepWidth' => $pdfStepW,
  12745. ]);
  12746. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  12747. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  12748. $this->view->engine->layout(false);
  12749. try {
  12750. $html = $this->view->fetch('procuremen/details_pdf_shell');
  12751. } catch (\Throwable $e) {
  12752. if ($restoreLayout) {
  12753. $this->view->engine->layout($restoreLayout);
  12754. }
  12755. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  12756. $this->view->assign([
  12757. 'pdf_export' => '', 'pdfMetaLine' => '', 'pdfMetaLeft' => '',
  12758. 'pdfMetaIds' => '', 'pdfMetaTitle' => '', 'pdfMetaTime' => '',
  12759. 'pdfSteps' => [], 'pdfStepWidth' => '',
  12760. ]);
  12761. return '';
  12762. }
  12763. if ($restoreLayout) {
  12764. $this->view->engine->layout($restoreLayout);
  12765. }
  12766. $this->view->assign([
  12767. 'pdf_export' => '', 'pdfMetaLine' => '', 'pdfMetaLeft' => '',
  12768. 'pdfMetaIds' => '', 'pdfMetaTitle' => '', 'pdfMetaTime' => '',
  12769. 'pdfSteps' => [], 'pdfStepWidth' => '',
  12770. ]);
  12771. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  12772. if (!is_dir($tempDir)) {
  12773. @mkdir($tempDir, 0755, true);
  12774. }
  12775. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  12776. try {
  12777. $mpdf = new \Mpdf\Mpdf([
  12778. 'mode' => 'utf-8',
  12779. 'format' => 'A4',
  12780. 'margin_left' => 12,
  12781. 'margin_right' => 12,
  12782. 'margin_top' => 14,
  12783. 'margin_bottom' => 14,
  12784. 'tempDir' => $tempDir,
  12785. 'autoScriptToLang' => true,
  12786. 'autoLangToFont' => true,
  12787. ]);
  12788. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  12789. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  12790. $mpdf->SetBasePath('http://127.0.0.1/');
  12791. $mpdf->WriteHTML($html);
  12792. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  12793. } catch (\Throwable $e) {
  12794. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  12795. if (is_file($tempPdf)) {
  12796. @unlink($tempPdf);
  12797. }
  12798. return '';
  12799. }
  12800. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  12801. if ($ossUrl !== '') {
  12802. @unlink($tempPdf);
  12803. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12804. return $ossUrl;
  12805. }
  12806. $pi = pathinfo($objectKey);
  12807. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  12808. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  12809. if ($baseFile === '') {
  12810. @unlink($tempPdf);
  12811. return '';
  12812. }
  12813. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  12814. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  12815. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  12816. @unlink($tempPdf);
  12817. return '';
  12818. }
  12819. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  12820. if (!@copy($tempPdf, $fullPath)) {
  12821. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  12822. @unlink($tempPdf);
  12823. return '';
  12824. }
  12825. @unlink($tempPdf);
  12826. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12827. return $webPath;
  12828. }
  12829. /**
  12830. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  12831. */
  12832. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  12833. {
  12834. if ($scydgyId <= 0 || $webPath === '') {
  12835. return;
  12836. }
  12837. try {
  12838. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  12839. } catch (\Throwable $e) {
  12840. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  12841. }
  12842. }
  12843. /**
  12844. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  12845. *
  12846. * @param array<string, string> $vars
  12847. * @return array<string, string>
  12848. */
  12849. protected function normalizeSmsTemplateVars(array $vars): array
  12850. {
  12851. $out = [];
  12852. foreach ($vars as $k => $v) {
  12853. $out[(string)$k] = trim((string)$v);
  12854. }
  12855. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  12856. $out['contact_name'] = $out['company_name'];
  12857. }
  12858. return $out;
  12859. }
  12860. /**
  12861. * 按手机号或公司名称查 customer 表联系人姓名
  12862. */
  12863. protected function resolveCustomerContactName(string $phone, string $companyName): string
  12864. {
  12865. $phone = trim($phone);
  12866. $companyName = trim($companyName);
  12867. try {
  12868. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  12869. $row = Db::table('customer')
  12870. ->where(function ($q) use ($phone) {
  12871. $q->where('phone', $phone)->whereOr('account', $phone);
  12872. })
  12873. ->order('id', 'asc')
  12874. ->find();
  12875. if (is_array($row)) {
  12876. $nm = trim((string)($row['username'] ?? ''));
  12877. if ($nm !== '') {
  12878. return $nm;
  12879. }
  12880. }
  12881. }
  12882. if ($companyName !== '') {
  12883. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  12884. if (is_array($row)) {
  12885. return trim((string)($row['username'] ?? ''));
  12886. }
  12887. }
  12888. } catch (\Throwable $e) {
  12889. }
  12890. return '';
  12891. }
  12892. /**
  12893. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;;http(s) 链接做成可点的 &lt;a&gt;(微信 QQ 邮箱提醒纯文本 URL 常不可点)
  12894. */
  12895. protected function plainTextToHtmlEmailBody(string $text): string
  12896. {
  12897. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  12898. $parts = explode("\n", $text);
  12899. $out = [];
  12900. foreach ($parts as $line) {
  12901. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  12902. $out[] = $line;
  12903. } else {
  12904. $esc = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  12905. $esc = preg_replace(
  12906. '#(https?://[^\s<>"\']+)#iu',
  12907. '<a href="$1" style="color:#1565c0;text-decoration:underline;word-break:break-all;">$1</a>',
  12908. $esc
  12909. );
  12910. $out[] = $esc;
  12911. }
  12912. }
  12913. return implode("<br>\n", $out);
  12914. }
  12915. /**
  12916. * 短信场景:去掉链接类变量,避免误填 URL
  12917. *
  12918. * @param array<string, string> $vars
  12919. * @return array<string, string>
  12920. */
  12921. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  12922. {
  12923. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  12924. return $vars;
  12925. }
  12926. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  12927. $vars[$k] = '';
  12928. }
  12929. return $vars;
  12930. }
  12931. /**
  12932. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  12933. *
  12934. * @param array<string, string> $vars
  12935. */
  12936. protected function renderNotifyTemplate(string $scene, array $vars): string
  12937. {
  12938. $vars = $this->normalizeSmsTemplateVars($vars);
  12939. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  12940. $row = $this->loadNotifyTemplateRow($scene);
  12941. if ($row === null) {
  12942. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12943. }
  12944. $tpl = trim((string)($row['content'] ?? ''));
  12945. if ($tpl === '') {
  12946. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12947. }
  12948. foreach ($vars as $k => $v) {
  12949. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  12950. }
  12951. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  12952. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  12953. return $tpl;
  12954. }
  12955. protected function resolveProcuremenEmailSubject(string $scene): string
  12956. {
  12957. // 询价 / 采购确认结果邮箱:模版名称即邮件主题
  12958. if (in_array($scene, ['rfq_salesman_email', 'rfq_supplier_email', 'confirm_ok_email', 'confirm_fail_email'], true)) {
  12959. $row = $this->loadNotifyTemplateRow($scene);
  12960. $title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
  12961. if ($title !== '') {
  12962. return $title;
  12963. }
  12964. $fallback = [
  12965. 'rfq_supplier_email' => '供应商询价通知',
  12966. 'rfq_salesman_email' => '协助采购询价通知',
  12967. 'confirm_ok_email' => '采购确认结果:已通过',
  12968. 'confirm_fail_email' => '采购确认结果:未通过',
  12969. ];
  12970. return $fallback[$scene] ?? '协助采购通知';
  12971. }
  12972. $map = [
  12973. 'review_email' => '您有新的协助加工订单',
  12974. ];
  12975. $subject = trim((string)($map[$scene] ?? ''));
  12976. if ($subject === '') {
  12977. $this->error('未配置邮件主题:' . $scene);
  12978. }
  12979. return $subject;
  12980. }
  12981. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  12982. {
  12983. $map = [
  12984. 'review_email' => '协助下发-邮箱',
  12985. 'review_sms' => '协助下发-短信',
  12986. 'confirm_ok' => '采购确认-通过',
  12987. 'confirm_fail' => '采购确认-未通过',
  12988. 'confirm_ok_email' => '采购确认通过-邮箱',
  12989. 'confirm_fail_email' => '采购确认未通过-邮箱',
  12990. 'bid_open' => '开标双重验证',
  12991. 'rfq_salesman_email' => '询价通知业务员-邮箱',
  12992. 'rfq_supplier_email' => '供应商询价通知',
  12993. ];
  12994. $label = $map[$scene] ?? $scene;
  12995. if ($titleRequired) {
  12996. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  12997. }
  12998. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  12999. }
  13000. /**
  13001. * 是否开启协助通知演练(不发真实短信/邮件)
  13002. */
  13003. protected function isProcuremenNotifyDryRun(): bool
  13004. {
  13005. return (bool)Config::get('procuremen_notify_dry_run');
  13006. }
  13007. /**
  13008. * @param array<string, mixed> $payload
  13009. */
  13010. protected function recordNotifyDryRunPreview(array $payload): void
  13011. {
  13012. $this->notifyDryRunPreview[] = $payload;
  13013. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  13014. }
  13015. /**
  13016. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  13017. * @throws \Exception
  13018. */
  13019. protected function smsbao($phone, $content)
  13020. {
  13021. if ($this->isProcuremenNotifyDryRun()) {
  13022. $this->recordNotifyDryRunPreview([
  13023. 'scene' => 'sms_only',
  13024. 'phone' => $phone,
  13025. 'sms_content' => $content,
  13026. ]);
  13027. return;
  13028. }
  13029. $statusStr = [
  13030. '0' => '短信发送成功',
  13031. '-1' => '参数不全',
  13032. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  13033. '30' => '密码错误',
  13034. '40' => '账号不存在',
  13035. '41' => '余额不足',
  13036. '42' => '帐户已过期',
  13037. '43' => 'IP地址限制',
  13038. '50' => '内容含有敏感词',
  13039. ];
  13040. $smsapi = 'http://api.smsbao.com/';
  13041. $user = 'zhuwei123';
  13042. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  13043. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  13044. $result = @file_get_contents($sendurl);
  13045. if ($result === false) {
  13046. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  13047. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  13048. }
  13049. $result = trim((string)$result);
  13050. if ($result !== '0') {
  13051. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  13052. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  13053. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  13054. }
  13055. }
  13056. }