Procuremen.php 520 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739
  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. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  4449. $this->success('操作成功');
  4450. return;
  4451. }
  4452. if ($exists) {
  4453. $upd = $data;
  4454. unset($upd['scydgy_id'], $upd['status']);
  4455. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4456. } else {
  4457. // 新增:不写 status(空/走库默认);仅写创建时间
  4458. $data['createtime'] = date('Y-m-d H:i:s');
  4459. Db::table('purchase_order')->insert($data);
  4460. }
  4461. } catch (\Throwable $e) {
  4462. $this->error($e->getMessage());
  4463. }
  4464. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  4465. $this->success('操作成功');
  4466. }
  4467. /**
  4468. * 未发列表
  4469. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  4470. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  4471. */
  4472. public function completeDirectly()
  4473. {
  4474. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4475. $this->error(__('参数错误'));
  4476. }
  4477. if (!$this->procuremenCanComplete()) {
  4478. $this->error(__('You have no permission'));
  4479. }
  4480. $row = json_decode($this->request->post('row_json', ''), true);
  4481. if (!is_array($row)) {
  4482. $this->error(__('Invalid parameters'));
  4483. }
  4484. $finishRaw = $this->request->post('finish', '1');
  4485. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  4486. $poIdLog = null;
  4487. try {
  4488. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  4489. $ids = $this->extractScydgyRowId($row);
  4490. if (!$this->isValidScydgyRowId($ids)) {
  4491. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4492. }
  4493. if ($asComplete) {
  4494. $this->assertPickRowCanComplete($ids, $row);
  4495. }
  4496. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4497. $data = [
  4498. 'scydgy_id' => $ids,
  4499. 'CCYDH' => $row['CCYDH'] ?? null,
  4500. 'CYJMC' => $row['CYJMC'] ?? null,
  4501. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4502. 'CDXMC' => $row['CDXMC'] ?? null,
  4503. 'CGYBH' => $row['CGYBH'] ?? null,
  4504. 'CGYMC' => $row['CGYMC'] ?? null,
  4505. 'CDW' => $row['CDW'] ?? null,
  4506. 'czlyq' => $row['czlyq'] ?? null,
  4507. 'NGZL' => $row['NGZL'] ?? null,
  4508. 'CDF' => $row['CDF'] ?? null,
  4509. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4510. 'MBZ' => $row['MBZ'] ?? null,
  4511. 'bwjg' => $row['bwjg'] ?? null,
  4512. 'iStatus' => $row['iStatus'] ?? null,
  4513. 'dStamp' => $row['dStamp'] ?? null,
  4514. 'dputrecord' => $row['dputrecord'] ?? null,
  4515. 'cywyxm' => $row['cywyxm'] ?? null,
  4516. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4517. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4518. ];
  4519. if ($asComplete) {
  4520. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  4521. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  4522. }
  4523. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  4524. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  4525. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  4526. $this->success('操作成功');
  4527. return;
  4528. }
  4529. if ($exists) {
  4530. $upd = $data;
  4531. unset($upd['scydgy_id']);
  4532. if (!$asComplete) {
  4533. unset($upd['status']);
  4534. }
  4535. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4536. } else {
  4537. // 新增:不写 status;完结时 $data 已含 status=1
  4538. $data['createtime'] = date('Y-m-d H:i:s');
  4539. Db::table('purchase_order')->insert($data);
  4540. }
  4541. } catch (\Throwable $e) {
  4542. $this->error($e->getMessage());
  4543. }
  4544. try {
  4545. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4546. if (is_array($rpo)) {
  4547. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4548. $poIdLog = $tid > 0 ? $tid : null;
  4549. }
  4550. } catch (\Throwable $e) {
  4551. $poIdLog = null;
  4552. }
  4553. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  4554. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  4555. if ($asComplete) {
  4556. $this->addOrderLog(
  4557. $ids,
  4558. 'mark_complete',
  4559. '点击「完结」,已标记为已完结',
  4560. $poIdLog
  4561. );
  4562. try {
  4563. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  4564. if ($pdfPublicPath === '') {
  4565. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  4566. }
  4567. } catch (\Throwable $e) {
  4568. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  4569. }
  4570. } else {
  4571. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  4572. $qtyPart = '本次数量「' . ($q !== '' ? $q : '') . '」';
  4573. $pricePart = '最高限价「' . ($p !== '' ? $p : '') . '」';
  4574. $detail = ($gymc !== '' ? ($gymc . $qtyPart) : $qtyPart) . ',' . $pricePart;
  4575. $this->addOrderLog(
  4576. $ids,
  4577. 'save_qty_price',
  4578. '保存本次数量、最高限价:' . $detail,
  4579. $poIdLog
  4580. );
  4581. }
  4582. $this->pickHiddenScydgySetCache = null;
  4583. $this->success("操作成功");
  4584. }
  4585. /**
  4586. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  4587. *
  4588. * @param array<int, array> $rows 引用传递当前页行
  4589. */
  4590. protected function mergePurchaseOrder(array &$rows)
  4591. {
  4592. if ($rows === []) {
  4593. return;
  4594. }
  4595. $ids = [];
  4596. foreach ($rows as $rw) {
  4597. if (!is_array($rw)) {
  4598. continue;
  4599. }
  4600. $id = (int)($rw['ID'] ?? 0);
  4601. // 含手工新增负数 scydgy_id,避免限价/数量不同步
  4602. if ($this->isValidScydgyRowId($id)) {
  4603. $ids[$id] = true;
  4604. }
  4605. }
  4606. $idList = array_keys($ids);
  4607. if ($idList === []) {
  4608. return;
  4609. }
  4610. try {
  4611. $list = Db::table('purchase_order')
  4612. ->where('scydgy_id', 'in', $idList)
  4613. ->field('scydgy_id,This_quantity,ceilingPrice')
  4614. ->select();
  4615. } catch (\Throwable $e) {
  4616. return;
  4617. }
  4618. if (!is_array($list)) {
  4619. return;
  4620. }
  4621. $byId = [];
  4622. foreach ($list as $dbRow) {
  4623. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4624. continue;
  4625. }
  4626. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4627. }
  4628. foreach ($rows as &$rw) {
  4629. if (!is_array($rw)) {
  4630. continue;
  4631. }
  4632. $sid = (int)($rw['ID'] ?? 0);
  4633. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  4634. continue;
  4635. }
  4636. $db = $byId[$sid];
  4637. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  4638. if (array_key_exists('This_quantity', $db)) {
  4639. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  4640. }
  4641. if (array_key_exists('ceilingPrice', $db)) {
  4642. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  4643. } elseif (array_key_exists('ceiling_price', $db)) {
  4644. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  4645. }
  4646. }
  4647. unset($rw);
  4648. }
  4649. /**
  4650. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  4651. */
  4652. public function purchaseConfirmPick()
  4653. {
  4654. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4655. $this->error(__('Invalid parameters'));
  4656. }
  4657. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  4658. $this->error(__('You have no permission'));
  4659. }
  4660. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  4661. if ($batchRaw !== '') {
  4662. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  4663. return;
  4664. }
  4665. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  4666. $sid = (int)$scydgyId;
  4667. if (!$this->isValidScydgyRowId($sid)) {
  4668. $this->error('参数无效');
  4669. }
  4670. $parseIdList = function ($raw) {
  4671. if (is_array($raw)) {
  4672. $arr = $raw;
  4673. } else {
  4674. $decoded = json_decode((string)$raw, true);
  4675. $arr = is_array($decoded) ? $decoded : [];
  4676. }
  4677. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  4678. };
  4679. $selectedRaw = $this->request->post('selected_ids', null);
  4680. if ($selectedRaw === null || $selectedRaw === '') {
  4681. $legacy = (int)$this->request->post('selected_id', 0);
  4682. $selectedIds = $legacy > 0 ? [$legacy] : [];
  4683. } else {
  4684. $selectedIds = $parseIdList($selectedRaw);
  4685. }
  4686. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  4687. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  4688. try {
  4689. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  4690. } catch (\InvalidArgumentException $e) {
  4691. $this->error($e->getMessage());
  4692. } catch (\Throwable $e) {
  4693. $this->error($e->getMessage());
  4694. }
  4695. $this->pickHiddenScydgySetCache = null;
  4696. $this->success('操作成功', '', $result);
  4697. }
  4698. /**
  4699. * 整单采购确认(多道工序一次提交)
  4700. */
  4701. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  4702. {
  4703. $decoded = json_decode($batchRaw, true);
  4704. if (!is_array($decoded) || $decoded === []) {
  4705. $this->error('提交数据无效');
  4706. }
  4707. $picks = [];
  4708. foreach ($decoded as $item) {
  4709. if (!is_array($item)) {
  4710. continue;
  4711. }
  4712. $sid = (int)($item['scydgy_id'] ?? 0);
  4713. if (!$this->isValidScydgyRowId($sid)) {
  4714. continue;
  4715. }
  4716. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  4717. if (!is_array($sel)) {
  4718. $sel = [(int)$sel];
  4719. }
  4720. $unsel = $item['unselected_ids'] ?? [];
  4721. if (!is_array($unsel)) {
  4722. $unsel = json_decode((string)$unsel, true);
  4723. $unsel = is_array($unsel) ? $unsel : [];
  4724. }
  4725. $picks[] = [
  4726. 'scydgy_id' => $sid,
  4727. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  4728. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  4729. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  4730. ];
  4731. }
  4732. if ($picks === []) {
  4733. $this->error('提交数据无效');
  4734. }
  4735. Db::startTrans();
  4736. $results = [];
  4737. try {
  4738. foreach ($picks as $pick) {
  4739. $results[] = $this->runPurchaseConfirmPick(
  4740. (int)$pick['scydgy_id'],
  4741. $pick['selected_ids'],
  4742. $pick['unselected_ids'],
  4743. (int)$pick['purchase_order_id'],
  4744. false,
  4745. false
  4746. );
  4747. }
  4748. Db::commit();
  4749. } catch (\Throwable $e) {
  4750. Db::rollback();
  4751. $msg = $e->getMessage();
  4752. $this->error($msg !== '' ? $msg : '提交失败');
  4753. }
  4754. try {
  4755. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  4756. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  4757. } catch (\Throwable $e) {
  4758. Log::write('采购确认通知批量发送异常: ' . $e->getMessage(), 'error');
  4759. }
  4760. $this->pickHiddenScydgySetCache = null;
  4761. $this->success('操作成功', '', ['batch' => $results]);
  4762. }
  4763. /**
  4764. * @return array<string, mixed>
  4765. */
  4766. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  4767. {
  4768. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  4769. ProcuremenGuard::assertWflowPendingApproval($poRow);
  4770. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  4771. $scydgyId = (string)$sid;
  4772. if ($selectedIds === []) {
  4773. throw new \InvalidArgumentException('请至少勾选一条明细');
  4774. }
  4775. $inter = array_intersect($selectedIds, $unselectedIds);
  4776. if ($inter !== []) {
  4777. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  4778. }
  4779. $allIds = $this->purchaseOrderDetail($sid);
  4780. if ($allIds === []) {
  4781. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  4782. }
  4783. foreach ($selectedIds as $id) {
  4784. if (!in_array($id, $allIds, true)) {
  4785. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  4786. }
  4787. }
  4788. foreach ($unselectedIds as $id) {
  4789. if (!in_array($id, $allIds, true)) {
  4790. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  4791. }
  4792. }
  4793. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  4794. sort($union, SORT_NUMERIC);
  4795. $expect = $allIds;
  4796. sort($expect, SORT_NUMERIC);
  4797. if ($union !== $expect) {
  4798. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  4799. }
  4800. if ($manageTransaction) {
  4801. Db::startTrans();
  4802. }
  4803. try {
  4804. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  4805. $aff = 0;
  4806. try {
  4807. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4808. } catch (\Throwable $e) {
  4809. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4810. }
  4811. if ($aff < 1) {
  4812. throw new \Exception('更新选中状态失败');
  4813. }
  4814. $poPayload = [
  4815. // 审核通过后进入「待入库评分」;合格/不合格后才置已完结
  4816. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  4817. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  4818. ];
  4819. if ($purchaseOrderId > 0) {
  4820. $poAff = (int)Db::table('purchase_order')
  4821. ->where('id', $purchaseOrderId)
  4822. ->where('scydgy_id', $sid)
  4823. ->update($poPayload);
  4824. if ($poAff < 1) {
  4825. throw new \Exception('主表订单不存在或与工序行不匹配');
  4826. }
  4827. } else {
  4828. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  4829. if ($poAff < 1) {
  4830. throw new \Exception('未找到');
  4831. }
  4832. }
  4833. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  4834. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  4835. if ($manageTransaction) {
  4836. Db::commit();
  4837. }
  4838. } catch (\Throwable $e) {
  4839. if ($manageTransaction) {
  4840. Db::rollback();
  4841. }
  4842. throw $e;
  4843. }
  4844. $poIdFinal = $purchaseOrderId;
  4845. if ($poIdFinal <= 0) {
  4846. try {
  4847. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4848. if (is_array($rpo)) {
  4849. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4850. }
  4851. } catch (\Throwable $e) {
  4852. $poIdFinal = 0;
  4853. }
  4854. }
  4855. $pickNames = [];
  4856. foreach ($selectedIds as $pid) {
  4857. $dr = $this->purchaseOrderDetai($sid, $pid);
  4858. $nm = trim((string)($dr['company_name'] ?? ''));
  4859. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  4860. }
  4861. $this->addOrderLog(
  4862. $sid,
  4863. 'purchase_confirm',
  4864. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  4865. $poIdFinal > 0 ? $poIdFinal : null
  4866. );
  4867. if ($sendNotifications) {
  4868. try {
  4869. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  4870. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  4871. 'scydgy_id' => $sid,
  4872. 'selected_ids' => $selectedIds,
  4873. 'unselected_ids' => $unselectedIds,
  4874. 'purchase_order_id' => $purchaseOrderId,
  4875. ]]);
  4876. } catch (\Throwable $e) {
  4877. Log::write('采购确认通知发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  4878. }
  4879. }
  4880. Log::write(sprintf(
  4881. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  4882. $scydgyId,
  4883. $purchaseOrderId,
  4884. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  4885. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  4886. ), 'notice');
  4887. $pdfPublicPath = '';
  4888. try {
  4889. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  4890. } catch (\Throwable $e) {
  4891. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  4892. }
  4893. return [
  4894. 'scydgy_id' => $scydgyId,
  4895. 'purchase_order_id' => $purchaseOrderId,
  4896. 'selected_ids' => $selectedIds,
  4897. 'unselected_ids' => $unselectedIds,
  4898. 'purchase_confirm_pdf' => $pdfPublicPath,
  4899. ];
  4900. }
  4901. /**
  4902. * 审批通过短信:按本次涉及的工序汇总 process_lines
  4903. *
  4904. * @param int[]|string[] $scydgyIds
  4905. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4906. */
  4907. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  4908. {
  4909. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4910. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4911. if ($scydgyIds === []) {
  4912. return $empty;
  4913. }
  4914. $pos = [];
  4915. try {
  4916. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  4917. } catch (\Throwable $e) {
  4918. $rows = [];
  4919. }
  4920. if (is_array($rows)) {
  4921. foreach ($rows as $po) {
  4922. if (is_array($po)) {
  4923. $pos[] = $po;
  4924. }
  4925. }
  4926. }
  4927. if ($pos === []) {
  4928. return $empty;
  4929. }
  4930. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  4931. return [
  4932. 'ccydh' => $ccydh,
  4933. 'pos' => $pos,
  4934. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4935. ];
  4936. }
  4937. /**
  4938. * 审批通过/未通过:短信 + 邮件(同一供应商只发一条;邮件含平台链接)
  4939. *
  4940. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  4941. * @param array<int, array<string, mixed>> $picks
  4942. */
  4943. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  4944. {
  4945. if ($picks === []) {
  4946. return;
  4947. }
  4948. $this->ensureConfirmResultEmailTemplates();
  4949. $fallbackDetailId = 0;
  4950. $winners = [];
  4951. $losers = [];
  4952. foreach ($picks as $pick) {
  4953. if (!is_array($pick)) {
  4954. continue;
  4955. }
  4956. $sid = (int)($pick['scydgy_id'] ?? 0);
  4957. if (!$this->isValidScydgyRowId($sid)) {
  4958. continue;
  4959. }
  4960. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  4961. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  4962. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  4963. $fallbackDetailId = (int)$selectedIds[0];
  4964. }
  4965. foreach ($selectedIds as $pid) {
  4966. $dr = $this->purchaseOrderDetai($sid, $pid);
  4967. if (!is_array($dr)) {
  4968. continue;
  4969. }
  4970. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  4971. }
  4972. foreach ($unselectedIds as $pid) {
  4973. $dr = $this->purchaseOrderDetai($sid, $pid);
  4974. if (!is_array($dr)) {
  4975. continue;
  4976. }
  4977. $key = $this->notifySupplierDedupeKey($dr);
  4978. if (!isset($winners[$key])) {
  4979. $losers[$key] = $dr;
  4980. }
  4981. }
  4982. }
  4983. if ($winners === [] && $losers === []) {
  4984. return;
  4985. }
  4986. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  4987. $poIdLog = 0;
  4988. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  4989. if (isset($pos[0]) && is_array($pos[0])) {
  4990. $poIdLog = (int)($pos[0]['id'] ?? 0);
  4991. }
  4992. $sendSmsSafe = function ($phone, $content) {
  4993. $phone = trim((string)$phone);
  4994. if ($phone === '') {
  4995. return;
  4996. }
  4997. try {
  4998. $this->smsbao($phone, $content);
  4999. } catch (\Throwable $e) {
  5000. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  5001. }
  5002. };
  5003. $sendConfirmEmailSafe = function (array $dr, string $emailScene) use ($confirmNotifyVars, $poIdLog) {
  5004. $cname = trim((string)($dr['company_name'] ?? ''));
  5005. $ph = trim((string)($dr['phone'] ?? ''));
  5006. $toEmail = trim((string)($dr['email'] ?? ''));
  5007. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  5008. Log::write('采购确认邮件跳过:无有效邮箱 company=' . $cname, 'error');
  5009. return;
  5010. }
  5011. $detailId = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5012. if ($detailId <= 0) {
  5013. $detailId = (int)($confirmNotifyVars['_fallback_detail_id'] ?? 0);
  5014. }
  5015. try {
  5016. $platformUrl = $this->buildMprocMobileOrderUrl($detailId);
  5017. } catch (\Throwable $e) {
  5018. Log::write('采购确认邮件链接失败: ' . $e->getMessage(), 'error');
  5019. $platformUrl = '';
  5020. }
  5021. $vars = array_merge($confirmNotifyVars, [
  5022. 'company_name' => $cname,
  5023. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5024. 'phone' => $ph,
  5025. 'email' => $toEmail,
  5026. 'platform_url' => $platformUrl,
  5027. ]);
  5028. unset($vars['_fallback_detail_id']);
  5029. try {
  5030. $mailPlain = $this->renderNotifyTemplate($emailScene, $vars);
  5031. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  5032. $mailSubject = $this->resolveProcuremenEmailSubject($emailScene);
  5033. $mailConfig = $this->loadMailerConfig();
  5034. $this->issueSendSupplierEmail([
  5035. 'company_name' => $cname,
  5036. 'email' => $toEmail,
  5037. 'mail_plain' => $mailPlain,
  5038. 'mail_body' => $mailBody,
  5039. 'notify_vars' => $vars,
  5040. 'sms_content' => '',
  5041. 'detail_links' => $platformUrl !== '' ? [['url' => $platformUrl, 'cgymc' => '']] : [],
  5042. 'email_log_scene' => 'confirm_result',
  5043. 'email_log_scydgy_id' => (int)($dr['scydgy_id'] ?? 0),
  5044. 'email_log_purchase_order_id' => $poIdLog,
  5045. ], $mailConfig, $mailSubject);
  5046. } catch (\Throwable $e) {
  5047. Log::write('采购确认邮件失败 company=' . $cname . ' email=' . $toEmail . ' ' . $e->getMessage(), 'error');
  5048. }
  5049. };
  5050. $confirmNotifyVars['_fallback_detail_id'] = $fallbackDetailId;
  5051. foreach ($winners as $dr) {
  5052. $cname = trim((string)($dr['company_name'] ?? ''));
  5053. $ph = trim((string)($dr['phone'] ?? ''));
  5054. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  5055. 'company_name' => $cname,
  5056. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5057. 'phone' => $ph,
  5058. ]));
  5059. $sendSmsSafe($ph, $sms);
  5060. $sendConfirmEmailSafe($dr, 'confirm_ok_email');
  5061. }
  5062. foreach ($losers as $dr) {
  5063. $cname = trim((string)($dr['company_name'] ?? ''));
  5064. $ph = trim((string)($dr['phone'] ?? ''));
  5065. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  5066. 'company_name' => $cname,
  5067. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5068. 'phone' => $ph,
  5069. ]));
  5070. $sendSmsSafe($ph, $sms);
  5071. $sendConfirmEmailSafe($dr, 'confirm_fail_email');
  5072. }
  5073. }
  5074. /**
  5075. * 短信去重键:优先手机号,否则公司名
  5076. */
  5077. protected function notifySupplierDedupeKey(array $detailRow): string
  5078. {
  5079. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  5080. if ($ph !== '') {
  5081. return 'p:' . $ph;
  5082. }
  5083. $cn = trim((string)($detailRow['company_name'] ?? ''));
  5084. return 'c:' . $cn;
  5085. }
  5086. /**
  5087. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  5088. *
  5089. * @param int[] $detailIds
  5090. */
  5091. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  5092. {
  5093. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  5094. if ($detailIds === []) {
  5095. return;
  5096. }
  5097. $payload = ['status_name' => $statusName];
  5098. try {
  5099. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  5100. } catch (\Throwable $e) {
  5101. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  5102. }
  5103. }
  5104. /**
  5105. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  5106. */
  5107. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  5108. {
  5109. try {
  5110. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  5111. } catch (\Throwable $e) {
  5112. return;
  5113. }
  5114. if (!is_array($rows)) {
  5115. return;
  5116. }
  5117. foreach ($rows as $dr) {
  5118. if (!is_array($dr)) {
  5119. continue;
  5120. }
  5121. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5122. if ($id <= 0) {
  5123. continue;
  5124. }
  5125. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  5126. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  5127. try {
  5128. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  5129. } catch (\Throwable $e) {
  5130. }
  5131. }
  5132. }
  5133. /**
  5134. * @param array<string, mixed> $detailRow
  5135. */
  5136. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  5137. {
  5138. $am = $detailRow['amount'] ?? null;
  5139. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  5140. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  5141. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  5142. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  5143. }
  5144. /**
  5145. * @return int[]
  5146. */
  5147. protected function purchaseOrderDetail(int $scydgyId): array
  5148. {
  5149. if (!$this->isValidScydgyRowId($scydgyId)) {
  5150. return [];
  5151. }
  5152. try {
  5153. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  5154. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  5155. $list = $listQuery->select();
  5156. } catch (\Throwable $e) {
  5157. return [];
  5158. }
  5159. if (!is_array($list)) {
  5160. return [];
  5161. }
  5162. $ids = [];
  5163. foreach ($list as $r) {
  5164. if (!is_array($r)) {
  5165. continue;
  5166. }
  5167. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  5168. if ($pk > 0) {
  5169. $ids[] = $pk;
  5170. }
  5171. }
  5172. return array_values(array_unique($ids));
  5173. }
  5174. /**
  5175. * 获取当前登录用户信息 [id, 展示名]
  5176. */
  5177. protected function GetUseName(): array
  5178. {
  5179. $id = 0;
  5180. $name = '';
  5181. try {
  5182. if ($this->auth && $this->auth->isLogin()) {
  5183. $u = $this->auth->getUserInfo();
  5184. if (is_array($u)) {
  5185. $id = (int)($u['id'] ?? 0);
  5186. $name = trim((string)($u['nickname'] ?? ''));
  5187. if ($name === '') {
  5188. $name = trim((string)($u['username'] ?? ''));
  5189. }
  5190. }
  5191. }
  5192. } catch (\Throwable $e) {
  5193. }
  5194. if ($name === '') {
  5195. $name = '未知用户';
  5196. }
  5197. return [$id, $name];
  5198. }
  5199. /**
  5200. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  5201. */
  5202. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  5203. {
  5204. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  5205. }
  5206. /**
  5207. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  5208. *
  5209. * @param array<int, array<string, mixed>> $rows
  5210. */
  5211. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  5212. {
  5213. $sidList = [];
  5214. foreach ($rows as $rw) {
  5215. if (!is_array($rw)) {
  5216. continue;
  5217. }
  5218. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5219. foreach ($rw['_order_merge_rows'] as $mr) {
  5220. $mid = (int)($mr['ID'] ?? 0);
  5221. if ($this->isValidScydgyRowId($mid)) {
  5222. $sidList[$mid] = true;
  5223. }
  5224. }
  5225. }
  5226. $id = (int)($rw['ID'] ?? 0);
  5227. if ($this->isValidScydgyRowId($id)) {
  5228. $sidList[$id] = true;
  5229. }
  5230. }
  5231. $sids = array_keys($sidList);
  5232. $issueBySid = [];
  5233. $confirmBySid = [];
  5234. $approveBySid = [];
  5235. if ($sids !== []) {
  5236. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  5237. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  5238. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  5239. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  5240. try {
  5241. $logs = Db::table('purchase_order_oper_log')
  5242. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  5243. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  5244. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  5245. ->order('id', 'asc')
  5246. ->select();
  5247. } catch (\Throwable $e) {
  5248. $logs = [];
  5249. }
  5250. if (is_array($logs)) {
  5251. $issueSet = array_fill_keys($issueActs, true);
  5252. $confirmSet = array_fill_keys($confirmActs, true);
  5253. $approveSet = array_fill_keys($approveActs, true);
  5254. foreach ($logs as $lg) {
  5255. if (!is_array($lg)) {
  5256. continue;
  5257. }
  5258. $lg = ProcuremenOperLog::normalizeRow($lg);
  5259. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  5260. if ($sid === 0) {
  5261. continue;
  5262. }
  5263. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  5264. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  5265. if ($t === '') {
  5266. continue;
  5267. }
  5268. if (isset($issueSet[$action])) {
  5269. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  5270. $issueBySid[$sid] = $t;
  5271. }
  5272. }
  5273. if (isset($confirmSet[$action])) {
  5274. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  5275. $confirmBySid[$sid] = $t;
  5276. }
  5277. }
  5278. if (isset($approveSet[$action])) {
  5279. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  5280. $approveBySid[$sid] = $t;
  5281. }
  5282. }
  5283. }
  5284. }
  5285. }
  5286. foreach ($rows as &$rw) {
  5287. if (!is_array($rw)) {
  5288. continue;
  5289. }
  5290. $mergeSids = [];
  5291. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5292. foreach ($rw['_order_merge_rows'] as $mr) {
  5293. $mid = (int)($mr['ID'] ?? 0);
  5294. if ($this->isValidScydgyRowId($mid)) {
  5295. $mergeSids[] = $mid;
  5296. }
  5297. }
  5298. }
  5299. $rid = (int)($rw['ID'] ?? 0);
  5300. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  5301. $mergeSids[] = $rid;
  5302. }
  5303. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  5304. $issue = $pick;
  5305. $confirm = '';
  5306. $approve = '';
  5307. foreach ($mergeSids as $sid) {
  5308. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  5309. $issue = $issueBySid[$sid];
  5310. }
  5311. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  5312. $confirm = $confirmBySid[$sid];
  5313. }
  5314. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  5315. $approve = $approveBySid[$sid];
  5316. }
  5317. }
  5318. if ($issue === '' && $pick !== '') {
  5319. $issue = $pick;
  5320. }
  5321. $rw['issue_time'] = $issue;
  5322. $rw['confirm_time'] = $confirm;
  5323. $rw['approve_time'] = $approve;
  5324. }
  5325. unset($rw);
  5326. }
  5327. /**
  5328. * 按主键取一条
  5329. */
  5330. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  5331. {
  5332. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  5333. return [];
  5334. }
  5335. try {
  5336. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  5337. if (is_array($one)) {
  5338. return $one;
  5339. }
  5340. } catch (\Throwable $e) {
  5341. }
  5342. try {
  5343. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  5344. if (is_array($one)) {
  5345. return $one;
  5346. }
  5347. } catch (\Throwable $e) {
  5348. }
  5349. return [];
  5350. }
  5351. /**
  5352. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  5353. */
  5354. protected function formatProcuremenDetailTime($v): string
  5355. {
  5356. if ($v === null || $v === '') {
  5357. return '';
  5358. }
  5359. if (is_numeric($v) && (int)$v > 946684800) {
  5360. return date('Y-m-d H:i:s', (int)$v);
  5361. }
  5362. return ProcuremenTime::formatDisplayDateTime($v);
  5363. }
  5364. /**
  5365. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  5366. */
  5367. protected function formatDeliveryYmd($v): string
  5368. {
  5369. if ($v === null || $v === '') {
  5370. return '';
  5371. }
  5372. $s = trim((string)$v);
  5373. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  5374. return '';
  5375. }
  5376. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5377. return $m[1];
  5378. }
  5379. $ts = strtotime($s);
  5380. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  5381. }
  5382. /**
  5383. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  5384. */
  5385. protected function detailRowSupplierOperated(array $r): bool
  5386. {
  5387. $am = $r['amount'] ?? null;
  5388. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5389. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5390. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5391. return $okAmt || $okDel;
  5392. }
  5393. /**
  5394. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  5395. */
  5396. protected function resolveDetailSupplierOperTime(array $r): string
  5397. {
  5398. if (!$this->detailRowSupplierOperated($r)) {
  5399. return '';
  5400. }
  5401. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  5402. if ($t !== '') {
  5403. return $t;
  5404. }
  5405. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  5406. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  5407. continue;
  5408. }
  5409. $t = $this->formatProcuremenDetailTime($r[$col]);
  5410. if ($t !== '') {
  5411. return $t;
  5412. }
  5413. }
  5414. return '';
  5415. }
  5416. /**
  5417. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  5418. */
  5419. protected function detailRowSupplierAccepted(array $r): bool
  5420. {
  5421. $am = $r['amount'] ?? null;
  5422. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5423. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5424. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5425. return $okAmt && $okDel;
  5426. }
  5427. /**
  5428. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  5429. */
  5430. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  5431. {
  5432. if ($detailCount > 0) {
  5433. return true;
  5434. }
  5435. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  5436. return true;
  5437. }
  5438. $pickTime = trim((string)($main['pick_time'] ?? ''));
  5439. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  5440. return true;
  5441. }
  5442. return false;
  5443. }
  5444. /**
  5445. * 下发时间:优先 pick_time,其次首条下发明细时间
  5446. */
  5447. protected function resolveProcuremenIssueTime(array $main, array $details): string
  5448. {
  5449. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  5450. if ($issueTime !== '') {
  5451. return $issueTime;
  5452. }
  5453. foreach ($details as $dr) {
  5454. if (!is_array($dr)) {
  5455. continue;
  5456. }
  5457. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5458. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  5459. $issueTime = $t;
  5460. }
  5461. }
  5462. if ($issueTime !== '') {
  5463. return $issueTime;
  5464. }
  5465. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5466. }
  5467. /**
  5468. * 直接点「完结」时间:优先操作记录 mark_complete
  5469. */
  5470. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  5471. {
  5472. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  5473. }
  5474. /**
  5475. * 操作记录时间(取指定 action 最近一条)
  5476. *
  5477. * @param string|array<int, string> $actions
  5478. */
  5479. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  5480. {
  5481. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  5482. }
  5483. /**
  5484. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  5485. *
  5486. * @param array $main purchase_order 一行
  5487. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  5488. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  5489. */
  5490. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  5491. {
  5492. $issueCnt = count($details);
  5493. $acceptCnt = 0;
  5494. $pickedName = '';
  5495. $pickedTime = '';
  5496. foreach ($details as $dr) {
  5497. if (!is_array($dr)) {
  5498. continue;
  5499. }
  5500. if ($this->detailRowSupplierAccepted($dr)) {
  5501. $acceptCnt++;
  5502. }
  5503. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5504. if ($pickedName === '') {
  5505. $pickedName = trim((string)($dr['company_name'] ?? ''));
  5506. }
  5507. if ($pickedTime === '') {
  5508. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  5509. if ($pickedTime === '') {
  5510. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5511. }
  5512. }
  5513. }
  5514. }
  5515. $hasMain = $main !== [];
  5516. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  5517. if ($poTime === '') {
  5518. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  5519. }
  5520. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  5521. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  5522. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  5523. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  5524. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  5525. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  5526. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  5527. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  5528. $inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
  5529. $inboundResult = '';
  5530. if ($scydgyId > 0) {
  5531. try {
  5532. $inRow = Db::table('purchase_order_inbound_score')
  5533. ->where('scydgy_id', $scydgyId)
  5534. ->field('result,updatetime,createtime')
  5535. ->find();
  5536. } catch (\Throwable $e) {
  5537. $inRow = null;
  5538. }
  5539. if (is_array($inRow) && $inRow !== []) {
  5540. $inboundResult = trim((string)($inRow['result'] ?? ''));
  5541. if ($inboundScoreTime === '') {
  5542. $inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
  5543. }
  5544. }
  5545. }
  5546. $inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
  5547. $supplierTime = '';
  5548. if ($acceptCnt > 0) {
  5549. foreach ($details as $dr) {
  5550. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  5551. continue;
  5552. }
  5553. $t = $this->resolveDetailSupplierOperTime($dr);
  5554. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  5555. $supplierTime = $t;
  5556. }
  5557. }
  5558. }
  5559. $directComplete = ($mainCompleted && !$issued);
  5560. $doneTime = '';
  5561. if ($mainCompleted) {
  5562. if ($directComplete) {
  5563. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  5564. }
  5565. if ($doneTime === '' && $inboundScoreTime !== '') {
  5566. $doneTime = $inboundScoreTime;
  5567. }
  5568. if ($doneTime === '') {
  5569. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5570. }
  5571. if ($doneTime === '') {
  5572. foreach ($details as $dr) {
  5573. if (!is_array($dr)) {
  5574. continue;
  5575. }
  5576. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  5577. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  5578. $doneTime = $t;
  5579. }
  5580. }
  5581. }
  5582. if ($doneTime === '') {
  5583. $doneTime = $poTime;
  5584. }
  5585. // 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
  5586. if ($doneTime === '' && $confirmApproveTime !== '') {
  5587. $doneTime = $confirmApproveTime;
  5588. }
  5589. }
  5590. if ($directComplete) {
  5591. // 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
  5592. $step1Done = $hasMain;
  5593. $step2Done = false;
  5594. $step3Done = false;
  5595. $step4Done = false;
  5596. $step5Done = false;
  5597. $stepInboundDone = $inboundScored;
  5598. $step6Done = $mainCompleted && $inboundScored;
  5599. } else {
  5600. $step1Done = $issued;
  5601. $step2Done = $issued;
  5602. $step3Done = $acceptCnt > 0;
  5603. $step4Done = $wflowPendingApproval;
  5604. if (!$step4Done) {
  5605. foreach ($details as $dr) {
  5606. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5607. $step4Done = true;
  5608. break;
  5609. }
  5610. }
  5611. }
  5612. $step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
  5613. $stepInboundDone = $inboundScored;
  5614. // 未确认合格/不合格时,「已完结」保持未点亮(灰色)
  5615. $step6Done = $mainCompleted && $inboundScored;
  5616. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  5617. if ($mainCompleted && $issued) {
  5618. $step3Done = true;
  5619. $step4Done = true;
  5620. $step5Done = true;
  5621. // 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
  5622. if ($supplierTime === '') {
  5623. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5624. if ($fillT !== '') {
  5625. $supplierTime = $fillT;
  5626. }
  5627. }
  5628. if ($pickedTime === '') {
  5629. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5630. if ($fillT !== '') {
  5631. $pickedTime = $fillT;
  5632. }
  5633. }
  5634. if ($auditSelectTime === '') {
  5635. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5636. if ($fillT !== '') {
  5637. $auditSelectTime = $fillT;
  5638. }
  5639. }
  5640. if ($confirmApproveTime === '') {
  5641. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5642. if ($fillT !== '') {
  5643. $confirmApproveTime = $fillT;
  5644. }
  5645. }
  5646. }
  5647. }
  5648. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  5649. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  5650. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  5651. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  5652. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  5653. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  5654. $inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
  5655. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  5656. $deadlineLines = [];
  5657. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  5658. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  5659. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  5660. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  5661. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  5662. }
  5663. }
  5664. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  5665. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  5666. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  5667. if ($deliveryDisp === '') {
  5668. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  5669. }
  5670. if ($deliveryDisp !== '') {
  5671. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  5672. }
  5673. }
  5674. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  5675. $deadlineText = implode("\n", $deadlineLines);
  5676. $prefixOperTime = static function (string $t): string {
  5677. $t = trim($t);
  5678. if ($t === '' || $t === '—') {
  5679. return $t;
  5680. }
  5681. if (strpos($t, '操作时间') === 0) {
  5682. return $t;
  5683. }
  5684. return '操作时间:' . $t;
  5685. };
  5686. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  5687. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  5688. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
  5689. $stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5690. $step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5691. $steps = [
  5692. [
  5693. 'title' => '未发',
  5694. 'subtitle' => '',
  5695. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  5696. 'done' => $step1Done,
  5697. ],
  5698. [
  5699. 'title' => '下发',
  5700. 'subtitle' => $deadlineText,
  5701. 'time' => $prefixOperTime($step2Time),
  5702. 'done' => $step2Done,
  5703. ],
  5704. [
  5705. 'title' => '供应商接单',
  5706. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  5707. 'time' => '',
  5708. 'done' => $step3Done,
  5709. ],
  5710. [
  5711. 'title' => '待确认',
  5712. 'subtitle' => $step4Done
  5713. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  5714. : ($issued ? '待选供应商' : ''),
  5715. 'time' => $prefixOperTime($step4Time),
  5716. 'done' => $step4Done,
  5717. ],
  5718. [
  5719. 'title' => '待审批',
  5720. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  5721. 'time' => $prefixOperTime($step5Time),
  5722. 'done' => $step5Done,
  5723. ],
  5724. [
  5725. 'title' => '是否合格',
  5726. 'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
  5727. 'time' => $prefixOperTime($stepInboundTime),
  5728. 'done' => $stepInboundDone,
  5729. ],
  5730. [
  5731. 'title' => '已完结',
  5732. 'subtitle' => '',
  5733. 'time' => $prefixOperTime($step6Time),
  5734. 'done' => $step6Done,
  5735. ],
  5736. ];
  5737. $currentIdx = count($steps) - 1;
  5738. if ($directComplete) {
  5739. // 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
  5740. if (!$step6Done) {
  5741. foreach ($steps as $i => $s) {
  5742. if (($s['title'] ?? '') === '是否合格') {
  5743. $currentIdx = $i;
  5744. break;
  5745. }
  5746. }
  5747. }
  5748. } else {
  5749. foreach ($steps as $i => $s) {
  5750. if (!$s['done']) {
  5751. $currentIdx = $i;
  5752. break;
  5753. }
  5754. }
  5755. }
  5756. $nSteps = count($steps);
  5757. foreach ($steps as $idx => &$s) {
  5758. $s['current'] = ($idx === $currentIdx);
  5759. if ($idx === 0) {
  5760. $s['pdf_left_bg'] = '';
  5761. } else {
  5762. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  5763. }
  5764. if ($idx >= $nSteps - 1) {
  5765. $s['pdf_right_bg'] = '';
  5766. } else {
  5767. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  5768. }
  5769. }
  5770. unset($s);
  5771. $labelMap = [
  5772. 'CCYDH' => '订单号',
  5773. 'CYJMC' => '印件名称',
  5774. 'CCLBMMC' => '承揽部门',
  5775. 'CGYMC' => '工序名称',
  5776. 'CDW' => '单位',
  5777. 'czlyq' => '类型',
  5778. 'NGZL' => '工作量',
  5779. 'CDF' => '单价',
  5780. 'cGzzxMc' => '工作中心',
  5781. 'MBZ' => '备注',
  5782. 'This_quantity' => '本次数量',
  5783. 'ceilingPrice' => '最高限价',
  5784. ];
  5785. $orderSummary = [];
  5786. foreach ($labelMap as $key => $lab) {
  5787. if (!array_key_exists($key, $main)) {
  5788. continue;
  5789. }
  5790. $val = $main[$key];
  5791. if ($val === null) {
  5792. $val = '';
  5793. } elseif (!is_scalar($val)) {
  5794. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  5795. } else {
  5796. $val = (string)$val;
  5797. }
  5798. $orderSummary[] = ['label' => $lab, 'value' => $val];
  5799. }
  5800. $orderSummary[] = [
  5801. 'label' => '是否合格',
  5802. 'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
  5803. ];
  5804. $orderSummaryGrid = [];
  5805. $n = count($orderSummary);
  5806. for ($i = 0; $i < $n; $i += 2) {
  5807. $left = $orderSummary[$i];
  5808. $hasRight = ($i + 1) < $n;
  5809. $orderSummaryGrid[] = [
  5810. 'l1' => $left['label'],
  5811. 'v1' => $left['value'],
  5812. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  5813. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  5814. ];
  5815. }
  5816. return [
  5817. 'steps' => $steps,
  5818. 'orderSummary' => $orderSummary,
  5819. 'orderSummaryGrid' => $orderSummaryGrid,
  5820. 'inbound_result' => $inboundResult,
  5821. 'inbound_score_time'=> $inboundScoreTime,
  5822. 'detailRows' => $details,
  5823. ];
  5824. }
  5825. /**
  5826. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  5827. *
  5828. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  5829. */
  5830. protected function prepareProcuremenDetailsView(string $ids): array
  5831. {
  5832. $main = [];
  5833. try {
  5834. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5835. $main = is_array($one) ? $one : [];
  5836. } catch (\Throwable $e) {
  5837. $main = [];
  5838. }
  5839. $details = [];
  5840. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  5841. if ($mergeRows === []) {
  5842. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  5843. if ($mergeRows === [] && $main !== []) {
  5844. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  5845. }
  5846. }
  5847. $detailSidList = [];
  5848. $anchorSid = (int)$ids;
  5849. if ($anchorSid !== 0) {
  5850. $detailSidList[$anchorSid] = true;
  5851. }
  5852. foreach ($mergeRows as $mr) {
  5853. if (!is_array($mr)) {
  5854. continue;
  5855. }
  5856. $sid = $this->extractScydgyRowId($mr);
  5857. if ($sid !== 0) {
  5858. $detailSidList[$sid] = true;
  5859. }
  5860. }
  5861. try {
  5862. if ($detailSidList !== []) {
  5863. $details = Db::table('purchase_order_detail')
  5864. ->where('scydgy_id', 'in', array_keys($detailSidList))
  5865. ->order('id', 'asc')
  5866. ->select();
  5867. }
  5868. } catch (\Throwable $e) {
  5869. $details = [];
  5870. }
  5871. if (!is_array($details)) {
  5872. $details = [];
  5873. }
  5874. foreach ($details as &$r) {
  5875. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  5876. $r['id'] = $r['ID'];
  5877. }
  5878. if (isset($r['createtime'])) {
  5879. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  5880. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  5881. } else {
  5882. $r['createtime_text'] = (string)$r['createtime'];
  5883. }
  5884. } else {
  5885. $r['createtime_text'] = '';
  5886. }
  5887. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  5888. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  5889. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  5890. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  5891. if (is_array($r)) {
  5892. $r = $this->maskSupplierContactFields($r);
  5893. }
  5894. }
  5895. unset($r);
  5896. $activeDetails = [];
  5897. foreach ($details as $r) {
  5898. if (is_array($r) && empty($r['is_void'])) {
  5899. $activeDetails[] = $r;
  5900. }
  5901. }
  5902. $operLogs = [];
  5903. try {
  5904. $operSidList = array_keys($detailSidList);
  5905. if ($operSidList === [] && (int)$ids !== 0) {
  5906. $operSidList = [(int)$ids];
  5907. }
  5908. if ($operSidList !== []) {
  5909. $operLogs = Db::table('purchase_order_oper_log')
  5910. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  5911. ->order('id', 'asc')
  5912. ->select();
  5913. }
  5914. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  5915. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  5916. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  5917. if ($poId > 0) {
  5918. $operLogs = Db::table('purchase_order_oper_log')
  5919. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  5920. ->order('id', 'asc')
  5921. ->select();
  5922. }
  5923. }
  5924. } catch (\Throwable $e) {
  5925. $operLogs = [];
  5926. }
  5927. if (!is_array($operLogs)) {
  5928. $operLogs = [];
  5929. }
  5930. $operLogsRaw = $operLogs;
  5931. $processNameBySid = [];
  5932. foreach ($mergeRows as $mr) {
  5933. if (!is_array($mr)) {
  5934. continue;
  5935. }
  5936. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  5937. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5938. if ($psid !== 0 && $gymc !== '') {
  5939. $processNameBySid[$psid] = $gymc;
  5940. }
  5941. }
  5942. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  5943. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
  5944. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  5945. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  5946. if ($ccydh === '') {
  5947. foreach ($details as $r) {
  5948. if (!is_array($r)) {
  5949. continue;
  5950. }
  5951. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  5952. if ($ccydh !== '') {
  5953. break;
  5954. }
  5955. }
  5956. }
  5957. $this->view->assign('ccydh', $ccydh);
  5958. $this->view->assign('steps', $bundle['steps']);
  5959. $this->view->assign('orderSummary', $bundle['orderSummary']);
  5960. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  5961. $this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
  5962. $this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
  5963. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  5964. $this->view->assign('processCount', count($mergeRows));
  5965. $this->view->assign('detailRows', $details);
  5966. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  5967. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  5968. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  5969. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  5970. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  5971. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  5972. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  5973. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  5974. $this->view->assign('operLogs', $operLogs);
  5975. $sg = $quoteView['supplier_groups'] ?? [];
  5976. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
  5977. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  5978. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
  5979. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
  5980. return [
  5981. 'ok' => $main !== [] || $details !== [],
  5982. 'ccydh' => $ccydh,
  5983. ];
  5984. }
  5985. /**
  5986. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  5987. */
  5988. public function details()
  5989. {
  5990. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5991. if (is_array($ids)) {
  5992. $ids = isset($ids[0]) ? $ids[0] : '';
  5993. }
  5994. $ids = trim((string)$ids);
  5995. if ($ids === '') {
  5996. $this->error(__('Invalid parameters'));
  5997. }
  5998. $this->assertManualOrderDetailsViewable((int)$ids);
  5999. $this->prepareProcuremenDetailsView($ids);
  6000. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  6001. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  6002. $this->view->engine->layout(false);
  6003. try {
  6004. return $this->view->fetch('procuremen/details_dialog_shell');
  6005. } finally {
  6006. if ($restoreLayout) {
  6007. $this->view->engine->layout($restoreLayout);
  6008. }
  6009. }
  6010. }
  6011. /**
  6012. * 解析合并审核工序行(订单号须一致,且均未协助)
  6013. *
  6014. * @return array<int, array<string, mixed>>
  6015. */
  6016. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  6017. {
  6018. $primary = json_decode($rowJson, true);
  6019. if (!is_array($primary)) {
  6020. $this->error(__('Invalid parameters'));
  6021. }
  6022. $merge = json_decode($mergeRowsJson, true);
  6023. if (!is_array($merge) || $merge === []) {
  6024. $merge = [$primary];
  6025. }
  6026. $seen = [];
  6027. $out = [];
  6028. foreach ($merge as $r) {
  6029. if (!is_array($r)) {
  6030. continue;
  6031. }
  6032. $id = $this->extractScydgyRowId($r);
  6033. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  6034. continue;
  6035. }
  6036. $seen[$id] = true;
  6037. $out[] = $r;
  6038. }
  6039. if ($out === []) {
  6040. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  6041. }
  6042. $ccydh = null;
  6043. foreach ($out as $r) {
  6044. $dh = trim((string)($r['CCYDH'] ?? ''));
  6045. if ($ccydh === null) {
  6046. $ccydh = $dh;
  6047. } elseif ($dh !== $ccydh) {
  6048. $this->error('合并审核要求所选行的订单号一致');
  6049. }
  6050. }
  6051. $ids = [];
  6052. foreach ($out as $r) {
  6053. $id = $this->extractScydgyRowId($r);
  6054. if ($this->isValidScydgyRowId($id)) {
  6055. $ids[$id] = true;
  6056. }
  6057. }
  6058. $poBySid = [];
  6059. $detCntBySid = [];
  6060. if ($ids !== []) {
  6061. $idList = array_keys($ids);
  6062. try {
  6063. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  6064. if (is_array($poList)) {
  6065. foreach ($poList as $po) {
  6066. if (!is_array($po)) {
  6067. continue;
  6068. }
  6069. $sid = (int)($po['scydgy_id'] ?? 0);
  6070. if ($this->isValidScydgyRowId($sid)) {
  6071. $poBySid[$sid] = $po;
  6072. }
  6073. }
  6074. }
  6075. } catch (\Throwable $e) {
  6076. }
  6077. try {
  6078. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  6079. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  6080. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  6081. if (is_array($detRows)) {
  6082. foreach ($detRows as $dr) {
  6083. if (!is_array($dr)) {
  6084. continue;
  6085. }
  6086. $sid = (int)($dr['scydgy_id'] ?? 0);
  6087. if ($this->isValidScydgyRowId($sid)) {
  6088. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  6089. }
  6090. }
  6091. }
  6092. } catch (\Throwable $e) {
  6093. }
  6094. }
  6095. foreach ($out as $r) {
  6096. $id = $this->extractScydgyRowId($r);
  6097. if (!$this->isValidScydgyRowId($id)) {
  6098. continue;
  6099. }
  6100. $po = $poBySid[$id] ?? null;
  6101. if (!is_array($po)) {
  6102. continue;
  6103. }
  6104. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6105. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6106. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  6107. }
  6108. $detCnt = (int)($detCntBySid[$id] ?? 0);
  6109. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  6110. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6111. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  6112. }
  6113. }
  6114. return $out;
  6115. }
  6116. /**
  6117. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  6118. */
  6119. protected function maskSupplierContactFields(array $item): array
  6120. {
  6121. if (array_key_exists('email', $item)) {
  6122. $item['email'] = mask_email((string)$item['email']);
  6123. }
  6124. if (array_key_exists('phone', $item)) {
  6125. $item['phone'] = mask_phone((string)$item['phone']);
  6126. }
  6127. return $item;
  6128. }
  6129. /**
  6130. * @param array<int, array<string, mixed>> $list
  6131. * @return array<int, array<string, mixed>>
  6132. */
  6133. protected function maskSupplierContactList(array $list): array
  6134. {
  6135. $out = [];
  6136. foreach ($list as $item) {
  6137. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  6138. }
  6139. return $out;
  6140. }
  6141. /**
  6142. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  6143. *
  6144. * @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
  6145. * @return array<string, string>|null
  6146. */
  6147. protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
  6148. {
  6149. if (!is_array($row)) {
  6150. return null;
  6151. }
  6152. $norm = [];
  6153. foreach ($row as $k => $v) {
  6154. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  6155. }
  6156. $row = $norm;
  6157. $st = $row['status'] ?? '';
  6158. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  6159. return null;
  6160. }
  6161. $companyName = '';
  6162. foreach (['company_name', 'name'] as $nk) {
  6163. if (!empty($row[$nk])) {
  6164. $companyName = trim((string)$row[$nk]);
  6165. break;
  6166. }
  6167. }
  6168. if ($companyName === '') {
  6169. return null;
  6170. }
  6171. $username = '';
  6172. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  6173. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  6174. $username = trim((string)$row[$uk]);
  6175. break;
  6176. }
  6177. }
  6178. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  6179. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  6180. if ($phone === '' && isset($row['account'])) {
  6181. $phone = trim((string)$row['account']);
  6182. }
  6183. if ($phone === '' && isset($row['mobile'])) {
  6184. $phone = trim((string)$row['mobile']);
  6185. }
  6186. if ($requireContactChannels && $email === '' && $phone === '') {
  6187. return null;
  6188. }
  6189. $category = '';
  6190. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6191. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6192. $category = trim((string)$row[$ck]);
  6193. break;
  6194. }
  6195. }
  6196. return [
  6197. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  6198. 'name' => $companyName,
  6199. 'company_name' => $companyName,
  6200. 'username' => $username,
  6201. 'email' => $email,
  6202. 'phone' => $phone,
  6203. 'category' => $category,
  6204. 'company_type' => $category,
  6205. ];
  6206. }
  6207. /**
  6208. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  6209. */
  6210. protected function resolveCustomerContactById(string $id): ?array
  6211. {
  6212. $id = trim($id);
  6213. if ($id === '' || !ctype_digit($id)) {
  6214. return null;
  6215. }
  6216. try {
  6217. $row = Db::table('customer')->where('id', (int)$id)->find();
  6218. } catch (\Throwable $e) {
  6219. return null;
  6220. }
  6221. return $this->buildCustomerContactPayloadFromRow($row);
  6222. }
  6223. /**
  6224. * 按供应商名称解析联系信息(兼容旧提交数据)
  6225. *
  6226. * @param bool $requireContactChannels true 时须有邮箱或手机
  6227. */
  6228. protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
  6229. {
  6230. $name = trim($name);
  6231. if ($name === '') {
  6232. return null;
  6233. }
  6234. try {
  6235. // customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
  6236. $row = Db::table('customer')
  6237. ->where('company_name', $name)
  6238. ->order('id', 'desc')
  6239. ->find();
  6240. } catch (\Throwable $e) {
  6241. return null;
  6242. }
  6243. return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
  6244. }
  6245. /**
  6246. * 规范化下发/确认时勾选的供应商
  6247. *
  6248. * @param array<int, mixed> $companies
  6249. * @return array<int, array<string, string>>
  6250. */
  6251. protected function normalizePickCompanies(array $companies): array
  6252. {
  6253. $out = [];
  6254. foreach ($companies as $c) {
  6255. if (!is_array($c)) {
  6256. continue;
  6257. }
  6258. $resolved = null;
  6259. $cid = trim((string)($c['id'] ?? ''));
  6260. if ($cid !== '') {
  6261. $resolved = $this->resolveCustomerContactById($cid);
  6262. }
  6263. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  6264. if ($resolved === null && $name !== '') {
  6265. $resolved = $this->resolveCustomerContactByCompanyName($name);
  6266. }
  6267. if ($resolved === null) {
  6268. continue;
  6269. }
  6270. $out[] = $resolved;
  6271. }
  6272. return $out;
  6273. }
  6274. /**
  6275. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  6276. *
  6277. * @param array<int, array<string, mixed>> $pool
  6278. * @return array<int, array<string, mixed>>
  6279. */
  6280. protected function collapseProcuremenPoolByOrder(array $pool): array
  6281. {
  6282. if ($pool === []) {
  6283. return [];
  6284. }
  6285. $groups = [];
  6286. foreach ($pool as $row) {
  6287. if (!is_array($row)) {
  6288. continue;
  6289. }
  6290. $dh = trim((string)($row['CCYDH'] ?? ''));
  6291. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  6292. if (!isset($groups[$key])) {
  6293. $groups[$key] = [];
  6294. }
  6295. $groups[$key][] = $row;
  6296. }
  6297. $out = [];
  6298. foreach ($groups as $ccydh => $rows) {
  6299. if ($rows === []) {
  6300. continue;
  6301. }
  6302. usort($rows, function ($a, $b) {
  6303. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  6304. });
  6305. $head = $rows[0];
  6306. $gymcList = [];
  6307. foreach ($rows as $r) {
  6308. $g = trim((string)($r['CGYMC'] ?? ''));
  6309. if ($g !== '' && !in_array($g, $gymcList, true)) {
  6310. $gymcList[] = $g;
  6311. }
  6312. }
  6313. $merged = $head;
  6314. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  6315. $merged['process_count'] = count($rows);
  6316. $merged['_order_merge_rows'] = $rows;
  6317. $qtyList = [];
  6318. $priceList = [];
  6319. foreach ($rows as $r) {
  6320. if (!is_array($r)) {
  6321. continue;
  6322. }
  6323. $qtyList[] = $this->resolveProcuremenThisQuantity($r);
  6324. $priceList[] = $this->resolveProcuremenCeilingPrice($r);
  6325. }
  6326. if (count($rows) > 1) {
  6327. $merged['CGYMC'] = implode('、', $gymcList);
  6328. // 多工序:数量/限价按有值项顿号间隔(空值不占位)
  6329. $merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  6330. $merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  6331. } else {
  6332. $merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
  6333. $merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
  6334. }
  6335. // 已选供应商:取合并行中首个非空 pick_company_name
  6336. $pickedName = '';
  6337. foreach ($rows as $r) {
  6338. if (!is_array($r)) {
  6339. continue;
  6340. }
  6341. $pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
  6342. if ($pn !== '') {
  6343. $pickedName = $pn;
  6344. break;
  6345. }
  6346. }
  6347. if ($pickedName !== '') {
  6348. $merged['pick_company_name'] = $pickedName;
  6349. $merged['picked_supplier_name'] = $pickedName;
  6350. }
  6351. $mergedPickTime = '';
  6352. foreach ($rows as $r) {
  6353. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  6354. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  6355. $mergedPickTime = $t;
  6356. }
  6357. }
  6358. if ($mergedPickTime !== '') {
  6359. $merged['pick_time'] = $mergedPickTime;
  6360. }
  6361. $out[] = $merged;
  6362. }
  6363. usort($out, function ($a, $b) {
  6364. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  6365. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  6366. if ($ta === $tb) {
  6367. $ida = (int)($a['purchase_order_id'] ?? 0);
  6368. $idb = (int)($b['purchase_order_id'] ?? 0);
  6369. if ($ida !== $idb) {
  6370. return $idb <=> $ida;
  6371. }
  6372. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  6373. }
  6374. if ($ta === '') {
  6375. return 1;
  6376. }
  6377. if ($tb === '') {
  6378. return -1;
  6379. }
  6380. return strcmp($tb, $ta);
  6381. });
  6382. return $out;
  6383. }
  6384. /**
  6385. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  6386. *
  6387. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6388. */
  6389. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  6390. {
  6391. $scydgyId = trim($scydgyId);
  6392. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6393. if ($scydgyId === '') {
  6394. return $empty;
  6395. }
  6396. try {
  6397. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6398. } catch (\Throwable $e) {
  6399. $anchor = null;
  6400. }
  6401. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  6402. return $empty;
  6403. }
  6404. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6405. if ($ccydh === '') {
  6406. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  6407. }
  6408. try {
  6409. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  6410. } catch (\Throwable $e) {
  6411. $pos = [$anchor];
  6412. }
  6413. if (!is_array($pos) || $pos === []) {
  6414. $pos = [$anchor];
  6415. }
  6416. return [
  6417. 'ccydh' => $ccydh,
  6418. 'pos' => $pos,
  6419. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6420. ];
  6421. }
  6422. /**
  6423. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  6424. */
  6425. protected function purchaseOrderRowInConfirmStage(array $po): bool
  6426. {
  6427. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6428. return false;
  6429. }
  6430. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  6431. return false;
  6432. }
  6433. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  6434. return true;
  6435. }
  6436. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  6437. $sid = (int)($po['scydgy_id'] ?? 0);
  6438. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  6439. }
  6440. return false;
  6441. }
  6442. /**
  6443. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  6444. *
  6445. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6446. */
  6447. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  6448. {
  6449. $scydgyId = trim($scydgyId);
  6450. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6451. if ($scydgyId === '') {
  6452. return $empty;
  6453. }
  6454. try {
  6455. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6456. } catch (\Throwable $e) {
  6457. $anchor = null;
  6458. }
  6459. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  6460. return $empty;
  6461. }
  6462. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6463. if ($ccydh === '') {
  6464. return [
  6465. 'ccydh' => '',
  6466. 'pos' => [$anchor],
  6467. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  6468. ];
  6469. }
  6470. try {
  6471. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  6472. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  6473. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  6474. } catch (\Throwable $e) {
  6475. $pos = [$anchor];
  6476. }
  6477. if (!is_array($pos) || $pos === []) {
  6478. $pos = [$anchor];
  6479. }
  6480. $pos = array_values(array_filter($pos, function ($po) {
  6481. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  6482. }));
  6483. if ($pos === []) {
  6484. $pos = [$anchor];
  6485. }
  6486. return [
  6487. 'ccydh' => $ccydh,
  6488. 'pos' => $pos,
  6489. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6490. ];
  6491. }
  6492. /**
  6493. * @param array<int, array<string, mixed>> $purchaseOrders
  6494. * @return array<int, array<string, mixed>>
  6495. */
  6496. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  6497. {
  6498. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  6499. $byId = [];
  6500. foreach ($pool as $r) {
  6501. if (!is_array($r)) {
  6502. continue;
  6503. }
  6504. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  6505. if ($this->isValidScydgyRowId($sid)) {
  6506. $byId[$sid] = $r;
  6507. }
  6508. }
  6509. $out = [];
  6510. foreach ($purchaseOrders as $po) {
  6511. if (!is_array($po)) {
  6512. continue;
  6513. }
  6514. $sid = (int)($po['scydgy_id'] ?? 0);
  6515. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  6516. $out[] = $byId[$sid];
  6517. }
  6518. }
  6519. return $out;
  6520. }
  6521. /**
  6522. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  6523. *
  6524. * @return array<int, array<string, mixed>>
  6525. */
  6526. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  6527. {
  6528. $scydgyId = trim($scydgyId);
  6529. if ($scydgyId === '') {
  6530. return [];
  6531. }
  6532. try {
  6533. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6534. } catch (\Throwable $e) {
  6535. $anchor = null;
  6536. }
  6537. if (!is_array($anchor)) {
  6538. return [];
  6539. }
  6540. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  6541. return [];
  6542. }
  6543. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6544. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  6545. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  6546. try {
  6547. $q = Db::table('purchase_order');
  6548. if ($ccydh !== '') {
  6549. $q->where('CCYDH', $ccydh);
  6550. } else {
  6551. $q->where('scydgy_id', $scydgyId);
  6552. }
  6553. if ($isValidPick) {
  6554. $q->where('pick_time', $pickTime);
  6555. }
  6556. $pos = $q->order('scydgy_id', 'asc')->select();
  6557. } catch (\Throwable $e) {
  6558. $pos = [$anchor];
  6559. }
  6560. if (!is_array($pos) || $pos === []) {
  6561. $pos = [$anchor];
  6562. }
  6563. $pos = array_values(array_filter($pos, function ($po) {
  6564. if (!is_array($po)) {
  6565. return false;
  6566. }
  6567. $mr = $po['mod_rq'] ?? null;
  6568. if ($mr === null || $mr === '') {
  6569. return true;
  6570. }
  6571. $mrs = trim((string)$mr);
  6572. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  6573. }));
  6574. if ($pos === []) {
  6575. $pos = [$anchor];
  6576. }
  6577. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  6578. if ($rows === []) {
  6579. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  6580. }
  6581. return $rows;
  6582. }
  6583. /**
  6584. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  6585. *
  6586. * @param array<int, array<string, mixed>> $mergeRows
  6587. * @return array<int, array<string, mixed>>
  6588. */
  6589. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  6590. {
  6591. $list = array_values($mergeRows);
  6592. $n = count($list);
  6593. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  6594. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  6595. $mergeSame = $n > 1 && $orderKey0 !== '';
  6596. if ($mergeSame) {
  6597. foreach ($list as $rr) {
  6598. if (!is_array($rr)) {
  6599. $mergeSame = false;
  6600. break;
  6601. }
  6602. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  6603. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  6604. $mergeSame = false;
  6605. break;
  6606. }
  6607. }
  6608. }
  6609. $out = [];
  6610. foreach ($list as $idx => $r) {
  6611. if (!is_array($r)) {
  6612. continue;
  6613. }
  6614. $qty = $this->resolveProcuremenThisQuantity($r);
  6615. $price = $this->resolveProcuremenCeilingPrice($r);
  6616. $sid = $this->extractScydgyRowId($r);
  6617. $out[] = [
  6618. 'seq' => $idx + 1,
  6619. 'scydgy_id' => $sid,
  6620. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6621. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6622. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6623. 'CDW' => trim((string)($r['CDW'] ?? '')),
  6624. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  6625. 'NGZL' => $r['NGZL'] ?? '',
  6626. 'This_quantity' => $qty,
  6627. 'ceilingPrice' => $price,
  6628. 'CDF' => trim((string)($r['CDF'] ?? '')),
  6629. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  6630. 'show_order_cells' => !$mergeSame || $idx === 0,
  6631. 'order_rowspan' => $mergeSame ? $n : 1,
  6632. ];
  6633. }
  6634. return $out;
  6635. }
  6636. /**
  6637. * 解析金额/数量(去千分位等非数字字符)
  6638. */
  6639. protected function parseProcuremenMoneyNumber($value): ?float
  6640. {
  6641. if ($value === null || $value === '') {
  6642. return null;
  6643. }
  6644. if (is_numeric($value)) {
  6645. return (float)$value;
  6646. }
  6647. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  6648. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  6649. }
  6650. protected function formatProcuremenMoneyDisplay(?float $amount): string
  6651. {
  6652. if ($amount === null) {
  6653. return '';
  6654. }
  6655. // 保留小数(最多 5 位),去掉末尾无意义的 0,避免 0.25 被显示成 0
  6656. $s = rtrim(rtrim(sprintf('%.5F', (float)$amount), '0'), '.');
  6657. return $s === '' ? '0' : $s;
  6658. }
  6659. /**
  6660. * 列表/详情展示:工作量为 0 时显示空
  6661. */
  6662. protected function formatProcuremenWorkloadDisplay($value): string
  6663. {
  6664. if ($value === null || $value === '') {
  6665. return '';
  6666. }
  6667. $s = trim((string)$value);
  6668. if ($s === '') {
  6669. return '';
  6670. }
  6671. if (is_numeric($s) && (float)$s == 0) {
  6672. return '';
  6673. }
  6674. return $s;
  6675. }
  6676. /**
  6677. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  6678. */
  6679. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  6680. {
  6681. foreach ($details as $d) {
  6682. if (!is_array($d)) {
  6683. continue;
  6684. }
  6685. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  6686. $cn = trim((string)($d['company_name'] ?? ''));
  6687. if ($cn !== '') {
  6688. return $cn;
  6689. }
  6690. }
  6691. }
  6692. return trim((string)($main['pick_company_name'] ?? ''));
  6693. }
  6694. /**
  6695. * 详情报价小计:单价 × 本工序本次数量
  6696. */
  6697. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  6698. {
  6699. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  6700. if ($unit === null) {
  6701. return null;
  6702. }
  6703. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  6704. if ($qty === null || $qty <= 0) {
  6705. return null;
  6706. }
  6707. return $unit * $qty;
  6708. }
  6709. /**
  6710. * 详情页:工序小计 + 供应商分组报价与总计
  6711. *
  6712. * @param array<int, array<string, mixed>> $mergeRows
  6713. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  6714. * @return array{
  6715. * process_rows: array,
  6716. * supplier_groups: array,
  6717. * order_total_text: string,
  6718. * order_total_has: bool,
  6719. * selected_company: string
  6720. * }
  6721. */
  6722. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  6723. {
  6724. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  6725. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  6726. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
  6727. || ((int)($main['manual_pick'] ?? 0) === 1);
  6728. $qtyBySid = [];
  6729. $gymcBySid = [];
  6730. $orderedSids = [];
  6731. foreach ($mergeRows as $mr) {
  6732. if (!is_array($mr)) {
  6733. continue;
  6734. }
  6735. $sid = $this->extractScydgyRowId($mr);
  6736. if ($this->isValidScydgyRowId($sid)) {
  6737. $orderedSids[] = $sid;
  6738. }
  6739. $qty = trim((string)($mr['This_quantity'] ?? ''));
  6740. if ($qty === '') {
  6741. $qty = trim((string)($mr['NGZL'] ?? ''));
  6742. }
  6743. $qtyBySid[$sid] = $qty;
  6744. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  6745. }
  6746. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  6747. $detailByCompanySid = [];
  6748. foreach ($details as $d) {
  6749. if (!is_array($d)) {
  6750. continue;
  6751. }
  6752. $cn = trim((string)($d['company_name'] ?? ''));
  6753. $sid = (int)($d['scydgy_id'] ?? 0);
  6754. if ($cn === '' || $sid === 0) {
  6755. continue;
  6756. }
  6757. if (!isset($detailByCompanySid[$cn])) {
  6758. $detailByCompanySid[$cn] = [];
  6759. }
  6760. $detailByCompanySid[$cn][$sid] = $d;
  6761. }
  6762. $supplierGroups = [];
  6763. foreach ($detailByCompanySid as $cn => $bySid) {
  6764. $lines = [];
  6765. $groupTotal = 0.0;
  6766. $groupHas = false;
  6767. $groupVoid = true;
  6768. $usedSids = [];
  6769. $appendLine = function (int $sid, array $d) use (
  6770. &$lines,
  6771. &$groupTotal,
  6772. &$groupHas,
  6773. &$groupVoid,
  6774. $qtyBySid,
  6775. $gymcBySid,
  6776. $quoteVisible
  6777. ) {
  6778. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  6779. if (!$isVoid) {
  6780. $groupVoid = false;
  6781. }
  6782. $qtyStr = $qtyBySid[$sid] ?? '';
  6783. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  6784. $am = trim((string)($d['amount'] ?? ''));
  6785. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  6786. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  6787. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  6788. $sub = null;
  6789. if (!$isVoid && $amountNum !== null) {
  6790. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  6791. }
  6792. $ct = $this->resolveDetailSupplierOperTime($d);
  6793. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  6794. $leadFilled = ($leadDays !== null);
  6795. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  6796. $line = [
  6797. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  6798. 'amount' => $am,
  6799. 'unit_price_text' => $amountFilled
  6800. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  6801. : '未填写',
  6802. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  6803. 'delivery_ymd' => $deliveryYmd,
  6804. 'amount_filled' => $amountFilled,
  6805. 'delivery_filled' => $deliveryFilled,
  6806. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  6807. 'lead_days' => $leadFilled ? $leadDays : '',
  6808. 'lead_days_filled'=> $leadFilled,
  6809. 'lead_days_show' => $leadText,
  6810. 'lead_days_text' => $leadText,
  6811. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  6812. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  6813. 'is_void' => $isVoid,
  6814. 'oper_time_text' => $ct,
  6815. ];
  6816. if (!$quoteVisible && !$isVoid) {
  6817. $this->maskSupplierQuoteLineBeforeDeadline($line);
  6818. } elseif ($sub !== null) {
  6819. $groupTotal += $sub;
  6820. $groupHas = true;
  6821. }
  6822. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  6823. };
  6824. foreach ($orderedSids as $sid) {
  6825. if (!isset($bySid[$sid])) {
  6826. continue;
  6827. }
  6828. $usedSids[$sid] = true;
  6829. $appendLine($sid, $bySid[$sid]);
  6830. }
  6831. foreach ($bySid as $sid => $d) {
  6832. if (isset($usedSids[$sid])) {
  6833. continue;
  6834. }
  6835. $appendLine((int)$sid, $d);
  6836. }
  6837. $firstDetail = null;
  6838. foreach ($bySid as $d) {
  6839. if (is_array($d)) {
  6840. $firstDetail = $d;
  6841. break;
  6842. }
  6843. }
  6844. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  6845. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  6846. if ($username === '' && $ph !== '') {
  6847. $username = $this->resolveCustomerContactName($ph, $cn);
  6848. }
  6849. $remark = '';
  6850. foreach ($bySid as $d) {
  6851. if (!is_array($d)) {
  6852. continue;
  6853. }
  6854. $rm = '';
  6855. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  6856. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  6857. $rm = trim((string)$d[$rk]);
  6858. break;
  6859. }
  6860. }
  6861. if ($rm !== '') {
  6862. $remark = $rm;
  6863. break;
  6864. }
  6865. }
  6866. $lineCount = count($lines);
  6867. $hasRemark = $lineCount > 0;
  6868. $supplierGroup = [
  6869. 'company_name' => $cn,
  6870. 'username' => $username,
  6871. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  6872. 'phone' => $ph,
  6873. 'remark' => $remark,
  6874. 'has_remark' => $hasRemark,
  6875. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  6876. 'is_void' => $groupVoid,
  6877. 'lines' => $lines,
  6878. 'line_count' => $lineCount,
  6879. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  6880. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  6881. 'has_total' => $lineCount > 0,
  6882. ];
  6883. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  6884. $supplierGroups[] = $supplierGroup;
  6885. }
  6886. usort($supplierGroups, function ($a, $b) {
  6887. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  6888. return ($a['is_void'] ?? false) ? 1 : -1;
  6889. }
  6890. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  6891. return ($a['is_selected'] ?? false) ? -1 : 1;
  6892. }
  6893. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  6894. });
  6895. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  6896. return [
  6897. 'process_rows' => $processRows,
  6898. 'supplier_groups' => $supplierGroups,
  6899. 'order_total_text' => '',
  6900. 'order_total_has' => false,
  6901. 'selected_company' => $selectedCompany,
  6902. ];
  6903. }
  6904. /**
  6905. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  6906. */
  6907. protected function buildProcessLinesPlain(array $mergeRows): string
  6908. {
  6909. $lines = [];
  6910. $i = 1;
  6911. foreach ($mergeRows as $r) {
  6912. if (!is_array($r)) {
  6913. continue;
  6914. }
  6915. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6916. $dw = trim((string)($r['CDW'] ?? ''));
  6917. $gzl = trim((string)($r['NGZL'] ?? ''));
  6918. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  6919. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  6920. if ($dw !== '') {
  6921. $parts[] = '单位:' . $dw;
  6922. }
  6923. if ($gzl !== '') {
  6924. $parts[] = '工作量:' . $gzl;
  6925. }
  6926. if ($qty !== '') {
  6927. $parts[] = '本次数量:' . $qty;
  6928. }
  6929. $lines[] = implode(' ', $parts);
  6930. $i++;
  6931. }
  6932. return implode("\n", $lines);
  6933. }
  6934. /**
  6935. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  6936. *
  6937. * @return array<string, string>
  6938. */
  6939. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  6940. {
  6941. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  6942. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  6943. }
  6944. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  6945. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  6946. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6947. $cyjmc = '';
  6948. foreach ($mergeRows as $mr) {
  6949. if (!is_array($mr)) {
  6950. continue;
  6951. }
  6952. if ($ccydh === '') {
  6953. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  6954. }
  6955. if ($cyjmc === '') {
  6956. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  6957. }
  6958. }
  6959. if ($pos !== []) {
  6960. $firstPo = $pos[0];
  6961. if (is_array($firstPo)) {
  6962. if ($ccydh === '') {
  6963. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  6964. }
  6965. if ($cyjmc === '') {
  6966. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  6967. }
  6968. }
  6969. }
  6970. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  6971. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  6972. if (is_array($any)) {
  6973. if ($ccydh === '') {
  6974. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  6975. }
  6976. if ($cyjmc === '') {
  6977. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  6978. }
  6979. }
  6980. }
  6981. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  6982. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  6983. $cgymc = '';
  6984. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  6985. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  6986. }
  6987. return [
  6988. 'ccydh' => $ccydh,
  6989. 'cyjmc' => $cyjmc,
  6990. 'cgymc' => $cgymc,
  6991. 'process_lines' => $processLines,
  6992. 'process_lines_html' => '',
  6993. ];
  6994. }
  6995. /**
  6996. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  6997. */
  6998. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  6999. {
  7000. $lines = [];
  7001. if ($ccydh !== '') {
  7002. $lines[] = '订单号:' . $ccydh;
  7003. }
  7004. if ($cyjmc !== '') {
  7005. $lines[] = '印件名称:' . $cyjmc;
  7006. }
  7007. if ($processPlain !== '') {
  7008. $lines[] = $processPlain;
  7009. }
  7010. return implode("\n", $lines);
  7011. }
  7012. /**
  7013. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  7014. *
  7015. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  7016. */
  7017. protected function buildPlatformLinksPlain(array $detailLinks): string
  7018. {
  7019. $lines = [];
  7020. $i = 1;
  7021. foreach ($detailLinks as $lk) {
  7022. if (!is_array($lk)) {
  7023. continue;
  7024. }
  7025. $url = trim((string)($lk['url'] ?? ''));
  7026. if ($url === '') {
  7027. continue;
  7028. }
  7029. $label = trim((string)($lk['cgymc'] ?? ''));
  7030. if ($label === '') {
  7031. $label = '工序' . $i;
  7032. }
  7033. $lines[] = $label . ':' . $url;
  7034. $i++;
  7035. }
  7036. return implode("\n", $lines);
  7037. }
  7038. /**
  7039. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  7040. *
  7041. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  7042. */
  7043. protected function buildPlatformLinksHtml(array $detailLinks): string
  7044. {
  7045. $parts = [];
  7046. $i = 1;
  7047. foreach ($detailLinks as $lk) {
  7048. if (!is_array($lk)) {
  7049. continue;
  7050. }
  7051. $url = trim((string)($lk['url'] ?? ''));
  7052. if ($url === '') {
  7053. continue;
  7054. }
  7055. $label = trim((string)($lk['cgymc'] ?? ''));
  7056. if ($label === '') {
  7057. $label = '工序' . $i;
  7058. }
  7059. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  7060. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  7061. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  7062. $i++;
  7063. }
  7064. return implode("<br>\n", $parts);
  7065. }
  7066. /**
  7067. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  7068. *
  7069. * @return array<string, mixed>
  7070. */
  7071. protected function loadMailerConfig(): array
  7072. {
  7073. try {
  7074. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  7075. } catch (\Throwable $e) {
  7076. $cfg = [];
  7077. }
  7078. return is_array($cfg) ? $cfg : [];
  7079. }
  7080. protected function loadNotifyTemplateRow(string $scene): ?array
  7081. {
  7082. try {
  7083. $row = Db::table('purchase_sms_template')
  7084. ->where('scene', $scene)
  7085. ->where(function ($q) {
  7086. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  7087. })
  7088. ->order('id', 'asc')
  7089. ->find();
  7090. } catch (\Throwable $e) {
  7091. return null;
  7092. }
  7093. if (!is_array($row) || $row === []) {
  7094. return null;
  7095. }
  7096. return [
  7097. 'title' => trim((string)($row['title'] ?? '')),
  7098. 'content' => trim((string)($row['content'] ?? '')),
  7099. ];
  7100. }
  7101. /**
  7102. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  7103. */
  7104. protected function buildProcessLinesHtml(array $mergeRows): string
  7105. {
  7106. if (count($mergeRows) <= 1) {
  7107. $r = $mergeRows[0] ?? [];
  7108. if (!is_array($r)) {
  7109. return '';
  7110. }
  7111. $gymc = trim((string)($r['CGYMC'] ?? ''));
  7112. $dw = trim((string)($r['CDW'] ?? ''));
  7113. $gzl = trim((string)($r['NGZL'] ?? ''));
  7114. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  7115. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  7116. if ($dw !== '') {
  7117. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  7118. }
  7119. if ($gzl !== '') {
  7120. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  7121. }
  7122. if ($qty !== '') {
  7123. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  7124. }
  7125. return $html;
  7126. }
  7127. $rows = '';
  7128. $i = 1;
  7129. foreach ($mergeRows as $r) {
  7130. if (!is_array($r)) {
  7131. continue;
  7132. }
  7133. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  7134. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  7135. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  7136. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  7137. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  7138. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  7139. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  7140. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  7141. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  7142. $i++;
  7143. }
  7144. if ($rows === '') {
  7145. return '';
  7146. }
  7147. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  7148. . '<thead><tr style="background:#f5f5f5;">'
  7149. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  7150. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  7151. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  7152. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  7153. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  7154. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  7155. }
  7156. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  7157. {
  7158. $sysRq = trim($sysRq);
  7159. if ($sysRq === '') {
  7160. if ($required) {
  7161. $this->error('请选择招标截止日期');
  7162. }
  7163. return '';
  7164. }
  7165. $ts = strtotime($sysRq);
  7166. if ($ts === false || $ts <= 0) {
  7167. $this->error('招标截止日期格式无效');
  7168. }
  7169. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  7170. if (!$allowPast) {
  7171. $ymd = date('Y-m-d', $ts);
  7172. if ($ymd < date('Y-m-d')) {
  7173. $this->error('招标截止日期不能早于今天');
  7174. }
  7175. if ($ts <= time()) {
  7176. $this->error('招标截止时间不能早于当前时间');
  7177. }
  7178. }
  7179. return date('Y-m-d H:i:s', $ts);
  7180. }
  7181. /**
  7182. * 确保 purchase_order.czlyq(类型)存在
  7183. */
  7184. protected function ensurePurchaseOrderCzlyqColumn(): void
  7185. {
  7186. static $done = false;
  7187. if ($done) {
  7188. return;
  7189. }
  7190. $done = true;
  7191. try {
  7192. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  7193. if (empty($cols)) {
  7194. Db::execute(
  7195. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  7196. );
  7197. }
  7198. } catch (\Throwable $e) {
  7199. // ignore
  7200. }
  7201. }
  7202. /**
  7203. * 确保 purchase_order.delivery_deadline 存在
  7204. */
  7205. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  7206. {
  7207. static $done = false;
  7208. if ($done) {
  7209. return;
  7210. }
  7211. $done = true;
  7212. try {
  7213. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  7214. if (empty($cols)) {
  7215. Db::execute(
  7216. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  7217. );
  7218. }
  7219. } catch (\Throwable $e) {
  7220. // ignore
  7221. }
  7222. }
  7223. /**
  7224. * 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
  7225. */
  7226. protected function ensurePurchaseOrderScoreRuleIdColumn(): void
  7227. {
  7228. static $done = false;
  7229. if ($done) {
  7230. return;
  7231. }
  7232. $done = true;
  7233. // 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
  7234. $adds = [
  7235. 'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
  7236. 'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
  7237. 'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
  7238. 'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
  7239. 'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
  7240. ];
  7241. $changed = false;
  7242. foreach ($adds as $col => $ddl) {
  7243. try {
  7244. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  7245. if (!is_array($cols) || $cols === []) {
  7246. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  7247. $changed = true;
  7248. }
  7249. } catch (\Throwable $e) {
  7250. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  7251. }
  7252. }
  7253. if ($changed) {
  7254. $this->clearPurchaseOrderTableFieldsCache();
  7255. }
  7256. }
  7257. /**
  7258. * ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
  7259. */
  7260. protected function clearPurchaseOrderTableFieldsCache(): void
  7261. {
  7262. try {
  7263. $db = (string)Config::get('database.database');
  7264. $key = $db . '.purchase_order';
  7265. $ref = new \ReflectionProperty(\think\db\Query::class, 'info');
  7266. $ref->setAccessible(true);
  7267. $info = $ref->getValue();
  7268. if (is_array($info) && isset($info[$key])) {
  7269. unset($info[$key]);
  7270. $ref->setValue(null, $info);
  7271. }
  7272. } catch (\Throwable $e) {
  7273. }
  7274. try {
  7275. $db = (string)Config::get('database.database');
  7276. $schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
  7277. if (is_file($schemaFile)) {
  7278. @unlink($schemaFile);
  7279. }
  7280. } catch (\Throwable $e) {
  7281. }
  7282. }
  7283. /**
  7284. * @return array<string, bool>
  7285. */
  7286. protected function loadPurchaseOrderColumnSet(): array
  7287. {
  7288. static $set = null;
  7289. if (is_array($set)) {
  7290. return $set;
  7291. }
  7292. $set = [];
  7293. try {
  7294. $cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
  7295. } catch (\Throwable $e) {
  7296. return $set;
  7297. }
  7298. if (!is_array($cols)) {
  7299. return $set;
  7300. }
  7301. foreach ($cols as $c) {
  7302. if (!is_array($c)) {
  7303. continue;
  7304. }
  7305. $f = (string)($c['Field'] ?? $c['field'] ?? '');
  7306. if ($f !== '') {
  7307. $set[$f] = true;
  7308. }
  7309. }
  7310. return $set;
  7311. }
  7312. /**
  7313. * 解析交货截止日期(仅年月日)
  7314. */
  7315. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  7316. {
  7317. $raw = trim($raw);
  7318. if ($raw === '') {
  7319. if ($required) {
  7320. $this->error('请选择交货截止日期');
  7321. }
  7322. return '';
  7323. }
  7324. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  7325. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  7326. } else {
  7327. $ts = strtotime(str_replace('/', '-', $raw));
  7328. if ($ts === false || $ts <= 0) {
  7329. $this->error('交货截止日期格式无效');
  7330. }
  7331. $ymd = date('Y-m-d', $ts);
  7332. }
  7333. if ($ymd < date('Y-m-d')) {
  7334. $this->error('交货截止日期不能早于今天');
  7335. }
  7336. return $ymd;
  7337. }
  7338. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  7339. {
  7340. $s = trim((string)$value);
  7341. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  7342. return '';
  7343. }
  7344. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  7345. return $m[1];
  7346. }
  7347. $ts = strtotime(str_replace('/', '-', $s));
  7348. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  7349. }
  7350. /**
  7351. * @param array{pos?:array} $bundle
  7352. */
  7353. protected function resolveBundleDeliveryDeadline(array $bundle): string
  7354. {
  7355. foreach ($bundle['pos'] ?? [] as $po) {
  7356. if (!is_array($po)) {
  7357. continue;
  7358. }
  7359. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7360. if ($d !== '') {
  7361. return $d;
  7362. }
  7363. }
  7364. return '';
  7365. }
  7366. protected function formatProcuremenSysRqForInput($sysRq): string
  7367. {
  7368. $sr = trim((string)$sysRq);
  7369. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  7370. return '';
  7371. }
  7372. $ts = strtotime($sr);
  7373. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  7374. }
  7375. protected function formatProcuremenSysRqForDisplay($sysRq): string
  7376. {
  7377. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  7378. if ($sr === '') {
  7379. return '—';
  7380. }
  7381. $ts = strtotime($sr);
  7382. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  7383. }
  7384. /**
  7385. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  7386. *
  7387. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  7388. * @return array{ccydh?:string,pos:array,merge_rows:array}
  7389. */
  7390. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  7391. {
  7392. return $bundle;
  7393. }
  7394. /**
  7395. * 写入/更新 purchase_order(单道工序行)
  7396. *
  7397. * @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
  7398. */
  7399. protected function upsertPurchaseOrderFromRow(
  7400. array $row,
  7401. string $sysRqDb,
  7402. $wflowStatus = null,
  7403. ?string $pickTime = null,
  7404. ?array $exists = null,
  7405. ?string $deliveryDeadline = null,
  7406. $scoreRuleId = null
  7407. ): void {
  7408. $ids = $this->extractScydgyRowId($row);
  7409. if (!$this->isValidScydgyRowId($ids)) {
  7410. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  7411. }
  7412. if ($exists === null) {
  7413. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7414. }
  7415. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  7416. $this->ensurePurchaseOrderScoreRuleIdColumn();
  7417. $this->ensurePurchaseOrderCzlyqColumn();
  7418. $data = [
  7419. 'scydgy_id' => $ids,
  7420. 'CCYDH' => $row['CCYDH'] ?? null,
  7421. 'CYJMC' => $row['CYJMC'] ?? null,
  7422. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  7423. 'CDXMC' => $row['CDXMC'] ?? null,
  7424. 'CGYBH' => $row['CGYBH'] ?? null,
  7425. 'CGYMC' => $row['CGYMC'] ?? null,
  7426. 'CDW' => $row['CDW'] ?? null,
  7427. 'czlyq' => $row['czlyq'] ?? null,
  7428. 'NGZL' => $row['NGZL'] ?? null,
  7429. 'CDF' => $row['CDF'] ?? null,
  7430. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  7431. 'MBZ' => $row['MBZ'] ?? null,
  7432. 'bwjg' => $row['bwjg'] ?? null,
  7433. 'iStatus' => $row['iStatus'] ?? null,
  7434. 'dStamp' => $row['dStamp'] ?? null,
  7435. 'dputrecord' => $row['dputrecord'] ?? null,
  7436. 'cywyxm' => $row['cywyxm'] ?? null,
  7437. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  7438. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  7439. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7440. 'sys_rq' => $sysRqDb,
  7441. ];
  7442. // 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
  7443. $qtyUp = trim((string)($data['This_quantity'] ?? ''));
  7444. if ($qtyUp === '') {
  7445. $qtyFallback = $this->resolveProcuremenThisQuantity([
  7446. 'This_quantity' => '',
  7447. 'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
  7448. ]);
  7449. if ($qtyFallback !== '') {
  7450. $data['This_quantity'] = $qtyFallback;
  7451. }
  7452. }
  7453. if ($deliveryDeadline !== null) {
  7454. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  7455. }
  7456. // 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
  7457. $scoreRule = null;
  7458. if (is_array($scoreRuleId)) {
  7459. $scoreRule = $scoreRuleId;
  7460. $scoreRuleId = (int)($scoreRule['id'] ?? 0);
  7461. } else {
  7462. $scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
  7463. }
  7464. if ($scoreRuleId !== null && $scoreRuleId > 0) {
  7465. $poCols = $this->loadPurchaseOrderColumnSet();
  7466. if (!empty($poCols['score_rule_id'])) {
  7467. $data['score_rule_id'] = $scoreRuleId;
  7468. if (is_array($scoreRule)) {
  7469. if (!empty($poCols['score_rule_name'])) {
  7470. $data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
  7471. }
  7472. if (!empty($poCols['score_quality_weight'])) {
  7473. $data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
  7474. }
  7475. if (!empty($poCols['score_price_weight'])) {
  7476. $data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
  7477. }
  7478. if (!empty($poCols['score_lead_weight'])) {
  7479. $data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
  7480. }
  7481. }
  7482. }
  7483. }
  7484. if ($wflowStatus !== null && $wflowStatus !== '') {
  7485. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  7486. }
  7487. if ($pickTime !== null && $pickTime !== '') {
  7488. $data['pick_time'] = $pickTime;
  7489. $data['pick_company_name'] = '';
  7490. }
  7491. if ($exists) {
  7492. $upd = $data;
  7493. unset($upd['scydgy_id']);
  7494. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  7495. } else {
  7496. $data['createtime'] = date('Y-m-d H:i:s');
  7497. Db::table('purchase_order')->insert($data);
  7498. }
  7499. }
  7500. /**
  7501. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  7502. *
  7503. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  7504. */
  7505. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
  7506. {
  7507. $toDb = function ($value) {
  7508. if ($value === null) {
  7509. return null;
  7510. }
  7511. if (is_scalar($value)) {
  7512. return $value;
  7513. }
  7514. return json_encode($value, JSON_UNESCAPED_UNICODE);
  7515. };
  7516. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7517. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7518. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7519. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  7520. if ($username === '') {
  7521. $username = $this->resolveCustomerContactName($phone, $companyName);
  7522. }
  7523. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  7524. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  7525. }
  7526. if ($requirePhone && $phone === '') {
  7527. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  7528. }
  7529. $detailLinks = [];
  7530. foreach ($mergeRows as $row) {
  7531. if (!is_array($row)) {
  7532. continue;
  7533. }
  7534. $sid = $this->extractScydgyRowId($row);
  7535. $detailId = 0;
  7536. if ($skipExisting) {
  7537. try {
  7538. $existsQuery = Db::table('purchase_order_detail')
  7539. ->where('scydgy_id', $sid)
  7540. ->where('company_name', $companyName);
  7541. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  7542. $exists = $existsQuery->find();
  7543. } catch (\Throwable $e) {
  7544. $exists = null;
  7545. }
  7546. if (is_array($exists)) {
  7547. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  7548. }
  7549. }
  7550. if ($detailId <= 0) {
  7551. $one = [
  7552. 'scydgy_id' => $toDb($sid),
  7553. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  7554. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  7555. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  7556. 'username' => $username !== '' ? $username : null,
  7557. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  7558. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  7559. 'createtime' => date('Y-m-d H:i:s'),
  7560. 'status' => ProcuremenStatus::POD_UNPICKED,
  7561. 'status_name' => '未提交',
  7562. ];
  7563. Db::table('purchase_order_detail')->insert($one);
  7564. $detailId = (int)Db::getLastInsID();
  7565. }
  7566. $mprocUrl = '';
  7567. if ($buildMobileLinks && $detailId > 0) {
  7568. // 手工询价 → 待报价;协助下发 → 未提交
  7569. $listTab = ($sid < 0) ? 'rfq' : 'draft';
  7570. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId, $listTab);
  7571. }
  7572. $detailLinks[] = [
  7573. 'detail_id' => $detailId,
  7574. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  7575. 'url' => $mprocUrl,
  7576. ];
  7577. }
  7578. $this->invalidatePickHiddenScydgyCache();
  7579. return $detailLinks;
  7580. }
  7581. /**
  7582. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  7583. * @return array<string, mixed>
  7584. */
  7585. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks, string $emailTplScene = 'review_email'): array
  7586. {
  7587. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7588. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7589. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7590. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  7591. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  7592. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  7593. $isMerge = !empty($ctx['is_merge']);
  7594. $contactName = trim((string)($c['username'] ?? ''));
  7595. if ($contactName === '') {
  7596. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  7597. }
  7598. $notifyVars = [
  7599. 'company_name' => $companyName,
  7600. 'contact_name' => $contactName,
  7601. 'phone' => $phone,
  7602. 'email' => $toEmail,
  7603. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  7604. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  7605. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  7606. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  7607. 'deadline' => (string)($ctx['deadline'] ?? ''),
  7608. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  7609. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  7610. 'order_type' => (string)($ctx['order_type'] ?? ''),
  7611. 'score_weights' => (string)($ctx['score_weights'] ?? ''),
  7612. 'platform_url' => $platformUrl,
  7613. 'platform_links' => $platformLinksPlain,
  7614. 'platform_links_html' => $platformLinksHtml,
  7615. ];
  7616. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  7617. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  7618. $mailPlain = $this->renderNotifyTemplate($emailTplScene, $notifyVars);
  7619. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  7620. return [
  7621. 'company_name' => $companyName,
  7622. 'phone' => $phone,
  7623. 'email' => $toEmail,
  7624. 'sms_content' => $smsContent,
  7625. 'mail_plain' => $mailPlain,
  7626. 'mail_body' => $mailBody,
  7627. 'notify_vars' => $notifyVars,
  7628. 'detail_links' => $detailLinks,
  7629. ];
  7630. }
  7631. /**
  7632. * @param array<string, mixed> $chosen
  7633. * @param array<int, array<string, mixed>> $mergeRows
  7634. * @param array{ccydh:string, pos:array} $bundle
  7635. */
  7636. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue', string $emailTplScene = 'review_email'): void
  7637. {
  7638. if (!$sendSms && !$sendEmail) {
  7639. return;
  7640. }
  7641. $companyName = trim((string)($chosen['name'] ?? ''));
  7642. $phone = trim((string)($chosen['phone'] ?? ''));
  7643. $toEmail = trim((string)($chosen['email'] ?? ''));
  7644. if ($companyName === '') {
  7645. throw new \Exception('供应商名称无效');
  7646. }
  7647. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  7648. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  7649. }
  7650. if ($sendSms && $phone === '') {
  7651. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  7652. }
  7653. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  7654. $linkListTab = (strpos($emailTplScene, 'rfq_') === 0) ? 'rfq' : 'draft';
  7655. $sids = [];
  7656. foreach ($mergeRows as $mr) {
  7657. if (!is_array($mr)) {
  7658. continue;
  7659. }
  7660. $sid = $this->extractScydgyRowId($mr);
  7661. if ($this->isValidScydgyRowId($sid)) {
  7662. $sids[$sid] = true;
  7663. }
  7664. }
  7665. if ($sids === []) {
  7666. throw new \Exception('未找到工序行,无法发送通知');
  7667. }
  7668. $sysRqNotify = '';
  7669. $pos = $bundle['pos'] ?? [];
  7670. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7671. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  7672. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  7673. $ts = strtotime($sr);
  7674. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  7675. }
  7676. }
  7677. try {
  7678. $detailsQuery = Db::table('purchase_order_detail')
  7679. ->where('scydgy_id', 'in', array_keys($sids))
  7680. ->where('company_name', $companyName);
  7681. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7682. $details = $detailsQuery->order('id', 'asc')->select();
  7683. } catch (\Throwable $e) {
  7684. $details = [];
  7685. }
  7686. if (!is_array($details) || $details === []) {
  7687. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  7688. try {
  7689. $detailsQuery = Db::table('purchase_order_detail')
  7690. ->where('scydgy_id', 'in', array_keys($sids))
  7691. ->where('company_name', $companyName);
  7692. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7693. $details = $detailsQuery->order('id', 'asc')->select();
  7694. } catch (\Throwable $e) {
  7695. $details = [];
  7696. }
  7697. }
  7698. if (!is_array($details) || $details === []) {
  7699. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  7700. }
  7701. $detailLinks = [];
  7702. foreach ($details as $d) {
  7703. if (!is_array($d)) {
  7704. continue;
  7705. }
  7706. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  7707. if ($detailId <= 0) {
  7708. continue;
  7709. }
  7710. $sid = (int)($d['scydgy_id'] ?? 0);
  7711. $gymc = '';
  7712. foreach ($mergeRows as $mr) {
  7713. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  7714. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  7715. break;
  7716. }
  7717. }
  7718. $detailLinks[] = [
  7719. 'detail_id' => $detailId,
  7720. 'cgymc' => $gymc,
  7721. // 询价邮件 → 待报价;下发报价 → 未提交
  7722. 'url' => $this->buildMprocMobileOrderUrl(
  7723. $detailId,
  7724. ($linkListTab === 'rfq' || $sid < 0) ? 'rfq' : 'draft'
  7725. ),
  7726. ];
  7727. }
  7728. if ($detailLinks === []) {
  7729. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  7730. }
  7731. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  7732. $orderTypeCtx = $this->resolveIssueNotifyOrderTypeFromBundle($bundle);
  7733. $ctx['order_type'] = (string)($orderTypeCtx['order_type'] ?? '');
  7734. $ctx['score_weights'] = (string)($orderTypeCtx['score_weights'] ?? '');
  7735. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks, $emailTplScene);
  7736. $notifyBundle['email_log_scene'] = $emailLogScene;
  7737. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  7738. $poIdLog = 0;
  7739. $pos = $bundle['pos'] ?? [];
  7740. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7741. $poIdLog = (int)($pos[0]['id'] ?? 0);
  7742. }
  7743. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  7744. if ($sendEmail) {
  7745. $mailTplRow = $this->loadNotifyTemplateRow($emailTplScene);
  7746. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  7747. throw new \Exception($this->notifyTemplateMissingMessage($emailTplScene));
  7748. }
  7749. $mailSubject = $this->resolveProcuremenEmailSubject($emailTplScene);
  7750. $mailConfig = $this->loadMailerConfig();
  7751. if (!$this->isProcuremenNotifyDryRun()) {
  7752. if (empty($mailConfig['host'])) {
  7753. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  7754. }
  7755. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  7756. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  7757. }
  7758. }
  7759. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  7760. }
  7761. if ($sendSms) {
  7762. $this->issueSendSupplierSms($notifyBundle);
  7763. }
  7764. }
  7765. /**
  7766. * @param array<int, array<string, mixed>> $quoteGroups
  7767. * @return array<int, array<string, mixed>>
  7768. */
  7769. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  7770. {
  7771. $names = [];
  7772. if (is_string($companiesJson) && $companiesJson !== '') {
  7773. $decoded = json_decode($companiesJson, true);
  7774. if (is_array($decoded)) {
  7775. foreach ($decoded as $nm) {
  7776. $nm = trim((string)$nm);
  7777. if ($nm !== '') {
  7778. $names[] = $nm;
  7779. }
  7780. }
  7781. }
  7782. }
  7783. $names = array_values(array_unique($names));
  7784. if ($names === [] && $selectedCompany !== '') {
  7785. $names = [$selectedCompany];
  7786. }
  7787. if ($names === []) {
  7788. return $quoteGroups;
  7789. }
  7790. $targets = [];
  7791. foreach ($quoteGroups as $g) {
  7792. if (!is_array($g)) {
  7793. continue;
  7794. }
  7795. $cn = trim((string)($g['name'] ?? ''));
  7796. if ($cn !== '' && in_array($cn, $names, true)) {
  7797. $targets[] = $g;
  7798. }
  7799. }
  7800. return $targets;
  7801. }
  7802. /**
  7803. * @return array{pos:array, merge_rows:array, bundle:array}
  7804. */
  7805. protected function loadAuditResendBundle(string $scydgyId): array
  7806. {
  7807. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7808. $pos = $bundle['pos'];
  7809. $mergeRows = $bundle['merge_rows'];
  7810. if ($pos === [] || $mergeRows === []) {
  7811. $this->error('该订单不在待确认供应商状态');
  7812. }
  7813. $sysRqDb = '';
  7814. if (isset($pos[0]) && is_array($pos[0])) {
  7815. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  7816. }
  7817. foreach ($pos as $i => $poRow) {
  7818. if (is_array($pos[$i]) && $sysRqDb !== '') {
  7819. $pos[$i]['sys_rq'] = $sysRqDb;
  7820. }
  7821. }
  7822. $bundle['pos'] = $pos;
  7823. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  7824. }
  7825. /**
  7826. * @param array<int, array<string, mixed>> $targets
  7827. */
  7828. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  7829. {
  7830. if ($targets === []) {
  7831. $this->error('未找到可通知的供应商');
  7832. }
  7833. $notifyErrors = [];
  7834. try {
  7835. $this->notifyDryRunPreview = [];
  7836. foreach ($targets as $g) {
  7837. if (!is_array($g)) {
  7838. continue;
  7839. }
  7840. $cname = trim((string)($g['name'] ?? ''));
  7841. if ($cname === '') {
  7842. continue;
  7843. }
  7844. $chosen = [
  7845. 'name' => $cname,
  7846. 'company_name' => $cname,
  7847. 'email' => trim((string)($g['email'] ?? '')),
  7848. 'phone' => trim((string)($g['phone'] ?? '')),
  7849. 'username' => trim((string)($g['username'] ?? '')),
  7850. ];
  7851. try {
  7852. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  7853. } catch (\Throwable $e) {
  7854. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7855. }
  7856. }
  7857. } catch (\Throwable $e) {
  7858. $this->error('通知发送失败:' . $e->getMessage());
  7859. }
  7860. if ($notifyErrors !== []) {
  7861. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  7862. }
  7863. if ($this->isProcuremenNotifyDryRun()) {
  7864. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  7865. 'notify_dry_run' => true,
  7866. 'notify_preview' => $this->notifyDryRunPreview,
  7867. ]);
  7868. }
  7869. $nameLabels = [];
  7870. foreach ($targets as $g) {
  7871. if (!is_array($g)) {
  7872. continue;
  7873. }
  7874. $n = trim((string)($g['name'] ?? ''));
  7875. if ($n !== '') {
  7876. $nameLabels[] = $n;
  7877. }
  7878. }
  7879. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  7880. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  7881. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  7882. $seenLogSid = [];
  7883. foreach ($bundle['pos'] ?? [] as $poRow) {
  7884. if (!is_array($poRow)) {
  7885. continue;
  7886. }
  7887. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7888. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  7889. continue;
  7890. }
  7891. $seenLogSid[$sid] = true;
  7892. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7893. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7894. }
  7895. if ($seenLogSid === []) {
  7896. foreach ($mergeRows as $mr) {
  7897. if (!is_array($mr)) {
  7898. continue;
  7899. }
  7900. $sid = $this->extractScydgyRowId($mr);
  7901. if ($this->isValidScydgyRowId($sid)) {
  7902. $this->addOrderLog($sid, $logAction, $logMsg, null);
  7903. break;
  7904. }
  7905. }
  7906. }
  7907. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  7908. }
  7909. /**
  7910. * 协助下发 — 发送短信(一家供应商)
  7911. *
  7912. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  7913. */
  7914. protected function issueSendSupplierSms(array $bundle): void
  7915. {
  7916. $companyName = (string)($bundle['company_name'] ?? '');
  7917. $phone = (string)($bundle['phone'] ?? '');
  7918. $smsContent = (string)($bundle['sms_content'] ?? '');
  7919. $this->logIssueNotifyDebug('短信', [
  7920. 'company' => $companyName,
  7921. 'phone' => $phone,
  7922. 'sms_content' => $smsContent,
  7923. ]);
  7924. if ($this->isProcuremenNotifyDryRun()) {
  7925. $this->recordNotifyDryRunPreview([
  7926. 'scene' => 'issue_sms',
  7927. 'company_name' => $companyName,
  7928. 'phone' => $phone,
  7929. 'sms_content' => $smsContent,
  7930. ]);
  7931. return;
  7932. }
  7933. $this->smsbao($phone, $smsContent);
  7934. }
  7935. /**
  7936. * 协助下发 — 发送邮件(一家供应商)
  7937. *
  7938. * @param array<string, mixed> $bundle
  7939. * @param array<string, mixed> $mailConfig
  7940. */
  7941. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  7942. {
  7943. $companyName = (string)($bundle['company_name'] ?? '');
  7944. $toEmail = (string)($bundle['email'] ?? '');
  7945. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  7946. $mailBody = (string)($bundle['mail_body'] ?? '');
  7947. $this->logIssueNotifyDebug('邮件', [
  7948. 'company' => $companyName,
  7949. 'email' => $toEmail,
  7950. 'mail_subject' => $mailSubject,
  7951. 'mail_body' => $mailPlain,
  7952. ]);
  7953. if ($this->isProcuremenNotifyDryRun()) {
  7954. $this->recordNotifyDryRunPreview([
  7955. 'scene' => 'issue_email',
  7956. 'company_name' => $companyName,
  7957. 'email' => $toEmail,
  7958. 'mail_subject' => $mailSubject,
  7959. 'mail_body' => $mailPlain,
  7960. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  7961. 'notify_vars' => $bundle['notify_vars'] ?? [],
  7962. 'detail_links' => $bundle['detail_links'] ?? [],
  7963. ]);
  7964. return;
  7965. }
  7966. $mail = new PHPMailer(true);
  7967. $mail->isSMTP();
  7968. $mail->Host = $mailConfig['host'];
  7969. $mail->SMTPAuth = true;
  7970. $mail->Username = $mailConfig['addr'];
  7971. $mail->Password = $mailConfig['pass'];
  7972. $mail->SMTPSecure = $mailConfig['security'];
  7973. $mail->Port = $mailConfig['port'];
  7974. $mail->CharSet = $mailConfig['charset'];
  7975. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  7976. $mail->addAddress($toEmail, $companyName);
  7977. $mail->isHTML(true);
  7978. $mail->Subject = $mailSubject;
  7979. $mail->Body = $mailBody;
  7980. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  7981. $sendOk = true;
  7982. $failReason = '';
  7983. try {
  7984. $mail->send();
  7985. } catch (\Throwable $e) {
  7986. $sendOk = false;
  7987. $failReason = $e->getMessage();
  7988. $this->persistEmailSendLog([
  7989. 'from_email' => $fromEmail,
  7990. 'to_email' => $toEmail,
  7991. 'send_time' => date('Y-m-d H:i:s'),
  7992. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7993. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7994. 'company_name' => $companyName,
  7995. 'mail_subject' => $mailSubject,
  7996. 'status' => 0,
  7997. 'fail_reason' => $failReason,
  7998. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7999. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  8000. ]);
  8001. throw $e;
  8002. }
  8003. $this->persistEmailSendLog([
  8004. 'from_email' => $fromEmail,
  8005. 'to_email' => $toEmail,
  8006. 'send_time' => date('Y-m-d H:i:s'),
  8007. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  8008. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  8009. 'company_name' => $companyName,
  8010. 'mail_subject' => $mailSubject,
  8011. 'status' => 1,
  8012. 'fail_reason' => '',
  8013. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  8014. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  8015. ]);
  8016. }
  8017. /**
  8018. * 下发通知:解析订单类型名称与评分比例文案
  8019. *
  8020. * @param array<string, mixed> $bundle
  8021. * @return array{order_type:string,score_weights:string}
  8022. */
  8023. protected function resolveIssueNotifyOrderTypeFromBundle(array $bundle): array
  8024. {
  8025. $orderType = '';
  8026. $scoreWeights = '';
  8027. $rule = null;
  8028. if (!empty($bundle['score_rule']) && is_array($bundle['score_rule'])) {
  8029. $rule = $bundle['score_rule'];
  8030. }
  8031. $pos = $bundle['pos'] ?? [];
  8032. $po0 = (is_array($pos) && isset($pos[0]) && is_array($pos[0])) ? $pos[0] : null;
  8033. if ($rule === null && is_array($po0)) {
  8034. $ruleId = (int)($po0['score_rule_id'] ?? 0);
  8035. if ($ruleId > 0) {
  8036. try {
  8037. $rule = ProcuremenSupplierScore::getRuleById($ruleId);
  8038. } catch (\Throwable $e) {
  8039. $rule = null;
  8040. }
  8041. }
  8042. if (!is_array($rule) || (int)($rule['id'] ?? 0) <= 0) {
  8043. $qw = (int)($po0['score_quality_weight'] ?? 0);
  8044. $pw = (int)($po0['score_price_weight'] ?? 0);
  8045. $lw = (int)($po0['score_lead_weight'] ?? 0);
  8046. if ($qw > 0 || $pw > 0 || $lw > 0) {
  8047. $rule = [
  8048. 'name' => trim((string)($po0['score_rule_name'] ?? '')),
  8049. 'quality_weight' => $qw,
  8050. 'price_weight' => $pw,
  8051. 'lead_weight' => $lw,
  8052. ];
  8053. }
  8054. }
  8055. }
  8056. if (is_array($rule)) {
  8057. $orderType = trim((string)($rule['name'] ?? ''));
  8058. $scoreWeights = $this->formatScoreRuleWeightsText($rule);
  8059. }
  8060. if ($orderType === '' && is_array($po0)) {
  8061. $orderType = trim((string)($po0['score_rule_name'] ?? ''));
  8062. }
  8063. return [
  8064. 'order_type' => $orderType,
  8065. 'score_weights' => $scoreWeights,
  8066. ];
  8067. }
  8068. /**
  8069. * 评分比例文案:质量30%、价格50%、交货20%
  8070. *
  8071. * @param array{quality_weight?:mixed,price_weight?:mixed,lead_weight?:mixed} $rule
  8072. */
  8073. protected function formatScoreRuleWeightsText(array $rule): string
  8074. {
  8075. $parts = [];
  8076. $qw = max(0, (float)($rule['quality_weight'] ?? 0));
  8077. $pw = max(0, (float)($rule['price_weight'] ?? 0));
  8078. $lw = max(0, (float)($rule['lead_weight'] ?? 0));
  8079. $fmt = static function ($n) {
  8080. $s = rtrim(rtrim(sprintf('%.2F', (float)$n), '0'), '.');
  8081. return $s === '' ? '0' : $s;
  8082. };
  8083. if ($qw > 0) {
  8084. $parts[] = '质量' . $fmt($qw) . '%';
  8085. }
  8086. if ($pw > 0) {
  8087. $parts[] = '价格' . $fmt($pw) . '%';
  8088. }
  8089. if ($lw > 0) {
  8090. $parts[] = '交货' . $fmt($lw) . '%';
  8091. }
  8092. return implode('、', $parts);
  8093. }
  8094. /**
  8095. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  8096. *
  8097. * @param array<int, array<string, mixed>> $mergeRows
  8098. * @return array<string, mixed>
  8099. */
  8100. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  8101. {
  8102. $head = $mergeRows[0] ?? [];
  8103. $isMerge = count($mergeRows) > 1;
  8104. return [
  8105. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  8106. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  8107. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  8108. 'is_merge' => $isMerge,
  8109. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  8110. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  8111. 'deadline' => $sysRqNotify,
  8112. 'order_type' => '',
  8113. 'score_weights' => '',
  8114. ];
  8115. }
  8116. /**
  8117. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  8118. *
  8119. * @param array<string, mixed> $data
  8120. */
  8121. protected function logIssueNotifyDebug(string $type, array $data): void
  8122. {
  8123. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  8124. return;
  8125. }
  8126. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  8127. }
  8128. protected function ensurePurchaseEmailSendLogTableOnce(): void
  8129. {
  8130. try {
  8131. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  8132. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  8133. return;
  8134. } catch (\Throwable $e) {
  8135. }
  8136. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  8137. if (is_file($sqlFile)) {
  8138. $sql = file_get_contents($sqlFile);
  8139. if (is_string($sql) && $sql !== '') {
  8140. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  8141. $stmt = trim($stmt);
  8142. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  8143. continue;
  8144. }
  8145. try {
  8146. Db::execute($stmt);
  8147. } catch (\Throwable $ignore) {
  8148. }
  8149. }
  8150. }
  8151. }
  8152. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  8153. }
  8154. /**
  8155. * @param array<string, mixed> $row
  8156. */
  8157. protected function persistEmailSendLog(array $row): void
  8158. {
  8159. try {
  8160. $this->ensurePurchaseEmailSendLogTableOnce();
  8161. } catch (\Throwable $e) {
  8162. return;
  8163. }
  8164. list($adminId, $adminName) = $this->GetUseName();
  8165. $cut = function ($s, $max) {
  8166. $s = (string)$s;
  8167. if (function_exists('mb_substr')) {
  8168. return mb_substr($s, 0, $max, 'UTF-8');
  8169. }
  8170. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  8171. };
  8172. $data = [
  8173. 'from_email' => $cut($row['from_email'] ?? '', 128),
  8174. 'to_email' => $cut($row['to_email'] ?? '', 128),
  8175. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  8176. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  8177. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  8178. 'company_name' => $cut($row['company_name'] ?? '', 128),
  8179. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  8180. 'status' => !empty($row['status']) ? 1 : 0,
  8181. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  8182. 'admin_id' => (int)$adminId,
  8183. 'admin_name' => $cut($adminName, 64),
  8184. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  8185. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  8186. 'createtime' => date('Y-m-d H:i:s'),
  8187. ];
  8188. try {
  8189. Db::table('purchase_email_send_log')->insert($data);
  8190. } catch (\Throwable $e) {
  8191. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  8192. }
  8193. }
  8194. protected function formatEmailLogSceneText(string $scene): string
  8195. {
  8196. $map = [
  8197. 'pick_issue' => '初选下发',
  8198. 'audit_resend' => '确认页重发',
  8199. 'rfq_salesman' => '询价通知业务员',
  8200. 'rfq_supplier' => '供应商询价通知',
  8201. ];
  8202. return $map[$scene] ?? $scene;
  8203. }
  8204. /**
  8205. * 邮件发送日志列表
  8206. */
  8207. public function emailLog()
  8208. {
  8209. $this->relationSearch = false;
  8210. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  8211. $this->request->filter(['strip_tags', 'trim']);
  8212. $bakModel = $this->model;
  8213. $this->model = new \app\admin\model\Purchaseemailsendlog;
  8214. if ($this->request->isAjax()) {
  8215. $this->ensurePurchaseEmailSendLogTableOnce();
  8216. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  8217. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  8218. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  8219. $list = $this->model
  8220. ->where($where)
  8221. ->order($sortField, $orderDir)
  8222. ->paginate($limit);
  8223. $rows = [];
  8224. foreach ($list->items() as $item) {
  8225. $row = is_array($item) ? $item : $item->toArray();
  8226. $scene = trim((string)($row['scene'] ?? ''));
  8227. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  8228. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  8229. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  8230. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  8231. $rows[] = $row;
  8232. }
  8233. $this->model = $bakModel;
  8234. return json(['total' => $list->total(), 'rows' => $rows]);
  8235. }
  8236. $this->model = $bakModel;
  8237. return $this->view->fetch('procuremen/emaillog');
  8238. }
  8239. /**
  8240. * 协助下发弹窗(选多家供应商并通知)
  8241. */
  8242. public function pickReview()
  8243. {
  8244. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  8245. $this->error(__('You have no permission'));
  8246. }
  8247. if ($this->request->isPost()) {
  8248. $this->error('请使用弹窗内「确认下发」提交');
  8249. }
  8250. $this->view->assign('pickMode', 1);
  8251. $this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
  8252. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  8253. }
  8254. /**
  8255. * 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
  8256. */
  8257. protected function ensurePurchaseOrderNotifySalesmanColumn(): void
  8258. {
  8259. static $done = false;
  8260. if ($done) {
  8261. return;
  8262. }
  8263. $done = true;
  8264. try {
  8265. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'notify_salesman'");
  8266. if (empty($cols)) {
  8267. Db::execute(
  8268. "ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
  8269. );
  8270. } else {
  8271. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  8272. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
  8273. Db::execute(
  8274. "ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
  8275. );
  8276. }
  8277. }
  8278. } catch (\Throwable $e) {
  8279. // ignore
  8280. }
  8281. }
  8282. /**
  8283. * 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
  8284. */
  8285. protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
  8286. {
  8287. static $done = false;
  8288. if ($done) {
  8289. return;
  8290. }
  8291. $done = true;
  8292. try {
  8293. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
  8294. if (empty($cols)) {
  8295. Db::execute(
  8296. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
  8297. );
  8298. }
  8299. } catch (\Throwable $e) {
  8300. // ignore
  8301. }
  8302. try {
  8303. $cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
  8304. if (empty($cols2)) {
  8305. Db::execute(
  8306. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
  8307. );
  8308. }
  8309. } catch (\Throwable $e) {
  8310. // ignore
  8311. }
  8312. }
  8313. /**
  8314. * 确保「采购确认通过/未通过」邮箱模版存在(正文同短信,末尾加平台链接)
  8315. */
  8316. protected function ensureConfirmResultEmailTemplates(): void
  8317. {
  8318. static $done = false;
  8319. if ($done) {
  8320. return;
  8321. }
  8322. $done = true;
  8323. $now = date('Y-m-d H:i:s');
  8324. $seeds = [
  8325. 'confirm_ok_email' => [
  8326. 'title' => '采购确认结果:已通过',
  8327. 'content' => "【可集达】您好,{company_name}:\n\n您参与的外发加工订单采购确认结果:已通过。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  8328. 'remark' => '审批通过-中标供应商邮箱通知;模版名称作邮件主题',
  8329. ],
  8330. 'confirm_fail_email' => [
  8331. 'title' => '采购确认结果:未通过',
  8332. 'content' => "【可集达】您好,{company_name}:\n\n您参与的外发加工订单采购确认结果:未通过。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  8333. 'remark' => '审批通过-未中标供应商邮箱通知;模版名称作邮件主题',
  8334. ],
  8335. ];
  8336. try {
  8337. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8338. } catch (\Throwable $e) {
  8339. return;
  8340. }
  8341. $colNames = [];
  8342. foreach ($cols as $c) {
  8343. if (!is_array($c)) {
  8344. continue;
  8345. }
  8346. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8347. if ($n !== '') {
  8348. $colNames[$n] = true;
  8349. }
  8350. }
  8351. foreach ($seeds as $scene => $seed) {
  8352. try {
  8353. $row = Db::table('purchase_sms_template')->where('scene', $scene)->find();
  8354. } catch (\Throwable $e) {
  8355. continue;
  8356. }
  8357. if (is_array($row) && $row !== []) {
  8358. continue;
  8359. }
  8360. $data = [
  8361. 'scene' => $scene,
  8362. 'title' => $seed['title'],
  8363. 'content' => $seed['content'],
  8364. 'remark' => $seed['remark'],
  8365. 'status' => 1,
  8366. ];
  8367. if (isset($colNames['updatetime'])) {
  8368. $data['updatetime'] = $now;
  8369. }
  8370. if (isset($colNames['createtime'])) {
  8371. $data['createtime'] = $now;
  8372. }
  8373. try {
  8374. Db::table('purchase_sms_template')->insert($data);
  8375. } catch (\Throwable $e) {
  8376. // ignore
  8377. }
  8378. }
  8379. }
  8380. /**
  8381. * 确保「供应商询价通知」邮箱模版存在(查询询价-询价/发邮件;可在短信模版配置中修改)
  8382. */
  8383. protected function ensureRfqSupplierEmailTemplate(): void
  8384. {
  8385. static $done = false;
  8386. if ($done) {
  8387. return;
  8388. }
  8389. $done = true;
  8390. $content = "您好,{company_name}:\n\n"
  8391. . "您有新的协助采购询价需求,请登录平台查看并处理。\n\n"
  8392. . "需求编号:{ccydh}\n"
  8393. . "印件名称:{cyjmc}\n"
  8394. . "{process_lines}\n\n"
  8395. . "请在 {deadline} 前完成回复。\n\n"
  8396. . "平台链接:{platform_url}\n";
  8397. try {
  8398. $row = Db::table('purchase_sms_template')
  8399. ->where('scene', 'rfq_supplier_email')
  8400. ->find();
  8401. } catch (\Throwable $e) {
  8402. return;
  8403. }
  8404. $now = date('Y-m-d H:i:s');
  8405. if (is_array($row) && $row !== []) {
  8406. return;
  8407. }
  8408. try {
  8409. $data = [
  8410. 'scene' => 'rfq_supplier_email',
  8411. 'title' => '供应商询价通知',
  8412. 'content' => $content,
  8413. 'remark' => '查询询价-询价/发邮件通知供应商;模版名称作邮件主题',
  8414. 'status' => 1,
  8415. ];
  8416. try {
  8417. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8418. } catch (\Throwable $e) {
  8419. $cols = [];
  8420. }
  8421. $colNames = [];
  8422. foreach ($cols as $c) {
  8423. if (!is_array($c)) {
  8424. continue;
  8425. }
  8426. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8427. if ($n !== '') {
  8428. $colNames[$n] = true;
  8429. }
  8430. }
  8431. if (isset($colNames['updatetime'])) {
  8432. $data['updatetime'] = $now;
  8433. }
  8434. if (isset($colNames['createtime'])) {
  8435. $data['createtime'] = $now;
  8436. }
  8437. Db::table('purchase_sms_template')->insert($data);
  8438. } catch (\Throwable $e) {
  8439. // ignore
  8440. }
  8441. }
  8442. /**
  8443. * 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
  8444. */
  8445. protected function ensureRfqSalesmanEmailTemplate(): void
  8446. {
  8447. static $done = false;
  8448. if ($done) {
  8449. return;
  8450. }
  8451. $done = true;
  8452. $content = "您好,{contact_name}:\n\n"
  8453. . "有新的协助采购询价需求,请知悉。\n"
  8454. . "印件名称:{cyjmc}\n"
  8455. . "工序名称:{cgymc}\n"
  8456. . "本次数量:{this_quantity}\n"
  8457. . "供应商报价:\n{supplier_quotes}\n"
  8458. . "平台链接:{platform_url}\n"
  8459. . "需求发起人:{cywyxm}\n";
  8460. try {
  8461. $row = Db::table('purchase_sms_template')
  8462. ->where('scene', 'rfq_salesman_email')
  8463. ->find();
  8464. } catch (\Throwable $e) {
  8465. return;
  8466. }
  8467. $now = date('Y-m-d H:i:s');
  8468. if (is_array($row) && $row !== []) {
  8469. $old = (string)($row['content'] ?? '');
  8470. // 无报价表格 / 无平台链接 / 链接不在「需求发起人」上方时,同步默认文案
  8471. $urlPos = strpos($old, '{platform_url}');
  8472. $cywyPos = strpos($old, '需求发起人');
  8473. $linkNotAboveStarter = ($urlPos === false)
  8474. || ($cywyPos !== false && $urlPos > $cywyPos);
  8475. $needMigrate = (strpos($old, '{supplier_quotes}') === false)
  8476. || (strpos($old, '供应商:{supplier_name}') !== false)
  8477. || $linkNotAboveStarter;
  8478. if ($needMigrate) {
  8479. $data = ['content' => $content];
  8480. if (trim((string)($row['title'] ?? '')) === '' || trim((string)($row['title'] ?? '')) === '询价通知') {
  8481. $data['title'] = '业务员询价通知';
  8482. }
  8483. try {
  8484. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
  8485. if (!empty($cols)) {
  8486. $data['updatetime'] = $now;
  8487. }
  8488. } catch (\Throwable $e) {
  8489. }
  8490. try {
  8491. Db::table('purchase_sms_template')
  8492. ->where('id', (int)($row['id'] ?? 0))
  8493. ->update($data);
  8494. } catch (\Throwable $e) {
  8495. }
  8496. }
  8497. return;
  8498. }
  8499. try {
  8500. $data = [
  8501. 'scene' => 'rfq_salesman_email',
  8502. 'title' => '业务员询价通知',
  8503. 'content' => $content,
  8504. 'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
  8505. 'status' => 1,
  8506. ];
  8507. try {
  8508. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8509. } catch (\Throwable $e) {
  8510. $cols = [];
  8511. }
  8512. $colNames = [];
  8513. foreach ($cols as $c) {
  8514. if (!is_array($c)) {
  8515. continue;
  8516. }
  8517. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8518. if ($n !== '') {
  8519. $colNames[$n] = true;
  8520. }
  8521. }
  8522. if (isset($colNames['updatetime'])) {
  8523. $data['updatetime'] = $now;
  8524. }
  8525. if (isset($colNames['createtime'])) {
  8526. $data['createtime'] = $now;
  8527. }
  8528. Db::table('purchase_sms_template')->insert($data);
  8529. } catch (\Throwable $e) {
  8530. // ignore
  8531. }
  8532. }
  8533. /**
  8534. * 通知业务员邮件:供应商报价明细行(仅名称+单价)
  8535. *
  8536. * @return array<int, array{name:string,amount:string}>
  8537. */
  8538. protected function loadRfqSalesmanSupplierQuoteRows(int $sid, string $supplierRaw = ''): array
  8539. {
  8540. $list = [];
  8541. $seen = [];
  8542. try {
  8543. $rows = Db::table('purchase_order_detail')
  8544. ->where('scydgy_id', $sid)
  8545. ->field('company_name,amount')
  8546. ->order('id', 'asc')
  8547. ->select();
  8548. if (is_array($rows)) {
  8549. foreach ($rows as $r) {
  8550. if (!is_array($r)) {
  8551. continue;
  8552. }
  8553. $cn = trim((string)($r['company_name'] ?? ''));
  8554. if ($cn === '' || isset($seen[$cn])) {
  8555. continue;
  8556. }
  8557. $seen[$cn] = true;
  8558. $amount = trim((string)($r['amount'] ?? ''));
  8559. $list[] = [
  8560. 'name' => $cn,
  8561. 'amount' => $amount !== '' ? $amount : '未报价',
  8562. ];
  8563. }
  8564. }
  8565. } catch (\Throwable $e) {
  8566. }
  8567. if ($list === [] && $supplierRaw !== '') {
  8568. foreach ($this->splitRfqSalesmanNames($supplierRaw) as $cn) {
  8569. if ($cn === '' || isset($seen[$cn])) {
  8570. continue;
  8571. }
  8572. $seen[$cn] = true;
  8573. $list[] = [
  8574. 'name' => $cn,
  8575. 'amount' => '未报价',
  8576. ];
  8577. }
  8578. }
  8579. return $list;
  8580. }
  8581. /**
  8582. * 通知业务员邮件:供应商报价 HTML 表格(名称+单价,不含时间)
  8583. */
  8584. protected function buildRfqSalesmanSupplierQuotesHtml(int $sid, string $supplierRaw = ''): string
  8585. {
  8586. $rows = $this->loadRfqSalesmanSupplierQuoteRows($sid, $supplierRaw);
  8587. if ($rows === []) {
  8588. return '<p style="margin:8px 0;color:#888;">暂无报价</p>';
  8589. }
  8590. $html = '<table cellpadding="0" cellspacing="0" border="1" '
  8591. . 'style="border-collapse:collapse;border-color:#ddd;width:100%;max-width:560px;font-size:14px;margin:8px 0;">'
  8592. . '<thead><tr style="background:#f5f5f5;">'
  8593. . '<th style="padding:8px 10px;text-align:center;width:56px;">序号</th>'
  8594. . '<th style="padding:8px 10px;text-align:left;">供应商名称</th>'
  8595. . '<th style="padding:8px 10px;text-align:center;width:100px;">单价</th>'
  8596. . '</tr></thead><tbody>';
  8597. foreach ($rows as $i => $row) {
  8598. $html .= '<tr>'
  8599. . '<td style="padding:8px 10px;text-align:center;">' . ($i + 1) . '</td>'
  8600. . '<td style="padding:8px 10px;">' . htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8') . '</td>'
  8601. . '<td style="padding:8px 10px;text-align:center;">' . htmlspecialchars($row['amount'], ENT_QUOTES, 'UTF-8') . '</td>'
  8602. . '</tr>';
  8603. }
  8604. $html .= '</tbody></table>';
  8605. return $html;
  8606. }
  8607. /**
  8608. * 询价多选字段:数组或字符串统一为顿号拼接
  8609. *
  8610. * @param mixed $raw
  8611. */
  8612. protected function joinRfqMultiSelectValues($raw): string
  8613. {
  8614. $parts = [];
  8615. if (is_array($raw)) {
  8616. foreach ($raw as $item) {
  8617. if (is_array($item)) {
  8618. continue;
  8619. }
  8620. $v = trim((string)$item);
  8621. if ($v !== '') {
  8622. $parts[] = $v;
  8623. }
  8624. }
  8625. } else {
  8626. $s = trim((string)$raw);
  8627. if ($s !== '') {
  8628. foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
  8629. $v = trim((string)$piece);
  8630. if ($v !== '') {
  8631. $parts[] = $v;
  8632. }
  8633. }
  8634. }
  8635. }
  8636. $parts = array_values(array_unique($parts));
  8637. return implode('、', $parts);
  8638. }
  8639. /**
  8640. * 新增询价:可选供应商名称(仅落库记录,不发通知)
  8641. *
  8642. * @return string[]
  8643. */
  8644. protected function loadRfqSupplierNameOptions(): array
  8645. {
  8646. $out = [];
  8647. try {
  8648. $rows = Db::table('customer')
  8649. ->where(function ($q) {
  8650. $q->where('status', 1)
  8651. ->whereOr('status', '1')
  8652. ->whereOr('status', '')
  8653. ->whereNull('status');
  8654. })
  8655. ->order('id', 'desc')
  8656. ->column('company_name');
  8657. } catch (\Throwable $e) {
  8658. return [];
  8659. }
  8660. if (!is_array($rows)) {
  8661. return [];
  8662. }
  8663. foreach ($rows as $name) {
  8664. $name = trim((string)$name);
  8665. if ($name === '' || isset($out[$name])) {
  8666. continue;
  8667. }
  8668. $out[$name] = $name;
  8669. }
  8670. return array_values($out);
  8671. }
  8672. /**
  8673. * 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
  8674. */
  8675. protected function rfqNotifySalesmanAuthGroupId(): int
  8676. {
  8677. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  8678. if ($id > 0) {
  8679. return $id;
  8680. }
  8681. try {
  8682. $found = Db::name('auth_group')
  8683. ->where('name', '业务员')
  8684. ->where('status', 'normal')
  8685. ->order('id', 'asc')
  8686. ->value('id');
  8687. $id = (int)$found;
  8688. } catch (\Throwable $e) {
  8689. $id = 0;
  8690. }
  8691. return $id > 0 ? $id : 12;
  8692. }
  8693. /**
  8694. * 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
  8695. *
  8696. * @return string[]
  8697. */
  8698. protected function loadRfqSalesmanNameOptions(): array
  8699. {
  8700. $out = [];
  8701. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8702. $name = trim((string)($row['name'] ?? ''));
  8703. if ($name !== '') {
  8704. $out[] = $name;
  8705. }
  8706. }
  8707. return $out;
  8708. }
  8709. /**
  8710. * 业务员角色组下管理员:姓名、邮箱、手机
  8711. *
  8712. * @return array<int, array{name:string,email:string,mobile:string}>
  8713. */
  8714. protected function loadRfqSalesmanContactOptions(): array
  8715. {
  8716. $out = [];
  8717. $seen = [];
  8718. $groupId = $this->rfqNotifySalesmanAuthGroupId();
  8719. if ($groupId <= 0) {
  8720. return [];
  8721. }
  8722. try {
  8723. $adminIds = Db::name('auth_group_access')
  8724. ->where('group_id', $groupId)
  8725. ->column('uid');
  8726. } catch (\Throwable $e) {
  8727. return [];
  8728. }
  8729. $adminIds = is_array($adminIds)
  8730. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  8731. : [];
  8732. if ($adminIds === []) {
  8733. return [];
  8734. }
  8735. try {
  8736. $rows = Db::name('admin')
  8737. ->where('status', 'normal')
  8738. ->where('id', 'in', $adminIds)
  8739. ->order('id', 'asc')
  8740. ->field('id,nickname,username,email,mobile')
  8741. ->select();
  8742. } catch (\Throwable $e) {
  8743. return [];
  8744. }
  8745. if (!is_array($rows)) {
  8746. return [];
  8747. }
  8748. foreach ($rows as $row) {
  8749. if (!is_array($row)) {
  8750. continue;
  8751. }
  8752. $name = trim((string)($row['nickname'] ?? ''));
  8753. if ($name === '') {
  8754. $name = trim((string)($row['username'] ?? ''));
  8755. }
  8756. if ($name === '' || isset($seen[$name])) {
  8757. continue;
  8758. }
  8759. $seen[$name] = true;
  8760. $out[] = [
  8761. 'name' => $name,
  8762. 'email' => trim((string)($row['email'] ?? '')),
  8763. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  8764. ];
  8765. }
  8766. return $out;
  8767. }
  8768. /**
  8769. * 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
  8770. *
  8771. * @return string[]
  8772. */
  8773. protected function loadRfqDeptNameOptions(): array
  8774. {
  8775. $out = [];
  8776. // ERP 承揽部门(主来源)
  8777. try {
  8778. $vals = Db::table('mcyd')
  8779. ->where('CCLBMMC', '<>', '')
  8780. ->whereNotNull('CCLBMMC')
  8781. ->distinct(true)
  8782. ->limit(300)
  8783. ->column('CCLBMMC');
  8784. } catch (\Throwable $e) {
  8785. $vals = [];
  8786. }
  8787. if (is_array($vals)) {
  8788. foreach ($vals as $v) {
  8789. $v = trim((string)$v);
  8790. if ($v === '' || isset($out[$v])) {
  8791. continue;
  8792. }
  8793. $out[$v] = $v;
  8794. }
  8795. }
  8796. // 手工询价历史部门补全
  8797. try {
  8798. $poVals = Db::table('purchase_order')
  8799. ->where('CCLBMMC', '<>', '')
  8800. ->whereNotNull('CCLBMMC')
  8801. ->distinct(true)
  8802. ->limit(200)
  8803. ->column('CCLBMMC');
  8804. } catch (\Throwable $e) {
  8805. $poVals = [];
  8806. }
  8807. if (is_array($poVals)) {
  8808. foreach ($poVals as $v) {
  8809. $v = trim((string)$v);
  8810. if ($v === '' || isset($out[$v])) {
  8811. continue;
  8812. }
  8813. $out[$v] = $v;
  8814. }
  8815. }
  8816. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  8817. if (!isset($out[$preset])) {
  8818. $out[$preset] = $preset;
  8819. }
  8820. }
  8821. $list = array_values($out);
  8822. // 常用部门靠前
  8823. usort($list, static function ($a, $b) {
  8824. $weight = [
  8825. '营销中心' => 1,
  8826. '业务部' => 2,
  8827. '市场部' => 3,
  8828. '外贸部' => 4,
  8829. '新华技术业务部' => 5,
  8830. ];
  8831. $wa = $weight[$a] ?? 100;
  8832. $wb = $weight[$b] ?? 100;
  8833. if ($wa !== $wb) {
  8834. return $wa <=> $wb;
  8835. }
  8836. return strcmp((string)$a, (string)$b);
  8837. });
  8838. return $list;
  8839. }
  8840. /**
  8841. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  8842. */
  8843. public function add()
  8844. {
  8845. if ($this->request->isPost()) {
  8846. $params = $this->request->post('row/a');
  8847. if (!is_array($params)) {
  8848. $this->error(__('Parameter %s can not be empty', ''));
  8849. }
  8850. [, $adminName] = $this->GetUseName();
  8851. $params['cywyxm'] = $adminName;
  8852. try {
  8853. $sid = $this->saveManualPickOrder($params);
  8854. } catch (\InvalidArgumentException $e) {
  8855. $this->error($e->getMessage());
  8856. } catch (\Throwable $e) {
  8857. $this->error($e->getMessage());
  8858. }
  8859. $this->success('新增成功', '', [
  8860. 'scydgy_id' => $sid,
  8861. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  8862. ]);
  8863. }
  8864. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8865. [, $adminName] = $this->GetUseName();
  8866. $this->view->assign('adminNickname', $adminName);
  8867. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  8868. $this->view->assign('defaultCclbmmc', '营销中心');
  8869. $this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
  8870. $this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
  8871. $this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
  8872. return $this->view->fetch();
  8873. }
  8874. /**
  8875. * 业务员新增进度查询(手工询价;有查询权限看全部,含手机端新增且未通知业务员的)
  8876. */
  8877. public function rfqlist()
  8878. {
  8879. $this->relationSearch = false;
  8880. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ';
  8881. $this->request->filter(['strip_tags', 'trim']);
  8882. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8883. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8884. $this->ensureRfqSalesmanEmailTemplate();
  8885. $this->ensureRfqSupplierEmailTemplate();
  8886. if ($this->request->isAjax()) {
  8887. try {
  8888. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  8889. $limit = max(10, min(500, (int)$limit));
  8890. $filterYm = trim((string)$this->request->param('filter_ym', ''));
  8891. if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
  8892. $filterYm = date('Y-m');
  8893. }
  8894. $applyFilters = function ($query) use ($where, $filterYm) {
  8895. $query->where('scydgy_id', '<', 0);
  8896. $this->applyPurchaseOrderNotDeletedWhere($query);
  8897. // 查询询价:有菜单权限即可看全部手工单(含手机端新增、尚未通知业务员的)
  8898. $this->applyRfqListMonthFilter($query, $filterYm);
  8899. if (!empty($where)) {
  8900. // 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
  8901. $safeWhere = [];
  8902. $skipFields = [
  8903. 'supplier_name' => true,
  8904. 'progress_text' => true,
  8905. 'createtime_text' => true,
  8906. 'notify_time_text' => true,
  8907. 'can_notify_salesman' => true,
  8908. 'has_issued' => true,
  8909. 'has_quoted' => true,
  8910. ];
  8911. foreach ((array)$where as $cond) {
  8912. if (!is_array($cond) || !isset($cond[0])) {
  8913. continue;
  8914. }
  8915. $field = (string)$cond[0];
  8916. $fieldBase = (string)preg_replace('/\|.*$/', '', $field);
  8917. $fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
  8918. if (isset($skipFields[$fieldBase])) {
  8919. continue;
  8920. }
  8921. if ($fieldBase === 'supplier_name') {
  8922. continue;
  8923. }
  8924. $safeWhere[] = $cond;
  8925. }
  8926. if ($safeWhere !== []) {
  8927. $query->where($safeWhere);
  8928. }
  8929. }
  8930. };
  8931. $countQuery = Db::table('purchase_order');
  8932. $applyFilters($countQuery);
  8933. $total = (int)$countQuery->count();
  8934. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  8935. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  8936. $listQuery = Db::table('purchase_order');
  8937. $applyFilters($listQuery);
  8938. $rows = $listQuery
  8939. ->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')
  8940. ->order($sortField, $orderDir)
  8941. ->limit($offset, $limit)
  8942. ->select();
  8943. if (!is_array($rows)) {
  8944. $rows = [];
  8945. }
  8946. $sidList = [];
  8947. foreach ($rows as $r) {
  8948. if (!is_array($r)) {
  8949. continue;
  8950. }
  8951. $sid = (int)($r['scydgy_id'] ?? 0);
  8952. if ($sid < 0) {
  8953. $sidList[$sid] = true;
  8954. }
  8955. }
  8956. $issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
  8957. $quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
  8958. $out = [];
  8959. foreach ($rows as $r) {
  8960. if (!is_array($r)) {
  8961. continue;
  8962. }
  8963. $sid = (int)($r['scydgy_id'] ?? 0);
  8964. if ($sid >= 0) {
  8965. continue;
  8966. }
  8967. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  8968. if ($createdText === '') {
  8969. $createdText = trim((string)($r['dStamp'] ?? ''));
  8970. }
  8971. $notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
  8972. $supplier = trim((string)($r['cGzzxMc'] ?? ''));
  8973. if ($supplier === '') {
  8974. $supplier = trim((string)($r['pick_company_name'] ?? ''));
  8975. }
  8976. $hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
  8977. || isset($issuedSidSet[$sid]);
  8978. $hasQuoted = isset($quotedSidSet[$sid]);
  8979. $salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
  8980. $canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
  8981. $out[] = [
  8982. 'id' => (int)($r['id'] ?? 0),
  8983. 'scydgy_id' => $sid,
  8984. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  8985. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  8986. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  8987. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  8988. 'CDW' => trim((string)($r['CDW'] ?? '')),
  8989. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  8990. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  8991. 'CDF' => trim((string)($r['CDF'] ?? '')),
  8992. 'supplier_name' => $supplier,
  8993. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  8994. 'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
  8995. 'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
  8996. 'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
  8997. 'notify_time_text' => $notifyTimeText,
  8998. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  8999. 'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
  9000. 'has_issued' => $hasIssued ? 1 : 0,
  9001. 'has_quoted' => $hasQuoted ? 1 : 0,
  9002. 'can_notify_salesman' => $canNotifySalesman,
  9003. 'createtime' => $r['createtime'] ?? null,
  9004. 'createtime_text' => $createdText,
  9005. ];
  9006. }
  9007. return json(['total' => $total, 'rows' => $out]);
  9008. } catch (\Throwable $e) {
  9009. Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
  9010. return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
  9011. }
  9012. }
  9013. $sidebar = $this->loadRfqSidebarYearMonths();
  9014. $defaultYm = $this->resolveRfqListDefaultYm($sidebar);
  9015. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  9016. [, $adminName] = $this->GetUseName();
  9017. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  9018. $this->view->assign('adminNickname', $adminName);
  9019. $this->view->assign('defaultYm', $defaultYm);
  9020. $this->view->assign('sidebarYearMonths', $sidebar);
  9021. return $this->view->fetch('procuremen/rfqlist');
  9022. }
  9023. /**
  9024. * 列表默认月份:当月有数据用当月,否则取最近有数据的月份
  9025. *
  9026. * @param array<int, array{year:string, months:array}> $sidebar
  9027. */
  9028. protected function resolveRfqListDefaultYm(array $sidebar): string
  9029. {
  9030. $current = date('Y-m');
  9031. $yms = $this->flattenProcuremenSidebarYms($sidebar);
  9032. if (in_array($current, $yms, true)) {
  9033. return $current;
  9034. }
  9035. if ($yms !== []) {
  9036. rsort($yms, SORT_STRING);
  9037. return (string)$yms[0];
  9038. }
  9039. return $current;
  9040. }
  9041. /**
  9042. * 手工询价列表左侧月份(按 createtime / dStamp)
  9043. *
  9044. * @return array<int, array{year:string, months:array}>
  9045. */
  9046. protected function loadRfqSidebarYearMonths(): array
  9047. {
  9048. $ymSet = [];
  9049. try {
  9050. $q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
  9051. $this->applyPurchaseOrderNotDeletedWhere($q);
  9052. $rows = $q->field('createtime,dStamp')->limit(5000)->select();
  9053. } catch (\Throwable $e) {
  9054. $rows = [];
  9055. }
  9056. if (!is_array($rows)) {
  9057. $rows = [];
  9058. }
  9059. foreach ($rows as $r) {
  9060. if (!is_array($r)) {
  9061. continue;
  9062. }
  9063. $t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  9064. if ($t === '') {
  9065. $t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
  9066. }
  9067. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  9068. $ymSet[$m[1] . '-' . $m[2]] = true;
  9069. }
  9070. }
  9071. return $this->buildYearMonthSidebar(array_keys($ymSet));
  9072. }
  9073. /**
  9074. * 手工询价可见范围(用于详情/操作校验):
  9075. * 超管、具备「查询询价」权限、需求发起人、通知业务员 → 可见
  9076. * 列表页本身不再按发起人/通知过滤,避免手机端新增后后台看不到。
  9077. */
  9078. protected function applyManualRfqViewerWhere($query): void
  9079. {
  9080. if ($this->auth->isSuperAdmin() || $this->hasProcuremenPerm(['rfqlist'])) {
  9081. return;
  9082. }
  9083. [, $adminName] = $this->GetUseName();
  9084. $adminName = trim((string)$adminName);
  9085. if ($adminName === '') {
  9086. $query->whereRaw('1 = 0');
  9087. return;
  9088. }
  9089. // 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
  9090. $query->where(function ($q) use ($adminName) {
  9091. $q->where('cywyxm', $adminName)
  9092. ->whereOr('notify_salesman', $adminName)
  9093. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  9094. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  9095. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  9096. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  9097. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  9098. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  9099. });
  9100. }
  9101. /**
  9102. * 当前用户是否可查看/操作该手工询价单
  9103. */
  9104. protected function canViewManualRfqOrder(array $po): bool
  9105. {
  9106. if ($this->auth->isSuperAdmin()) {
  9107. return true;
  9108. }
  9109. // 有查询询价权限则可操作全部手工询价(询价/查看报价/通知业务员等)
  9110. if ($this->hasProcuremenPerm(['rfqlist'])) {
  9111. return true;
  9112. }
  9113. [, $adminName] = $this->GetUseName();
  9114. $adminName = trim((string)$adminName);
  9115. if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
  9116. return true;
  9117. }
  9118. if ($adminName !== '') {
  9119. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  9120. if ($n === $adminName) {
  9121. return true;
  9122. }
  9123. }
  9124. }
  9125. return false;
  9126. }
  9127. /**
  9128. * 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
  9129. */
  9130. protected function applyRfqListMonthFilter($query, string $ym): void
  9131. {
  9132. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  9133. $ym = date('Y-m');
  9134. }
  9135. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  9136. // 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
  9137. $query->whereRaw(
  9138. "("
  9139. . "CASE "
  9140. . "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  9141. . "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
  9142. . "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
  9143. . "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  9144. . "THEN TRIM(CAST(createtime AS CHAR(32))) "
  9145. . "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
  9146. . "END"
  9147. . ") LIKE '{$ymEsc}-%'"
  9148. );
  9149. }
  9150. /**
  9151. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  9152. */
  9153. public function rfqlistDetails()
  9154. {
  9155. return $this->details();
  9156. }
  9157. /**
  9158. * 查询询价 — 弹窗:可选通知业务员名单(勾选后确认通知)
  9159. */
  9160. public function rfqnotifysalesmen()
  9161. {
  9162. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman'])) {
  9163. $this->error(__('You have no permission'));
  9164. }
  9165. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9166. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  9167. $sid = (int)$this->request->param('scydgy_id', 0);
  9168. if ($sid >= 0) {
  9169. $this->error('仅支持手工新增询价单');
  9170. }
  9171. $po = $this->loadManualRfqOrderForNotify($sid);
  9172. $selectedMap = [];
  9173. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  9174. $selectedMap[$n] = true;
  9175. }
  9176. $list = [];
  9177. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  9178. $name = trim((string)($row['name'] ?? ''));
  9179. if ($name === '') {
  9180. continue;
  9181. }
  9182. $email = trim((string)($row['email'] ?? ''));
  9183. $mobile = trim((string)($row['mobile'] ?? ''));
  9184. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  9185. $list[] = [
  9186. 'name' => $name,
  9187. 'email' => $email,
  9188. 'mobile' => $mobile,
  9189. 'can_select' => $hasEmail ? 1 : 0,
  9190. 'checked' => (!empty($selectedMap[$name]) && $hasEmail) ? 1 : 0,
  9191. ];
  9192. }
  9193. $canNotify = $this->canRfqNotifySalesman($po);
  9194. $this->success('', null, [
  9195. 'scydgy_id' => $sid,
  9196. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9197. 'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
  9198. 'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
  9199. 'can_notify_salesman' => $canNotify ? 1 : 0,
  9200. 'list' => $list,
  9201. ]);
  9202. }
  9203. /**
  9204. * 查询询价 — 补加通知业务员可选名单
  9205. */
  9206. public function rfqsalesmanoptions()
  9207. {
  9208. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen'])) {
  9209. $this->error(__('You have no permission'));
  9210. }
  9211. $out = [];
  9212. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  9213. $email = trim((string)($row['email'] ?? ''));
  9214. $mobile = trim((string)($row['mobile'] ?? ''));
  9215. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  9216. $out[] = [
  9217. 'name' => (string)($row['name'] ?? ''),
  9218. 'email' => $email,
  9219. 'mobile' => $mobile,
  9220. 'can_select' => $hasEmail ? 1 : 0,
  9221. ];
  9222. }
  9223. $this->success('', null, ['list' => $out]);
  9224. }
  9225. /**
  9226. * 查询询价 — 补加通知业务员(合并更新 notify_salesman)
  9227. */
  9228. public function rfqappendsalesmen()
  9229. {
  9230. if (!$this->request->isPost()) {
  9231. $this->error(__('Invalid parameters'));
  9232. }
  9233. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen'])) {
  9234. $this->error(__('You have no permission'));
  9235. }
  9236. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9237. $sid = (int)$this->request->post('scydgy_id', 0);
  9238. if ($sid >= 0) {
  9239. $this->error('仅支持手工新增询价单');
  9240. }
  9241. $po = $this->loadManualRfqOrderForNotify($sid);
  9242. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9243. $this->error('订单已完结,无法添加业务员');
  9244. }
  9245. $raw = $this->request->post('salesmen/a', []);
  9246. if (!is_array($raw) || $raw === []) {
  9247. $salesmenJson = $this->request->post('salesmen_json', '');
  9248. if (is_string($salesmenJson) && $salesmenJson !== '') {
  9249. $decoded = json_decode($salesmenJson, true);
  9250. $raw = is_array($decoded) ? $decoded : [];
  9251. }
  9252. }
  9253. $addNames = [];
  9254. foreach ((array)$raw as $item) {
  9255. if (is_array($item)) {
  9256. $n = trim((string)($item['name'] ?? ''));
  9257. } else {
  9258. $n = trim((string)$item);
  9259. }
  9260. if ($n !== '') {
  9261. $addNames[] = $n;
  9262. }
  9263. }
  9264. $addNames = array_values(array_unique($addNames));
  9265. if ($addNames === []) {
  9266. $this->error('请选择要添加的业务员');
  9267. }
  9268. $allowedOptions = $this->loadRfqSalesmanContactOptions();
  9269. $allowedMap = [];
  9270. foreach ($allowedOptions as $opt) {
  9271. $n = trim((string)($opt['name'] ?? ''));
  9272. if ($n === '') {
  9273. continue;
  9274. }
  9275. $email = trim((string)($opt['email'] ?? ''));
  9276. $allowedMap[$n] = ($email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL));
  9277. }
  9278. foreach ($addNames as $n) {
  9279. if (!array_key_exists($n, $allowedMap)) {
  9280. $this->error('业务员不在可选名单中:' . $n);
  9281. }
  9282. if (!$allowedMap[$n]) {
  9283. $this->error('业务员未填写有效邮箱,无法添加:' . $n);
  9284. }
  9285. }
  9286. $existingRaw = trim((string)($po['notify_salesman'] ?? ''));
  9287. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9288. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9289. try {
  9290. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['notify_salesman' => $mergedStr]);
  9291. } catch (\Throwable $e) {
  9292. $this->error('保存失败:' . $e->getMessage());
  9293. }
  9294. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9295. $this->addOrderLog($sid, 'rfq_append_salesman', '添加通知业务员:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9296. $this->success('已添加业务员', null, [
  9297. 'scydgy_id' => $sid,
  9298. 'notify_salesman' => $mergedStr,
  9299. 'added_count' => count($addNames),
  9300. ]);
  9301. }
  9302. /**
  9303. * 查询询价 — 勾选业务员后邮箱通知(salesmen_json)
  9304. */
  9305. public function rfqnotifysalesman()
  9306. {
  9307. if (!$this->request->isPost()) {
  9308. $this->error(__('Invalid parameters'));
  9309. }
  9310. if (!$this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen'])) {
  9311. $this->error(__('You have no permission'));
  9312. }
  9313. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9314. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  9315. $sid = (int)$this->request->post('scydgy_id', 0);
  9316. if ($sid >= 0) {
  9317. $this->error('仅支持手工新增询价单');
  9318. }
  9319. $po = $this->loadManualRfqOrderForNotify($sid);
  9320. $this->assertRfqCanNotifySalesman($po);
  9321. $raw = $this->request->post('salesmen/a', []);
  9322. if (!is_array($raw) || $raw === []) {
  9323. $salesmenJson = $this->request->post('salesmen_json', '');
  9324. if (is_string($salesmenJson) && $salesmenJson !== '') {
  9325. $decoded = json_decode($salesmenJson, true);
  9326. $raw = is_array($decoded) ? $decoded : [];
  9327. }
  9328. }
  9329. // 兼容旧参数:notify_all / 单人 name
  9330. if ((!is_array($raw) || $raw === []) && (int)$this->request->post('notify_all', 0) === 1) {
  9331. $raw = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  9332. }
  9333. if ((!is_array($raw) || $raw === [])) {
  9334. $oneName = trim((string)$this->request->post('name', ''));
  9335. if ($oneName !== '') {
  9336. $raw = [$oneName];
  9337. }
  9338. }
  9339. $selectedNames = [];
  9340. foreach ((array)$raw as $item) {
  9341. if (is_array($item)) {
  9342. $n = trim((string)($item['name'] ?? ''));
  9343. } else {
  9344. $n = trim((string)$item);
  9345. }
  9346. if ($n !== '') {
  9347. $selectedNames[] = $n;
  9348. }
  9349. }
  9350. $selectedNames = array_values(array_unique($selectedNames));
  9351. if ($selectedNames === []) {
  9352. $this->error('请选择要通知的业务员');
  9353. }
  9354. $optionMap = [];
  9355. foreach ($this->loadRfqSalesmanContactOptions() as $opt) {
  9356. $n = trim((string)($opt['name'] ?? ''));
  9357. if ($n === '') {
  9358. continue;
  9359. }
  9360. $optionMap[$n] = $opt;
  9361. }
  9362. $targets = [];
  9363. foreach ($selectedNames as $n) {
  9364. if (!isset($optionMap[$n])) {
  9365. $this->error('业务员不在可选名单中:' . $n);
  9366. }
  9367. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  9368. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9369. $this->error('业务员未填写有效邮箱,无法通知:' . $n);
  9370. }
  9371. $resolved = $this->resolveRfqSalesmanContactRows([$n]);
  9372. $targets[] = $resolved[0] ?? [
  9373. 'admin_id' => 0,
  9374. 'name' => $n,
  9375. 'email' => $email,
  9376. ];
  9377. }
  9378. $mergedStr = $this->joinRfqMultiSelectValues($selectedNames);
  9379. try {
  9380. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  9381. 'notify_salesman' => $mergedStr,
  9382. ]);
  9383. } catch (\Throwable $e) {
  9384. $this->error('保存通知业务员失败:' . $e->getMessage());
  9385. }
  9386. $po['notify_salesman'] = $mergedStr;
  9387. $mailConfig = $this->loadMailerConfig();
  9388. if (empty($mailConfig['host'])) {
  9389. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9390. }
  9391. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9392. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9393. }
  9394. $this->ensureRfqSalesmanEmailTemplate();
  9395. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  9396. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  9397. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  9398. $cdw = trim((string)($po['CDW'] ?? ''));
  9399. $qty = trim((string)$this->resolveProcuremenThisQuantity($po));
  9400. $ceiling = trim((string)$this->resolveProcuremenCeilingPrice($po));
  9401. $mbz = trim((string)($po['MBZ'] ?? ''));
  9402. $cywyxm = trim((string)($po['cywyxm'] ?? ''));
  9403. $supplier = trim((string)($po['cGzzxMc'] ?? ''));
  9404. if ($supplier === '') {
  9405. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  9406. }
  9407. $supplierQuotesHtml = $this->buildRfqSalesmanSupplierQuotesHtml($sid, $supplier);
  9408. try {
  9409. $platformUrl = $this->buildMprocMobileRfqAddUrl($sid, 'pending');
  9410. } catch (\Throwable $e) {
  9411. $platformUrl = '';
  9412. }
  9413. try {
  9414. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
  9415. } catch (\Throwable $e) {
  9416. $this->error($e->getMessage());
  9417. }
  9418. $okNames = [];
  9419. $failMsgs = [];
  9420. foreach ($targets as $contact) {
  9421. $toEmail = trim((string)($contact['email'] ?? ''));
  9422. $toName = trim((string)($contact['name'] ?? ''));
  9423. $notifyVars = [
  9424. 'contact_name' => $toName,
  9425. 'salesman_name' => $toName,
  9426. 'company_name' => $toName,
  9427. 'email' => $toEmail,
  9428. 'ccydh' => $ccydh,
  9429. 'cyjmc' => $cyjmc,
  9430. 'cgymc' => $cgymc,
  9431. 'cdw' => $cdw,
  9432. 'this_quantity' => $qty,
  9433. 'ceilingPrice' => $ceiling,
  9434. 'MBZ' => $mbz,
  9435. 'supplier_name' => $supplier,
  9436. // 占位符,转 HTML 后再替换成表格,避免被 htmlspecialchars 转义
  9437. 'supplier_quotes' => '__RFQ_SUPPLIER_QUOTES_TABLE__',
  9438. 'cywyxm' => $cywyxm,
  9439. 'platform_url' => $platformUrl,
  9440. ];
  9441. try {
  9442. $mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
  9443. $mailSubject = $mailSubjectTpl;
  9444. foreach ($notifyVars as $k => $v) {
  9445. if ($k === 'supplier_quotes') {
  9446. continue;
  9447. }
  9448. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  9449. }
  9450. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  9451. $mailSubject = trim((string)$mailSubject);
  9452. if ($mailSubject === '') {
  9453. $mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  9454. }
  9455. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  9456. $mailBody = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', $supplierQuotesHtml, $mailBody);
  9457. $mailPlainForLog = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', strip_tags(str_replace(['</tr>', '</p>'], "\n", $supplierQuotesHtml)), $mailPlain);
  9458. $bundle = [
  9459. 'company_name' => $toName,
  9460. 'email' => $toEmail,
  9461. 'mail_plain' => $mailPlainForLog,
  9462. 'mail_body' => $mailBody,
  9463. 'ccydh' => $ccydh,
  9464. 'email_log_scene' => 'rfq_salesman',
  9465. 'email_log_scydgy_id' => $sid,
  9466. 'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
  9467. 'notify_vars' => $notifyVars,
  9468. ];
  9469. $this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
  9470. $okNames[] = $toName . '(' . $toEmail . ')';
  9471. } catch (\Throwable $e) {
  9472. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  9473. }
  9474. }
  9475. if ($okNames === []) {
  9476. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  9477. }
  9478. $now = date('Y-m-d H:i:s');
  9479. try {
  9480. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  9481. 'rfq_salesman_notified' => 1,
  9482. 'rfq_salesman_notify_time' => $now,
  9483. ]);
  9484. } catch (\Throwable $e) {
  9485. // ignore
  9486. }
  9487. $this->addOrderLog(
  9488. $sid,
  9489. 'rfq_notify_salesman',
  9490. '邮箱通知业务员:' . implode('、', $okNames),
  9491. (int)($po['id'] ?? 0)
  9492. );
  9493. $msg = '已通知 ' . count($okNames) . ' 人';
  9494. if ($failMsgs !== []) {
  9495. $msg .= ';部分失败:' . implode(';', $failMsgs);
  9496. }
  9497. $this->success($msg, null, [
  9498. 'scydgy_id' => $sid,
  9499. 'notify_salesman' => $mergedStr,
  9500. 'rfq_salesman_notified' => 1,
  9501. 'rfq_salesman_notify_time' => $now,
  9502. 'notify_time_text' => $now,
  9503. 'ok_count' => count($okNames),
  9504. 'fail_count' => count($failMsgs),
  9505. ]);
  9506. }
  9507. /**
  9508. * 查询询价 — 下发前:返回将通知的供应商表格数据
  9509. */
  9510. public function rfqissuesuppliers()
  9511. {
  9512. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers'])) {
  9513. $this->error(__('You have no permission'));
  9514. }
  9515. $sid = (int)$this->request->param('scydgy_id', 0);
  9516. if ($sid >= 0) {
  9517. $this->error('仅支持手工新增询价单');
  9518. }
  9519. $po = $this->loadManualRfqOrderForNotify($sid);
  9520. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9521. if ($supplierRaw === '') {
  9522. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9523. }
  9524. $names = $this->splitRfqSalesmanNames($supplierRaw);
  9525. // 已成功发过询价邮件的供应商(含历史 pick_issue 场景)
  9526. $notifiedMap = [];
  9527. try {
  9528. $this->ensurePurchaseEmailSendLogTableOnce();
  9529. $logRows = Db::table('purchase_email_send_log')
  9530. ->where('scydgy_id', $sid)
  9531. ->where('status', 1)
  9532. ->where('scene', 'in', ['rfq_supplier', 'pick_issue'])
  9533. ->field('company_name')
  9534. ->select();
  9535. if (is_array($logRows)) {
  9536. foreach ($logRows as $lr) {
  9537. if (!is_array($lr)) {
  9538. continue;
  9539. }
  9540. $cn = trim((string)($lr['company_name'] ?? ''));
  9541. if ($cn !== '') {
  9542. $notifiedMap[$cn] = true;
  9543. }
  9544. }
  9545. }
  9546. } catch (\Throwable $e) {
  9547. }
  9548. // 兼容:明细已生成(曾下发)也视为已通知
  9549. try {
  9550. $detRows = Db::table('purchase_order_detail')
  9551. ->where('scydgy_id', $sid)
  9552. ->field('company_name')
  9553. ->select();
  9554. if (is_array($detRows)) {
  9555. foreach ($detRows as $dr) {
  9556. if (!is_array($dr)) {
  9557. continue;
  9558. }
  9559. $cn = trim((string)($dr['company_name'] ?? ''));
  9560. if ($cn !== '') {
  9561. $notifiedMap[$cn] = true;
  9562. }
  9563. }
  9564. }
  9565. } catch (\Throwable $e) {
  9566. }
  9567. $list = [];
  9568. foreach ($names as $name) {
  9569. // 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
  9570. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9571. $email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
  9572. $phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
  9573. $username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
  9574. $okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
  9575. $notified = !empty($notifiedMap[$name]) ? 1 : 0;
  9576. $list[] = [
  9577. 'name' => $name,
  9578. 'username' => $username,
  9579. 'email' => $email,
  9580. 'phone' => $phone,
  9581. 'can_notify' => $okEmail ? 1 : 0,
  9582. 'found' => is_array($contact) ? 1 : 0,
  9583. 'notified' => $notified,
  9584. 'notify_status_text' => $notified ? '已通知' : '未通知',
  9585. ];
  9586. }
  9587. $this->success('', null, [
  9588. 'scydgy_id' => $sid,
  9589. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9590. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9591. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9592. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9593. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9594. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9595. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9596. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9597. 'list' => $list,
  9598. ]);
  9599. }
  9600. /**
  9601. * 查询询价 — 补加供应商可选名单
  9602. */
  9603. public function rfqsupplieroptions()
  9604. {
  9605. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
  9606. $this->error(__('You have no permission'));
  9607. }
  9608. $names = array_values($this->loadRfqSupplierNameOptions());
  9609. $out = [];
  9610. foreach ($names as $name) {
  9611. $out[] = ['name' => $name];
  9612. }
  9613. $this->success('', null, ['list' => $out]);
  9614. }
  9615. /**
  9616. * 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
  9617. */
  9618. public function rfqappendsuppliers()
  9619. {
  9620. if (!$this->request->isPost()) {
  9621. $this->error(__('Invalid parameters'));
  9622. }
  9623. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers'])) {
  9624. $this->error(__('You have no permission'));
  9625. }
  9626. $sid = (int)$this->request->post('scydgy_id', 0);
  9627. if ($sid >= 0) {
  9628. $this->error('仅支持手工新增询价单');
  9629. }
  9630. $po = $this->loadManualRfqOrderForNotify($sid);
  9631. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9632. $this->error('订单已完结,无法补加供应商');
  9633. }
  9634. $raw = $this->request->post('suppliers/a', []);
  9635. if (!is_array($raw) || $raw === []) {
  9636. $suppliersJson = $this->request->post('suppliers_json', '');
  9637. if (is_string($suppliersJson) && $suppliersJson !== '') {
  9638. $decoded = json_decode($suppliersJson, true);
  9639. $raw = is_array($decoded) ? $decoded : [];
  9640. }
  9641. }
  9642. $addNames = [];
  9643. foreach ((array)$raw as $item) {
  9644. if (is_array($item)) {
  9645. $n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
  9646. } else {
  9647. $n = trim((string)$item);
  9648. }
  9649. if ($n !== '') {
  9650. $addNames[] = $n;
  9651. }
  9652. }
  9653. $addNames = array_values(array_unique($addNames));
  9654. if ($addNames === []) {
  9655. $this->error('请选择要补加的供应商');
  9656. }
  9657. $existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9658. if ($existingRaw === '') {
  9659. $existingRaw = trim((string)($po['pick_company_name'] ?? ''));
  9660. }
  9661. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9662. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9663. try {
  9664. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
  9665. } catch (\Throwable $e) {
  9666. $this->error('保存失败:' . $e->getMessage());
  9667. }
  9668. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9669. $this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9670. $this->success('已补加供应商', null, [
  9671. 'scydgy_id' => $sid,
  9672. 'cGzzxMc' => $mergedStr,
  9673. 'added_count' => count($addNames),
  9674. ]);
  9675. }
  9676. /**
  9677. * 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
  9678. */
  9679. public function rfqissue()
  9680. {
  9681. if (!$this->request->isPost()) {
  9682. $this->error(__('Invalid parameters'));
  9683. }
  9684. if (!$this->hasProcuremenPerm(['rfqissue'])) {
  9685. $this->error(__('You have no permission'));
  9686. }
  9687. $this->ensureRfqSupplierEmailTemplate();
  9688. $sid = (int)$this->request->post('scydgy_id', 0);
  9689. if ($sid >= 0) {
  9690. $this->error('仅支持手工新增询价单');
  9691. }
  9692. $po = $this->loadManualRfqOrderForNotify($sid);
  9693. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9694. $this->error('订单已完结,无法下发');
  9695. }
  9696. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9697. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9698. $this->error('订单已进入后续流程,无法再下发');
  9699. }
  9700. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9701. if ($supplierRaw === '') {
  9702. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9703. }
  9704. $supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
  9705. if ($supplierNames === []) {
  9706. $this->error('请先在新增询价时选择供应商');
  9707. }
  9708. $companies = [];
  9709. $missing = [];
  9710. $noEmail = [];
  9711. foreach ($supplierNames as $name) {
  9712. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9713. if ($contact === null) {
  9714. $missing[] = $name;
  9715. continue;
  9716. }
  9717. $em = trim((string)($contact['email'] ?? ''));
  9718. if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
  9719. $noEmail[] = $name;
  9720. continue;
  9721. }
  9722. $companies[] = $contact;
  9723. }
  9724. if ($missing !== []) {
  9725. $this->error('未找到供应商档案:' . implode('、', $missing));
  9726. }
  9727. if ($noEmail !== []) {
  9728. $this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
  9729. }
  9730. if ($companies === []) {
  9731. $this->error('没有可通知的供应商');
  9732. }
  9733. $mailConfig = $this->loadMailerConfig();
  9734. if (empty($mailConfig['host'])) {
  9735. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9736. }
  9737. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9738. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9739. }
  9740. $mergeRow = $po;
  9741. $mergeRow['ID'] = $sid;
  9742. $mergeRow['id'] = $sid;
  9743. $mergeRows = [$mergeRow];
  9744. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9745. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9746. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9747. }
  9748. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9749. $issueTime = date('Y-m-d H:i:s');
  9750. $nameLabels = [];
  9751. foreach ($companies as $c) {
  9752. $nameLabels[] = trim((string)($c['name'] ?? ''));
  9753. }
  9754. $logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
  9755. Db::startTrans();
  9756. try {
  9757. $this->upsertPurchaseOrderFromRow(
  9758. $mergeRow,
  9759. $sysRqDb,
  9760. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9761. $issueTime,
  9762. $po,
  9763. null,
  9764. $scoreRule
  9765. );
  9766. foreach ($companies as $c) {
  9767. $this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
  9768. }
  9769. Db::commit();
  9770. } catch (\Throwable $e) {
  9771. Db::rollback();
  9772. $this->error($e->getMessage());
  9773. }
  9774. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9775. if ($poId <= 0) {
  9776. try {
  9777. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9778. } catch (\Throwable $e) {
  9779. $poId = 0;
  9780. }
  9781. }
  9782. $this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
  9783. $posNotify = [];
  9784. try {
  9785. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9786. if (is_array($fresh)) {
  9787. $fresh['sys_rq'] = $sysRqDb;
  9788. $posNotify = [$fresh];
  9789. }
  9790. } catch (\Throwable $e) {
  9791. $posNotify = [$po];
  9792. $posNotify[0]['sys_rq'] = $sysRqDb;
  9793. }
  9794. $notifyBundle = [
  9795. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9796. 'pos' => $posNotify,
  9797. 'merge_rows' => $mergeRows,
  9798. ];
  9799. $notifyErrors = [];
  9800. foreach ($companies as $c) {
  9801. $cname = trim((string)($c['name'] ?? ''));
  9802. try {
  9803. // 询价下发:仅邮箱通知供应商
  9804. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  9805. } catch (\Throwable $e) {
  9806. $notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
  9807. }
  9808. }
  9809. if ($notifyErrors !== []) {
  9810. $this->error('下发已保存,但邮件通知失败:' . implode(';', $notifyErrors));
  9811. }
  9812. $this->success('已询价并邮件通知供应商', null, [
  9813. 'scydgy_id' => $sid,
  9814. 'progress_text' => '待报价',
  9815. 'supplier_count' => count($companies),
  9816. ]);
  9817. }
  9818. /**
  9819. * 查询询价 — 弹窗内向单个供应商发送询价邮件
  9820. */
  9821. public function rfqissuesendmail()
  9822. {
  9823. if (!$this->request->isPost()) {
  9824. $this->error(__('Invalid parameters'));
  9825. }
  9826. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail'])) {
  9827. $this->error(__('You have no permission'));
  9828. }
  9829. $this->ensureRfqSupplierEmailTemplate();
  9830. $sid = (int)$this->request->post('scydgy_id', 0);
  9831. $companyName = trim((string)$this->request->post('company_name', ''));
  9832. if ($sid >= 0) {
  9833. $this->error('仅支持手工新增询价单');
  9834. }
  9835. if ($companyName === '') {
  9836. $this->error('请选择供应商');
  9837. }
  9838. $po = $this->loadManualRfqOrderForNotify($sid);
  9839. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9840. $this->error('订单已完结,无法发送');
  9841. }
  9842. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9843. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9844. $this->error('订单已进入后续流程,无法再发送');
  9845. }
  9846. $contact = $this->resolveCustomerContactByCompanyName($companyName, false);
  9847. if ($contact === null) {
  9848. $this->error('未找到供应商档案:' . $companyName);
  9849. }
  9850. $email = trim((string)($contact['email'] ?? ''));
  9851. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9852. $this->error('该供应商未填写有效邮箱');
  9853. }
  9854. $mailConfig = $this->loadMailerConfig();
  9855. if (empty($mailConfig['host'])) {
  9856. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9857. }
  9858. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9859. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9860. }
  9861. $mergeRow = $po;
  9862. $mergeRow['ID'] = $sid;
  9863. $mergeRow['id'] = $sid;
  9864. $mergeRows = [$mergeRow];
  9865. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9866. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9867. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9868. }
  9869. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9870. $issueTime = date('Y-m-d H:i:s');
  9871. Db::startTrans();
  9872. try {
  9873. $this->upsertPurchaseOrderFromRow(
  9874. $mergeRow,
  9875. $sysRqDb,
  9876. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9877. $issueTime,
  9878. $po,
  9879. null,
  9880. $scoreRule
  9881. );
  9882. $this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
  9883. Db::commit();
  9884. } catch (\Throwable $e) {
  9885. Db::rollback();
  9886. $this->error($e->getMessage());
  9887. }
  9888. $posNotify = [];
  9889. try {
  9890. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9891. if (is_array($fresh)) {
  9892. $fresh['sys_rq'] = $sysRqDb;
  9893. $posNotify = [$fresh];
  9894. }
  9895. } catch (\Throwable $e) {
  9896. $posNotify = [$po];
  9897. $posNotify[0]['sys_rq'] = $sysRqDb;
  9898. }
  9899. $notifyBundle = [
  9900. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9901. 'pos' => $posNotify,
  9902. 'merge_rows' => $mergeRows,
  9903. ];
  9904. try {
  9905. $this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  9906. } catch (\Throwable $e) {
  9907. $this->error('明细已保存,但邮件发送失败:' . $e->getMessage());
  9908. }
  9909. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9910. if ($poId <= 0) {
  9911. try {
  9912. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9913. } catch (\Throwable $e) {
  9914. $poId = 0;
  9915. }
  9916. }
  9917. $this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
  9918. $this->success('已向「' . $companyName . '」发送询价邮件', null, [
  9919. 'scydgy_id' => $sid,
  9920. 'company_name' => $companyName,
  9921. ]);
  9922. }
  9923. /**
  9924. * 查询询价 — 查看各供应商报价(单价)
  9925. */
  9926. public function rfqquotes()
  9927. {
  9928. if (!$this->hasProcuremenPerm(['rfqquotes', 'rfqissue'])) {
  9929. $this->error(__('You have no permission'));
  9930. }
  9931. $sid = (int)$this->request->param('scydgy_id', 0);
  9932. if ($sid >= 0) {
  9933. $this->error('仅支持手工新增询价单');
  9934. }
  9935. $po = $this->loadManualRfqOrderForNotify($sid);
  9936. $rows = [];
  9937. try {
  9938. // 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
  9939. $q = Db::table('purchase_order_detail')
  9940. ->where('scydgy_id', $sid)
  9941. ->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
  9942. ->order('id', 'asc');
  9943. $this->applyActivePurchaseOrderDetailWhere($q);
  9944. $rows = $q->select();
  9945. } catch (\Throwable $e) {
  9946. try {
  9947. $q = Db::table('purchase_order_detail')
  9948. ->where('scydgy_id', $sid)
  9949. ->order('id', 'asc');
  9950. $this->applyActivePurchaseOrderDetailWhere($q);
  9951. $rows = $q->select();
  9952. } catch (\Throwable $e2) {
  9953. $rows = [];
  9954. }
  9955. }
  9956. if (!is_array($rows)) {
  9957. $rows = [];
  9958. }
  9959. $list = [];
  9960. foreach ($rows as $row) {
  9961. if (!is_array($row)) {
  9962. continue;
  9963. }
  9964. $amount = trim((string)($row['amount'] ?? ''));
  9965. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  9966. // 未报价不显示时间(createtime 是下发时间,不是报价时间)
  9967. $oper = '';
  9968. if ($isQuoted) {
  9969. $oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
  9970. if ($oper === '') {
  9971. $oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  9972. }
  9973. }
  9974. $list[] = [
  9975. 'id' => (int)($row['id'] ?? 0),
  9976. 'company_name' => trim((string)($row['company_name'] ?? '')),
  9977. 'amount' => $amount,
  9978. 'amount_text' => $isQuoted ? $amount : '',
  9979. 'is_quoted' => $isQuoted,
  9980. 'quote_label' => $isQuoted ? '已报价' : '未报价',
  9981. 'status_name' => trim((string)($row['status_name'] ?? '')),
  9982. 'oper_time' => $oper,
  9983. ];
  9984. }
  9985. $this->success('', null, [
  9986. 'scydgy_id' => $sid,
  9987. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9988. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9989. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9990. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9991. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9992. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9993. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9994. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9995. 'list' => $list,
  9996. ]);
  9997. }
  9998. /**
  9999. * 手工询价是否已下发(有下发明细或已进入待确认及之后)
  10000. */
  10001. protected function isRfqOrderIssued(array $po): bool
  10002. {
  10003. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  10004. return true;
  10005. }
  10006. $sid = (int)($po['scydgy_id'] ?? 0);
  10007. if ($sid >= 0) {
  10008. return false;
  10009. }
  10010. try {
  10011. $q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  10012. $this->applyActivePurchaseOrderDetailWhere($q);
  10013. return (int)$q->count() > 0;
  10014. } catch (\Throwable $e) {
  10015. return false;
  10016. }
  10017. }
  10018. /**
  10019. * 批量:已有下发明细的手工询价 scydgy_id
  10020. *
  10021. * @param int[] $scydgyIds
  10022. * @return array<int, bool>
  10023. */
  10024. protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
  10025. {
  10026. $set = [];
  10027. $ids = [];
  10028. foreach ($scydgyIds as $sid) {
  10029. $sid = (int)$sid;
  10030. if ($sid < 0) {
  10031. $ids[$sid] = true;
  10032. }
  10033. }
  10034. if ($ids === []) {
  10035. return $set;
  10036. }
  10037. try {
  10038. $q = Db::table('purchase_order_detail')
  10039. ->where('scydgy_id', 'in', array_keys($ids))
  10040. ->field('scydgy_id');
  10041. $this->applyActivePurchaseOrderDetailWhere($q);
  10042. $rows = $q->select();
  10043. } catch (\Throwable $e) {
  10044. return $set;
  10045. }
  10046. if (!is_array($rows)) {
  10047. return $set;
  10048. }
  10049. foreach ($rows as $row) {
  10050. if (!is_array($row)) {
  10051. continue;
  10052. }
  10053. $sid = (int)($row['scydgy_id'] ?? 0);
  10054. if ($sid < 0) {
  10055. $set[$sid] = true;
  10056. }
  10057. }
  10058. return $set;
  10059. }
  10060. /**
  10061. * 批量:已填单价(已报价)的手工询价 scydgy_id
  10062. *
  10063. * @param int[] $scydgyIds
  10064. * @return array<int, bool>
  10065. */
  10066. protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
  10067. {
  10068. $set = [];
  10069. $ids = [];
  10070. foreach ($scydgyIds as $sid) {
  10071. $sid = (int)$sid;
  10072. if ($sid < 0) {
  10073. $ids[$sid] = true;
  10074. }
  10075. }
  10076. if ($ids === []) {
  10077. return $set;
  10078. }
  10079. try {
  10080. $q = Db::table('purchase_order_detail')
  10081. ->where('scydgy_id', 'in', array_keys($ids))
  10082. ->field('scydgy_id,amount');
  10083. $this->applyActivePurchaseOrderDetailWhere($q);
  10084. $rows = $q->select();
  10085. } catch (\Throwable $e) {
  10086. return $set;
  10087. }
  10088. if (!is_array($rows)) {
  10089. return $set;
  10090. }
  10091. foreach ($rows as $row) {
  10092. if (!is_array($row)) {
  10093. continue;
  10094. }
  10095. $amount = trim((string)($row['amount'] ?? ''));
  10096. if ($amount === '' || $amount === '0' || $amount === '0.00') {
  10097. continue;
  10098. }
  10099. $sid = (int)($row['scydgy_id'] ?? 0);
  10100. if ($sid < 0) {
  10101. $set[$sid] = true;
  10102. }
  10103. }
  10104. return $set;
  10105. }
  10106. /**
  10107. * 已下发且至少一家供应商已报价,才允许通知业务员
  10108. */
  10109. protected function canRfqNotifySalesman(array $po): bool
  10110. {
  10111. if (!$this->isRfqOrderIssued($po)) {
  10112. return false;
  10113. }
  10114. $sid = (int)($po['scydgy_id'] ?? 0);
  10115. if ($sid >= 0) {
  10116. return false;
  10117. }
  10118. $quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
  10119. return isset($quoted[$sid]);
  10120. }
  10121. protected function assertRfqCanNotifySalesman(array $po): void
  10122. {
  10123. if (!$this->isRfqOrderIssued($po)) {
  10124. $this->error('请先询价并等待供应商报价后再通知业务员');
  10125. }
  10126. if (!$this->canRfqNotifySalesman($po)) {
  10127. $this->error('供应商尚未报价,暂不能通知业务员');
  10128. }
  10129. }
  10130. /**
  10131. * 加载手工询价单(含可见性校验)
  10132. *
  10133. * @return array<string, mixed>
  10134. */
  10135. protected function loadManualRfqOrderForNotify(int $scydgyId): array
  10136. {
  10137. try {
  10138. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10139. } catch (\Throwable $e) {
  10140. $po = null;
  10141. }
  10142. if (!is_array($po)) {
  10143. $this->error('订单不存在');
  10144. }
  10145. $modRq = trim((string)($po['mod_rq'] ?? ''));
  10146. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  10147. $this->error('订单不存在');
  10148. }
  10149. if ($this->auth->isSuperAdmin()) {
  10150. return $po;
  10151. }
  10152. if ($this->canViewManualRfqOrder($po)) {
  10153. return $po;
  10154. }
  10155. $this->error('无权操作该订单');
  10156. }
  10157. /**
  10158. * @return string[]
  10159. */
  10160. protected function splitRfqSalesmanNames(string $raw): array
  10161. {
  10162. $parts = [];
  10163. $raw = trim($raw);
  10164. if ($raw === '') {
  10165. return [];
  10166. }
  10167. foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
  10168. $v = trim((string)$piece);
  10169. if ($v !== '' && !in_array($v, $parts, true)) {
  10170. $parts[] = $v;
  10171. }
  10172. }
  10173. return $parts;
  10174. }
  10175. /**
  10176. * 按姓名匹配 fa_admin 邮箱
  10177. *
  10178. * @param string[] $names
  10179. * @return array<int, array{admin_id:int,name:string,email:string}>
  10180. */
  10181. protected function resolveRfqSalesmanContactRows(array $names): array
  10182. {
  10183. $out = [];
  10184. foreach ($names as $name) {
  10185. $name = trim((string)$name);
  10186. if ($name === '') {
  10187. continue;
  10188. }
  10189. $adminId = 0;
  10190. $email = '';
  10191. try {
  10192. $row = Db::name('admin')
  10193. ->where(function ($q) use ($name) {
  10194. $q->where('nickname', $name)->whereOr('username', $name);
  10195. })
  10196. ->where('status', 'normal')
  10197. ->order('id', 'asc')
  10198. ->field('id,nickname,username,email')
  10199. ->find();
  10200. } catch (\Throwable $e) {
  10201. $row = null;
  10202. }
  10203. if (is_array($row)) {
  10204. $adminId = (int)($row['id'] ?? 0);
  10205. $email = trim((string)($row['email'] ?? ''));
  10206. $disp = trim((string)($row['nickname'] ?? ''));
  10207. if ($disp === '') {
  10208. $disp = trim((string)($row['username'] ?? ''));
  10209. }
  10210. if ($disp !== '') {
  10211. $name = $disp;
  10212. }
  10213. }
  10214. $out[] = [
  10215. 'admin_id' => $adminId,
  10216. 'name' => $name,
  10217. 'email' => $email,
  10218. ];
  10219. }
  10220. return $out;
  10221. }
  10222. /**
  10223. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  10224. */
  10225. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  10226. {
  10227. if ($scydgyId >= 0) {
  10228. return;
  10229. }
  10230. try {
  10231. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10232. } catch (\Throwable $e) {
  10233. $po = null;
  10234. }
  10235. if (!is_array($po)) {
  10236. $this->error('订单不存在');
  10237. }
  10238. $modRq = trim((string)($po['mod_rq'] ?? ''));
  10239. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  10240. $this->error('订单不存在');
  10241. }
  10242. if ($this->auth->isSuperAdmin()) {
  10243. return;
  10244. }
  10245. [, $adminName] = $this->GetUseName();
  10246. $cywy = trim((string)($po['cywyxm'] ?? ''));
  10247. if ($cywy !== '' && $cywy === $adminName) {
  10248. return;
  10249. }
  10250. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  10251. try {
  10252. if ($this->auth->check($rule)) {
  10253. return;
  10254. }
  10255. } catch (\Throwable $e) {
  10256. }
  10257. }
  10258. $this->error('无权查看该订单');
  10259. }
  10260. /**
  10261. * 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
  10262. */
  10263. protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
  10264. {
  10265. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  10266. return ProcuremenStatus::PO_COMPLETED;
  10267. }
  10268. $sid = (int)($row['scydgy_id'] ?? 0);
  10269. if ($sid < 0) {
  10270. if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
  10271. return '已通知业务员';
  10272. }
  10273. if ($hasQuoted) {
  10274. return '供应商已报价';
  10275. }
  10276. if ($hasIssued
  10277. || ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
  10278. || ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
  10279. return '待报价';
  10280. }
  10281. try {
  10282. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  10283. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  10284. if ((int)$detCntQuery->count() > 0) {
  10285. return '待报价';
  10286. }
  10287. } catch (\Throwable $e) {
  10288. }
  10289. return '待询价';
  10290. }
  10291. if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
  10292. return '待入库评分';
  10293. }
  10294. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  10295. return '待采购确认';
  10296. }
  10297. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  10298. return '待确认供应商';
  10299. }
  10300. return '待协助下发';
  10301. }
  10302. /**
  10303. * 协助初选列表 — 批量软删除
  10304. */
  10305. public function pickDelete()
  10306. {
  10307. if (!$this->request->isPost() || !$this->request->isAjax()) {
  10308. $this->error(__('Invalid parameters'));
  10309. }
  10310. if (!$this->procuremenCanPickDelete()) {
  10311. $this->error(__('You have no permission'));
  10312. }
  10313. $rowsRaw = $this->request->post('rows_json', '[]');
  10314. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  10315. if (!is_array($rows) || $rows === []) {
  10316. $this->error('请至少勾选一条工序');
  10317. }
  10318. $done = 0;
  10319. Db::startTrans();
  10320. try {
  10321. foreach ($rows as $row) {
  10322. if (!is_array($row)) {
  10323. continue;
  10324. }
  10325. $this->softDeleteProcuremenPickRow($row);
  10326. $done++;
  10327. }
  10328. if ($done < 1) {
  10329. throw new \Exception('没有可删除的工序');
  10330. }
  10331. Db::commit();
  10332. } catch (\InvalidArgumentException $e) {
  10333. Db::rollback();
  10334. $this->error($e->getMessage());
  10335. } catch (\Throwable $e) {
  10336. Db::rollback();
  10337. $this->error($e->getMessage());
  10338. }
  10339. $this->pickHiddenScydgySetCache = null;
  10340. $this->success('已删除 ' . $done . ' 条工序');
  10341. }
  10342. /**
  10343. * 下发 — 手工新增工序(弹窗)
  10344. */
  10345. public function pickAdd()
  10346. {
  10347. if ($this->request->isPost()) {
  10348. $params = $this->request->post('row/a');
  10349. if (!is_array($params)) {
  10350. $this->error(__('Parameter %s can not be empty', ''));
  10351. }
  10352. try {
  10353. $sid = $this->saveManualPickOrder($params);
  10354. } catch (\InvalidArgumentException $e) {
  10355. $this->error($e->getMessage());
  10356. } catch (\Throwable $e) {
  10357. $this->error($e->getMessage());
  10358. }
  10359. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  10360. }
  10361. return $this->view->fetch('procuremen/pick_add');
  10362. }
  10363. /**
  10364. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  10365. */
  10366. public function pickSubmit()
  10367. {
  10368. if (!$this->request->isPost()) {
  10369. $this->error(__('Invalid parameters'));
  10370. }
  10371. // ---------- 接口订单数据 ----------
  10372. $rowJson = $this->request->post('row_json', '');
  10373. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  10374. $companiesJson = $this->request->post('companies_json', '[]');
  10375. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  10376. $companies = json_decode($companiesJson, true);
  10377. if (!is_array($companies)) {
  10378. $this->error('供应商数据无效');
  10379. }
  10380. $issueCompanies = $this->normalizePickCompanies($companies);
  10381. if ($issueCompanies === []) {
  10382. $this->error('请至少选择一家合作供应商');
  10383. }
  10384. $issueNameLabels = [];
  10385. foreach ($issueCompanies as $pc) {
  10386. $issueNameLabels[] = $pc['name'];
  10387. }
  10388. $issueNamesSummary = implode('、', $issueNameLabels);
  10389. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  10390. if ($sysRq === '') {
  10391. $this->error('请选择招标截止日期');
  10392. }
  10393. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  10394. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  10395. (string)$this->request->post('delivery_deadline', ''),
  10396. true
  10397. );
  10398. $scoreRuleId = (int)$this->request->post('score_rule_id', 0);
  10399. if ($scoreRuleId <= 0) {
  10400. $this->error('请选择订单类型');
  10401. }
  10402. $scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
  10403. if ((int)($scoreRule['id'] ?? 0) <= 0) {
  10404. $this->error('订单类型无效,请刷新后重选');
  10405. }
  10406. $scoreRuleId = (int)$scoreRule['id'];
  10407. $this->ensurePurchaseOrderScoreRuleIdColumn();
  10408. $isMerge = count($mergeRows) > 1;
  10409. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  10410. $logMsg = '下发' . $procPart
  10411. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  10412. $issueTime = date('Y-m-d H:i:s');
  10413. $logSidList = [];
  10414. foreach ($mergeRows as $row) {
  10415. if (!is_array($row)) {
  10416. continue;
  10417. }
  10418. $sid = $this->extractScydgyRowId($row);
  10419. if ($this->isValidScydgyRowId($sid)) {
  10420. $logSidList[$sid] = true;
  10421. }
  10422. }
  10423. $existingBySid = [];
  10424. if ($logSidList !== []) {
  10425. try {
  10426. $existingRows = Db::table('purchase_order')
  10427. ->where('scydgy_id', 'in', array_keys($logSidList))
  10428. ->select();
  10429. if (is_array($existingRows)) {
  10430. foreach ($existingRows as $poRow) {
  10431. if (!is_array($poRow)) {
  10432. continue;
  10433. }
  10434. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10435. if ($this->isValidScydgyRowId($sid)) {
  10436. $existingBySid[$sid] = $poRow;
  10437. }
  10438. }
  10439. }
  10440. } catch (\Throwable $e) {
  10441. $existingBySid = [];
  10442. }
  10443. }
  10444. Db::startTrans();
  10445. try {
  10446. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  10447. foreach ($mergeRows as $row) {
  10448. if (!is_array($row)) {
  10449. continue;
  10450. }
  10451. $sid = $this->extractScydgyRowId($row);
  10452. $this->upsertPurchaseOrderFromRow(
  10453. $row,
  10454. $sysRqDb,
  10455. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  10456. $issueTime,
  10457. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  10458. $deliveryDeadlineDb,
  10459. $scoreRule
  10460. );
  10461. }
  10462. foreach ($issueCompanies as $c) {
  10463. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10464. }
  10465. Db::commit();
  10466. } catch (\Throwable $e) {
  10467. Db::rollback();
  10468. $this->error($e->getMessage());
  10469. }
  10470. $poIdBySid = [];
  10471. if ($logSidList !== []) {
  10472. try {
  10473. $poIdBySid = Db::table('purchase_order')
  10474. ->where('scydgy_id', 'in', array_keys($logSidList))
  10475. ->column('id', 'scydgy_id');
  10476. } catch (\Throwable $e) {
  10477. $poIdBySid = [];
  10478. }
  10479. }
  10480. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  10481. if ($logSidList !== []) {
  10482. list($adminId, $adminName) = $this->GetUseName();
  10483. $logRows = [];
  10484. $seenLogSid = [];
  10485. foreach ($mergeRows as $row) {
  10486. if (!is_array($row)) {
  10487. continue;
  10488. }
  10489. $ids = $this->extractScydgyRowId($row);
  10490. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  10491. continue;
  10492. }
  10493. $seenLogSid[$ids] = true;
  10494. $poIdLog = null;
  10495. if (isset($poIdBySid[$ids])) {
  10496. $tid = (int)$poIdBySid[$ids];
  10497. $poIdLog = $tid > 0 ? $tid : null;
  10498. }
  10499. $logRows[] = ProcuremenOperLog::buildInsertRow(
  10500. $ids,
  10501. 'issue_submit',
  10502. $logMsg,
  10503. $poIdLog,
  10504. (int)$adminId,
  10505. (string)$adminName
  10506. );
  10507. }
  10508. if ($logRows !== []) {
  10509. try {
  10510. Db::table('purchase_order_oper_log')->insertAll($logRows);
  10511. } catch (\Throwable $e) {
  10512. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  10513. }
  10514. }
  10515. }
  10516. $notifyErrors = [];
  10517. $posNotify = [];
  10518. if ($logSidList !== []) {
  10519. try {
  10520. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  10521. } catch (\Throwable $e) {
  10522. $posNotify = [];
  10523. }
  10524. }
  10525. if (!is_array($posNotify)) {
  10526. $posNotify = [];
  10527. }
  10528. foreach ($posNotify as $i => $prow) {
  10529. if (is_array($posNotify[$i])) {
  10530. $posNotify[$i]['sys_rq'] = $sysRqDb;
  10531. }
  10532. }
  10533. $ccydhPick = '';
  10534. foreach ($mergeRows as $row) {
  10535. if (!is_array($row)) {
  10536. continue;
  10537. }
  10538. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  10539. if ($ccydhPick !== '') {
  10540. break;
  10541. }
  10542. }
  10543. $notifyBundleBase = [
  10544. 'ccydh' => $ccydhPick,
  10545. 'pos' => $posNotify,
  10546. 'merge_rows' => $mergeRows,
  10547. 'score_rule' => is_array($scoreRule) ? $scoreRule : null,
  10548. ];
  10549. try {
  10550. $this->notifyDryRunPreview = [];
  10551. foreach ($issueCompanies as $c) {
  10552. if (!is_array($c)) {
  10553. continue;
  10554. }
  10555. $cname = trim((string)($c['name'] ?? ''));
  10556. if ($cname === '') {
  10557. continue;
  10558. }
  10559. try {
  10560. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  10561. } catch (\Throwable $e) {
  10562. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10563. }
  10564. }
  10565. } catch (\Throwable $e) {
  10566. $this->error('通知发送失败:' . $e->getMessage());
  10567. }
  10568. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10569. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  10570. }
  10571. if ($this->isProcuremenNotifyDryRun()) {
  10572. $this->success('【演练模式】已保存并生成通知预览', '', [
  10573. 'notify_dry_run' => true,
  10574. 'notify_preview' => $this->notifyDryRunPreview,
  10575. ]);
  10576. }
  10577. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  10578. }
  10579. /**
  10580. * 确认供应商弹窗
  10581. */
  10582. public function auditIssue()
  10583. {
  10584. $ids = $this->request->param('ids', $this->request->param('id', ''));
  10585. if (is_array($ids)) {
  10586. $ids = isset($ids[0]) ? $ids[0] : '';
  10587. }
  10588. $ids = trim((string)$ids);
  10589. if ($ids === '') {
  10590. $this->error(__('Invalid parameters'));
  10591. }
  10592. if ($this->request->isPost()) {
  10593. $this->error('请使用弹窗内「确认」提交');
  10594. }
  10595. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10596. $pos = $bundle['pos'];
  10597. if ($pos === []) {
  10598. $this->error('该订单不在待确认供应商状态');
  10599. }
  10600. $po = $pos[0];
  10601. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10602. if ($quoteGroups === []) {
  10603. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  10604. }
  10605. $pickedName = '';
  10606. foreach ($pos as $poRow) {
  10607. if (!is_array($poRow)) {
  10608. continue;
  10609. }
  10610. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  10611. if ($pn !== '') {
  10612. $pickedName = $pn;
  10613. break;
  10614. }
  10615. }
  10616. $this->view->assign('po', $po);
  10617. $this->view->assign('scydgyId', $ids);
  10618. $this->view->assign('orderCcydh', $bundle['ccydh']);
  10619. $mergeRows = $bundle['merge_rows'];
  10620. $this->view->assign('processRows', $mergeRows);
  10621. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  10622. $this->view->assign('processCount', count($mergeRows));
  10623. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  10624. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  10625. $this->view->assign('pickedCompanyName', $pickedName);
  10626. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10627. if ($sysRqForView === '') {
  10628. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10629. }
  10630. $this->view->assign('sysRq', $sysRqForView);
  10631. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  10632. if ($deliveryDeadlineForView === '') {
  10633. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10634. }
  10635. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10636. $this->ensurePurchaseOrderManualPickColumns();
  10637. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
  10638. $manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
  10639. $manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
  10640. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  10641. if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
  10642. $pickedName = $manualPickInfo['company'];
  10643. $this->view->assign('pickedCompanyName', $pickedName);
  10644. }
  10645. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  10646. $this->view->assign('manualPicked', $manualPicked);
  10647. $this->view->assign('manualPickReason', $manualPickInfo['reason']);
  10648. $this->view->assign('quoteVisible', $quoteVisible);
  10649. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
  10650. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  10651. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
  10652. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
  10653. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  10654. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  10655. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  10656. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  10657. return $this->view->fetch('procuremen/audit_issue');
  10658. }
  10659. /**
  10660. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  10661. *
  10662. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10663. */
  10664. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  10665. {
  10666. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10667. return false;
  10668. }
  10669. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10670. return false;
  10671. }
  10672. return true;
  10673. }
  10674. /**
  10675. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  10676. *
  10677. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10678. */
  10679. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  10680. {
  10681. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10682. return false;
  10683. }
  10684. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10685. return false;
  10686. }
  10687. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  10688. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  10689. return true;
  10690. }
  10691. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  10692. }
  10693. /**
  10694. * 确认页 — 补加供应商弹窗
  10695. */
  10696. public function auditAppend()
  10697. {
  10698. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  10699. $this->error(__('You have no permission'));
  10700. }
  10701. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  10702. if (is_array($ids)) {
  10703. $ids = isset($ids[0]) ? $ids[0] : '';
  10704. }
  10705. $ids = trim((string)$ids);
  10706. if ($ids === '') {
  10707. $this->error(__('Invalid parameters'));
  10708. }
  10709. if ($this->request->isPost()) {
  10710. $this->error('请使用弹窗内「确认」提交');
  10711. }
  10712. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10713. if (($bundle['pos'] ?? []) === []) {
  10714. $this->error('该订单不在待确认供应商状态');
  10715. }
  10716. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10717. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10718. $this->error('已开标验证,不能再补加供应商');
  10719. }
  10720. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10721. $this->error('已指定供应商,不能再补加供应商');
  10722. }
  10723. $this->error('已经超过了招标截止日期,不可操作');
  10724. }
  10725. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10726. $existingNames = [];
  10727. foreach ($quoteGroups as $g) {
  10728. if (!is_array($g)) {
  10729. continue;
  10730. }
  10731. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  10732. if ($n !== '') {
  10733. $existingNames[$n] = true;
  10734. }
  10735. }
  10736. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  10737. $mergeRows = $bundle['merge_rows'] ?? [];
  10738. $this->view->assign('scydgyId', $ids);
  10739. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  10740. $this->view->assign('po', $po);
  10741. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  10742. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  10743. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  10744. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10745. if ($sysRqForView === '') {
  10746. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10747. }
  10748. $this->view->assign('sysRq', $sysRqForView);
  10749. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  10750. if ($deliveryDeadlineForView === '') {
  10751. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10752. }
  10753. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10754. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  10755. }
  10756. /**
  10757. * 确认页 — 补加供应商提交
  10758. */
  10759. public function auditAppendSubmit()
  10760. {
  10761. if (!$this->request->isPost()) {
  10762. $this->error(__('Invalid parameters'));
  10763. }
  10764. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  10765. $this->error(__('You have no permission'));
  10766. }
  10767. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  10768. if ($ids === '') {
  10769. $this->error(__('Invalid parameters'));
  10770. }
  10771. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10772. if (($bundle['pos'] ?? []) === []) {
  10773. $this->error('该订单不在待确认供应商状态');
  10774. }
  10775. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10776. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10777. $this->error('已开标验证,不能再补加供应商');
  10778. }
  10779. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10780. $this->error('已指定供应商,不能再补加供应商');
  10781. }
  10782. $this->error('已经超过了招标截止日期,不可操作');
  10783. }
  10784. $companiesJson = $this->request->post('companies_json', '[]');
  10785. $companies = json_decode((string)$companiesJson, true);
  10786. if (!is_array($companies)) {
  10787. $this->error('供应商数据无效');
  10788. }
  10789. $issueCompanies = $this->normalizePickCompanies($companies);
  10790. if ($issueCompanies === []) {
  10791. $this->error('请至少选择一家合作供应商');
  10792. }
  10793. $mergeRows = $bundle['merge_rows'] ?? [];
  10794. if (!is_array($mergeRows) || $mergeRows === []) {
  10795. $this->error('未找到工序行,无法补加');
  10796. }
  10797. $existingNames = [];
  10798. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  10799. if (!is_array($g)) {
  10800. continue;
  10801. }
  10802. $n = trim((string)($g['company_name'] ?? ''));
  10803. if ($n !== '') {
  10804. $existingNames[$n] = true;
  10805. }
  10806. }
  10807. $toAdd = [];
  10808. foreach ($issueCompanies as $c) {
  10809. if (!is_array($c)) {
  10810. continue;
  10811. }
  10812. $n = trim((string)($c['name'] ?? ''));
  10813. if ($n === '' || isset($existingNames[$n])) {
  10814. continue;
  10815. }
  10816. $toAdd[] = $c;
  10817. }
  10818. if ($toAdd === []) {
  10819. $this->error('所选供应商均已在本单中,请选择新的供应商');
  10820. }
  10821. $addedNames = [];
  10822. Db::startTrans();
  10823. try {
  10824. foreach ($toAdd as $c) {
  10825. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10826. $addedNames[] = trim((string)($c['name'] ?? ''));
  10827. }
  10828. Db::commit();
  10829. } catch (\Throwable $e) {
  10830. Db::rollback();
  10831. $this->error($e->getMessage());
  10832. }
  10833. $notifyErrors = [];
  10834. $notifyBundleBase = [
  10835. 'ccydh' => $bundle['ccydh'] ?? '',
  10836. 'pos' => $bundle['pos'] ?? [],
  10837. 'merge_rows' => $mergeRows,
  10838. ];
  10839. foreach ($toAdd as $c) {
  10840. if (!is_array($c)) {
  10841. continue;
  10842. }
  10843. $cname = trim((string)($c['name'] ?? ''));
  10844. if ($cname === '') {
  10845. continue;
  10846. }
  10847. try {
  10848. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  10849. } catch (\Throwable $e) {
  10850. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10851. }
  10852. }
  10853. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  10854. $seenLogSid = [];
  10855. foreach ($bundle['pos'] ?? [] as $poRow) {
  10856. if (!is_array($poRow)) {
  10857. continue;
  10858. }
  10859. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10860. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  10861. continue;
  10862. }
  10863. $seenLogSid[$sid] = true;
  10864. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10865. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10866. }
  10867. if ($seenLogSid === []) {
  10868. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  10869. if ($this->isValidScydgyRowId($logSid)) {
  10870. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  10871. }
  10872. }
  10873. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10874. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  10875. }
  10876. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  10877. }
  10878. /**
  10879. * 开标双重验证 — 可选验证人列表
  10880. */
  10881. public function bidOpenUsers()
  10882. {
  10883. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10884. $this->error('无权限');
  10885. }
  10886. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  10887. if ($scydgyId !== '') {
  10888. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10889. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10890. $this->success('已完成开标验证', null, [
  10891. 'verified' => 1,
  10892. 'users' => [],
  10893. ]);
  10894. }
  10895. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10896. $this->error('本单已指定供应商,无需再开标');
  10897. }
  10898. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10899. }
  10900. $this->success('', null, [
  10901. 'verified' => 0,
  10902. 'users' => $this->listBidOpenVerifierCandidates(),
  10903. ]);
  10904. }
  10905. /**
  10906. * 开标双重验证 — 向指定管理员发送短信验证码
  10907. */
  10908. public function bidOpenSendCode()
  10909. {
  10910. if (!$this->request->isPost()) {
  10911. $this->error(__('Invalid parameters'));
  10912. }
  10913. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10914. $this->error('无权限');
  10915. }
  10916. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10917. $adminId = (int)$this->request->post('admin_id', 0);
  10918. if ($scydgyId === '' || $adminId <= 0) {
  10919. $this->error('参数无效');
  10920. }
  10921. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10922. if ($bundle['pos'] === []) {
  10923. $this->error('该订单不在待确认供应商状态');
  10924. }
  10925. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10926. $this->success('已完成开标验证,无需重复发送');
  10927. }
  10928. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10929. $this->error('本单已指定供应商,无需再开标');
  10930. }
  10931. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10932. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10933. if ($ccydh === '') {
  10934. $this->error('订单号无效');
  10935. }
  10936. $admin = $this->loadBidOpenAdminUser($adminId);
  10937. if ($admin === null) {
  10938. $this->error('验证人无效或未绑定手机号');
  10939. }
  10940. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  10941. $cd = max(30, min(120, $cd));
  10942. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  10943. $this->error('发送过于频繁,请稍后再试');
  10944. }
  10945. $code = (string)random_int(100000, 999999);
  10946. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  10947. $ttl = max(60, min(600, $ttl));
  10948. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  10949. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  10950. try {
  10951. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  10952. } catch (\Throwable $e) {
  10953. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  10954. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  10955. $this->error($e->getMessage());
  10956. }
  10957. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  10958. }
  10959. /**
  10960. * 开标双重验证 — 两人验证码校验并记录
  10961. */
  10962. public function bidOpenVerify()
  10963. {
  10964. if (!$this->request->isPost()) {
  10965. $this->error(__('Invalid parameters'));
  10966. }
  10967. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10968. $this->error('无权限');
  10969. }
  10970. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10971. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  10972. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  10973. $code1 = trim((string)$this->request->post('code1', ''));
  10974. $code2 = trim((string)$this->request->post('code2', ''));
  10975. if ($scydgyId === '') {
  10976. $this->error('参数无效');
  10977. }
  10978. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  10979. $this->error('请选择两位验证人');
  10980. }
  10981. if ($verifier1Id === $verifier2Id) {
  10982. $this->error('两位验证人不能相同');
  10983. }
  10984. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  10985. $this->error('请输入6位短信验证码');
  10986. }
  10987. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10988. if ($bundle['pos'] === []) {
  10989. $this->error('该订单不在待确认供应商状态');
  10990. }
  10991. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10992. if ($ccydh === '') {
  10993. $this->error('订单号无效');
  10994. }
  10995. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10996. $this->success('已完成开标验证');
  10997. }
  10998. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10999. $this->error('本单已指定供应商,无需再开标');
  11000. }
  11001. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  11002. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  11003. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  11004. if ($verifier1 === null || $verifier2 === null) {
  11005. $this->error('验证人无效或未绑定手机号');
  11006. }
  11007. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  11008. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  11009. }
  11010. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  11011. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  11012. }
  11013. try {
  11014. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  11015. } catch (\Throwable $e) {
  11016. $this->error($e->getMessage());
  11017. }
  11018. $this->success('开标验证成功,可查看供应商报价与交货日期');
  11019. }
  11020. /**
  11021. * 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
  11022. */
  11023. public function auditManualPick()
  11024. {
  11025. if (!$this->request->isPost()) {
  11026. $this->error(__('Invalid parameters'));
  11027. }
  11028. if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
  11029. $this->error('无权限');
  11030. }
  11031. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11032. if ($scydgyId === '') {
  11033. $this->error('参数无效');
  11034. }
  11035. $companyName = trim((string)$this->request->post('selected_company', ''));
  11036. $reason = trim((string)$this->request->post('pick_reason', ''));
  11037. if ($companyName === '') {
  11038. $this->error('请选择一家供应商');
  11039. }
  11040. if ($reason === '') {
  11041. $this->error('请填写选择说明');
  11042. }
  11043. if (mb_strlen($reason) > 500) {
  11044. $this->error('选择说明不能超过500字');
  11045. }
  11046. $this->ensurePurchaseOrderManualPickColumns();
  11047. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11048. $pos = $bundle['pos'];
  11049. if ($pos === []) {
  11050. $this->error('该订单不在待确认供应商状态');
  11051. }
  11052. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  11053. $this->error('本单已开标验证,请直接在列表中选定供应商后确认');
  11054. }
  11055. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11056. if ($quoteGroups === []) {
  11057. $this->error('暂无供应商,请确认已完成协助初选通知');
  11058. }
  11059. $matched = null;
  11060. foreach ($quoteGroups as $g) {
  11061. if (!is_array($g)) {
  11062. continue;
  11063. }
  11064. if (trim((string)($g['name'] ?? '')) === $companyName) {
  11065. $matched = $g;
  11066. break;
  11067. }
  11068. }
  11069. if ($matched === null) {
  11070. $this->error('所选供应商不在本单报价列表中');
  11071. }
  11072. $logMsg = '指定供应商:已选定「' . $companyName . '」;说明:' . $reason;
  11073. Db::startTrans();
  11074. try {
  11075. foreach ($pos as $poRow) {
  11076. if (!is_array($poRow)) {
  11077. continue;
  11078. }
  11079. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11080. if (!$this->isValidScydgyRowId($sid)) {
  11081. continue;
  11082. }
  11083. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11084. 'pick_company_name' => $companyName,
  11085. 'manual_pick' => 1,
  11086. 'manual_pick_reason' => $reason,
  11087. ]);
  11088. }
  11089. Db::commit();
  11090. } catch (\Throwable $e) {
  11091. Db::rollback();
  11092. $this->error($e->getMessage());
  11093. }
  11094. foreach ($pos as $poRow) {
  11095. if (!is_array($poRow)) {
  11096. continue;
  11097. }
  11098. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11099. if (!$this->isValidScydgyRowId($sid)) {
  11100. continue;
  11101. }
  11102. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11103. $this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11104. }
  11105. // 自选后可见报价:按本单规则计算评分(与开标后一致)
  11106. try {
  11107. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11108. if ($ccydh !== '') {
  11109. // 重新加载以拿到未掩码报价参与计分
  11110. $bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11111. $groupsFresh = $this->loadAuditSupplierQuoteGroups($bundleFresh);
  11112. ProcuremenSupplierScore::saveForOrder($ccydh, $groupsFresh, date('Y-m'));
  11113. }
  11114. } catch (\Throwable $e) {
  11115. Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
  11116. }
  11117. $this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
  11118. }
  11119. /**
  11120. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  11121. */
  11122. public function auditSubmit()
  11123. {
  11124. if (!$this->request->isPost()) {
  11125. $this->error(__('Invalid parameters'));
  11126. }
  11127. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11128. if ($scydgyId === '') {
  11129. $this->error('参数无效');
  11130. }
  11131. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11132. $pos = $bundle['pos'];
  11133. $mergeRows = $bundle['merge_rows'];
  11134. if ($pos === [] || $mergeRows === []) {
  11135. $this->error('该订单不在待确认供应商状态');
  11136. }
  11137. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11138. if ($quoteGroups === []) {
  11139. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  11140. }
  11141. $companyName = trim((string)$this->request->post('selected_company', ''));
  11142. if ($companyName === '') {
  11143. $this->error('请选择一家供应商');
  11144. }
  11145. $matched = null;
  11146. foreach ($quoteGroups as $g) {
  11147. if (!is_array($g)) {
  11148. continue;
  11149. }
  11150. if (trim((string)($g['name'] ?? '')) === $companyName) {
  11151. $matched = $g;
  11152. break;
  11153. }
  11154. }
  11155. if ($matched === null) {
  11156. $this->error('所选供应商不在本单报价列表中');
  11157. }
  11158. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  11159. if ($sysRqDb === '') {
  11160. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  11161. } else {
  11162. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  11163. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  11164. }
  11165. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  11166. $this->error('未到招标截止日期,暂不可确认');
  11167. }
  11168. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
  11169. && !$this->isProcuremenManualPickedForBundle($bundle)
  11170. ) {
  11171. $this->error('请先完成开标双重验证或指定供应商后再确认');
  11172. }
  11173. $procCnt = count($mergeRows);
  11174. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  11175. $logMsg = '确认供应商' . $procPart . ':已选定「' . $companyName . '」';
  11176. Db::startTrans();
  11177. try {
  11178. foreach ($pos as $poRow) {
  11179. if (!is_array($poRow)) {
  11180. continue;
  11181. }
  11182. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11183. if (!$this->isValidScydgyRowId($sid)) {
  11184. continue;
  11185. }
  11186. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11187. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  11188. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11189. 'pick_company_name' => $companyName,
  11190. 'sys_rq' => $sysRqDb,
  11191. ]);
  11192. }
  11193. Db::commit();
  11194. } catch (\Throwable $e) {
  11195. Db::rollback();
  11196. $this->error($e->getMessage());
  11197. }
  11198. foreach ($pos as $poRow) {
  11199. if (!is_array($poRow)) {
  11200. continue;
  11201. }
  11202. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11203. if (!$this->isValidScydgyRowId($sid)) {
  11204. continue;
  11205. }
  11206. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11207. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11208. }
  11209. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  11210. }
  11211. /**
  11212. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  11213. */
  11214. public function auditResendSms()
  11215. {
  11216. if (!$this->request->isPost()) {
  11217. $this->error(__('Invalid parameters'));
  11218. }
  11219. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11220. if ($scydgyId === '') {
  11221. $this->error('参数无效');
  11222. }
  11223. $loaded = $this->loadAuditResendBundle($scydgyId);
  11224. $mergeRows = $loaded['merge_rows'];
  11225. $bundle = $loaded['bundle'];
  11226. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  11227. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11228. if ($quoteGroups === []) {
  11229. $this->error('暂无可通知的供应商');
  11230. }
  11231. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  11232. $companiesJson = (string)$this->request->post('companies_json', '');
  11233. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  11234. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  11235. }
  11236. /**
  11237. * 确认供应商 — 二次发送邮件(可选单家/批量)
  11238. */
  11239. public function auditResendEmail()
  11240. {
  11241. if (!$this->request->isPost()) {
  11242. $this->error(__('Invalid parameters'));
  11243. }
  11244. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11245. if ($scydgyId === '') {
  11246. $this->error('参数无效');
  11247. }
  11248. $loaded = $this->loadAuditResendBundle($scydgyId);
  11249. $mergeRows = $loaded['merge_rows'];
  11250. $bundle = $loaded['bundle'];
  11251. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  11252. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11253. if ($quoteGroups === []) {
  11254. $this->error('暂无可通知的供应商');
  11255. }
  11256. $companiesJson = (string)$this->request->post('companies_json', '');
  11257. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  11258. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  11259. if ($companiesJson === '' && $selectedCompany === '') {
  11260. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  11261. }
  11262. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  11263. }
  11264. /**
  11265. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  11266. *
  11267. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  11268. * @return array<int, true> 已处理的 scydgy_id 集合
  11269. */
  11270. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  11271. {
  11272. $pos = $bundle['pos'] ?? [];
  11273. if (!is_array($pos) || $pos === []) {
  11274. return [];
  11275. }
  11276. $sids = [];
  11277. $poIdBySid = [];
  11278. foreach ($pos as $poRow) {
  11279. if (!is_array($poRow)) {
  11280. continue;
  11281. }
  11282. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11283. if ($this->isValidScydgyRowId($sid)) {
  11284. $sids[$sid] = true;
  11285. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11286. if ($poId > 0) {
  11287. $poIdBySid[$sid] = $poId;
  11288. }
  11289. }
  11290. }
  11291. if ($sids === []) {
  11292. return [];
  11293. }
  11294. $logMsg = '重新下发';
  11295. $suffix = trim((string)$logSuffix, ',, ');
  11296. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  11297. $logMsg .= ':从历史存证退回协助初选';
  11298. } else {
  11299. $logMsg .= ':退回协助初选';
  11300. }
  11301. Db::table('purchase_order')
  11302. ->where('scydgy_id', 'in', array_keys($sids))
  11303. ->update([
  11304. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  11305. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11306. 'pick_company_name' => '',
  11307. 'pick_time' => null,
  11308. 'sys_rq' => null,
  11309. 'mod_rq' => null,
  11310. ]);
  11311. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  11312. foreach (array_keys($sids) as $sid) {
  11313. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  11314. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11315. }
  11316. return $sids;
  11317. }
  11318. /**
  11319. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  11320. *
  11321. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  11322. */
  11323. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  11324. {
  11325. $scydgyId = trim($scydgyId);
  11326. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11327. if ($scydgyId === '') {
  11328. return $empty;
  11329. }
  11330. try {
  11331. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  11332. } catch (\Throwable $e) {
  11333. $anchor = null;
  11334. }
  11335. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  11336. return $empty;
  11337. }
  11338. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  11339. if ($ccydh === '') {
  11340. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  11341. }
  11342. try {
  11343. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  11344. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  11345. $pos = $query->order('scydgy_id', 'asc')->select();
  11346. } catch (\Throwable $e) {
  11347. $pos = [$anchor];
  11348. }
  11349. if (!is_array($pos) || $pos === []) {
  11350. $pos = [$anchor];
  11351. }
  11352. return [
  11353. 'ccydh' => $ccydh,
  11354. 'pos' => $pos,
  11355. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  11356. ];
  11357. }
  11358. protected function purchaseOrderRowIsCompleted(array $po): bool
  11359. {
  11360. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11361. }
  11362. /**
  11363. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  11364. *
  11365. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  11366. */
  11367. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  11368. {
  11369. $scydgyId = trim($scydgyId);
  11370. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11371. if ($scydgyId === '') {
  11372. return $empty;
  11373. }
  11374. try {
  11375. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  11376. } catch (\Throwable $e) {
  11377. $anchor = null;
  11378. }
  11379. if (!is_array($anchor)) {
  11380. return $empty;
  11381. }
  11382. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  11383. if ($ccydh === '') {
  11384. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  11385. }
  11386. try {
  11387. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  11388. } catch (\Throwable $e) {
  11389. $pos = [$anchor];
  11390. }
  11391. if (!is_array($pos) || $pos === []) {
  11392. $pos = [$anchor];
  11393. }
  11394. return [
  11395. 'ccydh' => $ccydh,
  11396. 'pos' => $pos,
  11397. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  11398. ];
  11399. }
  11400. /**
  11401. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  11402. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  11403. */
  11404. public function auditAbandon()
  11405. {
  11406. if (!$this->request->isPost()) {
  11407. $this->error(__('Invalid parameters'));
  11408. }
  11409. $anchorIds = [];
  11410. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  11411. if ($batchRaw !== '') {
  11412. $decoded = json_decode($batchRaw, true);
  11413. if (is_array($decoded)) {
  11414. foreach ($decoded as $id) {
  11415. $s = trim((string)$id);
  11416. if ($s !== '') {
  11417. $anchorIds[] = $s;
  11418. }
  11419. }
  11420. }
  11421. }
  11422. if ($anchorIds === []) {
  11423. $single = trim((string)$this->request->post('scydgy_id', ''));
  11424. if ($single !== '') {
  11425. $anchorIds[] = $single;
  11426. }
  11427. }
  11428. if ($anchorIds === []) {
  11429. $this->error('请至少选择一条订单');
  11430. }
  11431. $processedCcydh = [];
  11432. $doneOrders = 0;
  11433. $allSids = [];
  11434. Db::startTrans();
  11435. try {
  11436. foreach ($anchorIds as $anchorId) {
  11437. $fromArchive = false;
  11438. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  11439. if (($bundle['pos'] ?? []) === []) {
  11440. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  11441. $fromArchive = ($bundle['pos'] ?? []) !== [];
  11442. }
  11443. if (($bundle['pos'] ?? []) === []) {
  11444. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  11445. $fromArchive = ($bundle['pos'] ?? []) !== [];
  11446. }
  11447. if (($bundle['pos'] ?? []) === []) {
  11448. continue;
  11449. }
  11450. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11451. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  11452. if (isset($processedCcydh[$dedupeKey])) {
  11453. continue;
  11454. }
  11455. $processedCcydh[$dedupeKey] = true;
  11456. $sids = $fromArchive
  11457. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回协助初选')
  11458. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  11459. if ($sids === []) {
  11460. continue;
  11461. }
  11462. $doneOrders++;
  11463. foreach (array_keys($sids) as $sid) {
  11464. $allSids[(int)$sid] = true;
  11465. }
  11466. }
  11467. if ($doneOrders < 1) {
  11468. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  11469. }
  11470. Db::commit();
  11471. } catch (\Throwable $e) {
  11472. Db::rollback();
  11473. $this->error($e->getMessage());
  11474. }
  11475. $this->pickHiddenScydgySetCache = null;
  11476. $msg = $doneOrders > 1
  11477. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  11478. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  11479. $this->success($msg);
  11480. }
  11481. /**
  11482. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  11483. */
  11484. public function archiveAbandon()
  11485. {
  11486. return $this->auditAbandon();
  11487. }
  11488. /**
  11489. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  11490. */
  11491. public function purchaseApprovalReject()
  11492. {
  11493. if (!$this->request->isPost() || !$this->request->isAjax()) {
  11494. $this->error(__('Invalid parameters'));
  11495. }
  11496. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  11497. $this->error(__('You have no permission'));
  11498. }
  11499. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  11500. $decoded = json_decode($batchRaw, true);
  11501. if (!is_array($decoded) || $decoded === []) {
  11502. $this->error('提交数据无效');
  11503. }
  11504. $done = 0;
  11505. Db::startTrans();
  11506. try {
  11507. foreach ($decoded as $item) {
  11508. if (!is_array($item)) {
  11509. continue;
  11510. }
  11511. $sid = (int)($item['scydgy_id'] ?? 0);
  11512. if (!$this->isValidScydgyRowId($sid)) {
  11513. continue;
  11514. }
  11515. $this->runPurchaseApprovalRejectForSid($sid);
  11516. $done++;
  11517. }
  11518. if ($done < 1) {
  11519. throw new \Exception('所选订单均不在待审批状态');
  11520. }
  11521. Db::commit();
  11522. } catch (\Throwable $e) {
  11523. Db::rollback();
  11524. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  11525. }
  11526. $this->pickHiddenScydgySetCache = null;
  11527. $this->success('已驳回并退回「协助审批下发」');
  11528. }
  11529. /**
  11530. * @throws \Exception
  11531. */
  11532. protected function runPurchaseApprovalRejectForSid(int $sid): void
  11533. {
  11534. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  11535. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  11536. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  11537. $allIds = $this->purchaseOrderDetail($sid);
  11538. if ($allIds === []) {
  11539. throw new \Exception('未找到下发明细');
  11540. }
  11541. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11542. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  11543. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11544. 'pick_company_name' => '',
  11545. ]);
  11546. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  11547. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  11548. $poId = 0;
  11549. try {
  11550. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  11551. if (is_array($po)) {
  11552. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11553. }
  11554. } catch (\Throwable $e) {
  11555. }
  11556. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  11557. }
  11558. /**
  11559. * 审核弹窗(旧入口,POST 已关闭)
  11560. */
  11561. public function review()
  11562. {
  11563. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  11564. $this->error(__('You have no permission'));
  11565. }
  11566. if ($this->request->isPost()) {
  11567. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  11568. }
  11569. $this->view->assign('pickMode', 0);
  11570. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  11571. }
  11572. /**
  11573. * 审核弹窗获取公司列表
  11574. */
  11575. public function reviewCompanies()
  11576. {
  11577. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  11578. $this->error(__('You have no permission'));
  11579. }
  11580. if (!$this->request->isAjax()) {
  11581. $this->error(__('Invalid parameters'));
  11582. }
  11583. $list = [];
  11584. try {
  11585. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  11586. $rows = Db::table('customer')
  11587. ->where(function ($q) {
  11588. $q->where('status', 1)
  11589. ->whereOr('status', '1')
  11590. ->whereOr('status', '')
  11591. ->whereNull('status');
  11592. })
  11593. ->order('id', 'desc')
  11594. ->select();
  11595. } catch (\Throwable $e) {
  11596. $this->success('', '', []);
  11597. return;
  11598. }
  11599. if (!is_array($rows)) {
  11600. $this->success('', '', []);
  11601. return;
  11602. }
  11603. $detailColCandidates = [
  11604. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  11605. 'company_detail', 'company_desc', 'address',
  11606. ];
  11607. foreach ($rows as $row) {
  11608. if (!is_array($row)) {
  11609. continue;
  11610. }
  11611. $norm = [];
  11612. foreach ($row as $k => $v) {
  11613. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  11614. }
  11615. $row = $norm;
  11616. $st = $row['status'] ?? '';
  11617. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  11618. continue;
  11619. }
  11620. $payload = $this->buildCustomerContactPayloadFromRow($row);
  11621. if ($payload === null) {
  11622. continue;
  11623. }
  11624. $detail = '';
  11625. foreach ($detailColCandidates as $dk) {
  11626. if (!isset($row[$dk])) {
  11627. continue;
  11628. }
  11629. $dv = trim((string)$row[$dk]);
  11630. if ($dv !== '') {
  11631. $detail = $dv;
  11632. break;
  11633. }
  11634. }
  11635. $payload['detail'] = $detail;
  11636. $list[] = $this->maskSupplierContactFields($payload);
  11637. }
  11638. $this->success('', '', $list);
  11639. }
  11640. /**
  11641. * 采购确认-下发明细弹窗:
  11642. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  11643. */
  11644. public function outward_detail()
  11645. {
  11646. $ids = $this->request->param('ids', $this->request->param('id', ''));
  11647. if (is_array($ids)) {
  11648. $ids = isset($ids[0]) ? $ids[0] : '';
  11649. }
  11650. $ids = trim((string)$ids);
  11651. if ($ids === '') {
  11652. $this->error(__('Invalid parameters'));
  11653. }
  11654. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  11655. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  11656. $wffTab = 'all';
  11657. }
  11658. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  11659. $purchaseOrderId = 0;
  11660. $po = null;
  11661. try {
  11662. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  11663. if (is_array($po)) {
  11664. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11665. }
  11666. } catch (\Throwable $e) {
  11667. $purchaseOrderId = 0;
  11668. $po = null;
  11669. }
  11670. if (!$isPurchaseConfirm && is_array($po)) {
  11671. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11672. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  11673. $isPurchaseConfirm = true;
  11674. }
  11675. }
  11676. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  11677. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11678. $confirmProcessCount = 1;
  11679. $confirmPickGroups = [];
  11680. $processDisplayRows = [];
  11681. $allDetailsBySid = [];
  11682. $requiredSidList = [];
  11683. $sidList = [$ids];
  11684. if ($isPurchaseConfirm) {
  11685. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  11686. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  11687. if ($mergeRows !== []) {
  11688. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  11689. }
  11690. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  11691. if ($confirmBundle['pos'] !== []) {
  11692. $sidList = [];
  11693. foreach ($confirmBundle['pos'] as $poRow) {
  11694. if (!is_array($poRow)) {
  11695. continue;
  11696. }
  11697. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11698. if (!$this->isValidScydgyRowId($sid)) {
  11699. continue;
  11700. }
  11701. $sidList[] = (string)$sid;
  11702. $requiredSidList[] = $sid;
  11703. }
  11704. }
  11705. if ($sidList === []) {
  11706. $sidList = [$ids];
  11707. $requiredSidList = [(int)$ids];
  11708. }
  11709. $confirmProcessCount = max(1, count($requiredSidList));
  11710. if (is_array($po) && $purchaseOrderId <= 0) {
  11711. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11712. }
  11713. }
  11714. $rows = [];
  11715. try {
  11716. if (count($sidList) === 1) {
  11717. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  11718. } else {
  11719. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  11720. }
  11721. } catch (\Throwable $e) {
  11722. $rows = [];
  11723. }
  11724. if ($isPurchaseConfirm) {
  11725. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  11726. }
  11727. foreach ($rows as &$r) {
  11728. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  11729. $r['id'] = $r['ID'];
  11730. }
  11731. if (isset($r['createtime'])) {
  11732. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  11733. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  11734. } else {
  11735. $r['createtime_text'] = (string)$r['createtime'];
  11736. }
  11737. } else {
  11738. $r['createtime_text'] = '';
  11739. }
  11740. if (is_array($r)) {
  11741. $r = $this->maskSupplierContactFields($r);
  11742. }
  11743. }
  11744. unset($r);
  11745. $pickedCompanyName = '';
  11746. $manualPicked = 0;
  11747. $manualPickReason = '';
  11748. $quoteVisible = 0;
  11749. $bidOpenVerified = 0;
  11750. if ($isPurchaseConfirm) {
  11751. // 确认包为空时,用当前主单兜底,避免指定说明读不到
  11752. if (($confirmBundle['ccydh'] ?? '') === '' && is_array($po)) {
  11753. $confirmBundle['ccydh'] = trim((string)($po['CCYDH'] ?? ''));
  11754. }
  11755. if (($confirmBundle['pos'] ?? []) === [] && is_array($po)) {
  11756. $confirmBundle['pos'] = [$po];
  11757. }
  11758. $manualPickInfo = $this->resolveProcuremenManualPickInfo($confirmBundle);
  11759. $manualPicked = $this->isProcuremenManualPickedForBundle($confirmBundle) ? 1 : 0;
  11760. $manualPickReason = (string)($manualPickInfo['reason'] ?? '');
  11761. if ($manualPickInfo['company'] !== '') {
  11762. $pickedCompanyName = $manualPickInfo['company'];
  11763. }
  11764. if ($pickedCompanyName === '') {
  11765. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  11766. if (!is_array($poRow)) {
  11767. continue;
  11768. }
  11769. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  11770. if ($pn !== '') {
  11771. $pickedCompanyName = $pn;
  11772. break;
  11773. }
  11774. }
  11775. }
  11776. // 再兜底:直接读当前主单字段
  11777. if (is_array($po) && (int)($po['manual_pick'] ?? 0) === 1) {
  11778. $manualPicked = 1;
  11779. if ($manualPickReason === '') {
  11780. $manualPickReason = trim((string)($po['manual_pick_reason'] ?? ''));
  11781. }
  11782. if ($pickedCompanyName === '') {
  11783. $pickedCompanyName = trim((string)($po['pick_company_name'] ?? ''));
  11784. }
  11785. }
  11786. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle) ? 1 : 0;
  11787. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  11788. }
  11789. $this->view->assign('rows', $rows ?: []);
  11790. $this->view->assign('rowCount', count($rows ?: []));
  11791. $this->view->assign('scydgyId', $ids);
  11792. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  11793. $this->view->assign('headTitle', $headTitle);
  11794. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  11795. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  11796. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  11797. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  11798. $this->view->assign('processDisplayRows', $processDisplayRows);
  11799. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  11800. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  11801. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  11802. $this->view->assign('manualPicked', $manualPicked);
  11803. $this->view->assign('manualPickReason', $manualPickReason);
  11804. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  11805. $this->view->assign('quoteVisible', $quoteVisible);
  11806. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
  11807. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  11808. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
  11809. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
  11810. $sysRqDisplay = '—';
  11811. if ($isPurchaseConfirm) {
  11812. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  11813. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  11814. );
  11815. }
  11816. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  11817. $this->view->assign('sysRq', $isPurchaseConfirm
  11818. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  11819. : '');
  11820. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  11821. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  11822. : '');
  11823. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  11824. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  11825. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  11826. if ($isPurchaseConfirm) {
  11827. return $this->view->fetch();
  11828. }
  11829. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  11830. $this->view->engine->layout(false);
  11831. try {
  11832. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  11833. $this->view->assign('dialogBody', $bodyHtml);
  11834. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  11835. } finally {
  11836. if ($restoreLayout) {
  11837. $this->view->engine->layout($restoreLayout);
  11838. }
  11839. }
  11840. }
  11841. /**
  11842. * 月度导出记录表(不存在时自动创建)
  11843. */
  11844. protected function ensurePurchaseMonthExportLogTable(): void
  11845. {
  11846. try {
  11847. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  11848. } catch (\Throwable $e) {
  11849. Db::execute(
  11850. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  11851. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  11852. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  11853. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  11854. `admin_name` varchar(64) NOT NULL DEFAULT '',
  11855. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  11856. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  11857. `createtime` int(10) unsigned DEFAULT NULL,
  11858. PRIMARY KEY (`id`),
  11859. KEY `idx_ym` (`ym`),
  11860. KEY `idx_ct` (`createtime`)
  11861. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  11862. );
  11863. }
  11864. }
  11865. /**
  11866. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  11867. *
  11868. * @param array<int, mixed> $dbRows
  11869. * @return array<int, array<string, mixed>>
  11870. */
  11871. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  11872. {
  11873. $keyword = trim((string)$this->request->get('search', ''));
  11874. if ($keyword === '') {
  11875. $keyword = trim((string)$this->request->request('search', ''));
  11876. }
  11877. $filter = $this->request->get('filter', '');
  11878. $op = $this->request->get('op', '');
  11879. if (is_string($filter) && $filter !== '') {
  11880. $filterArr = (array)json_decode($filter, true);
  11881. } else {
  11882. $filterArr = is_array($filter) ? $filter : [];
  11883. }
  11884. if (is_string($op) && $op !== '') {
  11885. $opArr = (array)json_decode($op, true);
  11886. } else {
  11887. $opArr = is_array($op) ? $op : [];
  11888. }
  11889. if ($keyword === '' && $filterArr === []) {
  11890. return array_values(array_filter($dbRows, 'is_array'));
  11891. }
  11892. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  11893. $out = [];
  11894. foreach ($dbRows as $row) {
  11895. if (!is_array($row)) {
  11896. continue;
  11897. }
  11898. if ($keyword !== '') {
  11899. $hit = false;
  11900. foreach ($searchFields as $f) {
  11901. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  11902. $hit = true;
  11903. break;
  11904. }
  11905. }
  11906. if (!$hit) {
  11907. continue;
  11908. }
  11909. }
  11910. $passFilter = true;
  11911. foreach ($filterArr as $field => $val) {
  11912. $field = (string)$field;
  11913. $val = trim((string)$val);
  11914. if ($field === '' || $val === '') {
  11915. continue;
  11916. }
  11917. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  11918. continue;
  11919. }
  11920. $cell = (string)($row[$field] ?? '');
  11921. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  11922. if ($mode === '=' || $mode === 'EQUAL') {
  11923. if (strcasecmp($cell, $val) !== 0) {
  11924. $passFilter = false;
  11925. break;
  11926. }
  11927. } elseif (mb_stripos($cell, $val) === false) {
  11928. $passFilter = false;
  11929. break;
  11930. }
  11931. }
  11932. if (!$passFilter) {
  11933. continue;
  11934. }
  11935. $out[] = $row;
  11936. }
  11937. return $out;
  11938. }
  11939. /**
  11940. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  11941. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  11942. */
  11943. public function export_month_outward()
  11944. {
  11945. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  11946. $this->error(__('You have no permission'));
  11947. }
  11948. $bundle = $this->prepareMonthOutwardExportBundle();
  11949. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  11950. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  11951. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  11952. $spreadsheet = new Spreadsheet();
  11953. $sheet = $spreadsheet->getActiveSheet();
  11954. $sheet->setTitle('外协加工明细');
  11955. $mon = (int)substr($ym, 5, 2);
  11956. $sheet->mergeCells('A1:H1');
  11957. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  11958. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  11959. $sheet->getStyle('A1')->getAlignment()
  11960. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11961. ->setVertical(Alignment::VERTICAL_CENTER);
  11962. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  11963. $col = 'A';
  11964. foreach ($headers as $h) {
  11965. $sheet->setCellValue($col . '2', $h);
  11966. $col++;
  11967. }
  11968. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  11969. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11970. $rowNum = 3;
  11971. $sumSubtotalCounts = 0;
  11972. $grandAmount = 0.0;
  11973. $globalSeq = 0;
  11974. if ($groups === []) {
  11975. $sheet->mergeCells('A3:H3');
  11976. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  11977. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11978. $rowNum = 4;
  11979. } else {
  11980. foreach ($groups as $items) {
  11981. if ($items === []) {
  11982. continue;
  11983. }
  11984. $groupLineCount = count($items);
  11985. $subAmount = 0.0;
  11986. foreach ($items as $line) {
  11987. $globalSeq++;
  11988. $dr = $line['detail'];
  11989. $amt = $this->procuremenExportAmount($dr);
  11990. $subAmount += $amt;
  11991. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  11992. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  11993. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  11994. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  11995. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  11996. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  11997. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  11998. $sheet->setCellValue('H' . $rowNum, $amt);
  11999. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  12000. $rowNum++;
  12001. }
  12002. $sumSubtotalCounts += $groupLineCount;
  12003. $grandAmount += $subAmount;
  12004. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  12005. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  12006. $sheet->getStyle('G' . $rowNum)->getAlignment()
  12007. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  12008. ->setVertical(Alignment::VERTICAL_CENTER);
  12009. $rowNum++;
  12010. }
  12011. }
  12012. $sheet->setCellValue('A' . $rowNum, '总计');
  12013. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  12014. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  12015. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  12016. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  12017. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  12018. $lastRow = $rowNum;
  12019. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  12020. 'borders' => [
  12021. 'allBorders' => [
  12022. 'borderStyle' => Border::BORDER_THIN,
  12023. 'color' => ['rgb' => '000000'],
  12024. ],
  12025. ],
  12026. ]);
  12027. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  12028. if ($lastRow >= 3) {
  12029. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12030. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12031. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12032. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12033. }
  12034. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  12035. $sheet->getColumnDimension('A')->setWidth(7);
  12036. $sheet->getColumnDimension('B')->setWidth(16);
  12037. $sheet->getColumnDimension('C')->setWidth(52);
  12038. $sheet->getColumnDimension('D')->setWidth(32);
  12039. $sheet->getColumnDimension('E')->setWidth(12);
  12040. $sheet->getColumnDimension('F')->setWidth(44);
  12041. $sheet->getColumnDimension('G')->setWidth(26);
  12042. $sheet->getColumnDimension('H')->setWidth(13);
  12043. $sheet->getRowDimension(1)->setRowHeight(28);
  12044. $ymCompact = str_replace('-', '', $ym);
  12045. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  12046. $filename = $fileBase . '.xlsx';
  12047. try {
  12048. $this->ensurePurchaseMonthExportLogTable();
  12049. list($adminId, $adminName) = $this->GetUseName();
  12050. Db::table('purchase_month_export_log')->insert([
  12051. 'ym' => $ym,
  12052. 'admin_id' => (int)$adminId,
  12053. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  12054. 'row_count' => count($exportLines),
  12055. 'total_amount' => round($grandAmount, 2),
  12056. 'createtime' => time(),
  12057. ]);
  12058. } catch (\Throwable $e) {
  12059. Log::write('month export log: ' . $e->getMessage(), 'error');
  12060. }
  12061. if (ob_get_length()) {
  12062. ob_end_clean();
  12063. }
  12064. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  12065. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  12066. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  12067. header('Cache-Control: max-age=0');
  12068. $writer = new Xlsx($spreadsheet);
  12069. $writer->save('php://output');
  12070. $spreadsheet->disconnectWorksheets();
  12071. unset($spreadsheet);
  12072. exit;
  12073. }
  12074. /**
  12075. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  12076. */
  12077. public function export_month_quote()
  12078. {
  12079. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  12080. $this->error(__('You have no permission'));
  12081. }
  12082. $bundle = $this->prepareMonthOutwardExportBundle();
  12083. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  12084. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  12085. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  12086. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  12087. $spreadsheet = new Spreadsheet();
  12088. $sheet = $spreadsheet->getActiveSheet();
  12089. $sheet->setTitle('供应商报价明细');
  12090. $mon = (int)substr($ym, 5, 2);
  12091. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  12092. $sheet->getColumnDimension('A')->setWidth(7);
  12093. $sheet->getColumnDimension('B')->setWidth(16);
  12094. $sheet->getColumnDimension('C')->setWidth(52);
  12095. $sheet->getColumnDimension('D')->setWidth(26);
  12096. $sheet->getColumnDimension('E')->setWidth(32);
  12097. $sheet->getColumnDimension('F')->setWidth(12);
  12098. $sheet->getColumnDimension('G')->setWidth(14);
  12099. $sheet->getColumnDimension('H')->setWidth(12);
  12100. if ($quoteLastRow < 1) {
  12101. $quoteLastRow = 3;
  12102. }
  12103. $ymCompact = str_replace('-', '', $ym);
  12104. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  12105. if (ob_get_length()) {
  12106. ob_end_clean();
  12107. }
  12108. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  12109. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  12110. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  12111. header('Cache-Control: max-age=0');
  12112. $writer = new Xlsx($spreadsheet);
  12113. $writer->save('php://output');
  12114. $spreadsheet->disconnectWorksheets();
  12115. unset($spreadsheet);
  12116. exit;
  12117. }
  12118. /**
  12119. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  12120. *
  12121. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  12122. */
  12123. protected function prepareMonthOutwardExportBundle(): array
  12124. {
  12125. $this->request->filter(['strip_tags', 'trim']);
  12126. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  12127. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  12128. $ym = date('Y-m');
  12129. }
  12130. $dbRows = [];
  12131. try {
  12132. $query = Db::table('purchase_order');
  12133. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  12134. $dbRows = $query->select();
  12135. } catch (\Throwable $e) {
  12136. $dbRows = [];
  12137. }
  12138. if (!is_array($dbRows)) {
  12139. $dbRows = [];
  12140. }
  12141. $completeTsMap = [];
  12142. $sidList = [];
  12143. foreach ($dbRows as $dbRow) {
  12144. if (!is_array($dbRow)) {
  12145. continue;
  12146. }
  12147. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  12148. if ($sid > 0) {
  12149. $sidList[$sid] = true;
  12150. }
  12151. }
  12152. if ($sidList !== []) {
  12153. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  12154. }
  12155. // 导出始终按「查看月份」取当月完结单;搜索只在当月内再缩小(勿跨月,否则会与列表不一致)
  12156. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  12157. if (!is_array($dbRow)) {
  12158. return false;
  12159. }
  12160. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  12161. if ($done['ts'] <= 0) {
  12162. return false;
  12163. }
  12164. return date('Y-m', $done['ts']) === $ym;
  12165. }));
  12166. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  12167. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  12168. $mainBySid = [];
  12169. foreach ($pool as $rw) {
  12170. if (!is_array($rw)) {
  12171. continue;
  12172. }
  12173. $rid = (int)($rw['ID'] ?? 0);
  12174. if ($rid > 0) {
  12175. $mainBySid[$rid] = $rw;
  12176. }
  12177. }
  12178. if ($mainBySid === []) {
  12179. $detailRows = [];
  12180. } else {
  12181. try {
  12182. $detailRows = Db::table('purchase_order_detail')
  12183. ->where('scydgy_id', 'in', array_keys($mainBySid))
  12184. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  12185. ->order('status', 'desc')
  12186. ->order('CCYDH', 'asc')
  12187. ->order('company_name', 'asc')
  12188. ->order('id', 'asc')
  12189. ->select();
  12190. } catch (\Throwable $e) {
  12191. try {
  12192. $detailRows = Db::table('purchase_order_detail')
  12193. ->where('scydgy_id', 'in', array_keys($mainBySid))
  12194. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  12195. ->order('status', 'desc')
  12196. ->order('CCYDH', 'asc')
  12197. ->order('company_name', 'asc')
  12198. ->order('ID', 'asc')
  12199. ->select();
  12200. } catch (\Throwable $e2) {
  12201. $detailRows = [];
  12202. }
  12203. }
  12204. }
  12205. if (!is_array($detailRows)) {
  12206. $detailRows = [];
  12207. }
  12208. $exportLines = [];
  12209. $detailSidSeen = [];
  12210. foreach ($detailRows as $dr) {
  12211. if (!is_array($dr)) {
  12212. continue;
  12213. }
  12214. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12215. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  12216. continue;
  12217. }
  12218. if (isset($detailSidSeen[$sid])) {
  12219. continue;
  12220. }
  12221. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  12222. continue;
  12223. }
  12224. $detailSidSeen[$sid] = true;
  12225. $m = $mainBySid[$sid];
  12226. $exportLines[] = [
  12227. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12228. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12229. 'company_name' => (string)($dr['company_name'] ?? ''),
  12230. 'CDF' => (string)($m['CDF'] ?? ''),
  12231. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12232. 'gx' => $this->procuremenExportGxText($m),
  12233. 'detail' => $dr,
  12234. ];
  12235. }
  12236. foreach ($detailRows as $dr) {
  12237. if (!is_array($dr)) {
  12238. continue;
  12239. }
  12240. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12241. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  12242. continue;
  12243. }
  12244. $detailSidSeen[$sid] = true;
  12245. $m = $mainBySid[$sid];
  12246. $exportLines[] = [
  12247. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12248. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12249. 'company_name' => (string)($dr['company_name'] ?? ''),
  12250. 'CDF' => (string)($m['CDF'] ?? ''),
  12251. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12252. 'gx' => $this->procuremenExportGxText($m),
  12253. 'detail' => $dr,
  12254. ];
  12255. }
  12256. foreach ($mainBySid as $sid => $m) {
  12257. if (isset($detailSidSeen[$sid])) {
  12258. continue;
  12259. }
  12260. $company = trim((string)($m['pick_company_name'] ?? ''));
  12261. $exportLines[] = [
  12262. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  12263. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  12264. 'company_name' => $company,
  12265. 'CDF' => (string)($m['CDF'] ?? ''),
  12266. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12267. 'gx' => $this->procuremenExportGxText($m),
  12268. 'detail' => [],
  12269. ];
  12270. }
  12271. $groups = [];
  12272. foreach ($exportLines as $line) {
  12273. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  12274. if (!isset($groups[$k])) {
  12275. $groups[$k] = [];
  12276. }
  12277. $groups[$k][] = $line;
  12278. }
  12279. ksort($groups, SORT_STRING);
  12280. return [
  12281. 'ym' => $ym,
  12282. 'mainBySid' => $mainBySid,
  12283. 'detailRows' => $detailRows,
  12284. 'exportLines' => $exportLines,
  12285. 'groups' => $groups,
  12286. ];
  12287. }
  12288. /**
  12289. * 导出用:工序列文案
  12290. */
  12291. protected function procuremenExportGxText(array $r)
  12292. {
  12293. $a = trim((string)($r['CDXMC'] ?? ''));
  12294. $b = trim((string)($r['CGYMC'] ?? ''));
  12295. if ($a !== '' && $b !== '') {
  12296. return $a . ':' . $b;
  12297. }
  12298. return $a !== '' ? $a : $b;
  12299. }
  12300. /**
  12301. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  12302. */
  12303. protected function procuremenExportAmount(array $r)
  12304. {
  12305. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  12306. if (!array_key_exists($k, $r)) {
  12307. continue;
  12308. }
  12309. $v = $r[$k];
  12310. if ($v === null || $v === '') {
  12311. continue;
  12312. }
  12313. if (is_numeric($v)) {
  12314. return (float)$v;
  12315. }
  12316. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  12317. if ($v !== '' && is_numeric($v)) {
  12318. return (float)$v;
  12319. }
  12320. }
  12321. return 0.0;
  12322. }
  12323. /**
  12324. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  12325. *
  12326. * @param array<int, array<string, mixed>> $detailRows
  12327. * @param array<int, array<string, mixed>> $mainBySid
  12328. * @return array<int, array<string, mixed>>
  12329. */
  12330. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  12331. {
  12332. $lines = [];
  12333. foreach ($detailRows as $dr) {
  12334. if (!is_array($dr)) {
  12335. continue;
  12336. }
  12337. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12338. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  12339. continue;
  12340. }
  12341. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  12342. continue;
  12343. }
  12344. $cn = trim((string)($dr['company_name'] ?? ''));
  12345. if ($cn === '') {
  12346. continue;
  12347. }
  12348. $m = $mainBySid[$sid];
  12349. $am = trim((string)($dr['amount'] ?? ''));
  12350. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  12351. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  12352. $amountText = $amountFilled
  12353. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  12354. : '未填写';
  12355. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  12356. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  12357. if ($deliveryShow === '' && $deliveryRaw !== '') {
  12358. $deliveryShow = $deliveryRaw;
  12359. }
  12360. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  12361. ? $deliveryShow
  12362. : '未填写';
  12363. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  12364. $lines[] = [
  12365. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12366. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12367. 'gx' => $this->procuremenExportGxText($m),
  12368. 'company_name' => $cn,
  12369. 'amount_text' => $amountText,
  12370. 'amount_num' => $amountFilled ? $amountNum : null,
  12371. 'delivery_text' => $deliveryText,
  12372. 'picked_text' => $picked ? '中标' : '未中标',
  12373. 'picked' => $picked,
  12374. ];
  12375. }
  12376. $winnerSupplierByOrder = [];
  12377. foreach ($lines as $line) {
  12378. $dh = trim((string)($line['CCYDH'] ?? ''));
  12379. $cn = trim((string)($line['company_name'] ?? ''));
  12380. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  12381. $winnerSupplierByOrder[$dh][$cn] = true;
  12382. }
  12383. }
  12384. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  12385. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  12386. if ($c !== 0) {
  12387. return $c;
  12388. }
  12389. $dh = trim((string)($a['CCYDH'] ?? ''));
  12390. $aCn = trim((string)($a['company_name'] ?? ''));
  12391. $bCn = trim((string)($b['company_name'] ?? ''));
  12392. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  12393. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  12394. if ($aSupplierWin !== $bSupplierWin) {
  12395. return $aSupplierWin ? -1 : 1;
  12396. }
  12397. $c = strcmp($aCn, $bCn);
  12398. if ($c !== 0) {
  12399. return $c;
  12400. }
  12401. if (!empty($a['picked']) !== !empty($b['picked'])) {
  12402. return !empty($a['picked']) ? -1 : 1;
  12403. }
  12404. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  12405. if ($c !== 0) {
  12406. return $c;
  12407. }
  12408. return 0;
  12409. });
  12410. return $lines;
  12411. }
  12412. /**
  12413. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  12414. *
  12415. * @param array<int, array<string, mixed>> $quoteLines
  12416. */
  12417. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  12418. {
  12419. $mon = (int)substr($ym, 5, 2);
  12420. $titleRow = $startRow;
  12421. $headerRow = $startRow + 1;
  12422. $dataStartRow = $startRow + 2;
  12423. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  12424. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  12425. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  12426. $sheet->getStyle('A' . $titleRow)->getAlignment()
  12427. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12428. ->setVertical(Alignment::VERTICAL_CENTER);
  12429. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  12430. $col = 'A';
  12431. foreach ($headers as $h) {
  12432. $sheet->setCellValue($col . $headerRow, $h);
  12433. $col++;
  12434. }
  12435. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  12436. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12437. $rowNum = $dataStartRow;
  12438. if ($quoteLines === []) {
  12439. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  12440. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  12441. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12442. $rowNum = $dataStartRow + 1;
  12443. } else {
  12444. $i = 0;
  12445. foreach ($quoteLines as $line) {
  12446. $i++;
  12447. $sheet->setCellValue('A' . $rowNum, $i);
  12448. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  12449. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  12450. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  12451. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  12452. if ($line['amount_num'] !== null) {
  12453. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  12454. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  12455. } else {
  12456. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  12457. }
  12458. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  12459. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  12460. if (!empty($line['picked'])) {
  12461. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  12462. }
  12463. $rowNum++;
  12464. }
  12465. }
  12466. $lastRow = $rowNum - 1;
  12467. if ($lastRow >= $headerRow) {
  12468. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  12469. 'borders' => [
  12470. 'allBorders' => [
  12471. 'borderStyle' => Border::BORDER_THIN,
  12472. 'color' => ['rgb' => '000000'],
  12473. ],
  12474. ],
  12475. ]);
  12476. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  12477. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12478. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12479. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12480. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  12481. if ($lastRow >= $dataStartRow) {
  12482. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  12483. }
  12484. }
  12485. return $lastRow;
  12486. }
  12487. /**
  12488. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  12489. */
  12490. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  12491. {
  12492. if ($lastRow < $dataStartRow || $headerRow < 1) {
  12493. return;
  12494. }
  12495. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  12496. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12497. ->setVertical(Alignment::VERTICAL_CENTER);
  12498. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  12499. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12500. ->setVertical(Alignment::VERTICAL_CENTER);
  12501. if ($lastCol > 'B') {
  12502. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  12503. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  12504. ->setVertical(Alignment::VERTICAL_CENTER);
  12505. }
  12506. }
  12507. /**
  12508. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  12509. */
  12510. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  12511. {
  12512. $s = trim($ccydh);
  12513. if ($s === '') {
  12514. return 'ORDER';
  12515. }
  12516. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  12517. $s = trim($s, '._-');
  12518. if ($s === '') {
  12519. return 'ORDER';
  12520. }
  12521. if (function_exists('mb_substr')) {
  12522. return mb_substr($s, 0, 80, 'UTF-8');
  12523. }
  12524. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  12525. }
  12526. /**
  12527. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  12528. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  12529. *
  12530. * @return array{objectKey: string, webPath: string}
  12531. */
  12532. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  12533. {
  12534. $sid = (int)$scydgyId;
  12535. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  12536. $y = date('Y');
  12537. $m = date('m');
  12538. $d = date('d');
  12539. $basename = $safeOrder . '_' . $sid . '.pdf';
  12540. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  12541. return [
  12542. 'objectKey' => $objectKey,
  12543. 'webPath' => '/' . $objectKey,
  12544. ];
  12545. }
  12546. /**
  12547. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  12548. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  12549. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  12550. *
  12551. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  12552. */
  12553. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  12554. {
  12555. if (!$this->isValidScydgyRowId($scydgyId)) {
  12556. return '';
  12557. }
  12558. $ids = trim((string)$scydgyId);
  12559. $prep = $this->prepareProcuremenDetailsView($ids);
  12560. if (!$prep['ok']) {
  12561. return '';
  12562. }
  12563. $ccydh = $prep['ccydh'];
  12564. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  12565. $objectKey = $paths['objectKey'];
  12566. $webPath = $paths['webPath'];
  12567. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  12568. $this->view->assign([
  12569. 'pdf_export' => 1,
  12570. 'pdfMetaLine' => $meta,
  12571. ]);
  12572. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  12573. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  12574. $this->view->engine->layout(false);
  12575. try {
  12576. $html = $this->view->fetch('procuremen/details_pdf_shell');
  12577. } catch (\Throwable $e) {
  12578. if ($restoreLayout) {
  12579. $this->view->engine->layout($restoreLayout);
  12580. }
  12581. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  12582. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12583. return '';
  12584. }
  12585. if ($restoreLayout) {
  12586. $this->view->engine->layout($restoreLayout);
  12587. }
  12588. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12589. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  12590. if (!is_dir($tempDir)) {
  12591. @mkdir($tempDir, 0755, true);
  12592. }
  12593. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  12594. try {
  12595. $mpdf = new \Mpdf\Mpdf([
  12596. 'mode' => 'utf-8',
  12597. 'format' => 'A4',
  12598. 'margin_left' => 12,
  12599. 'margin_right' => 12,
  12600. 'margin_top' => 14,
  12601. 'margin_bottom' => 14,
  12602. 'tempDir' => $tempDir,
  12603. 'autoScriptToLang' => true,
  12604. 'autoLangToFont' => true,
  12605. ]);
  12606. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  12607. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  12608. $mpdf->SetBasePath('http://127.0.0.1/');
  12609. $mpdf->WriteHTML($html);
  12610. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  12611. } catch (\Throwable $e) {
  12612. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  12613. if (is_file($tempPdf)) {
  12614. @unlink($tempPdf);
  12615. }
  12616. return '';
  12617. }
  12618. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  12619. if ($ossUrl !== '') {
  12620. @unlink($tempPdf);
  12621. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12622. return $ossUrl;
  12623. }
  12624. $pi = pathinfo($objectKey);
  12625. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  12626. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  12627. if ($baseFile === '') {
  12628. @unlink($tempPdf);
  12629. return '';
  12630. }
  12631. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  12632. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  12633. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  12634. @unlink($tempPdf);
  12635. return '';
  12636. }
  12637. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  12638. if (!@copy($tempPdf, $fullPath)) {
  12639. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  12640. @unlink($tempPdf);
  12641. return '';
  12642. }
  12643. @unlink($tempPdf);
  12644. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12645. return $webPath;
  12646. }
  12647. /**
  12648. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  12649. */
  12650. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  12651. {
  12652. if ($scydgyId <= 0 || $webPath === '') {
  12653. return;
  12654. }
  12655. try {
  12656. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  12657. } catch (\Throwable $e) {
  12658. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  12659. }
  12660. }
  12661. /**
  12662. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  12663. *
  12664. * @param array<string, string> $vars
  12665. * @return array<string, string>
  12666. */
  12667. protected function normalizeSmsTemplateVars(array $vars): array
  12668. {
  12669. $out = [];
  12670. foreach ($vars as $k => $v) {
  12671. $out[(string)$k] = trim((string)$v);
  12672. }
  12673. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  12674. $out['contact_name'] = $out['company_name'];
  12675. }
  12676. return $out;
  12677. }
  12678. /**
  12679. * 按手机号或公司名称查 customer 表联系人姓名
  12680. */
  12681. protected function resolveCustomerContactName(string $phone, string $companyName): string
  12682. {
  12683. $phone = trim($phone);
  12684. $companyName = trim($companyName);
  12685. try {
  12686. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  12687. $row = Db::table('customer')
  12688. ->where(function ($q) use ($phone) {
  12689. $q->where('phone', $phone)->whereOr('account', $phone);
  12690. })
  12691. ->order('id', 'asc')
  12692. ->find();
  12693. if (is_array($row)) {
  12694. $nm = trim((string)($row['username'] ?? ''));
  12695. if ($nm !== '') {
  12696. return $nm;
  12697. }
  12698. }
  12699. }
  12700. if ($companyName !== '') {
  12701. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  12702. if (is_array($row)) {
  12703. return trim((string)($row['username'] ?? ''));
  12704. }
  12705. }
  12706. } catch (\Throwable $e) {
  12707. }
  12708. return '';
  12709. }
  12710. /**
  12711. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;;http(s) 链接做成可点的 &lt;a&gt;(微信 QQ 邮箱提醒纯文本 URL 常不可点)
  12712. */
  12713. protected function plainTextToHtmlEmailBody(string $text): string
  12714. {
  12715. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  12716. $parts = explode("\n", $text);
  12717. $out = [];
  12718. foreach ($parts as $line) {
  12719. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  12720. $out[] = $line;
  12721. } else {
  12722. $esc = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  12723. $esc = preg_replace(
  12724. '#(https?://[^\s<>"\']+)#iu',
  12725. '<a href="$1" style="color:#1565c0;text-decoration:underline;word-break:break-all;">$1</a>',
  12726. $esc
  12727. );
  12728. $out[] = $esc;
  12729. }
  12730. }
  12731. return implode("<br>\n", $out);
  12732. }
  12733. /**
  12734. * 短信场景:去掉链接类变量,避免误填 URL
  12735. *
  12736. * @param array<string, string> $vars
  12737. * @return array<string, string>
  12738. */
  12739. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  12740. {
  12741. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  12742. return $vars;
  12743. }
  12744. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  12745. $vars[$k] = '';
  12746. }
  12747. return $vars;
  12748. }
  12749. /**
  12750. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  12751. *
  12752. * @param array<string, string> $vars
  12753. */
  12754. protected function renderNotifyTemplate(string $scene, array $vars): string
  12755. {
  12756. $vars = $this->normalizeSmsTemplateVars($vars);
  12757. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  12758. $row = $this->loadNotifyTemplateRow($scene);
  12759. if ($row === null) {
  12760. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12761. }
  12762. $tpl = trim((string)($row['content'] ?? ''));
  12763. if ($tpl === '') {
  12764. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12765. }
  12766. foreach ($vars as $k => $v) {
  12767. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  12768. }
  12769. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  12770. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  12771. return $tpl;
  12772. }
  12773. protected function resolveProcuremenEmailSubject(string $scene): string
  12774. {
  12775. // 询价 / 采购确认结果邮箱:模版名称即邮件主题
  12776. if (in_array($scene, ['rfq_salesman_email', 'rfq_supplier_email', 'confirm_ok_email', 'confirm_fail_email'], true)) {
  12777. $row = $this->loadNotifyTemplateRow($scene);
  12778. $title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
  12779. if ($title !== '') {
  12780. return $title;
  12781. }
  12782. $fallback = [
  12783. 'rfq_supplier_email' => '供应商询价通知',
  12784. 'rfq_salesman_email' => '协助采购询价通知',
  12785. 'confirm_ok_email' => '采购确认结果:已通过',
  12786. 'confirm_fail_email' => '采购确认结果:未通过',
  12787. ];
  12788. return $fallback[$scene] ?? '协助采购通知';
  12789. }
  12790. $map = [
  12791. 'review_email' => '您有新的协助加工订单',
  12792. ];
  12793. $subject = trim((string)($map[$scene] ?? ''));
  12794. if ($subject === '') {
  12795. $this->error('未配置邮件主题:' . $scene);
  12796. }
  12797. return $subject;
  12798. }
  12799. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  12800. {
  12801. $map = [
  12802. 'review_email' => '协助下发-邮箱',
  12803. 'review_sms' => '协助下发-短信',
  12804. 'confirm_ok' => '采购确认-通过',
  12805. 'confirm_fail' => '采购确认-未通过',
  12806. 'confirm_ok_email' => '采购确认通过-邮箱',
  12807. 'confirm_fail_email' => '采购确认未通过-邮箱',
  12808. 'bid_open' => '开标双重验证',
  12809. 'rfq_salesman_email' => '询价通知业务员-邮箱',
  12810. 'rfq_supplier_email' => '供应商询价通知',
  12811. ];
  12812. $label = $map[$scene] ?? $scene;
  12813. if ($titleRequired) {
  12814. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  12815. }
  12816. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  12817. }
  12818. /**
  12819. * 是否开启协助通知演练(不发真实短信/邮件)
  12820. */
  12821. protected function isProcuremenNotifyDryRun(): bool
  12822. {
  12823. return (bool)Config::get('procuremen_notify_dry_run');
  12824. }
  12825. /**
  12826. * @param array<string, mixed> $payload
  12827. */
  12828. protected function recordNotifyDryRunPreview(array $payload): void
  12829. {
  12830. $this->notifyDryRunPreview[] = $payload;
  12831. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  12832. }
  12833. /**
  12834. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  12835. * @throws \Exception
  12836. */
  12837. protected function smsbao($phone, $content)
  12838. {
  12839. if ($this->isProcuremenNotifyDryRun()) {
  12840. $this->recordNotifyDryRunPreview([
  12841. 'scene' => 'sms_only',
  12842. 'phone' => $phone,
  12843. 'sms_content' => $content,
  12844. ]);
  12845. return;
  12846. }
  12847. $statusStr = [
  12848. '0' => '短信发送成功',
  12849. '-1' => '参数不全',
  12850. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  12851. '30' => '密码错误',
  12852. '40' => '账号不存在',
  12853. '41' => '余额不足',
  12854. '42' => '帐户已过期',
  12855. '43' => 'IP地址限制',
  12856. '50' => '内容含有敏感词',
  12857. ];
  12858. $smsapi = 'http://api.smsbao.com/';
  12859. $user = 'zhuwei123';
  12860. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  12861. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  12862. $result = @file_get_contents($sendurl);
  12863. if ($result === false) {
  12864. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  12865. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  12866. }
  12867. $result = trim((string)$result);
  12868. if ($result !== '0') {
  12869. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  12870. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  12871. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  12872. }
  12873. }
  12874. }