Procuremen.php 517 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\library\AliyunOss;
  5. use app\common\library\ProcuremenGuard;
  6. use app\common\library\ProcuremenOperLog;
  7. use app\common\library\ProcuremenSchema;
  8. use app\common\library\ProcuremenStatus;
  9. use app\common\library\ProcuremenSupplierScore;
  10. use app\common\library\ProcuremenTime;
  11. use PHPMailer\PHPMailer\PHPMailer;
  12. use think\Config;
  13. use think\Cache;
  14. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  15. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  16. use PhpOffice\PhpSpreadsheet\Style\Border;
  17. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  18. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  19. use think\Db;
  20. use think\Log;
  21. class Procuremen extends Backend
  22. {
  23. /**
  24. * 顶部快速搜索(多列 OR LIKE);字段须为真实列名且带别名 a/b,列不宜过多以免 SQL 异常
  25. */
  26. protected $searchFields = 'a.ID,b.CCYDH,b.CYJMC,b.CCLBMMC,a.CGYMC,a.CDW,b.czlyq,a.CDF,a.cGzzxMc,a.MBZ,b.cywyxm';
  27. /**
  28. * Procuremen模型对象
  29. * @var \app\admin\model\Procuremen
  30. */
  31. protected $model = null;
  32. /**
  33. * @var array<int, array<string, mixed>> 演练模式下收集的下发/短信预览(供接口返回)
  34. */
  35. protected $notifyDryRunPreview = [];
  36. /** @var array<int, array<string, mixed>>|null 单次请求内 Redis 列表缓存 */
  37. protected $procuremenRedisCache = null;
  38. /** @var array<int, true>|null 单次请求内下发隐藏工序 ID 缓存 */
  39. protected $pickHiddenScydgySetCache = null;
  40. /** 邮件发送日志表结构已就绪缓存键 */
  41. protected const EMAIL_SEND_LOG_SCHEMA_CACHE_KEY = 'purchase_email_send_log_schema_v1';
  42. /**
  43. * 采购子接口均走菜单规则鉴权;下列方法在方法内用 hasProcuremenPerm 做别名校验。
  44. * @var array
  45. */
  46. protected $noNeedRight = [
  47. 'pickreview', 'review', 'reviewcompanies',
  48. // 方法内用 hasProcuremenPerm 校验(兼容 auditsubmit / auditissue)
  49. 'auditmanualpick',
  50. // 与 rfqlist 同权,方法内校验
  51. 'rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqissuesuppliers', 'rfqissue', 'rfqissuesendmail', 'rfqquotes',
  52. 'rfqappendsuppliers', 'rfqsupplieroptions', 'rfqsalesmanoptions', 'rfqappendsalesmen',
  53. ];
  54. public function _initialize()
  55. {
  56. parent::_initialize();
  57. $this->model = new \app\admin\model\Procuremen;
  58. $this->maybeMigrateLegacyWflowStatusText();
  59. $this->assignProcuremenAuthConfig();
  60. try {
  61. ProcuremenSchema::ensureAll();
  62. } catch (\Throwable $e) {
  63. }
  64. if (!Cache::get(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY)) {
  65. $this->ensurePurchaseEmailSendLogTableOnce();
  66. }
  67. }
  68. /**
  69. * 将 purchase_order.wflow_status 旧数字值(0–3)一次性迁移为中文文案
  70. */
  71. protected function maybeMigrateLegacyWflowStatusText(): void
  72. {
  73. $flagFile = RUNTIME_PATH . 'procuremen_wflow_text_migrated.flag';
  74. if (is_file($flagFile)) {
  75. return;
  76. }
  77. $map = [
  78. '0' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  79. '1' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  80. '2' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  81. '3' => ProcuremenStatus::WFLOW_APPROVED,
  82. ];
  83. try {
  84. foreach ($map as $num => $text) {
  85. Db::table('purchase_order')
  86. ->whereRaw("TRIM(CAST(wflow_status AS CHAR)) = '" . str_replace("'", "''", $num) . "'")
  87. ->update(['wflow_status' => $text]);
  88. }
  89. @file_put_contents($flagFile, date('c'));
  90. } catch (\Throwable $e) {
  91. Log::write('migrate wflow_status text failed: ' . $e->getMessage(), 'error');
  92. }
  93. }
  94. /**
  95. * 是否拥有采购子权限(支持 procuremen/pickreview 与 procuremen/pickreview/index 等写法)
  96. *
  97. * @param string[] $actions 如 pickreview、procuremen/picksubmit
  98. */
  99. protected function hasProcuremenPerm(array $actions): bool
  100. {
  101. foreach ($actions as $action) {
  102. $action = strtolower(trim((string)$action));
  103. if ($action === '') {
  104. continue;
  105. }
  106. if (strpos($action, 'procuremen/') !== 0) {
  107. $action = 'procuremen/' . $action;
  108. }
  109. if ($this->auth->check($action)) {
  110. return true;
  111. }
  112. }
  113. $suffixes = [];
  114. foreach ($actions as $action) {
  115. $action = strtolower(trim((string)$action));
  116. $action = preg_replace('#^procuremen/#', '', $action);
  117. if ($action !== '') {
  118. $suffixes[$action] = true;
  119. }
  120. }
  121. if ($suffixes === []) {
  122. return false;
  123. }
  124. try {
  125. foreach ($this->auth->getRuleList() as $rule) {
  126. $rule = strtolower((string)$rule);
  127. if (strpos($rule, 'procuremen/') !== 0) {
  128. continue;
  129. }
  130. foreach (array_keys($suffixes) as $suffix) {
  131. if ($rule === 'procuremen/' . $suffix || strpos($rule, 'procuremen/' . $suffix . '/') === 0) {
  132. return true;
  133. }
  134. }
  135. }
  136. } catch (\Throwable $e) {
  137. }
  138. return false;
  139. }
  140. /**
  141. * 仅精确匹配规则名(删除/完结等敏感操作,避免模糊匹配误放行)
  142. *
  143. * @param string[] $actions
  144. */
  145. protected function hasProcuremenPermStrict(array $actions): bool
  146. {
  147. foreach ($actions as $action) {
  148. $action = strtolower(trim((string)$action));
  149. if ($action === '') {
  150. continue;
  151. }
  152. if (strpos($action, 'procuremen/') !== 0) {
  153. $action = 'procuremen/' . $action;
  154. }
  155. if ($this->auth->check($action)) {
  156. return true;
  157. }
  158. }
  159. return false;
  160. }
  161. /**
  162. * 当前角色已勾选的菜单规则中,是否包含指定标题(与「删除按钮」「完结按钮」等中文节点对应)
  163. *
  164. * @param string[] $titles
  165. */
  166. protected function authHasAssignedRuleTitle(array $titles): bool
  167. {
  168. $titles = array_values(array_filter(array_map('trim', $titles)));
  169. if ($titles === []) {
  170. return false;
  171. }
  172. try {
  173. $ids = $this->auth->getRuleIds();
  174. if (in_array('*', $ids, true)) {
  175. return true;
  176. }
  177. if ($ids === []) {
  178. return false;
  179. }
  180. $rows = Db::name('auth_rule')
  181. ->where('status', 'normal')
  182. ->whereIn('id', $ids)
  183. ->column('title');
  184. foreach ($rows as $title) {
  185. $t = trim((string)$title);
  186. if ($t !== '' && in_array($t, $titles, true)) {
  187. return true;
  188. }
  189. }
  190. } catch (\Throwable $e) {
  191. }
  192. return false;
  193. }
  194. protected function procuremenCanPickDelete(): bool
  195. {
  196. if ($this->hasProcuremenPermStrict(['pickdelete'])) {
  197. return true;
  198. }
  199. return $this->authHasAssignedRuleTitle(['删除按钮', '删除']);
  200. }
  201. protected function procuremenCanComplete(): bool
  202. {
  203. if ($this->hasProcuremenPermStrict(['completedirectly', 'completeDirectly'])) {
  204. return true;
  205. }
  206. return $this->authHasAssignedRuleTitle(['完结按钮', '完结']);
  207. }
  208. protected function procuremenCanDispatch(): bool
  209. {
  210. return $this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review']);
  211. }
  212. /**
  213. * 前端按钮显隐(Config.procuremenAuth)
  214. */
  215. protected function assignProcuremenAuthConfig(): void
  216. {
  217. $authMap = [
  218. 'pickreview' => $this->procuremenCanDispatch(),
  219. 'picksubmit' => $this->hasProcuremenPerm(['picksubmit', 'pickreview', 'review']),
  220. 'pickdelete' => $this->procuremenCanPickDelete(),
  221. 'completedirectly' => $this->procuremenCanComplete(),
  222. 'snapshottoprocure' => $this->hasProcuremenPerm(['snapshottoprocure', 'snapshotToProcure']),
  223. 'auditissue' => $this->hasProcuremenPerm(['auditissue']),
  224. 'auditsubmit' => $this->hasProcuremenPerm(['auditsubmit']),
  225. 'auditresendsms' => $this->hasProcuremenPerm(['auditresendsms']),
  226. 'auditresendemail' => $this->hasProcuremenPerm(['auditresendemail']),
  227. 'auditabandon' => $this->hasProcuremenPerm(['auditabandon']),
  228. 'outward_detail' => $this->hasProcuremenPerm(['outward_detail', 'outwarddetail']),
  229. 'purchaseconfirmpick' => $this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick']),
  230. 'purchaseapprovalreject' => $this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject']),
  231. 'details' => $this->hasProcuremenPerm(['details']),
  232. 'archiveabandon' => $this->hasProcuremenPerm(['archiveabandon', 'archiveAbandon', 'auditabandon', 'auditAbandon']),
  233. 'export_month_outward' => $this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward']),
  234. 'export_month_quote' => $this->hasProcuremenPerm(['export_month_quote', 'exportMonthQuote', 'export_month_outward', 'exportMonthOutward']),
  235. 'review' => $this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview']),
  236. 'bidopenusers' => $this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit']),
  237. 'bidopensendcode' => $this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit']),
  238. 'bidopenverify' => $this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit']),
  239. 'auditmanualpick' => $this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue']),
  240. 'reviewcompanies' => $this->hasProcuremenPerm(['reviewcompanies', 'reviewCompanies', 'pickreview', 'picksubmit', 'review']),
  241. 'add' => $this->hasProcuremenPerm(['add']),
  242. 'rfqlist' => $this->hasProcuremenPerm(['rfqlist']),
  243. // 查询询价三个操作按钮:各自独立,不再因有 rfqlist 就全部放开
  244. 'rfqissue' => $this->hasProcuremenPerm(['rfqissue']),
  245. 'rfqquotes' => $this->hasProcuremenPerm(['rfqquotes']),
  246. 'rfqnotifysalesman' => $this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen']),
  247. 'rfqnotifysalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman']),
  248. // 询价附属接口:有「询价」按钮权限即可(无需再单独勾选)
  249. 'rfqissuesuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers']),
  250. 'rfqissuesendmail' => $this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail']),
  251. 'rfqappendsuppliers' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers']),
  252. 'rfqsupplieroptions' => $this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions']),
  253. 'rfqsalesmanoptions' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen']),
  254. 'rfqappendsalesmen' => $this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen']),
  255. 'pickadd' => $this->hasProcuremenPerm(['pickadd', 'pickAdd']),
  256. ];
  257. $this->assignconfig('procuremenAuth', $authMap);
  258. }
  259. /**
  260. * 手机端协助明细首页直达链接(登录后打开对应明细,免搜索)
  261. * 配置 application/extra/mproc.php:mobile_base_url、mobile_index_path
  262. *
  263. * @param int $purchaseOrderDetailId purchase_order_detail 主键
  264. */
  265. protected function buildMprocMobileOrderUrl($purchaseOrderDetailId)
  266. {
  267. static $mprocCfgLoaded = false;
  268. if (!$mprocCfgLoaded) {
  269. $mprocCfgLoaded = true;
  270. if (is_file(APP_PATH . 'extra/mproc.php')) {
  271. Config::load(APP_PATH . 'extra/mproc.php', 'mproc');
  272. }
  273. }
  274. $eid = (int)$purchaseOrderDetailId;
  275. $base = $this->resolveMprocMobilePublicBaseUrl();
  276. if ($base === '') {
  277. throw new \Exception('无法生成手机端链接,请检查站点访问地址或 application/extra/mproc.php 中的 mobile_base_url');
  278. }
  279. $path = trim((string)Config::get('mproc.mobile_index_path'));
  280. if ($path === '') {
  281. $path = '/index.php/index/index/index';
  282. } else {
  283. $path = '/' . ltrim($path, '/');
  284. }
  285. // 邮件 HTML 中多参数链接常被邮箱客户端错误解析(&amp; 后参数丢失),仅保留 focus_eid 单参数 + hash 备份
  286. if ($eid > 0) {
  287. return $base . $path . '?focus_eid=' . $eid . '#mproc_fe=' . $eid;
  288. }
  289. return $base . $path . '?main_tab=orders';
  290. }
  291. /**
  292. * 邮件/短信外链:须为带点的公网域名
  293. */
  294. protected function procuremenOutboundBaseUrlLooksValid($baseUrl)
  295. {
  296. $u = trim((string)$baseUrl);
  297. if ($u === '' || !preg_match('#^https?://#i', $u)) {
  298. return false;
  299. }
  300. $host = parse_url($u, PHP_URL_HOST);
  301. if (!is_string($host) || $host === '') {
  302. return false;
  303. }
  304. if (strcasecmp($host, 'localhost') === 0) {
  305. return false;
  306. }
  307. if (preg_match('/^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/', $host)) {
  308. return false;
  309. }
  310. if (strpos($host, '.') === false) {
  311. return false;
  312. }
  313. return true;
  314. }
  315. /**
  316. * 解析用于协助邮件/短信的手机端站点根
  317. */
  318. protected function resolveMprocMobilePublicBaseUrl()
  319. {
  320. $candidates = [];
  321. $candidates[] = trim((string)Config::get('mproc.mobile_base_url'));
  322. $candidates[] = trim((string)Config::get('site.indexurl'));
  323. $cdn = trim((string)Config::get('site.cdnurl'));
  324. if ($cdn !== '' && preg_match('#^https?://#i', $cdn)) {
  325. $candidates[] = rtrim($cdn, '/');
  326. }
  327. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  328. $candidates[] = $reqBase;
  329. foreach ($candidates as $c) {
  330. if ($c === '') {
  331. continue;
  332. }
  333. $c = rtrim($c, '/');
  334. if ($this->procuremenOutboundBaseUrlLooksValid($c)) {
  335. return $c;
  336. }
  337. }
  338. // 本地联调:127.0.0.1、内网 IP、虚拟主机等无法用「公网域名」规则时,退回当前请求根地址
  339. $reqBase = rtrim($this->request->scheme() . '://' . $this->request->host(), '/');
  340. if ($reqBase !== '' && preg_match('#^https?://#i', $reqBase)) {
  341. return $reqBase;
  342. }
  343. Log::write('协助邮件手机链接:配置地址失效', 'warning');
  344. return '';
  345. }
  346. /**
  347. * 获取 Redis 中 procuremen_redis
  348. */
  349. protected function ProcuremenRedis(): array
  350. {
  351. if ($this->procuremenRedisCache !== null) {
  352. return $this->procuremenRedisCache;
  353. }
  354. try {
  355. $redis = redis();
  356. $raw = $redis->get('procuremen_redis');
  357. if ($raw === false || $raw === '') {
  358. $this->procuremenRedisCache = [];
  359. return $this->procuremenRedisCache;
  360. }
  361. $decoded = json_decode($raw, true);
  362. if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) {
  363. $this->procuremenRedisCache = [];
  364. return $this->procuremenRedisCache;
  365. }
  366. $this->procuremenRedisCache = $decoded['data'];
  367. // 整包已解码时顺带补齐侧栏小键,避免下次首屏再扫库
  368. if ($this->loadProcuremenSidebarYmList() === []) {
  369. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($this->procuremenRedisCache));
  370. }
  371. return $this->procuremenRedisCache;
  372. } catch (\Throwable $e) {
  373. $this->procuremenRedisCache = [];
  374. return $this->procuremenRedisCache;
  375. }
  376. }
  377. /**
  378. * 从 ERP 库拉取协助工序池(与 api/procuremen/getprocuremen 一致),并尽力写入 Redis
  379. *
  380. * @return array<int, array<string, mixed>>
  381. */
  382. protected function procuremenFetchErpPoolFromDb(): array
  383. {
  384. try {
  385. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  386. $endTime = date('Y-m-d 23:59:59');
  387. $list = Db::table('scydgy')
  388. ->alias('a')
  389. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  390. ->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, b.czlyq, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  391. ->where([
  392. 'a.bwjg' => 1,
  393. 'a.iEndBz' => 0,
  394. 'a.iType' => 0,
  395. 'a.iStatus' => 10,
  396. ])
  397. ->where('a.dStamp', '>=', $startTime)
  398. ->where('a.dStamp', '<=', $endTime)
  399. ->order('a.dStamp', 'desc')
  400. ->select();
  401. if (!is_array($list)) {
  402. return [];
  403. }
  404. try {
  405. $redis = redis();
  406. $payload = [
  407. 'code' => 200,
  408. 'msg' => 'success',
  409. 'data' => $list,
  410. ];
  411. $redis->set('procuremen_redis', json_encode($payload, JSON_UNESCAPED_UNICODE));
  412. $this->procuremenRedisCache = $list;
  413. $this->saveProcuremenSidebarYmList($this->extractYearMonthsFromPoolRows($list));
  414. $this->clearPickMonthPoolCaches();
  415. $this->warmPickMonthPoolCachesFromPool($list);
  416. } catch (\Throwable $e) {
  417. }
  418. return $list;
  419. } catch (\Throwable $e) {
  420. Log::write('协助列表拉取 ERP 数据失败:' . $e->getMessage(), 'error');
  421. return [];
  422. }
  423. }
  424. /**
  425. * Redis 为空时从库补一份缓存(同请求内只尝试一次)
  426. *
  427. * @return array<int, array<string, mixed>>
  428. */
  429. protected function procuremenEnsureRedisPool(): array
  430. {
  431. $pool = $this->ProcuremenRedis();
  432. if (is_array($pool) && $pool !== []) {
  433. return $pool;
  434. }
  435. static $warmed = false;
  436. if ($warmed) {
  437. return is_array($pool) ? $pool : [];
  438. }
  439. $warmed = true;
  440. return $this->procuremenFetchErpPoolFromDb();
  441. }
  442. /**
  443. * 从工序行提取年月(与列表筛选一致:dputrecord 优先,回退 dStamp 等)
  444. *
  445. * @param array<string, mixed> $row
  446. */
  447. protected function procuremenRowYearMonth(array $row, string $primary = 'dputrecord'): ?string
  448. {
  449. $t = $this->procuremenRowListSortTime($row, $primary);
  450. if ($t === '' || !preg_match('/^([12]\d{3})-(\d{1,2})/', $t, $m)) {
  451. return null;
  452. }
  453. $mo = (int)$m[2];
  454. if ($mo < 1 || $mo > 12) {
  455. return null;
  456. }
  457. return $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  458. }
  459. /**
  460. * @param array<int, array{year:string, months:array}> $sidebar
  461. * @return array<int, array{year:string, months:array}>
  462. */
  463. protected function ensureProcuremenSidebarHasYm(array $sidebar, string $ym): array
  464. {
  465. $ym = trim($ym);
  466. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  467. return $sidebar;
  468. }
  469. foreach ($sidebar as $block) {
  470. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  471. continue;
  472. }
  473. foreach ($block['months'] as $item) {
  474. if (is_array($item) && ($item['ym'] ?? '') === $ym) {
  475. return $sidebar;
  476. }
  477. }
  478. }
  479. $y = substr($ym, 0, 4);
  480. $mo = (int)substr($ym, 5, 2);
  481. $sidebar[] = [
  482. 'year' => $y,
  483. 'months' => [['ym' => $ym, 'label' => $mo . '月']],
  484. ];
  485. return $this->buildYearMonthSidebar($this->flattenProcuremenSidebarYms($sidebar));
  486. }
  487. /**
  488. * @param array<int, array{year:string, months:array}> $sidebar
  489. * @return string[]
  490. */
  491. protected function flattenProcuremenSidebarYms(array $sidebar): array
  492. {
  493. $yms = [];
  494. foreach ($sidebar as $block) {
  495. if (!is_array($block) || empty($block['months']) || !is_array($block['months'])) {
  496. continue;
  497. }
  498. foreach ($block['months'] as $item) {
  499. if (!is_array($item)) {
  500. continue;
  501. }
  502. $ym = trim((string)($item['ym'] ?? ''));
  503. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  504. $yms[$ym] = true;
  505. }
  506. }
  507. }
  508. return array_keys($yms);
  509. }
  510. /**
  511. * 左侧菜单(协助初选)
  512. * 优先 Redis 月份小键;为空时用轻量 DISTINCT 查库补齐(避免只显示空当月、漏掉有数据的月份)。
  513. */
  514. protected function GetIndexYearMonths()
  515. {
  516. $ymList = $this->ensureProcuremenPickSidebarYmList();
  517. if ($ymList === []) {
  518. $def = date('Y-m');
  519. $ymList = [preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m')];
  520. }
  521. return $this->buildYearMonthSidebar($ymList);
  522. }
  523. /**
  524. * 初选侧栏月份:以轻量 DISTINCT 查库为准(有数据才显示),并写回 Redis 小键。
  525. *
  526. * @return string[]
  527. */
  528. protected function ensureProcuremenPickSidebarYmList(bool $forceRefresh = false): array
  529. {
  530. static $memo = null;
  531. if (!$forceRefresh && is_array($memo)) {
  532. return $memo;
  533. }
  534. $fromDb = $this->queryProcuremenPickSidebarYmListLight();
  535. if ($fromDb !== []) {
  536. $this->saveProcuremenSidebarYmList($fromDb);
  537. $memo = $fromDb;
  538. return $memo;
  539. }
  540. // 库侧暂无初选数据时,再回退 Redis / 当月,避免侧栏空白
  541. $cached = $this->loadProcuremenSidebarYmList();
  542. if ($cached !== []) {
  543. $memo = $cached;
  544. return $memo;
  545. }
  546. $memo = [date('Y-m')];
  547. return $memo;
  548. }
  549. /**
  550. * @return string[] 形如 2026-07
  551. */
  552. protected function loadProcuremenSidebarYmList(): array
  553. {
  554. try {
  555. $raw = redis()->get('procuremen_redis_yms');
  556. if ($raw === false || $raw === null || $raw === '') {
  557. return [];
  558. }
  559. $decoded = json_decode((string)$raw, true);
  560. if (!is_array($decoded)) {
  561. return [];
  562. }
  563. $out = [];
  564. foreach ($decoded as $ym) {
  565. $ym = trim((string)$ym);
  566. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  567. $out[$ym] = true;
  568. }
  569. }
  570. return array_keys($out);
  571. } catch (\Throwable $e) {
  572. return [];
  573. }
  574. }
  575. /**
  576. * @param string[] $ymList
  577. */
  578. protected function saveProcuremenSidebarYmList(array $ymList): void
  579. {
  580. $out = [];
  581. foreach ($ymList as $ym) {
  582. $ym = trim((string)$ym);
  583. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  584. $out[$ym] = true;
  585. }
  586. }
  587. if ($out === []) {
  588. return;
  589. }
  590. try {
  591. redis()->set('procuremen_redis_yms', json_encode(array_keys($out), JSON_UNESCAPED_UNICODE));
  592. } catch (\Throwable $e) {
  593. }
  594. }
  595. /**
  596. * @param array<int, array<string, mixed>> $pool
  597. * @return string[]
  598. */
  599. protected function extractYearMonthsFromPoolRows(array $pool): array
  600. {
  601. $ymSet = [];
  602. foreach ($pool as $r) {
  603. if (!is_array($r)) {
  604. continue;
  605. }
  606. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  607. continue;
  608. }
  609. $ym = $this->procuremenRowYearMonth($r, 'dputrecord');
  610. if ($ym !== null) {
  611. $ymSet[$ym] = true;
  612. }
  613. }
  614. return array_keys($ymSet);
  615. }
  616. /**
  617. * 轻量查询初选侧栏月份(只取 DISTINCT 年月,不拉整包工序)
  618. *
  619. * @return string[]
  620. */
  621. protected function queryProcuremenPickSidebarYmListLight(): array
  622. {
  623. try {
  624. $startTime = date('Y-m-d 00:00:00', strtotime('-1 year'));
  625. $endTime = date('Y-m-d 23:59:59');
  626. $sql = 'SELECT DISTINCT DATE_FORMAT('
  627. . 'IF(b.dputrecord IS NOT NULL AND TRIM(CAST(b.dputrecord AS CHAR(32))) <> \'\''
  628. . ' AND TRIM(CAST(b.dputrecord AS CHAR(32))) NOT LIKE \'0000-00-00%\','
  629. . ' b.dputrecord, a.dStamp), \'%Y-%m\') AS ym'
  630. . ' FROM scydgy a'
  631. . ' INNER JOIN mcyd b ON b.ICYDID = a.ICYDID AND b.iStatus >= 10'
  632. . ' WHERE a.bwjg = 1 AND a.iEndBz = 0 AND a.iType = 0 AND a.iStatus = 10'
  633. . ' AND a.dStamp >= ? AND a.dStamp <= ?';
  634. $rows = Db::query($sql, [$startTime, $endTime]);
  635. if (!is_array($rows)) {
  636. return [];
  637. }
  638. $out = [];
  639. foreach ($rows as $r) {
  640. $ym = trim((string)($r['ym'] ?? ''));
  641. if (preg_match('/^\d{4}-\d{2}$/', $ym)) {
  642. $out[$ym] = true;
  643. }
  644. }
  645. return array_keys($out);
  646. } catch (\Throwable $e) {
  647. Log::write('初选侧栏月份轻量查询失败:' . $e->getMessage(), 'warning');
  648. return [];
  649. }
  650. }
  651. /**
  652. * @return string[] 含当月在内的近 N 个自然月
  653. */
  654. protected function buildRecentCalendarYmList(int $months = 12): array
  655. {
  656. $months = max(1, min(24, $months));
  657. $out = [];
  658. $base = strtotime(date('Y-m-01'));
  659. for ($i = 0; $i < $months; $i++) {
  660. $out[] = date('Y-m', strtotime('-' . $i . ' month', $base));
  661. }
  662. return $out;
  663. }
  664. /**
  665. * 初选按月工序池:优先月缓存;未命中则直接按月查 ERP。
  666. * 禁止为列表去解近一年整包 Redis(解包/连接异常会造成长时间转圈)。
  667. *
  668. * @return array<int, array<string, mixed>>
  669. */
  670. protected function loadPickPoolForYm(string $ym): array
  671. {
  672. $ym = trim($ym);
  673. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  674. return [];
  675. }
  676. $hit = $this->readPickMonthPoolCache($ym);
  677. if ($hit !== null) {
  678. return $hit;
  679. }
  680. return $this->queryPickPoolForYmFromDb($ym);
  681. }
  682. /**
  683. * @return array<int, array<string, mixed>>|null null=无有效缓存(含旧版空数组误缓存)
  684. */
  685. protected function readPickMonthPoolCache(string $ym): ?array
  686. {
  687. try {
  688. $raw = redis()->get('procuremen_pick_pool:' . $ym);
  689. if ($raw === false || $raw === null || $raw === '') {
  690. return null;
  691. }
  692. $decoded = json_decode((string)$raw, true);
  693. if (!is_array($decoded)) {
  694. return null;
  695. }
  696. // 新格式:{ok:1, rows:[...]},空月也算有效(已从整包确认)
  697. if (isset($decoded['ok']) && (int)$decoded['ok'] === 1 && isset($decoded['rows']) && is_array($decoded['rows'])) {
  698. return $decoded['rows'];
  699. }
  700. // 旧格式:仅非空行列表可命中;[] 多半是错误 SQL 写入,视为未命中
  701. if ($decoded === []) {
  702. try {
  703. redis()->del('procuremen_pick_pool:' . $ym);
  704. } catch (\Throwable $e) {
  705. }
  706. return null;
  707. }
  708. if (isset($decoded[0]) && is_array($decoded[0])) {
  709. return $decoded;
  710. }
  711. return null;
  712. } catch (\Throwable $e) {
  713. return null;
  714. }
  715. }
  716. /**
  717. * @param array<int, array<string, mixed>> $rows
  718. */
  719. protected function writePickMonthPoolCache(string $ym, array $rows): void
  720. {
  721. try {
  722. redis()->setex(
  723. 'procuremen_pick_pool:' . $ym,
  724. 600,
  725. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  726. );
  727. } catch (\Throwable $e) {
  728. }
  729. }
  730. /**
  731. * @param array<int, array<string, mixed>> $pool
  732. * @return array<int, array<string, mixed>>
  733. */
  734. protected function filterPoolRowsByYm(array $pool, string $ym): array
  735. {
  736. $out = [];
  737. foreach ($pool as $r) {
  738. if (!is_array($r)) {
  739. continue;
  740. }
  741. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  742. continue;
  743. }
  744. if ($this->procuremenRowYearMonth($r, 'dputrecord') === $ym) {
  745. $out[] = $r;
  746. }
  747. }
  748. return $out;
  749. }
  750. /**
  751. * 按 dStamp 取当月附近数据,再用列表规则(dputrecord 优先)精确到 ym
  752. *
  753. * @return array<int, array<string, mixed>>
  754. */
  755. protected function queryPickPoolForYmFromDb(string $ym): array
  756. {
  757. $monthStart = $ym . '-01 00:00:00';
  758. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  759. // 略放大窗口,避免 dStamp 与 dputrecord 跨月导致漏数;最终仍按 ym 精确过滤
  760. $queryStart = date('Y-m-d 00:00:00', strtotime($monthStart . ' -7 days'));
  761. $queryEnd = date('Y-m-d 23:59:59', strtotime($monthEnd . ' +7 days'));
  762. try {
  763. $list = Db::table('scydgy')
  764. ->alias('a')
  765. ->join('mcyd b', 'b.ICYDID = a.ICYDID AND b.iStatus >= 10', 'inner')
  766. ->field('a.ID, b.CCYDH, b.CYJMC, b.CCLBMMC, a.CDXMC, a.CGYBH, a.CGYMC, a.CDW, a.NGZL, b.CDF, a.cGzzxMc, a.MBZ, b.czlyq, a.bwjg, a.iStatus, a.dStamp, b.dputrecord, b.cywyxm')
  767. ->where([
  768. 'a.bwjg' => 1,
  769. 'a.iEndBz' => 0,
  770. 'a.iType' => 0,
  771. 'a.iStatus' => 10,
  772. ])
  773. ->where('a.dStamp', '>=', $queryStart)
  774. ->where('a.dStamp', '<=', $queryEnd)
  775. ->order('a.dStamp', 'desc')
  776. ->select();
  777. } catch (\Throwable $e) {
  778. Log::write('初选按月取数失败 ym=' . $ym . ':' . $e->getMessage(), 'error');
  779. return [];
  780. }
  781. if (!is_array($list)) {
  782. $list = [];
  783. }
  784. $out = $this->filterPoolRowsByYm($list, $ym);
  785. // 新格式缓存(含空月),避免重复打库;读侧只认 ok=1
  786. $this->writePickMonthPoolCache($ym, $out);
  787. try {
  788. $yms = $this->loadProcuremenSidebarYmList();
  789. if ($out !== [] && ($yms === [] || !in_array($ym, $yms, true))) {
  790. $yms[] = $ym;
  791. $this->saveProcuremenSidebarYmList($yms);
  792. }
  793. } catch (\Throwable $e) {
  794. }
  795. return $out;
  796. }
  797. /**
  798. * 整包写入后拆成按月小缓存,供初选列表秒开
  799. *
  800. * @param array<int, array<string, mixed>> $pool
  801. */
  802. protected function warmPickMonthPoolCachesFromPool(array $pool): void
  803. {
  804. if ($pool === []) {
  805. return;
  806. }
  807. $byYm = [];
  808. foreach ($pool as $r) {
  809. if (!is_array($r)) {
  810. continue;
  811. }
  812. if ($this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0))) {
  813. continue;
  814. }
  815. $rowYm = $this->procuremenRowYearMonth($r, 'dputrecord');
  816. if ($rowYm === null) {
  817. continue;
  818. }
  819. $byYm[$rowYm][] = $r;
  820. }
  821. if ($byYm === []) {
  822. return;
  823. }
  824. try {
  825. $redis = redis();
  826. foreach ($byYm as $rowYm => $rows) {
  827. $redis->setex(
  828. 'procuremen_pick_pool:' . $rowYm,
  829. 600,
  830. json_encode(['ok' => 1, 'rows' => $rows], JSON_UNESCAPED_UNICODE)
  831. );
  832. }
  833. try {
  834. $redis->del('procuremen_pick_hidden_scydgy_v1');
  835. } catch (\Throwable $e) {
  836. }
  837. } catch (\Throwable $e) {
  838. }
  839. }
  840. /**
  841. * 刷新整包后清理近月缓存,避免脏读
  842. */
  843. protected function clearPickMonthPoolCaches(int $months = 24): void
  844. {
  845. try {
  846. $redis = redis();
  847. foreach ($this->buildRecentCalendarYmList($months) as $ym) {
  848. try {
  849. $redis->del('procuremen_pick_pool:' . $ym);
  850. } catch (\Throwable $e) {
  851. }
  852. }
  853. } catch (\Throwable $e) {
  854. }
  855. $this->invalidatePickHiddenScydgyCache();
  856. }
  857. /**
  858. * 下发/完结后清隐藏集缓存,避免初选列表最多 90 秒仍显示已下发行
  859. */
  860. protected function invalidatePickHiddenScydgyCache(): void
  861. {
  862. $this->pickHiddenScydgySetCache = null;
  863. try {
  864. redis()->del('procuremen_pick_hidden_scydgy_v1');
  865. } catch (\Throwable $e) {
  866. }
  867. }
  868. /** 列表/首屏读完鉴权后尽早释放 session,避免多 iframe 串行卡死 */
  869. protected function procuremenReleaseSessionLock(): void
  870. {
  871. if (session_status() === PHP_SESSION_ACTIVE) {
  872. @session_write_close();
  873. }
  874. }
  875. /**
  876. * @param string[] $ymList 形如 2026-06
  877. * @return array<int, array{year:string, months:array}>
  878. */
  879. protected function buildYearMonthSidebar(array $ymList): array
  880. {
  881. rsort($ymList, SORT_STRING);
  882. $byYear = [];
  883. foreach ($ymList as $ym) {
  884. $y = substr($ym, 0, 4);
  885. $mo = (int)substr($ym, 5, 2);
  886. if (!isset($byYear[$y])) {
  887. $byYear[$y] = [];
  888. }
  889. $byYear[$y][] = ['ym' => $ym, 'label' => $mo . '月'];
  890. }
  891. krsort($byYear, SORT_NUMERIC);
  892. foreach ($byYear as $y => $items) {
  893. usort($byYear[$y], function ($a, $b) {
  894. return strcmp($b['ym'], $a['ym']);
  895. });
  896. }
  897. $sidebar = [];
  898. foreach ($byYear as $y => $months) {
  899. $sidebar[] = ['year' => $y, 'months' => $months];
  900. }
  901. return $sidebar;
  902. }
  903. /**
  904. * 已下发/审批/确认列表左侧月份:直接查 purchase_order,避免读整包 Redis
  905. */
  906. protected function GetIssuedOrderYearMonths(string $stage): array
  907. {
  908. $ymSet = [];
  909. try {
  910. $query = Db::table('purchase_order');
  911. $this->applyPurchaseOrderNotDeletedWhere($query);
  912. if ($stage === 'audit') {
  913. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  914. } elseif ($stage === 'confirm') {
  915. $this->applyPurchaseOrderConfirmStageWhere($query);
  916. } else {
  917. return $this->GetIndexYearMonths();
  918. }
  919. $rows = $query->field('pick_time,createtime,dputrecord,dStamp')->select();
  920. if (is_array($rows)) {
  921. foreach ($rows as $r) {
  922. if (!is_array($r)) {
  923. continue;
  924. }
  925. $ym = $this->procuremenRowYearMonth($this->normalizePurchaseOrderListTimeRow($r), 'pick_time');
  926. if ($ym !== null) {
  927. $ymSet[$ym] = true;
  928. }
  929. }
  930. }
  931. } catch (\Throwable $e) {
  932. $ymSet = [];
  933. }
  934. $ymList = array_keys($ymSet);
  935. if ($ymList === []) {
  936. $def = $this->resolveProcuremenDefaultYm($stage);
  937. $ymList[] = preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  938. }
  939. return $this->buildYearMonthSidebar($ymList);
  940. }
  941. /**
  942. * 列表默认月份:已下发类取最近有数据的月份;初选也取最近有数据月份(避免跨月后落到空当月)
  943. */
  944. protected function resolveProcuremenDefaultYm(string $stage): string
  945. {
  946. if ($stage === 'pick') {
  947. $yms = $this->ensureProcuremenPickSidebarYmList();
  948. if ($yms !== []) {
  949. rsort($yms, SORT_STRING);
  950. return $yms[0];
  951. }
  952. return date('Y-m');
  953. }
  954. try {
  955. $query = Db::table('purchase_order');
  956. $this->applyPurchaseOrderNotDeletedWhere($query);
  957. if ($stage === 'audit') {
  958. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  959. } elseif ($stage === 'confirm') {
  960. $this->applyPurchaseOrderConfirmStageWhere($query);
  961. } else {
  962. return date('Y-m');
  963. }
  964. $latest = $query->order('pick_time', 'desc')->order('id', 'desc')->value('pick_time');
  965. if ($latest === null || $latest === '') {
  966. $latest = $query->order('createtime', 'desc')->order('id', 'desc')->value('createtime');
  967. }
  968. $t = $this->formatProcuremenDetailTime($latest);
  969. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  970. return $m[1] . '-' . $m[2];
  971. }
  972. } catch (\Throwable $e) {
  973. }
  974. return date('Y-m');
  975. }
  976. protected function applyPurchaseOrderNotDeletedWhere($query): void
  977. {
  978. $query->whereRaw(
  979. '(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')'
  980. );
  981. }
  982. /**
  983. * 审批列表:wflow_status = 待审批(兼容旧值 2)
  984. */
  985. protected function applyPurchaseOrderConfirmStageWhere($query): void
  986. {
  987. $vals = ProcuremenStatus::wflowPendingApprovalValues();
  988. $quoted = [];
  989. foreach ($vals as $v) {
  990. $quoted[] = "'" . str_replace("'", "''", (string)$v) . "'";
  991. }
  992. if ($quoted === []) {
  993. $query->whereRaw('1 = 0');
  994. return;
  995. }
  996. $query->whereRaw('TRIM(CAST(wflow_status AS CHAR)) IN (' . implode(',', $quoted) . ')');
  997. $query->whereRaw('NOT (' . ProcuremenStatus::sqlPoCompleted('status') . ')');
  998. }
  999. /**
  1000. * 列表月份提取前补齐 pick_time(与 buildListRowFromPurchaseOrderDbRow 回退一致)
  1001. *
  1002. * @param array<string, mixed> $row
  1003. * @return array<string, mixed>
  1004. */
  1005. protected function normalizePurchaseOrderListTimeRow(array $row): array
  1006. {
  1007. $row['createtime'] = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  1008. $pick = trim((string)($row['pick_time'] ?? ''));
  1009. if ($pick === '' || stripos($pick, '0000-00-00') === 0) {
  1010. foreach (['createtime', 'dputrecord', 'dStamp'] as $key) {
  1011. $t = trim((string)($row[$key] ?? ''));
  1012. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  1013. $row['pick_time'] = $t;
  1014. break;
  1015. }
  1016. }
  1017. }
  1018. return $row;
  1019. }
  1020. /**
  1021. * 确认/审批列表:请求月份无数据时回退到最近有数据的月份(避免侧栏仍显示旧年月导致空表)
  1022. */
  1023. protected function resolveProcuremenActiveYm(string $stage, string $requestedYm, array $pool, string $listTimePrimary): string
  1024. {
  1025. if (!in_array($stage, ['audit', 'confirm'], true)) {
  1026. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1027. }
  1028. if ($pool === []) {
  1029. $def = $this->resolveProcuremenDefaultYm($stage);
  1030. return preg_match('/^\d{4}-\d{2}$/', $def) ? $def : date('Y-m');
  1031. }
  1032. $tryYm = function (string $ym) use ($pool, $listTimePrimary): bool {
  1033. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1034. return false;
  1035. }
  1036. $monthStart = $ym . '-01 00:00:00';
  1037. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1038. $probe = $this->filterProcuremenIndexPool($pool, $monthStart, $monthEnd, true, '', [], [], $listTimePrimary);
  1039. return $probe !== [];
  1040. };
  1041. if ($tryYm($requestedYm)) {
  1042. return $requestedYm;
  1043. }
  1044. $fallback = $this->resolveProcuremenDefaultYm($stage);
  1045. if ($tryYm($fallback)) {
  1046. return $fallback;
  1047. }
  1048. $bestYm = '';
  1049. $bestTime = '';
  1050. foreach ($pool as $row) {
  1051. if (!is_array($row)) {
  1052. continue;
  1053. }
  1054. $t = $this->procuremenRowListSortTime($row, $listTimePrimary);
  1055. if ($t === '' || !preg_match('/^(\d{4}-\d{2})/', $t, $m)) {
  1056. continue;
  1057. }
  1058. $ymRow = $m[1];
  1059. if ($bestTime === '' || strcmp($t, $bestTime) > 0) {
  1060. $bestTime = $t;
  1061. $bestYm = $ymRow;
  1062. }
  1063. }
  1064. if ($bestYm !== '') {
  1065. return $bestYm;
  1066. }
  1067. return preg_match('/^\d{4}-\d{2}$/', $requestedYm) ? $requestedYm : date('Y-m');
  1068. }
  1069. protected function isPurchaseOrderDetailVoid(array $row): bool
  1070. {
  1071. if (ProcuremenStatus::isPodVoid($row['status'] ?? '')) {
  1072. return true;
  1073. }
  1074. return trim((string)($row['status_name'] ?? '')) === ProcuremenStatus::POD_VOID;
  1075. }
  1076. /**
  1077. * 仅当前有效下发明细(排除废弃归档)
  1078. */
  1079. protected function applyActivePurchaseOrderDetailWhere($query): void
  1080. {
  1081. $query->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1082. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . ProcuremenStatus::POD_VOID . '\')');
  1083. }
  1084. /**
  1085. * @param array<string, mixed> $detailRow
  1086. */
  1087. protected function isActivePurchaseOrderDetailRow(array $detailRow): bool
  1088. {
  1089. if (ProcuremenStatus::isPodVoid($detailRow['status'] ?? '')) {
  1090. return false;
  1091. }
  1092. $statusName = trim((string)($detailRow['status_name'] ?? ''));
  1093. return $statusName === '' || $statusName !== ProcuremenStatus::POD_VOID;
  1094. }
  1095. /**
  1096. * 废弃退回初选:下发明细标记归档,不物理删除
  1097. *
  1098. * @param array<int, int|string> $scydgyIds
  1099. */
  1100. protected function voidPurchaseOrderDetailsForScydgyIds(array $scydgyIds): void
  1101. {
  1102. $ids = [];
  1103. foreach ($scydgyIds as $sid) {
  1104. $n = (int)$sid;
  1105. if ($this->isValidScydgyRowId($n) || $n < 0) {
  1106. $ids[$n] = true;
  1107. }
  1108. }
  1109. if ($ids === []) {
  1110. return;
  1111. }
  1112. $void = ProcuremenStatus::POD_VOID;
  1113. Db::table('purchase_order_detail')
  1114. ->where('scydgy_id', 'in', array_keys($ids))
  1115. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  1116. ->whereRaw('(status_name IS NULL OR TRIM(status_name) = \'\' OR status_name <> \'' . $void . '\')')
  1117. ->update([
  1118. 'status' => $void,
  1119. 'status_name' => $void,
  1120. ]);
  1121. }
  1122. /**
  1123. * 列表月份/排序用时间 SQL 表达式(与 procuremenRowListSortTime 字段优先级一致)
  1124. */
  1125. protected function procuremenListTimeSqlExpr(string $primary = 'pick_time', string $alias = ''): string
  1126. {
  1127. $p = $alias !== '' ? rtrim($alias, '.') . '.' : '';
  1128. $norm = function (string $col) use ($p): string {
  1129. return "NULLIF(NULLIF(TRIM(CAST({$p}{$col} AS CHAR(32))), ''), '0000-00-00')";
  1130. };
  1131. $createtime = "IF({$p}createtime > 946684800, FROM_UNIXTIME({$p}createtime), {$norm('createtime')})";
  1132. $parts = [];
  1133. foreach (array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp'])) as $key) {
  1134. if ($key === 'createtime') {
  1135. $parts[] = $createtime;
  1136. } else {
  1137. $parts[] = $norm($key);
  1138. }
  1139. }
  1140. return 'COALESCE(' . implode(', ', $parts) . ')';
  1141. }
  1142. protected function applyProcuremenMonthRangeWhere($query, string $monthStart, string $monthEnd, string $primary = 'pick_time', string $alias = ''): void
  1143. {
  1144. $expr = $this->procuremenListTimeSqlExpr($primary, $alias);
  1145. $query->whereRaw("({$expr}) >= ? AND ({$expr}) <= ?", [$monthStart, $monthEnd]);
  1146. }
  1147. /**
  1148. * @return array<int, array<string, mixed>>
  1149. */
  1150. protected function loadPurchaseOrderRowsForListStage(string $stage, string $ym = '', bool $applyMonthRange = false): array
  1151. {
  1152. $this->ensurePurchaseOrderCzlyqColumn();
  1153. $fields = 'id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1154. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name';
  1155. try {
  1156. $query = Db::table('purchase_order')->field($fields);
  1157. $this->applyPurchaseOrderNotDeletedWhere($query);
  1158. if ($stage === 'audit') {
  1159. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1160. } elseif ($stage === 'confirm') {
  1161. $this->applyPurchaseOrderConfirmStageWhere($query);
  1162. } else {
  1163. return [];
  1164. }
  1165. $query->order('pick_time', 'desc')->order('id', 'desc');
  1166. if ($applyMonthRange && preg_match('/^\d{4}-\d{2}$/', $ym) && $stage === 'pick') {
  1167. $monthStart = $ym . '-01 00:00:00';
  1168. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1169. $this->applyProcuremenMonthRangeWhere($query, $monthStart, $monthEnd, 'pick_time');
  1170. }
  1171. $rows = $query->select();
  1172. } catch (\Throwable $e) {
  1173. Log::write('协助列表 loadPurchaseOrderRowsForListStage(' . $stage . ') 异常:' . $e->getMessage(), 'error');
  1174. $rows = [];
  1175. }
  1176. return is_array($rows) ? $rows : [];
  1177. }
  1178. /**
  1179. * 列表阶段:pick=下发(通知) audit=确认供应商 confirm=采购确认
  1180. */
  1181. protected function resolveProcuremenListStage(): string
  1182. {
  1183. $tab = trim((string)$this->request->request('wff_tab', ''));
  1184. if (in_array($tab, ['pick', 'audit', 'confirm'], true)) {
  1185. return $tab;
  1186. }
  1187. $action = strtolower((string)$this->request->action());
  1188. if (in_array($action, ['pick', 'audit', 'confirm'], true)) {
  1189. return $action;
  1190. }
  1191. return 'pick';
  1192. }
  1193. protected function assignProcuremenListPage(string $stage, string $pageTitle): void
  1194. {
  1195. $this->procuremenReleaseSessionLock();
  1196. $rootTrue = rtrim((string)$this->request->root(true), '/');
  1197. $indexPhpRoot = preg_replace('#/[^/]+\.php$#i', '/index.php', $rootTrue);
  1198. if ($indexPhpRoot === $rootTrue && !preg_match('#/index\.php$#i', $rootTrue)) {
  1199. $indexPhpRoot = $rootTrue . '/index.php';
  1200. }
  1201. $this->view->assign('procuremenRedisApi', $indexPhpRoot . '/api/procuremen/getprocuremen');
  1202. $defaultYm = $this->resolveProcuremenDefaultYm($stage);
  1203. $sidebar = $stage === 'pick' ? $this->GetIndexYearMonths() : $this->GetIssuedOrderYearMonths($stage);
  1204. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  1205. $this->view->assign('defaultYm', $defaultYm);
  1206. $this->view->assign('sidebarYearMonths', $sidebar);
  1207. $this->view->assign('procuremenStage', $stage);
  1208. $this->view->assign('procuremenPageTitle', $pageTitle);
  1209. $this->view->assign('procuremenBtnDispatch', $this->procuremenCanDispatch());
  1210. $this->view->assign('procuremenBtnPickDelete', $this->procuremenCanPickDelete());
  1211. $this->view->assign('procuremenBtnComplete', $this->procuremenCanComplete());
  1212. $this->view->assign('procuremenBtnAuditAbandon', $this->hasProcuremenPerm(['auditabandon']));
  1213. $this->assignconfig('procuremenFilterOptions', $this->buildProcuremenFilterOptions($stage));
  1214. }
  1215. /**
  1216. * 通用搜索 / 表头筛选下拉选项(轻量:禁止首屏全表扫描)
  1217. *
  1218. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1219. */
  1220. protected function buildProcuremenFilterOptions(string $stage): array
  1221. {
  1222. $buckets = [
  1223. 'czlyq' => [],
  1224. 'CCLBMMC' => [],
  1225. 'cywyxm' => [],
  1226. 'CGYMC' => [],
  1227. ];
  1228. $maxPerField = 300;
  1229. try {
  1230. if ($stage === 'pick') {
  1231. // 首屏不读 Redis(整包解析会卡白屏);筛选项由列表 AJAX 的 filterOptions 带回
  1232. return $buckets;
  1233. }
  1234. if (in_array($stage, ['audit', 'confirm'], true)) {
  1235. $this->ensurePurchaseOrderCzlyqColumn();
  1236. foreach (array_keys($buckets) as $field) {
  1237. try {
  1238. $query = Db::table('purchase_order')->field($field);
  1239. $this->applyPurchaseOrderNotDeletedWhere($query);
  1240. if ($stage === 'audit') {
  1241. $query->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues());
  1242. } else {
  1243. $this->applyPurchaseOrderConfirmStageWhere($query);
  1244. }
  1245. $query->where($field, '<>', '')->whereNotNull($field);
  1246. $vals = $query->distinct(true)->limit($maxPerField)->column($field);
  1247. if (!is_array($vals)) {
  1248. continue;
  1249. }
  1250. foreach ($vals as $v) {
  1251. $v = trim((string)$v);
  1252. if ($v !== '') {
  1253. $buckets[$field][$v] = $v;
  1254. }
  1255. }
  1256. } catch (\Throwable $e) {
  1257. // 单字段失败不影响其它
  1258. }
  1259. }
  1260. }
  1261. } catch (\Throwable $e) {
  1262. Log::write('协助列表筛选项构建失败:' . $e->getMessage(), 'error');
  1263. }
  1264. foreach ($buckets as &$set) {
  1265. if ($set !== []) {
  1266. ksort($set, SORT_STRING);
  1267. }
  1268. }
  1269. unset($set);
  1270. return $buckets;
  1271. }
  1272. /**
  1273. * filter JSON 是否含有效条件
  1274. *
  1275. * @param array<string, mixed> $filterArr
  1276. */
  1277. protected function procuremenFilterArrHasValue(array $filterArr): bool
  1278. {
  1279. foreach ($filterArr as $v) {
  1280. if (is_array($v)) {
  1281. if (array_filter($v, function ($x) {
  1282. return $x !== '' && $x !== null;
  1283. })) {
  1284. return true;
  1285. }
  1286. } elseif ($v !== '' && $v !== null) {
  1287. return true;
  1288. }
  1289. }
  1290. return false;
  1291. }
  1292. /**
  1293. * 是否按左侧月份缩窗:顶部搜索 / LIKE·RANGE 跨月;表头等值筛选仍按月
  1294. *
  1295. * @param array<string, mixed> $filterArr
  1296. * @param array<string, mixed> $opArr
  1297. */
  1298. protected function procuremenShouldApplyMonthRange(string $search, array $filterArr, array $opArr): bool
  1299. {
  1300. if ($search !== '') {
  1301. return false;
  1302. }
  1303. foreach ($filterArr as $fk => $fv) {
  1304. if (is_array($fv)) {
  1305. continue;
  1306. }
  1307. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  1308. continue;
  1309. }
  1310. if ($fv === null) {
  1311. continue;
  1312. }
  1313. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  1314. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  1315. if ($sym === '' || $sym === '=') {
  1316. continue;
  1317. }
  1318. return false;
  1319. }
  1320. return true;
  1321. }
  1322. /**
  1323. * 从已加载的列表池抽取筛选项(供 AJAX 列表响应带回,避免首屏重复扫库)
  1324. *
  1325. * @param array<int, mixed> $rows
  1326. * @return array{czlyq:array<string,string>,CCLBMMC:array<string,string>,cywyxm:array<string,string>,CGYMC:array<string,string>}
  1327. */
  1328. protected function extractProcuremenFilterOptionsFromRows(array $rows, int $maxPerField = 300): array
  1329. {
  1330. $buckets = [
  1331. 'czlyq' => [],
  1332. 'CCLBMMC' => [],
  1333. 'cywyxm' => [],
  1334. 'CGYMC' => [],
  1335. ];
  1336. foreach ($rows as $r) {
  1337. if (!is_array($r)) {
  1338. continue;
  1339. }
  1340. foreach ($buckets as $field => &$set) {
  1341. if (count($set) >= $maxPerField) {
  1342. continue;
  1343. }
  1344. $v = trim((string)($r[$field] ?? ''));
  1345. if ($v !== '') {
  1346. $set[$v] = $v;
  1347. }
  1348. }
  1349. unset($set);
  1350. $full = true;
  1351. foreach ($buckets as $set) {
  1352. if (count($set) < $maxPerField) {
  1353. $full = false;
  1354. break;
  1355. }
  1356. }
  1357. if ($full) {
  1358. break;
  1359. }
  1360. }
  1361. foreach ($buckets as &$set) {
  1362. if ($set !== []) {
  1363. // 保证 json 编码为对象(避免 list 下标 0,1,2… 被前端当选项)
  1364. $normalized = [];
  1365. foreach ($set as $k => $v) {
  1366. $s = trim((string)(is_scalar($v) ? $v : $k));
  1367. if ($s === '') {
  1368. continue;
  1369. }
  1370. $normalized[$s] = $s;
  1371. }
  1372. ksort($normalized, SORT_STRING);
  1373. $set = $normalized;
  1374. }
  1375. }
  1376. unset($set);
  1377. return $buckets;
  1378. }
  1379. /** 协助下发(选工序+供应商,发短信邮件通知报价) */
  1380. public function pick()
  1381. {
  1382. $this->request->filter(['strip_tags', 'trim']);
  1383. if (!$this->request->isAjax()) {
  1384. $this->assignProcuremenListPage('pick', '协助下发');
  1385. return $this->view->fetch('procuremen/index');
  1386. }
  1387. return $this->index();
  1388. }
  1389. /** 确认供应商(下发通知后,从报价中选定一家,进入采购确认) */
  1390. public function audit()
  1391. {
  1392. $this->request->filter(['strip_tags', 'trim']);
  1393. if (!$this->request->isAjax()) {
  1394. $this->assignProcuremenListPage('audit', '确认供应商');
  1395. return $this->view->fetch('procuremen/index');
  1396. }
  1397. return $this->index();
  1398. }
  1399. /** 采购确认(定标) */
  1400. public function confirm()
  1401. {
  1402. $this->request->filter(['strip_tags', 'trim']);
  1403. if (!$this->request->isAjax()) {
  1404. $this->assignProcuremenListPage('confirm', '采购确认');
  1405. return $this->view->fetch('procuremen/index');
  1406. }
  1407. return $this->index();
  1408. }
  1409. /**
  1410. * 列表页(兼容旧菜单 procuremen/index,等同协助下发)
  1411. */
  1412. public function index()
  1413. {
  1414. $this->request->filter(['strip_tags', 'trim']);
  1415. if (!$this->request->isAjax()) {
  1416. $this->assignProcuremenListPage('pick', '协助下发');
  1417. return $this->view->fetch('procuremen/index');
  1418. }
  1419. if ($this->request->request('keyField')) {
  1420. return $this->selectpage();
  1421. }
  1422. $this->procuremenReleaseSessionLock();
  1423. list(, $sort, $order, $offset, $limit) = $this->buildparams();
  1424. $limit = max(10, min(500, (int)$limit));
  1425. $ym = $this->request->request('ym', '');
  1426. $ym = is_string($ym) ? trim($ym) : '';
  1427. /* wff_tab / 菜单:pick=待下发 audit=待确认供应商 confirm=待采购确认 */
  1428. $wffTab = $this->resolveProcuremenListStage();
  1429. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1430. $ym = in_array($wffTab, ['audit', 'confirm'], true)
  1431. ? $this->resolveProcuremenDefaultYm($wffTab)
  1432. : date('Y-m');
  1433. }
  1434. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  1435. $ym = date('Y-m');
  1436. }
  1437. $monthStart = $ym . '-01 00:00:00';
  1438. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1439. $search = trim((string)$this->request->get('search', ''));
  1440. $filterArr = (array)json_decode($this->request->get('filter', ''), true);
  1441. $opArr = (array)json_decode($this->request->get('op', ''), true);
  1442. if (!is_array($filterArr)) {
  1443. $filterArr = [];
  1444. }
  1445. if (!is_array($opArr)) {
  1446. $opArr = [];
  1447. }
  1448. // 开标状态为计算字段,不能进池内等值筛选;单独抽出后在合并后再滤
  1449. $bidOpenStatusFilter = '';
  1450. foreach (['bid_open_status_text', 'a.bid_open_status_text'] as $bidFk) {
  1451. if (!array_key_exists($bidFk, $filterArr)) {
  1452. continue;
  1453. }
  1454. $bidOpenStatusFilter = trim((string)$filterArr[$bidFk]);
  1455. unset($filterArr[$bidFk], $opArr[$bidFk]);
  1456. }
  1457. // 顶部快速搜索 / LIKE·RANGE 才跨月;表头等值下拉仍按当前月份,避免扫近一年整池
  1458. $applyMonthRange = $this->procuremenShouldApplyMonthRange($search, $filterArr, $opArr);
  1459. $hasActiveSearch = ($search !== '') || $this->procuremenFilterArrHasValue($filterArr);
  1460. try {
  1461. $listTimePrimary = in_array($wffTab, ['audit', 'confirm'], true) ? 'pick_time' : 'dputrecord';
  1462. if ($wffTab === 'audit') {
  1463. $pool = $this->procuremenPoolFromPurchaseOrderDbRows(
  1464. $this->loadPurchaseOrderRowsForListStage('audit', $ym, $applyMonthRange)
  1465. );
  1466. } elseif ($wffTab === 'confirm') {
  1467. $dbRows = $this->loadPurchaseOrderRowsForListStage('confirm', $ym, $applyMonthRange);
  1468. if ($dbRows === []) {
  1469. try {
  1470. $dbRows = Db::table('purchase_order')
  1471. ->field('id,scydgy_id,CCYDH,CYJMC,CCLBMMC,CDXMC,CGYBH,CGYMC,CDW,NGZL,CDF,cGzzxMc,MBZ,cywyxm,czlyq,'
  1472. . 'This_quantity,ceilingPrice,pick_time,createtime,dputrecord,dStamp,wflow_status,status,pick_company_name')
  1473. ->whereRaw('(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')')
  1474. ->whereIn('wflow_status', ProcuremenStatus::wflowPendingApprovalValues())
  1475. ->order('pick_time', 'desc')->order('id', 'desc')
  1476. ->select();
  1477. } catch (\Throwable $e) {
  1478. Log::write('协助审批列表 fallback 查询异常:' . $e->getMessage(), 'error');
  1479. $dbRows = [];
  1480. }
  1481. }
  1482. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  1483. if ($pool === []) {
  1484. Log::write('协助审批列表 pool 为空 ym=' . $ym . ' wffTab=' . $wffTab, 'warning');
  1485. }
  1486. } else {
  1487. // 初选:按月直查 ERP(不解整包 Redis,避免长时间转圈)
  1488. if ($applyMonthRange) {
  1489. $pool = $this->loadPickPoolForYm($ym);
  1490. } else {
  1491. $pool = $this->procuremenEnsureRedisPool();
  1492. }
  1493. if (!is_array($pool)) {
  1494. $pool = [];
  1495. }
  1496. // 只针对本页候选 ID 查隐藏集,避免全表扫 purchase_order_detail
  1497. $hideSet = $this->loadPickHiddenScydgySetForIds($this->extractScydgyIdsFromPool($pool));
  1498. if ($pool !== [] && $hideSet !== []) {
  1499. $pool = array_values(array_filter($pool, function ($r) use ($hideSet) {
  1500. if (!is_array($r)) {
  1501. return false;
  1502. }
  1503. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1504. return $id <= 0 || !isset($hideSet[$id]);
  1505. }));
  1506. }
  1507. // 手工新增(YW / scydgy_id<0)只走「新增询价/查询询价」,不进初选表格
  1508. if ($pool === []) {
  1509. return json([
  1510. 'total' => 0,
  1511. 'rows' => [],
  1512. 'activeYm' => $ym,
  1513. 'filterOptions' => (
  1514. (int)$offset === 0
  1515. && !$hasActiveSearch
  1516. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1517. )
  1518. ? $this->extractProcuremenFilterOptionsFromRows([])
  1519. : new \stdClass(),
  1520. ]);
  1521. }
  1522. }
  1523. if (in_array($wffTab, ['audit', 'confirm'], true) && $applyMonthRange) {
  1524. $ym = $this->resolveProcuremenActiveYm($wffTab, $ym, $pool, $listTimePrimary);
  1525. $monthStart = $ym . '-01 00:00:00';
  1526. $monthEnd = date('Y-m-t 23:59:59', strtotime($monthStart));
  1527. }
  1528. $filtered = $this->filterProcuremenIndexPool(
  1529. $pool,
  1530. $monthStart,
  1531. $monthEnd,
  1532. $applyMonthRange,
  1533. $search,
  1534. $filterArr,
  1535. $opArr,
  1536. $listTimePrimary
  1537. );
  1538. /* audit / confirm:同一订单号合并为一行(多道工序只显示一次) */
  1539. if (in_array($wffTab, ['audit', 'confirm'], true)) {
  1540. $filtered = $this->collapseProcuremenPoolByOrder($filtered);
  1541. }
  1542. if ($wffTab === 'audit' && $bidOpenStatusFilter !== '') {
  1543. $filtered = $this->filterProcuremenPoolByBidOpenStatus($filtered, $bidOpenStatusFilter);
  1544. }
  1545. $sortField = 'ID';
  1546. if (is_string($sort) && $sort !== '') {
  1547. $parts = explode(',', $sort);
  1548. $sortField = preg_replace('/^[ab]\./i', '', trim($parts[0]));
  1549. if ($sortField === '') {
  1550. $sortField = 'ID';
  1551. }
  1552. }
  1553. $ord = strtoupper((string)$order) === 'ASC' ? 1 : -1;
  1554. $nFiltered = count($filtered);
  1555. if ($nFiltered > 1) {
  1556. if (in_array($sortField, ['pick_time', 'dputrecord', 'dStamp', 'createtime'], true)) {
  1557. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1558. $ta = $this->procuremenRowListSortTime($a, $sortField);
  1559. $tb = $this->procuremenRowListSortTime($b, $sortField);
  1560. if ($ta === $tb) {
  1561. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1562. }
  1563. if ($ta === '') {
  1564. return 1;
  1565. }
  1566. if ($tb === '') {
  1567. return -1;
  1568. }
  1569. return strcmp($ta, $tb) * $ord;
  1570. });
  1571. } elseif ($sortField === 'ID') {
  1572. $sortKeys = [];
  1573. foreach ($filtered as $i => $row) {
  1574. $sortKeys[$i] = (int)($row['ID'] ?? 0);
  1575. }
  1576. $dir = $ord === 1 ? SORT_ASC : SORT_DESC;
  1577. array_multisort($sortKeys, $dir, SORT_NUMERIC, $filtered);
  1578. } elseif ($sortField === 'CCYDH') {
  1579. usort($filtered, function ($a, $b) use ($ord) {
  1580. $sa = trim((string)($a['CCYDH'] ?? ''));
  1581. $sb = trim((string)($b['CCYDH'] ?? ''));
  1582. if ($sa === $sb) {
  1583. return ((int)($a['ID'] ?? 0) <=> (int)($b['ID'] ?? 0)) * $ord;
  1584. }
  1585. if ($sa === '') {
  1586. return 1;
  1587. }
  1588. if ($sb === '') {
  1589. return -1;
  1590. }
  1591. return strcmp($sa, $sb) * $ord;
  1592. });
  1593. } else {
  1594. usort($filtered, function ($a, $b) use ($sortField, $ord) {
  1595. $va = $a[$sortField] ?? null;
  1596. $vb = $b[$sortField] ?? null;
  1597. $sa = (string)$va;
  1598. $sb = (string)$vb;
  1599. if ($sa === $sb) {
  1600. return 0;
  1601. }
  1602. return strcmp($sa, $sb) * $ord;
  1603. });
  1604. }
  1605. }
  1606. $offset = max(0, (int)$offset);
  1607. $limit = max(1, (int)$limit);
  1608. $rows = array_slice($filtered, $offset, $limit);
  1609. foreach ($rows as &$rw) {
  1610. if (!is_array($rw)) {
  1611. continue;
  1612. }
  1613. $rid = (int)($rw['ID'] ?? 0);
  1614. $rw['_iss_out'] = ($wffTab !== 'pick');
  1615. }
  1616. unset($rw);
  1617. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1618. $idList = [];
  1619. foreach ($rows as $rw) {
  1620. if (!is_array($rw)) {
  1621. continue;
  1622. }
  1623. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1624. foreach ($rw['_order_merge_rows'] as $mr) {
  1625. $mid = (int)($mr['ID'] ?? 0);
  1626. if ($this->isValidScydgyRowId($mid)) {
  1627. $idList[$mid] = true;
  1628. }
  1629. }
  1630. }
  1631. $id = (int)($rw['ID'] ?? 0);
  1632. if ($this->isValidScydgyRowId($id)) {
  1633. $idList[$id] = true;
  1634. }
  1635. }
  1636. $detailRows = $this->loadOrderDetailRowsByScydgyIds(array_keys($idList));
  1637. foreach ($rows as &$rw) {
  1638. if (!is_array($rw)) {
  1639. continue;
  1640. }
  1641. $mergeIds = [];
  1642. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1643. foreach ($rw['_order_merge_rows'] as $mr) {
  1644. $mid = (int)($mr['ID'] ?? 0);
  1645. if ($this->isValidScydgyRowId($mid)) {
  1646. $mergeIds[$mid] = true;
  1647. }
  1648. }
  1649. }
  1650. $rid = (int)($rw['ID'] ?? 0);
  1651. if ($this->isValidScydgyRowId($rid)) {
  1652. $mergeIds[$rid] = true;
  1653. }
  1654. $s = $this->summarizeMergedOrderDetails(array_keys($mergeIds), $detailRows);
  1655. $rw['po_detail_count'] = $s['cnt'];
  1656. $rw['po_amount_fill_cnt'] = $s['amt'];
  1657. $rw['po_delivery_fill_cnt'] = $s['deliv'];
  1658. }
  1659. unset($rw);
  1660. }
  1661. if (in_array($wffTab, ['confirm', 'audit'], true) && count($rows) > 0) {
  1662. $idList = [];
  1663. foreach ($rows as $rw) {
  1664. if (!is_array($rw)) {
  1665. continue;
  1666. }
  1667. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1668. foreach ($rw['_order_merge_rows'] as $mr) {
  1669. $mid = (int)($mr['ID'] ?? 0);
  1670. if ($this->isValidScydgyRowId($mid)) {
  1671. $idList[$mid] = true;
  1672. }
  1673. }
  1674. }
  1675. $id = (int)($rw['ID'] ?? 0);
  1676. if ($this->isValidScydgyRowId($id)) {
  1677. $idList[$id] = true;
  1678. }
  1679. }
  1680. $quoteBucket = $this->loadQuotedSupplierBucketByScydgyIds(array_keys($idList));
  1681. $bidOpenSet = [];
  1682. $manualPickSet = [];
  1683. if ($wffTab === 'audit') {
  1684. $ccydhList = [];
  1685. foreach ($rows as $rw0) {
  1686. if (!is_array($rw0)) {
  1687. continue;
  1688. }
  1689. $c0 = trim((string)($rw0['CCYDH'] ?? ''));
  1690. if ($c0 !== '') {
  1691. $ccydhList[] = $c0;
  1692. }
  1693. }
  1694. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  1695. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  1696. }
  1697. foreach ($rows as &$rw) {
  1698. if (!is_array($rw)) {
  1699. continue;
  1700. }
  1701. $mergeIds = [];
  1702. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1703. foreach ($rw['_order_merge_rows'] as $mr) {
  1704. $mid = (int)($mr['ID'] ?? 0);
  1705. if ($this->isValidScydgyRowId($mid)) {
  1706. $mergeIds[$mid] = true;
  1707. }
  1708. }
  1709. }
  1710. $rid = (int)($rw['ID'] ?? 0);
  1711. if ($this->isValidScydgyRowId($rid)) {
  1712. $mergeIds[$rid] = true;
  1713. }
  1714. $buckets = [];
  1715. foreach (array_keys($mergeIds) as $mid) {
  1716. if (isset($quoteBucket[$mid])) {
  1717. $buckets[] = $quoteBucket[$mid];
  1718. }
  1719. }
  1720. $supplierText = $buckets !== []
  1721. ? $this->formatQuotedSupplierLines($this->mergeQuotedSupplierBuckets($buckets))
  1722. : '';
  1723. if ($wffTab === 'confirm') {
  1724. $picked = trim((string)($rw['pick_company_name'] ?? $rw['picked_supplier_name'] ?? ''));
  1725. if ($picked === '') {
  1726. // 兜底:从合并工序行取
  1727. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  1728. foreach ($rw['_order_merge_rows'] as $mr) {
  1729. if (!is_array($mr)) {
  1730. continue;
  1731. }
  1732. $pn = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  1733. if ($pn !== '') {
  1734. $picked = $pn;
  1735. break;
  1736. }
  1737. }
  1738. }
  1739. }
  1740. $rw['picked_supplier_name'] = $picked;
  1741. } else {
  1742. $rw['notify_supplier_text'] = $supplierText;
  1743. $ccydh = trim((string)($rw['CCYDH'] ?? ''));
  1744. $verified = ($ccydh !== '' && isset($bidOpenSet[$ccydh]));
  1745. $manualPicked = ($ccydh !== '' && isset($manualPickSet[$ccydh]));
  1746. $rw['bid_open_verified'] = $verified ? 1 : 0;
  1747. $rw['manual_picked'] = $manualPicked ? 1 : 0;
  1748. if ($verified) {
  1749. $rw['bid_open_status_text'] = '已开标';
  1750. } elseif ($manualPicked) {
  1751. $rw['bid_open_status_text'] = '已指定供应商';
  1752. } else {
  1753. $rw['bid_open_status_text'] = '待开标';
  1754. }
  1755. }
  1756. }
  1757. unset($rw);
  1758. }
  1759. if (in_array($wffTab, ['audit', 'confirm'], true) && count($rows) > 0) {
  1760. $this->enrichProcuremenListMilestoneTimes($rows);
  1761. $this->syncCollapsedOrderQtyPriceForList($rows);
  1762. }
  1763. if ($wffTab === 'all' && count($rows) > 0) {
  1764. $this->mergePurchaseOrder($rows);
  1765. }
  1766. if ($wffTab === 'pick' && count($rows) > 0) {
  1767. $this->mergePurchaseOrder($rows);
  1768. }
  1769. foreach ($rows as &$rwClean) {
  1770. if (is_array($rwClean)) {
  1771. unset($rwClean['_order_merge_rows']);
  1772. if (array_key_exists('NGZL', $rwClean)) {
  1773. $rwClean['NGZL'] = $this->formatProcuremenWorkloadDisplay($rwClean['NGZL']);
  1774. }
  1775. }
  1776. }
  1777. unset($rwClean);
  1778. return json([
  1779. 'total' => count($filtered),
  1780. 'rows' => $rows,
  1781. 'activeYm' => $ym,
  1782. // 初选:把有数据的月份带回,替换「空月份日历」侧栏
  1783. 'sidebarYms' => ($wffTab === 'pick' && (int)$offset === 0)
  1784. ? $this->ensureProcuremenPickSidebarYmList()
  1785. : [],
  1786. // 仅无筛选的首页带回选项;从当月过滤后结果抽 distinct,避免扫近一年整池
  1787. 'filterOptions' => (
  1788. (int)$offset === 0
  1789. && !$hasActiveSearch
  1790. && (string)$this->request->get('need_filter_options', '1') !== '0'
  1791. )
  1792. ? $this->extractProcuremenFilterOptionsFromRows(is_array($filtered) ? $filtered : [])
  1793. : new \stdClass(),
  1794. ]);
  1795. } catch (\Throwable $e) {
  1796. Log::write('协助列表加载异常:' . $e->getMessage(), 'error');
  1797. return json([
  1798. 'total' => 0,
  1799. 'rows' => [],
  1800. ]);
  1801. }
  1802. }
  1803. /**
  1804. * @param array<int, array<string, mixed>> $pool
  1805. * @return int[]
  1806. */
  1807. protected function extractScydgyIdsFromPool(array $pool): array
  1808. {
  1809. $ids = [];
  1810. foreach ($pool as $r) {
  1811. if (!is_array($r)) {
  1812. continue;
  1813. }
  1814. $id = (int)($r['ID'] ?? $r['id'] ?? 0);
  1815. if ($id > 0) {
  1816. $ids[$id] = $id;
  1817. }
  1818. }
  1819. return array_values($ids);
  1820. }
  1821. /**
  1822. * 仅查询指定工序 ID 是否已下发/进入后续流程(初选列表加速)
  1823. *
  1824. * @param int[] $scydgyIds
  1825. * @return array<int, true>
  1826. */
  1827. protected function loadPickHiddenScydgySetForIds(array $scydgyIds): array
  1828. {
  1829. $hideSet = [];
  1830. $scydgyIds = array_values(array_filter(array_map('intval', $scydgyIds), function ($id) {
  1831. return $id > 0;
  1832. }));
  1833. if ($scydgyIds === []) {
  1834. return $hideSet;
  1835. }
  1836. // 分批,避免 whereIn 过长
  1837. foreach (array_chunk($scydgyIds, 500) as $chunk) {
  1838. try {
  1839. $poIds = Db::table('purchase_order')
  1840. ->where('scydgy_id', 'in', $chunk)
  1841. ->where(function ($q) {
  1842. $q->whereIn('wflow_status', array_merge(
  1843. ProcuremenStatus::wflowPendingConfirmValues(),
  1844. ProcuremenStatus::wflowPendingApprovalValues()
  1845. ))
  1846. ->whereOr(function ($q1) {
  1847. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1848. })
  1849. ->whereOr(function ($q2) {
  1850. $q2->whereNotNull('pick_time')
  1851. ->where('pick_time', '<>', '')
  1852. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1853. })
  1854. ->whereOr(function ($q3) {
  1855. $q3->whereNotNull('mod_rq')
  1856. ->where('mod_rq', '<>', '')
  1857. ->where('mod_rq', 'not like', '0000-00-00%');
  1858. });
  1859. })
  1860. ->column('scydgy_id');
  1861. if (is_array($poIds)) {
  1862. foreach ($poIds as $pid) {
  1863. $k = (int)$pid;
  1864. if ($k !== 0) {
  1865. $hideSet[$k] = true;
  1866. }
  1867. }
  1868. }
  1869. } catch (\Throwable $e) {
  1870. }
  1871. try {
  1872. $detIdsQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $chunk);
  1873. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1874. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1875. if (is_array($detIds)) {
  1876. foreach ($detIds as $pid) {
  1877. $k = (int)$pid;
  1878. if ($this->isValidScydgyRowId($k)) {
  1879. $hideSet[$k] = true;
  1880. }
  1881. }
  1882. }
  1883. } catch (\Throwable $e) {
  1884. }
  1885. }
  1886. return $hideSet;
  1887. }
  1888. /**
  1889. * 协助下发列表需隐藏的工序 scydgy_id(已下发通知或已进入后续流程)
  1890. *
  1891. * @return array<int, true>
  1892. */
  1893. protected function loadPickHiddenScydgySet(): array
  1894. {
  1895. if ($this->pickHiddenScydgySetCache !== null) {
  1896. return $this->pickHiddenScydgySetCache;
  1897. }
  1898. $cacheKey = 'procuremen_pick_hidden_scydgy_v1';
  1899. try {
  1900. $raw = redis()->get($cacheKey);
  1901. if ($raw !== false && $raw !== null && $raw !== '') {
  1902. $ids = json_decode((string)$raw, true);
  1903. if (is_array($ids)) {
  1904. $hideSet = [];
  1905. foreach ($ids as $pid) {
  1906. $k = (int)$pid;
  1907. if ($k !== 0) {
  1908. $hideSet[$k] = true;
  1909. }
  1910. }
  1911. $this->pickHiddenScydgySetCache = $hideSet;
  1912. return $hideSet;
  1913. }
  1914. }
  1915. } catch (\Throwable $e) {
  1916. }
  1917. $hideSet = [];
  1918. try {
  1919. $poIds = Db::table('purchase_order')
  1920. ->where(function ($q) {
  1921. $q->whereIn('wflow_status', array_merge(
  1922. ProcuremenStatus::wflowPendingConfirmValues(),
  1923. ProcuremenStatus::wflowPendingApprovalValues()
  1924. ))
  1925. ->whereOr(function ($q1) {
  1926. $q1->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  1927. })
  1928. ->whereOr(function ($q2) {
  1929. $q2->whereNotNull('pick_time')
  1930. ->where('pick_time', '<>', '')
  1931. ->where('pick_time', '<>', '0000-00-00 00:00:00');
  1932. })
  1933. ->whereOr(function ($q3) {
  1934. $q3->whereNotNull('mod_rq')
  1935. ->where('mod_rq', '<>', '')
  1936. ->where('mod_rq', 'not like', '0000-00-00%');
  1937. });
  1938. })
  1939. ->column('scydgy_id');
  1940. if (is_array($poIds)) {
  1941. foreach ($poIds as $pid) {
  1942. $k = (int)$pid;
  1943. if ($k !== 0) {
  1944. $hideSet[$k] = true;
  1945. }
  1946. }
  1947. }
  1948. } catch (\Throwable $e) {
  1949. }
  1950. try {
  1951. $detIdsQuery = Db::table('purchase_order_detail');
  1952. $this->applyActivePurchaseOrderDetailWhere($detIdsQuery);
  1953. $detIds = $detIdsQuery->distinct(true)->column('scydgy_id');
  1954. if (is_array($detIds)) {
  1955. foreach ($detIds as $pid) {
  1956. $k = (int)$pid;
  1957. if ($this->isValidScydgyRowId($k)) {
  1958. $hideSet[$k] = true;
  1959. }
  1960. }
  1961. }
  1962. } catch (\Throwable $e) {
  1963. }
  1964. $this->pickHiddenScydgySetCache = $hideSet;
  1965. try {
  1966. redis()->setex($cacheKey, 90, json_encode(array_map('intval', array_keys($hideSet))));
  1967. } catch (\Throwable $e) {
  1968. }
  1969. return $hideSet;
  1970. }
  1971. /**
  1972. * 协助下发列表:手工新增工序(purchase_order.scydgy_id 为负数,与 ERP 缓存行区分)
  1973. *
  1974. * @return array<int, array<string, mixed>>
  1975. */
  1976. protected function loadPickManualOrderRows(): array
  1977. {
  1978. try {
  1979. $dbRows = Db::table('purchase_order')
  1980. ->where('scydgy_id', '<', 0)
  1981. ->whereRaw('(mod_rq IS NULL OR TRIM(CAST(mod_rq AS CHAR(32))) = \'\' OR TRIM(CAST(mod_rq AS CHAR(32))) LIKE \'0000-00-00%\')')
  1982. ->order('scydgy_id', 'asc')
  1983. ->select();
  1984. } catch (\Throwable $e) {
  1985. try {
  1986. $dbRows = Db::table('purchase_order')->where('scydgy_id', '<', 0)->order('scydgy_id', 'asc')->select();
  1987. } catch (\Throwable $e2) {
  1988. return [];
  1989. }
  1990. }
  1991. if (!is_array($dbRows) || $dbRows === []) {
  1992. return [];
  1993. }
  1994. $detailSidSet = [];
  1995. try {
  1996. $negIds = [];
  1997. foreach ($dbRows as $dbRow) {
  1998. if (!is_array($dbRow)) {
  1999. continue;
  2000. }
  2001. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2002. if ($sid < 0) {
  2003. $negIds[$sid] = true;
  2004. }
  2005. }
  2006. if ($negIds !== []) {
  2007. $detQuery = Db::table('purchase_order_detail')
  2008. ->where('scydgy_id', 'in', array_keys($negIds));
  2009. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  2010. $detRows = $detQuery->group('scydgy_id')->column('scydgy_id');
  2011. if (is_array($detRows)) {
  2012. foreach ($detRows as $did) {
  2013. $detailSidSet[(int)$did] = true;
  2014. }
  2015. }
  2016. }
  2017. } catch (\Throwable $e) {
  2018. }
  2019. $pool = [];
  2020. foreach ($dbRows as $dbRow) {
  2021. if (!is_array($dbRow)) {
  2022. continue;
  2023. }
  2024. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  2025. if ($sid >= 0) {
  2026. continue;
  2027. }
  2028. // 已进入确认/审批的不进初选;仅废弃明细残留的仍算可下发
  2029. if (ProcuremenStatus::wflowAtLeastConfirm($dbRow['wflow_status'] ?? '')) {
  2030. continue;
  2031. }
  2032. // 仅排除已完结;空 status / 「进行中」/ 0 均保留(新建手工单)
  2033. if (ProcuremenStatus::isPoCompleted($dbRow['status'] ?? '')) {
  2034. continue;
  2035. }
  2036. if (isset($detailSidSet[$sid])) {
  2037. continue;
  2038. }
  2039. $r = $this->buildListRowFromPurchaseOrderDbRow($dbRow);
  2040. $r['_is_manual'] = 1;
  2041. $pool[] = $r;
  2042. }
  2043. return $pool;
  2044. }
  2045. /**
  2046. * 列表排序用时间:下发时间 pick_time 优先,其次 createtime / dputrecord / dStamp
  2047. */
  2048. protected function procuremenRowListSortTime(array $row, string $primary = 'dputrecord'): string
  2049. {
  2050. $keys = array_values(array_unique([$primary, 'pick_time', 'createtime', 'dputrecord', 'dStamp']));
  2051. foreach ($keys as $k) {
  2052. $t = trim((string)($row[$k] ?? ''));
  2053. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  2054. return $t;
  2055. }
  2056. }
  2057. return '';
  2058. }
  2059. /**
  2060. * 分配手工新增工序行 ID(负数递减)
  2061. * 调用方须在命名锁内执行,避免并发重复
  2062. */
  2063. protected function allocateManualScydgyId(): int
  2064. {
  2065. try {
  2066. $min = Db::table('purchase_order')->where('scydgy_id', '<', 0)->min('scydgy_id');
  2067. $min = (int)$min;
  2068. return $min < 0 ? $min - 1 : -1;
  2069. } catch (\Throwable $e) {
  2070. return -1;
  2071. }
  2072. }
  2073. /**
  2074. * 手工新增订单号:YW + 年月日 + 当日序号(如 YW20260618001)
  2075. * 调用方须在命名锁内执行,避免并发重复
  2076. */
  2077. protected function allocateManualOrderCcydh(): string
  2078. {
  2079. $prefix = 'YW' . date('Ymd');
  2080. $maxSeq = 0;
  2081. try {
  2082. $rows = Db::table('purchase_order')
  2083. ->where('CCYDH', 'like', $prefix . '%')
  2084. ->column('CCYDH');
  2085. if (is_array($rows)) {
  2086. foreach ($rows as $ccydh) {
  2087. $ccydh = trim((string)$ccydh);
  2088. if (preg_match('/^' . preg_quote($prefix, '/') . '(\d{3,})$/', $ccydh, $m)) {
  2089. $maxSeq = max($maxSeq, (int)$m[1]);
  2090. }
  2091. }
  2092. }
  2093. } catch (\Throwable $e) {
  2094. }
  2095. $next = $maxSeq + 1;
  2096. $width = $next > 999 ? strlen((string)$next) : 3;
  2097. return $prefix . str_pad((string)$next, $width, '0', STR_PAD_LEFT);
  2098. }
  2099. /**
  2100. * MySQL 命名锁(跨连接防并发撞号)
  2101. */
  2102. protected function acquireProcuremenNamedLock(string $name, int $timeoutSec = 10): bool
  2103. {
  2104. $name = trim($name);
  2105. if ($name === '') {
  2106. return false;
  2107. }
  2108. try {
  2109. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2110. $rows = Db::query('SELECT GET_LOCK(\'' . $nameSql . '\', ' . max(1, $timeoutSec) . ') AS locked');
  2111. if (!is_array($rows) || $rows === []) {
  2112. return false;
  2113. }
  2114. $v = $rows[0]['locked'] ?? $rows[0]['LOCKED'] ?? null;
  2115. return (int)$v === 1;
  2116. } catch (\Throwable $e) {
  2117. return false;
  2118. }
  2119. }
  2120. protected function releaseProcuremenNamedLock(string $name): void
  2121. {
  2122. $name = trim($name);
  2123. if ($name === '') {
  2124. return;
  2125. }
  2126. try {
  2127. $nameSql = str_replace(['\\', "'"], ['\\\\', "\\'"], $name);
  2128. Db::query('SELECT RELEASE_LOCK(\'' . $nameSql . '\')');
  2129. } catch (\Throwable $e) {
  2130. }
  2131. }
  2132. /**
  2133. * purchase_order.mod_rq 是否有有效软删除时间
  2134. */
  2135. protected function isPurchaseOrderSoftDeleted($modRq): bool
  2136. {
  2137. $t = trim((string)$modRq);
  2138. return $t !== '' && stripos($t, '0000-00-00') !== 0;
  2139. }
  2140. /**
  2141. * 列表行 → purchase_order 写入字段
  2142. *
  2143. * @return array<string, mixed>
  2144. */
  2145. protected function purchaseOrderPayloadFromListRow(array $row, int $scydgyId): array
  2146. {
  2147. return [
  2148. 'scydgy_id' => $scydgyId,
  2149. 'CCYDH' => $row['CCYDH'] ?? null,
  2150. 'CYJMC' => $row['CYJMC'] ?? null,
  2151. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  2152. 'CDXMC' => $row['CDXMC'] ?? null,
  2153. 'CGYBH' => $row['CGYBH'] ?? null,
  2154. 'CGYMC' => $row['CGYMC'] ?? null,
  2155. 'CDW' => $row['CDW'] ?? null,
  2156. 'czlyq' => $row['czlyq'] ?? null,
  2157. 'NGZL' => $row['NGZL'] ?? null,
  2158. 'CDF' => $row['CDF'] ?? null,
  2159. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  2160. 'MBZ' => $row['MBZ'] ?? null,
  2161. 'bwjg' => $row['bwjg'] ?? null,
  2162. 'iStatus' => $row['iStatus'] ?? null,
  2163. 'dStamp' => $row['dStamp'] ?? null,
  2164. 'dputrecord' => $row['dputrecord'] ?? null,
  2165. 'cywyxm' => $row['cywyxm'] ?? null,
  2166. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  2167. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  2168. ];
  2169. }
  2170. /**
  2171. * 初选行对应的 purchase_order 与是否应从初选列表隐藏
  2172. *
  2173. * @return array{po:?array<string,mixed>, hidden:bool}
  2174. */
  2175. protected function resolvePickRowPoContext(int $sid): array
  2176. {
  2177. $po = null;
  2178. try {
  2179. $found = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2180. if (is_array($found)) {
  2181. $po = $found;
  2182. }
  2183. } catch (\Throwable $e) {
  2184. }
  2185. $hideSet = $this->loadPickHiddenScydgySet();
  2186. return ['po' => $po, 'hidden' => isset($hideSet[$sid])];
  2187. }
  2188. /**
  2189. * 初选删除前校验(已删除幂等跳过;已下发/已完结禁止)
  2190. */
  2191. protected function assertPickRowCanDelete(int $sid, array $row): void
  2192. {
  2193. $ctx = $this->resolvePickRowPoContext($sid);
  2194. $po = $ctx['po'];
  2195. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2196. return;
  2197. }
  2198. if (is_array($po)) {
  2199. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2200. throw new \InvalidArgumentException('该工序已完结,无法删除');
  2201. }
  2202. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2203. throw new \InvalidArgumentException('该工序已下发或进入后续流程,无法删除');
  2204. }
  2205. }
  2206. if ($ctx['hidden']) {
  2207. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  2208. $label = $ccydh !== '' ? $ccydh : ('工序' . $sid);
  2209. throw new \InvalidArgumentException('订单号「' . $label . '」已下发或已进入后续流程,无法删除');
  2210. }
  2211. }
  2212. /**
  2213. * 初选直接完结前校验
  2214. */
  2215. protected function assertPickRowCanComplete(int $sid, array $row): void
  2216. {
  2217. $ctx = $this->resolvePickRowPoContext($sid);
  2218. $po = $ctx['po'];
  2219. if (is_array($po) && ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  2220. throw new \Exception($this->formatProcuremenRowLabel($row) . '已完结,无需重复操作');
  2221. }
  2222. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2223. throw new \Exception($this->formatProcuremenRowLabel($row) . '已删除,无法完结');
  2224. }
  2225. if ($ctx['hidden'] || (is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? ''))) {
  2226. throw new \Exception($this->formatProcuremenRowLabel($row) . '已下发或进入后续流程,不能直接完结');
  2227. }
  2228. }
  2229. /**
  2230. * 协助初选列表软删除(mod_rq 记删除时间;ERP 行无记录则插入 purchase_order)
  2231. */
  2232. protected function softDeleteProcuremenPickRow(array $row): void
  2233. {
  2234. $sid = $this->extractScydgyRowId($row);
  2235. if (!$this->isValidScydgyRowId($sid)) {
  2236. throw new \InvalidArgumentException('无效的行主键');
  2237. }
  2238. $this->assertPickRowCanDelete($sid, $row);
  2239. $po = $this->resolvePickRowPoContext($sid)['po'];
  2240. if (is_array($po) && $this->isPurchaseOrderSoftDeleted($po['mod_rq'] ?? null)) {
  2241. return;
  2242. }
  2243. if ($sid < 0 && is_array($po) && ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  2244. throw new \InvalidArgumentException('手工新增工序已下发,无法删除');
  2245. }
  2246. $now = date('Y-m-d H:i:s');
  2247. $exists = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  2248. if (is_array($exists)) {
  2249. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['mod_rq' => $now]);
  2250. $poIdLog = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  2251. } else {
  2252. $data = $this->purchaseOrderPayloadFromListRow($row, $sid);
  2253. $data['mod_rq'] = $now;
  2254. $data['createtime'] = $now;
  2255. Db::table('purchase_order')->insert($data);
  2256. $poIdLog = (int)Db::getLastInsID();
  2257. }
  2258. $ccydhLog = trim((string)($row['CCYDH'] ?? ''));
  2259. $gymcLog = trim((string)($row['CGYMC'] ?? ''));
  2260. $logTail = $ccydhLog !== '' ? $ccydhLog : ('scydgy_id=' . $sid);
  2261. if ($gymcLog !== '') {
  2262. $logTail .= ' / ' . $gymcLog;
  2263. }
  2264. $this->addOrderLog($sid, 'pick_soft_delete', '协助初选删除:' . $logTail, $poIdLog > 0 ? $poIdLog : null);
  2265. }
  2266. /**
  2267. * 手工新增协助工序(写入 purchase_order)
  2268. *
  2269. * @param array<string, mixed> $params
  2270. * @return int scydgy_id
  2271. */
  2272. protected function saveManualPickOrder(array $params): int
  2273. {
  2274. $cyjmc = trim((string)($params['CYJMC'] ?? ''));
  2275. $cgymc = trim((string)($params['CGYMC'] ?? ''));
  2276. $ccydhIn = trim((string)($params['CCYDH'] ?? ''));
  2277. $lockName = 'procuremen_manual_order_alloc';
  2278. if (!$this->acquireProcuremenNamedLock($lockName, 10)) {
  2279. throw new \RuntimeException('系统繁忙,请稍后重试');
  2280. }
  2281. try {
  2282. $ccydh = $ccydhIn !== '' ? $ccydhIn : $this->allocateManualOrderCcydh();
  2283. $now = date('Y-m-d H:i:s');
  2284. $sid = $this->allocateManualScydgyId();
  2285. $this->ensurePurchaseOrderNotifySalesmanColumn();
  2286. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  2287. // 选择供应商 / 通知业务员:支持多选,落库用顿号拼接
  2288. $supplierName = $this->joinRfqMultiSelectValues($params['cGzzxMc'] ?? ($params['pick_company_name'] ?? ''));
  2289. $notifySalesman = $this->joinRfqMultiSelectValues($params['notify_salesman'] ?? '');
  2290. $data = [
  2291. 'scydgy_id' => $sid,
  2292. 'CCYDH' => $ccydh,
  2293. 'CYJMC' => $cyjmc,
  2294. 'CGYMC' => $cgymc,
  2295. 'CCLBMMC' => trim((string)($params['CCLBMMC'] ?? '')),
  2296. 'CDW' => trim((string)($params['CDW'] ?? '')),
  2297. 'NGZL' => trim((string)($params['NGZL'] ?? '')),
  2298. 'CDF' => trim((string)($params['CDF'] ?? '')),
  2299. 'cGzzxMc' => $supplierName,
  2300. 'MBZ' => trim((string)($params['MBZ'] ?? '')),
  2301. 'cywyxm' => trim((string)($params['cywyxm'] ?? '')),
  2302. 'notify_salesman' => $notifySalesman,
  2303. 'rfq_salesman_notified' => 0,
  2304. 'rfq_salesman_notify_time' => null,
  2305. 'This_quantity' => trim((string)($params['This_quantity'] ?? '')),
  2306. 'ceilingPrice' => trim((string)($params['ceilingPrice'] ?? '')),
  2307. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  2308. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  2309. 'createtime' => $now,
  2310. 'dStamp' => $now,
  2311. 'dputrecord' => $now,
  2312. ];
  2313. Db::table('purchase_order')->insert($data);
  2314. $poId = (int)Db::getLastInsID();
  2315. $this->addOrderLog($sid, 'manual_add', '手工新增协助工序', $poId > 0 ? $poId : null);
  2316. return $sid;
  2317. } finally {
  2318. $this->releaseProcuremenNamedLock($lockName);
  2319. }
  2320. }
  2321. protected function formatProcuremenRowLabel(array $row): string
  2322. {
  2323. $dh = trim((string)($row['CCYDH'] ?? ''));
  2324. $gymc = trim((string)($row['CGYMC'] ?? ''));
  2325. if ($dh !== '' && $gymc !== '') {
  2326. return '订单「' . $dh . '」、工序「' . $gymc . '」';
  2327. }
  2328. if ($dh !== '') {
  2329. return '订单「' . $dh . '」';
  2330. }
  2331. if ($gymc !== '') {
  2332. return '工序「' . $gymc . '」';
  2333. }
  2334. $id = $this->extractScydgyRowId($row);
  2335. return $id !== 0 ? ('工序编号 ' . $id) : '所选工序';
  2336. }
  2337. /**
  2338. * 工序行主键:ERP 为正 scydgy.ID;手工新增为负 purchase_order.scydgy_id
  2339. */
  2340. protected function extractScydgyRowId(array $row): int
  2341. {
  2342. // 优先 scydgy_id,避免明细行 ID(自增主键)被误当成工序主键;手工单为负数
  2343. if (array_key_exists('scydgy_id', $row) && $row['scydgy_id'] !== null && $row['scydgy_id'] !== '') {
  2344. return (int)$row['scydgy_id'];
  2345. }
  2346. if (array_key_exists('SCYDGY_ID', $row) && $row['SCYDGY_ID'] !== null && $row['SCYDGY_ID'] !== '') {
  2347. return (int)$row['SCYDGY_ID'];
  2348. }
  2349. return (int)($row['ID'] ?? $row['id'] ?? 0);
  2350. }
  2351. protected function isValidScydgyRowId(int $id): bool
  2352. {
  2353. return ProcuremenGuard::isValidScydgyId($id);
  2354. }
  2355. protected function isManualScydgyRowId(int $id): bool
  2356. {
  2357. return $id < 0;
  2358. }
  2359. /**
  2360. * 确认供应商列表:下发明细中的供应商名称(与确认供应商弹窗「通知对象」同源)
  2361. *
  2362. * @param int[] $scydgyIds
  2363. * @return array<int, string[]>
  2364. */
  2365. protected function loadNotifySupplierNamesByScydgyIds(array $scydgyIds): array
  2366. {
  2367. $out = [];
  2368. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2369. if ($scydgyIds === []) {
  2370. return $out;
  2371. }
  2372. try {
  2373. $rows = Db::table('purchase_order_detail')
  2374. ->where('scydgy_id', 'in', $scydgyIds)
  2375. ->field('scydgy_id,company_name')
  2376. ->order('company_name', 'asc')
  2377. ->select();
  2378. } catch (\Throwable $e) {
  2379. $rows = [];
  2380. }
  2381. if (!is_array($rows)) {
  2382. return $out;
  2383. }
  2384. foreach ($rows as $r) {
  2385. if (!is_array($r)) {
  2386. continue;
  2387. }
  2388. $sid = (int)($r['scydgy_id'] ?? 0);
  2389. $cn = trim((string)($r['company_name'] ?? ''));
  2390. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2391. continue;
  2392. }
  2393. if (!isset($out[$sid])) {
  2394. $out[$sid] = [];
  2395. }
  2396. if (!in_array($cn, $out[$sid], true)) {
  2397. $out[$sid][] = $cn;
  2398. }
  2399. }
  2400. return $out;
  2401. }
  2402. /**
  2403. * 列表展示通知供应商(完整列表,前端单行省略展开)
  2404. *
  2405. * @param string[] $names
  2406. */
  2407. protected function formatNotifySupplierDisplay(array $names): string
  2408. {
  2409. $names = array_values(array_unique(array_filter(array_map(function ($n) {
  2410. return trim((string)$n);
  2411. }, $names))));
  2412. if ($names === []) {
  2413. return '';
  2414. }
  2415. sort($names, SORT_STRING);
  2416. return implode("\n", $names);
  2417. }
  2418. /**
  2419. * 采购确认列表:工序行已通知/已报价供应商(purchase_order_detail 有加工金额视为已报价)
  2420. *
  2421. * @param int[] $scydgyIds
  2422. * @return array<int, array{all: array<string, bool>, quoted: array<string, bool>}>
  2423. */
  2424. protected function loadQuotedSupplierBucketByScydgyIds(array $scydgyIds): array
  2425. {
  2426. $out = [];
  2427. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  2428. if ($scydgyIds === []) {
  2429. return $out;
  2430. }
  2431. try {
  2432. $rows = Db::table('purchase_order_detail')
  2433. ->where('scydgy_id', 'in', $scydgyIds)
  2434. ->field('scydgy_id,company_name,amount')
  2435. ->select();
  2436. } catch (\Throwable $e) {
  2437. $rows = [];
  2438. }
  2439. if (!is_array($rows)) {
  2440. return $out;
  2441. }
  2442. foreach ($rows as $r) {
  2443. if (!is_array($r)) {
  2444. continue;
  2445. }
  2446. $sid = (int)($r['scydgy_id'] ?? 0);
  2447. $cn = trim((string)($r['company_name'] ?? ''));
  2448. if (!$this->isValidScydgyRowId($sid) || $cn === '') {
  2449. continue;
  2450. }
  2451. if (!isset($out[$sid])) {
  2452. $out[$sid] = ['all' => [], 'quoted' => []];
  2453. }
  2454. $out[$sid]['all'][$cn] = true;
  2455. $am = trim((string)($r['amount'] ?? ''));
  2456. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  2457. $out[$sid]['quoted'][$cn] = true;
  2458. }
  2459. }
  2460. return $out;
  2461. }
  2462. /**
  2463. * @param array<int, array{all: array<string, bool>, quoted: array<string, bool>}> $buckets
  2464. * @return array{all: array<string, bool>, quoted: array<string, bool>}
  2465. */
  2466. protected function mergeQuotedSupplierBuckets(array $buckets): array
  2467. {
  2468. $merged = ['all' => [], 'quoted' => []];
  2469. foreach ($buckets as $b) {
  2470. if (!is_array($b)) {
  2471. continue;
  2472. }
  2473. foreach ($b['all'] ?? [] as $cn => $_) {
  2474. $merged['all'][$cn] = true;
  2475. }
  2476. foreach ($b['quoted'] ?? [] as $cn => $_) {
  2477. $merged['quoted'][$cn] = true;
  2478. }
  2479. }
  2480. return $merged;
  2481. }
  2482. /**
  2483. * @param array{all: array<string, bool>, quoted: array<string, bool>} $bucket
  2484. */
  2485. protected function formatQuotedSupplierLines(array $bucket): string
  2486. {
  2487. $all = array_keys($bucket['all'] ?? []);
  2488. if ($all === []) {
  2489. return '';
  2490. }
  2491. sort($all, SORT_STRING);
  2492. $lines = [];
  2493. foreach ($all as $cn) {
  2494. $status = !empty($bucket['quoted'][$cn]) ? '已报价' : '未报价';
  2495. $lines[] = $cn . '(' . $status . ')';
  2496. }
  2497. return implode("\n", $lines);
  2498. }
  2499. /**
  2500. * 选商类弹窗:轻量壳(无后台菜单外壳),初选/补加样式与高度一致
  2501. */
  2502. protected function fetchProcuremenDialogLite(string $view, string $title = ''): string
  2503. {
  2504. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  2505. $this->view->engine->layout(false);
  2506. try {
  2507. $bodyHtml = $this->view->fetch($view);
  2508. $this->view->assign('dialogBody', $bodyHtml);
  2509. $this->view->assign('dialogTitle', $title !== '' ? $title : '选商');
  2510. return $this->view->fetch('procuremen/dialog_lite_shell');
  2511. } finally {
  2512. if ($restoreLayout) {
  2513. $this->view->engine->layout($restoreLayout);
  2514. }
  2515. }
  2516. }
  2517. /**
  2518. * 从订单 bundle 取报价截止时间(多工序取首个有效 sys_rq)
  2519. */
  2520. protected function resolveBundleSysRq(array $bundle): string
  2521. {
  2522. foreach ($bundle['pos'] ?? [] as $po) {
  2523. if (!is_array($po)) {
  2524. continue;
  2525. }
  2526. $sr = trim((string)($po['sys_rq'] ?? ''));
  2527. if ($sr !== '' && !preg_match('/^0000-00-00/i', $sr)) {
  2528. return $sr;
  2529. }
  2530. }
  2531. return '';
  2532. }
  2533. /**
  2534. * 报价截止时间是否已到(未设置截止时间则视为可查看报价)
  2535. */
  2536. protected function isProcuremenQuoteDeadlineReached($sysRq): bool
  2537. {
  2538. $raw = trim((string)$sysRq);
  2539. if ($raw === '' || preg_match('/^0000-00-00/i', $raw)) {
  2540. return true;
  2541. }
  2542. $ts = strtotime(str_replace('T', ' ', $raw));
  2543. if ($ts === false || $ts <= 0) {
  2544. return true;
  2545. }
  2546. return time() >= $ts;
  2547. }
  2548. /**
  2549. * 开标前校验:必须已过报价截止时间
  2550. *
  2551. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  2552. */
  2553. protected function assertProcuremenBidOpenAfterDeadline(array $bundle): void
  2554. {
  2555. $sysRq = $this->resolveBundleSysRq($bundle);
  2556. if (!$this->isProcuremenQuoteDeadlineReached($sysRq)) {
  2557. $this->error('未到招标截止日期');
  2558. }
  2559. }
  2560. /**
  2561. * 解析预估工期(天):优先明细 lead_days,否则按交货日期相对今天推算
  2562. *
  2563. * @param array<string, mixed> $d
  2564. * @param string $deliveryYmd
  2565. */
  2566. protected function resolveProcuremenLeadDays(array $d, string $deliveryYmd = ''): ?int
  2567. {
  2568. if (array_key_exists('lead_days', $d) && $d['lead_days'] !== null && $d['lead_days'] !== '' && is_numeric($d['lead_days'])) {
  2569. return max(0, (int)$d['lead_days']);
  2570. }
  2571. if ($deliveryYmd === '') {
  2572. $deliveryYmd = $this->formatDeliveryYmd($d['delivery'] ?? null);
  2573. }
  2574. if ($deliveryYmd === '' || !preg_match('/^(\d{4}-\d{2}-\d{2})/', $deliveryYmd, $m)) {
  2575. return null;
  2576. }
  2577. $t1 = strtotime(date('Y-m-d') . ' 00:00:00');
  2578. $t2 = strtotime($m[1] . ' 00:00:00');
  2579. if ($t1 === false || $t2 === false) {
  2580. return null;
  2581. }
  2582. return max(0, (int)round(($t2 - $t1) / 86400));
  2583. }
  2584. /**
  2585. * @param int|null $days
  2586. */
  2587. protected function formatProcuremenLeadDaysText($days): string
  2588. {
  2589. if ($days === null || $days === '') {
  2590. return '未填写';
  2591. }
  2592. if (!is_numeric($days)) {
  2593. return '未填写';
  2594. }
  2595. return ((int)$days) . '天';
  2596. }
  2597. /**
  2598. * 未开标验证前:隐藏单价/交期/工期/小计/操作时间真实值,统一展示文案
  2599. *
  2600. * @param array<string, mixed> $line
  2601. */
  2602. protected function maskSupplierQuoteLineBeforeDeadline(array &$line): void
  2603. {
  2604. $amountFilled = !empty($line['amount_filled']);
  2605. $deliveryFilled = !empty($line['delivery_filled']);
  2606. $leadFilled = !empty($line['lead_days_filled']);
  2607. $operFilled = trim((string)($line['oper_time_text'] ?? '')) !== '';
  2608. $line['unit_price_text'] = $amountFilled ? '开标验证后查看' : '未填写';
  2609. $line['amount_show'] = '';
  2610. if (array_key_exists('amount_text', $line)) {
  2611. $line['amount_text'] = $line['unit_price_text'];
  2612. }
  2613. $deliveryText = $deliveryFilled ? '开标验证后查看' : '未填写';
  2614. $line['delivery_show'] = $deliveryText;
  2615. if (array_key_exists('delivery_text', $line)) {
  2616. $line['delivery_text'] = $deliveryText;
  2617. }
  2618. $line['delivery_ymd'] = '';
  2619. $leadText = $leadFilled ? '开标验证后查看' : '未填写';
  2620. $line['lead_days_show'] = $leadText;
  2621. $line['lead_days_text'] = $leadText;
  2622. $line['lead_days'] = '';
  2623. // 小计、操作时间与单价等同属报价信息,开标前不可见
  2624. $line['subtotal_text'] = $amountFilled ? '开标验证后查看' : '';
  2625. $line['subtotal_num'] = null;
  2626. $line['oper_time_text'] = $operFilled ? '开标验证后查看' : '';
  2627. $line['amount_quote_pending'] = $amountFilled ? 1 : 0;
  2628. $line['delivery_quote_pending'] = $deliveryFilled ? 1 : 0;
  2629. $line['lead_days_quote_pending'] = $leadFilled ? 1 : 0;
  2630. $line['oper_time_quote_pending'] = $operFilled ? 1 : 0;
  2631. $line['quote_before_deadline'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? 1 : 0;
  2632. $line['amount_filled'] = false;
  2633. $line['delivery_filled'] = false;
  2634. $line['lead_days_filled'] = false;
  2635. $line['is_quoted'] = false;
  2636. if (array_key_exists('quote_label', $line)) {
  2637. $line['quote_label'] = ($amountFilled || $deliveryFilled || $leadFilled || $operFilled) ? '未开标验证' : '未报价';
  2638. }
  2639. }
  2640. protected function ensurePurchaseOrderBidOpenTable(): void
  2641. {
  2642. static $ready = false;
  2643. if ($ready) {
  2644. return;
  2645. }
  2646. $cacheKey = 'procuremen_bid_open_table_ok_v1';
  2647. try {
  2648. if (Cache::get($cacheKey)) {
  2649. $ready = true;
  2650. return;
  2651. }
  2652. } catch (\Throwable $e) {
  2653. }
  2654. try {
  2655. Db::query('SELECT 1 FROM `purchase_order_bid_open` LIMIT 1');
  2656. $ready = true;
  2657. try {
  2658. Cache::set($cacheKey, 1, 86400);
  2659. } catch (\Throwable $e) {
  2660. }
  2661. } catch (\Throwable $e) {
  2662. Db::execute(
  2663. "CREATE TABLE IF NOT EXISTS `purchase_order_bid_open` (
  2664. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  2665. `ccydh` varchar(64) NOT NULL DEFAULT '' COMMENT '订单号',
  2666. `verifier1_id` int(10) unsigned NOT NULL DEFAULT 0,
  2667. `verifier1_name` varchar(64) NOT NULL DEFAULT '',
  2668. `verifier2_id` int(10) unsigned NOT NULL DEFAULT 0,
  2669. `verifier2_name` varchar(64) NOT NULL DEFAULT '',
  2670. `operator_id` int(10) unsigned NOT NULL DEFAULT 0,
  2671. `operator_name` varchar(64) NOT NULL DEFAULT '',
  2672. `createtime` datetime DEFAULT NULL,
  2673. PRIMARY KEY (`id`),
  2674. UNIQUE KEY `uk_ccydh` (`ccydh`)
  2675. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='协助采购开标双重验证'"
  2676. );
  2677. $ready = true;
  2678. try {
  2679. Cache::set($cacheKey, 1, 86400);
  2680. } catch (\Throwable $e2) {
  2681. }
  2682. }
  2683. }
  2684. protected function isProcuremenBidOpenVerified(string $ccydh): bool
  2685. {
  2686. $ccydh = trim($ccydh);
  2687. if ($ccydh === '') {
  2688. return false;
  2689. }
  2690. $this->ensurePurchaseOrderBidOpenTable();
  2691. try {
  2692. $row = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  2693. return is_array($row);
  2694. } catch (\Throwable $e) {
  2695. return false;
  2696. }
  2697. }
  2698. /**
  2699. * 批量查询订单是否已开标验证
  2700. *
  2701. * @param array<int, string> $ccydhs
  2702. * @return array<string, bool> ccydh => true
  2703. */
  2704. protected function loadProcuremenBidOpenVerifiedCcydhSet(array $ccydhs): array
  2705. {
  2706. $set = [];
  2707. $list = [];
  2708. foreach ($ccydhs as $c) {
  2709. $c = trim((string)$c);
  2710. if ($c !== '') {
  2711. $list[$c] = true;
  2712. }
  2713. }
  2714. if ($list === []) {
  2715. return $set;
  2716. }
  2717. $this->ensurePurchaseOrderBidOpenTable();
  2718. try {
  2719. $rows = Db::table('purchase_order_bid_open')
  2720. ->where('ccydh', 'in', array_keys($list))
  2721. ->field('ccydh')
  2722. ->select();
  2723. foreach ($rows as $row) {
  2724. if (!is_array($row)) {
  2725. continue;
  2726. }
  2727. $c = trim((string)($row['ccydh'] ?? ''));
  2728. if ($c !== '') {
  2729. $set[$c] = true;
  2730. }
  2731. }
  2732. } catch (\Throwable $e) {
  2733. return [];
  2734. }
  2735. return $set;
  2736. }
  2737. /**
  2738. * 批量查询订单是否已指定供应商(免开标)
  2739. *
  2740. * @param array<int, string> $ccydhs
  2741. * @return array<string, bool> ccydh => true
  2742. */
  2743. protected function loadProcuremenManualPickedCcydhSet(array $ccydhs): array
  2744. {
  2745. $set = [];
  2746. $list = [];
  2747. foreach ($ccydhs as $c) {
  2748. $c = trim((string)$c);
  2749. if ($c !== '') {
  2750. $list[$c] = true;
  2751. }
  2752. }
  2753. if ($list === []) {
  2754. return $set;
  2755. }
  2756. $this->ensurePurchaseOrderManualPickColumns();
  2757. try {
  2758. $rows = Db::table('purchase_order')
  2759. ->where('CCYDH', 'in', array_keys($list))
  2760. ->where('manual_pick', 1)
  2761. ->field('CCYDH')
  2762. ->select();
  2763. foreach ($rows as $row) {
  2764. if (!is_array($row)) {
  2765. continue;
  2766. }
  2767. $c = trim((string)($row['CCYDH'] ?? ''));
  2768. if ($c !== '') {
  2769. $set[$c] = true;
  2770. }
  2771. }
  2772. } catch (\Throwable $e) {
  2773. return [];
  2774. }
  2775. return $set;
  2776. }
  2777. /**
  2778. * 确认供应商列表:按开标状态筛选(已开标 / 已指定供应商 / 待开标)
  2779. *
  2780. * @param array<int, array<string, mixed>> $pool
  2781. * @return array<int, array<string, mixed>>
  2782. */
  2783. protected function filterProcuremenPoolByBidOpenStatus(array $pool, string $status): array
  2784. {
  2785. $status = trim($status);
  2786. if ($status === '' || !in_array($status, ['待开标', '已开标', '已指定供应商'], true)) {
  2787. return $pool;
  2788. }
  2789. $ccydhList = [];
  2790. foreach ($pool as $rw) {
  2791. if (!is_array($rw)) {
  2792. continue;
  2793. }
  2794. $c = trim((string)($rw['CCYDH'] ?? ''));
  2795. if ($c !== '') {
  2796. $ccydhList[] = $c;
  2797. }
  2798. }
  2799. $bidOpenSet = $this->loadProcuremenBidOpenVerifiedCcydhSet($ccydhList);
  2800. $manualPickSet = $this->loadProcuremenManualPickedCcydhSet($ccydhList);
  2801. $out = [];
  2802. foreach ($pool as $rw) {
  2803. if (!is_array($rw)) {
  2804. continue;
  2805. }
  2806. $c = trim((string)($rw['CCYDH'] ?? ''));
  2807. if ($c !== '' && isset($bidOpenSet[$c])) {
  2808. $t = '已开标';
  2809. } elseif ($c !== '' && isset($manualPickSet[$c])) {
  2810. $t = '已指定供应商';
  2811. } else {
  2812. $t = '待开标';
  2813. }
  2814. if ($t === $status) {
  2815. $out[] = $rw;
  2816. }
  2817. }
  2818. return $out;
  2819. }
  2820. /**
  2821. * 未开标验证时隐藏供应商备注(留空,避免与单价列错位)
  2822. *
  2823. * @param array<string, mixed> $group
  2824. */
  2825. protected function maskSupplierRemarkBeforeBidOpen(array &$group, bool $quoteVisible): void
  2826. {
  2827. if ($quoteVisible) {
  2828. $group['remark_quote_pending'] = 0;
  2829. return;
  2830. }
  2831. $group['remark'] = '';
  2832. $group['remark_quote_pending'] = 0;
  2833. }
  2834. /**
  2835. * @param array{ccydh?:string} $bundle
  2836. */
  2837. protected function isProcuremenBidOpenVerifiedForBundle(array $bundle): bool
  2838. {
  2839. return $this->isProcuremenBidOpenVerified(trim((string)($bundle['ccydh'] ?? '')));
  2840. }
  2841. protected function canViewProcuremenSupplierQuotesForBundle(array $bundle): bool
  2842. {
  2843. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  2844. return true;
  2845. }
  2846. return $this->isProcuremenManualPickedForBundle($bundle);
  2847. }
  2848. /**
  2849. * 确保 purchase_order 自选供应商字段
  2850. */
  2851. protected function ensurePurchaseOrderManualPickColumns(): void
  2852. {
  2853. static $done = false;
  2854. if ($done) {
  2855. return;
  2856. }
  2857. $done = true;
  2858. $adds = [
  2859. 'manual_pick' => "ADD COLUMN `manual_pick` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '1=自选供应商(免开标)' AFTER `pick_company_name`",
  2860. 'manual_pick_reason' => "ADD COLUMN `manual_pick_reason` varchar(500) NOT NULL DEFAULT '' COMMENT '自选供应商选择说明' AFTER `manual_pick`",
  2861. ];
  2862. foreach ($adds as $col => $ddl) {
  2863. try {
  2864. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  2865. if (!is_array($cols) || $cols === []) {
  2866. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  2867. }
  2868. } catch (\Throwable $e) {
  2869. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  2870. }
  2871. }
  2872. }
  2873. /**
  2874. * 是否已自选供应商(免开标查看报价)
  2875. *
  2876. * @param array{pos?:array} $bundle
  2877. */
  2878. protected function isProcuremenManualPickedForBundle(array $bundle): bool
  2879. {
  2880. $this->ensurePurchaseOrderManualPickColumns();
  2881. foreach ($bundle['pos'] ?? [] as $poRow) {
  2882. if (!is_array($poRow)) {
  2883. continue;
  2884. }
  2885. if ((int)($poRow['manual_pick'] ?? 0) === 1) {
  2886. return true;
  2887. }
  2888. }
  2889. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2890. if ($ccydh === '') {
  2891. return false;
  2892. }
  2893. try {
  2894. $v = Db::table('purchase_order')->where('CCYDH', $ccydh)->where('manual_pick', 1)->value('id');
  2895. return $v !== null && $v !== false && (int)$v > 0;
  2896. } catch (\Throwable $e) {
  2897. return false;
  2898. }
  2899. }
  2900. /**
  2901. * @param array{pos?:array} $bundle
  2902. * @return array{company:string,reason:string}
  2903. */
  2904. protected function resolveProcuremenManualPickInfo(array $bundle): array
  2905. {
  2906. $this->ensurePurchaseOrderManualPickColumns();
  2907. foreach ($bundle['pos'] ?? [] as $poRow) {
  2908. if (!is_array($poRow)) {
  2909. continue;
  2910. }
  2911. if ((int)($poRow['manual_pick'] ?? 0) !== 1) {
  2912. continue;
  2913. }
  2914. $cn = trim((string)($poRow['pick_company_name'] ?? ''));
  2915. $reason = trim((string)($poRow['manual_pick_reason'] ?? ''));
  2916. return ['company' => $cn, 'reason' => $reason];
  2917. }
  2918. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  2919. if ($ccydh === '') {
  2920. return ['company' => '', 'reason' => ''];
  2921. }
  2922. try {
  2923. $row = Db::table('purchase_order')
  2924. ->where('CCYDH', $ccydh)
  2925. ->where('manual_pick', 1)
  2926. ->field('pick_company_name,manual_pick_reason')
  2927. ->order('id', 'asc')
  2928. ->find();
  2929. } catch (\Throwable $e) {
  2930. $row = null;
  2931. }
  2932. if (!is_array($row)) {
  2933. return ['company' => '', 'reason' => ''];
  2934. }
  2935. return [
  2936. 'company' => trim((string)($row['pick_company_name'] ?? '')),
  2937. 'reason' => trim((string)($row['manual_pick_reason'] ?? '')),
  2938. ];
  2939. }
  2940. protected function loadBidOpenAdminUser(int $adminId): ?array
  2941. {
  2942. if ($adminId <= 0) {
  2943. return null;
  2944. }
  2945. try {
  2946. $row = Db::name('admin')->where('id', $adminId)->find();
  2947. } catch (\Throwable $e) {
  2948. return null;
  2949. }
  2950. if (!is_array($row)) {
  2951. return null;
  2952. }
  2953. $status = strtolower(trim((string)($row['status'] ?? '')));
  2954. if ($status !== '' && $status !== 'normal') {
  2955. return null;
  2956. }
  2957. if (!$this->isBidOpenVerifierAdmin((int)($row['id'] ?? 0))) {
  2958. return null;
  2959. }
  2960. $phone = preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? '')));
  2961. if (!preg_match('/^1\d{10}$/', $phone)) {
  2962. return null;
  2963. }
  2964. $name = trim((string)($row['nickname'] ?? ''));
  2965. if ($name === '') {
  2966. $name = trim((string)($row['username'] ?? ''));
  2967. }
  2968. return [
  2969. 'id' => (int)$row['id'],
  2970. 'username' => trim((string)($row['username'] ?? '')),
  2971. 'nickname' => $name,
  2972. 'mobile' => $phone,
  2973. ];
  2974. }
  2975. /**
  2976. * 开标验证人可选范围:auth_group 根组 id(含其全部子组)
  2977. */
  2978. protected function bidOpenVerifierAuthGroupRootId(): int
  2979. {
  2980. $id = (int)Config::get('mproc.bid_open_auth_group_root_id');
  2981. return $id > 0 ? $id : 10;
  2982. }
  2983. /**
  2984. * @return int[]
  2985. */
  2986. protected function loadBidOpenVerifierAuthGroupIds(): array
  2987. {
  2988. static $memo = [];
  2989. $rootId = $this->bidOpenVerifierAuthGroupRootId();
  2990. if (isset($memo[$rootId])) {
  2991. return $memo[$rootId];
  2992. }
  2993. try {
  2994. $groups = Db::name('auth_group')->where('status', 'normal')->field('id,pid')->select();
  2995. } catch (\Throwable $e) {
  2996. $memo[$rootId] = [$rootId];
  2997. return $memo[$rootId];
  2998. }
  2999. if (!is_array($groups) || $groups === []) {
  3000. $memo[$rootId] = [$rootId];
  3001. return $memo[$rootId];
  3002. }
  3003. $groupList = [];
  3004. foreach ($groups as $g) {
  3005. if (is_array($g)) {
  3006. $groupList[] = $g;
  3007. }
  3008. }
  3009. if ($groupList === []) {
  3010. $memo[$rootId] = [$rootId];
  3011. return $memo[$rootId];
  3012. }
  3013. $tree = \fast\Tree::instance();
  3014. $tree->init($groupList);
  3015. $ids = $tree->getChildrenIds($rootId, true);
  3016. if (!is_array($ids) || $ids === []) {
  3017. $memo[$rootId] = [$rootId];
  3018. return $memo[$rootId];
  3019. }
  3020. $memo[$rootId] = array_values(array_unique(array_filter(array_map('intval', $ids))));
  3021. return $memo[$rootId];
  3022. }
  3023. protected function isBidOpenVerifierAdmin(int $adminId): bool
  3024. {
  3025. if ($adminId <= 0) {
  3026. return false;
  3027. }
  3028. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3029. if ($groupIds === []) {
  3030. return false;
  3031. }
  3032. try {
  3033. return (bool)Db::name('auth_group_access')
  3034. ->where('uid', $adminId)
  3035. ->where('group_id', 'in', $groupIds)
  3036. ->count();
  3037. } catch (\Throwable $e) {
  3038. return false;
  3039. }
  3040. }
  3041. /**
  3042. * @return array<int, array<string, mixed>>
  3043. */
  3044. protected function listBidOpenVerifierCandidates(): array
  3045. {
  3046. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3047. if ($groupIds === []) {
  3048. return [];
  3049. }
  3050. try {
  3051. $adminIds = Db::name('auth_group_access')
  3052. ->where('group_id', 'in', $groupIds)
  3053. ->column('uid');
  3054. } catch (\Throwable $e) {
  3055. $adminIds = [];
  3056. }
  3057. $adminIds = is_array($adminIds)
  3058. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  3059. : [];
  3060. if ($adminIds === []) {
  3061. return [];
  3062. }
  3063. try {
  3064. $rows = Db::name('admin')
  3065. ->where('status', 'normal')
  3066. ->where('id', 'in', $adminIds)
  3067. ->where('mobile', '<>', '')
  3068. ->order('id', 'asc')
  3069. ->select();
  3070. } catch (\Throwable $e) {
  3071. return [];
  3072. }
  3073. if (!is_array($rows)) {
  3074. return [];
  3075. }
  3076. $groupNameMap = $this->loadBidOpenVerifierGroupNameMap($adminIds);
  3077. $out = [];
  3078. foreach ($rows as $row) {
  3079. if (!is_array($row)) {
  3080. continue;
  3081. }
  3082. $one = $this->loadBidOpenAdminUser((int)($row['id'] ?? 0));
  3083. if ($one === null) {
  3084. continue;
  3085. }
  3086. $out[] = [
  3087. 'id' => $one['id'],
  3088. 'username' => $one['username'],
  3089. 'nickname' => $one['nickname'],
  3090. 'group_name' => $groupNameMap[$one['id']] ?? '',
  3091. 'mobile' => mask_phone($one['mobile']),
  3092. 'mobile_plain' => (string)$one['mobile'],
  3093. ];
  3094. }
  3095. return $out;
  3096. }
  3097. /**
  3098. * @param int[] $adminIds
  3099. * @return array<int, string>
  3100. */
  3101. protected function loadBidOpenVerifierGroupNameMap(array $adminIds): array
  3102. {
  3103. $adminIds = array_values(array_unique(array_filter(array_map('intval', $adminIds))));
  3104. if ($adminIds === []) {
  3105. return [];
  3106. }
  3107. $groupIds = $this->loadBidOpenVerifierAuthGroupIds();
  3108. try {
  3109. $rows = Db::name('auth_group_access')
  3110. ->alias('aga')
  3111. ->join('auth_group ag', 'aga.group_id = ag.id')
  3112. ->where('aga.uid', 'in', $adminIds)
  3113. ->where('aga.group_id', 'in', $groupIds)
  3114. ->field('aga.uid,ag.name')
  3115. ->order('aga.uid', 'asc')
  3116. ->order('aga.group_id', 'asc')
  3117. ->select();
  3118. } catch (\Throwable $e) {
  3119. return [];
  3120. }
  3121. if (!is_array($rows)) {
  3122. return [];
  3123. }
  3124. $out = [];
  3125. foreach ($rows as $row) {
  3126. if (!is_array($row)) {
  3127. continue;
  3128. }
  3129. $uid = (int)($row['uid'] ?? 0);
  3130. $name = trim((string)($row['name'] ?? ''));
  3131. if ($uid <= 0 || $name === '' || isset($out[$uid])) {
  3132. continue;
  3133. }
  3134. $out[$uid] = $name;
  3135. }
  3136. return $out;
  3137. }
  3138. protected function bidOpenSmsCacheKey(int $adminId, string $ccydh): string
  3139. {
  3140. return 'procuremen_bidopen_code_' . $adminId . '_' . md5($ccydh);
  3141. }
  3142. protected function bidOpenSmsWaitCacheKey(int $adminId): string
  3143. {
  3144. return 'procuremen_bidopen_wait_' . $adminId;
  3145. }
  3146. protected function renderBidOpenVerifySms(string $code): string
  3147. {
  3148. $tpl = '';
  3149. try {
  3150. $row = $this->loadNotifyTemplateRow('bid_open');
  3151. if (is_array($row)) {
  3152. $tpl = trim((string)($row['content'] ?? ''));
  3153. }
  3154. } catch (\Throwable $e) {
  3155. $tpl = '';
  3156. }
  3157. if ($tpl === '') {
  3158. $tpl = '【可集达】您的短信验证码是{code}';
  3159. }
  3160. return str_replace('{code}', $code, $tpl);
  3161. }
  3162. protected function sendBidOpenVerifySms(string $phone, string $code): void
  3163. {
  3164. $this->smsbao($phone, $this->renderBidOpenVerifySms($code));
  3165. }
  3166. protected function verifyBidOpenSmsCode(int $adminId, string $ccydh, string $code): bool
  3167. {
  3168. $code = trim($code);
  3169. if (!preg_match('/^\d{6}$/', $code)) {
  3170. return false;
  3171. }
  3172. $mock = Config::get('mproc.mock_sms_code');
  3173. if ($mock !== null && $mock !== '' && (string)$mock === $code) {
  3174. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3175. return true;
  3176. }
  3177. $cached = Cache::get($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3178. if ($cached === false || $cached === null || (string)$cached !== $code) {
  3179. return false;
  3180. }
  3181. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  3182. return true;
  3183. }
  3184. /**
  3185. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  3186. */
  3187. protected function recordProcuremenBidOpenVerification(array $bundle, array $verifier1, array $verifier2): void
  3188. {
  3189. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3190. if ($ccydh === '') {
  3191. throw new \InvalidArgumentException('订单号无效');
  3192. }
  3193. $this->ensurePurchaseOrderBidOpenTable();
  3194. list($operatorId, $operatorName) = $this->GetUseName();
  3195. $now = date('Y-m-d H:i:s');
  3196. $exists = Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->find();
  3197. $payload = [
  3198. 'ccydh' => $ccydh,
  3199. 'verifier1_id' => (int)($verifier1['id'] ?? 0),
  3200. 'verifier1_name' => trim((string)($verifier1['nickname'] ?? '')),
  3201. 'verifier2_id' => (int)($verifier2['id'] ?? 0),
  3202. 'verifier2_name' => trim((string)($verifier2['nickname'] ?? '')),
  3203. 'operator_id' => (int)$operatorId,
  3204. 'operator_name' => trim((string)$operatorName),
  3205. 'createtime' => $now,
  3206. ];
  3207. if (is_array($exists)) {
  3208. Db::table('purchase_order_bid_open')->where('ccydh', $ccydh)->update($payload);
  3209. } else {
  3210. Db::table('purchase_order_bid_open')->insert($payload);
  3211. }
  3212. $name1 = $payload['verifier1_name'] !== '' ? $payload['verifier1_name'] : ('ID' . $payload['verifier1_id']);
  3213. $name2 = $payload['verifier2_name'] !== '' ? $payload['verifier2_name'] : ('ID' . $payload['verifier2_id']);
  3214. $labelMap = ProcuremenOperLog::resolveAdminDisplayLabels([
  3215. (int)$payload['verifier1_id'],
  3216. (int)$payload['verifier2_id'],
  3217. ]);
  3218. if (isset($labelMap[(int)$payload['verifier1_id']]) && (int)$payload['verifier1_id'] > 0) {
  3219. $name1 = $labelMap[(int)$payload['verifier1_id']];
  3220. }
  3221. if (isset($labelMap[(int)$payload['verifier2_id']]) && (int)$payload['verifier2_id'] > 0) {
  3222. $name2 = $labelMap[(int)$payload['verifier2_id']];
  3223. }
  3224. $logMsg = '开标验证:' . $name1 . '、' . $name2 . ' 于 ' . $now . ' 完成双重验证';
  3225. $seenSid = [];
  3226. foreach ($bundle['pos'] ?? [] as $poRow) {
  3227. if (!is_array($poRow)) {
  3228. continue;
  3229. }
  3230. $sid = (int)($poRow['scydgy_id'] ?? 0);
  3231. if (!$this->isValidScydgyRowId($sid) || isset($seenSid[$sid])) {
  3232. continue;
  3233. }
  3234. $seenSid[$sid] = true;
  3235. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  3236. $this->addOrderLog($sid, 'bid_open_verify', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  3237. }
  3238. if ($seenSid === []) {
  3239. $anchor = (int)($this->request->post('scydgy_id', $this->request->param('ids', 0)));
  3240. if ($this->isValidScydgyRowId($anchor)) {
  3241. $this->addOrderLog($anchor, 'bid_open_verify', $logMsg, null);
  3242. }
  3243. }
  3244. // 开标通过后计算并写入供应商服务评分
  3245. try {
  3246. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  3247. ProcuremenSupplierScore::saveForOrder($ccydh, $quoteGroups, date('Y-m', strtotime($now) ?: time()));
  3248. } catch (\Throwable $e) {
  3249. Log::write('bid open supplier score: ' . $e->getMessage(), 'error');
  3250. }
  3251. }
  3252. /**
  3253. * 报价行展示字段默认值(模板安全访问)
  3254. *
  3255. * @param array<string, mixed> $line
  3256. * @return array<string, mixed>
  3257. */
  3258. protected function ensureSupplierQuoteLineDisplayKeys(array $line): array
  3259. {
  3260. if (!array_key_exists('amount_quote_pending', $line)) {
  3261. $line['amount_quote_pending'] = 0;
  3262. }
  3263. if (!array_key_exists('delivery_quote_pending', $line)) {
  3264. $line['delivery_quote_pending'] = 0;
  3265. }
  3266. if (!array_key_exists('quote_before_deadline', $line)) {
  3267. $line['quote_before_deadline'] = 0;
  3268. }
  3269. if (!array_key_exists('amount_filled', $line)) {
  3270. $line['amount_filled'] = 0;
  3271. }
  3272. if (!array_key_exists('delivery_filled', $line)) {
  3273. $line['delivery_filled'] = 0;
  3274. }
  3275. if (!array_key_exists('lead_days_filled', $line)) {
  3276. $line['lead_days_filled'] = 0;
  3277. }
  3278. if (!array_key_exists('lead_days_quote_pending', $line)) {
  3279. $line['lead_days_quote_pending'] = 0;
  3280. }
  3281. if (!array_key_exists('lead_days_show', $line)) {
  3282. $line['lead_days_show'] = '未填写';
  3283. }
  3284. if (!array_key_exists('lead_days_text', $line)) {
  3285. $line['lead_days_text'] = $line['lead_days_show'];
  3286. }
  3287. return $line;
  3288. }
  3289. /**
  3290. * 审核弹窗:按供应商汇总报价明细
  3291. *
  3292. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3293. * @return array<int, array<string, mixed>>
  3294. */
  3295. protected function loadAuditSupplierQuoteGroups(array $bundle): array
  3296. {
  3297. $sids = [];
  3298. foreach ($bundle['pos'] ?? [] as $po) {
  3299. if (!is_array($po)) {
  3300. continue;
  3301. }
  3302. $sid = (int)($po['scydgy_id'] ?? 0);
  3303. if ($this->isValidScydgyRowId($sid)) {
  3304. $sids[$sid] = true;
  3305. }
  3306. }
  3307. if ($sids === []) {
  3308. return [];
  3309. }
  3310. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3311. $gymcMap = [];
  3312. $qtyBySid = [];
  3313. $orderedSids = [];
  3314. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3315. if (!is_array($mr)) {
  3316. continue;
  3317. }
  3318. $gid = $this->extractScydgyRowId($mr);
  3319. if ($this->isValidScydgyRowId($gid)) {
  3320. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3321. $orderedSids[] = $gid;
  3322. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3323. if ($qty === '') {
  3324. $qty = trim((string)($mr['NGZL'] ?? ''));
  3325. }
  3326. $qtyBySid[$gid] = $qty;
  3327. }
  3328. }
  3329. foreach ($bundle['pos'] ?? [] as $po) {
  3330. if (!is_array($po)) {
  3331. continue;
  3332. }
  3333. $gid = (int)($po['scydgy_id'] ?? 0);
  3334. if ($this->isValidScydgyRowId($gid)) {
  3335. $nm = trim((string)($po['CGYMC'] ?? ''));
  3336. if ($nm !== '') {
  3337. $gymcMap[$gid] = $nm;
  3338. }
  3339. if (!in_array($gid, $orderedSids, true)) {
  3340. $orderedSids[] = $gid;
  3341. }
  3342. }
  3343. }
  3344. try {
  3345. $detailsQuery = Db::table('purchase_order_detail')
  3346. ->where('scydgy_id', 'in', array_keys($sids));
  3347. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3348. $details = $detailsQuery->order('company_name', 'asc')->order('id', 'asc')->select();
  3349. } catch (\Throwable $e) {
  3350. try {
  3351. $detailsQuery = Db::table('purchase_order_detail')
  3352. ->where('scydgy_id', 'in', array_keys($sids));
  3353. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  3354. $details = $detailsQuery->order('company_name', 'asc')->order('ID', 'asc')->select();
  3355. } catch (\Throwable $e2) {
  3356. $details = [];
  3357. }
  3358. }
  3359. if (!is_array($details)) {
  3360. $details = [];
  3361. }
  3362. $byCompany = [];
  3363. foreach ($details as $d) {
  3364. if (!is_array($d)) {
  3365. continue;
  3366. }
  3367. $cn = trim((string)($d['company_name'] ?? ''));
  3368. if ($cn === '') {
  3369. continue;
  3370. }
  3371. if (!isset($byCompany[$cn])) {
  3372. $ph = trim((string)($d['phone'] ?? ''));
  3373. $username = trim((string)($d['username'] ?? ''));
  3374. if ($username === '') {
  3375. $username = $this->resolveCustomerContactName($ph, $cn);
  3376. }
  3377. $byCompany[$cn] = [
  3378. 'name' => $cn,
  3379. 'email' => trim((string)($d['email'] ?? '')),
  3380. 'phone' => $ph,
  3381. 'username' => $username,
  3382. 'remark' => '',
  3383. 'has_quote' => false,
  3384. 'lines_map' => [],
  3385. ];
  3386. }
  3387. if ($byCompany[$cn]['remark'] === '') {
  3388. $rm = '';
  3389. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3390. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3391. $rm = trim((string)$d[$rk]);
  3392. break;
  3393. }
  3394. }
  3395. if ($rm !== '') {
  3396. $byCompany[$cn]['remark'] = $rm;
  3397. }
  3398. }
  3399. $sid = (int)($d['scydgy_id'] ?? 0);
  3400. $am = trim((string)($d['amount'] ?? ''));
  3401. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3402. if ($gymc === '') {
  3403. $gymc = '工序';
  3404. }
  3405. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3406. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3407. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3408. $deliveryShow = $deliveryRaw;
  3409. }
  3410. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3411. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3412. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3413. $subtotal = null;
  3414. if ($amountNum !== null) {
  3415. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3416. }
  3417. $unitPriceText = $amountFilled
  3418. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3419. : '未填写';
  3420. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3421. $leadFilled = ($leadDays !== null);
  3422. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3423. $lineRow = [
  3424. 'cgymc' => $gymc,
  3425. 'amount' => $am,
  3426. 'amount_show' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '',
  3427. 'amount_filled' => $amountFilled,
  3428. 'unit_price_text' => $unitPriceText,
  3429. 'delivery' => $deliveryRaw,
  3430. 'delivery_show' => $deliveryFilled ? $deliveryShow : '未填写',
  3431. 'delivery_filled' => $deliveryFilled,
  3432. 'delivery_ymd' => $deliveryFilled ? $deliveryShow : '',
  3433. 'lead_days' => $leadFilled ? $leadDays : '',
  3434. 'lead_days_filled'=> $leadFilled,
  3435. 'lead_days_show' => $leadText,
  3436. 'lead_days_text' => $leadText,
  3437. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3438. 'subtotal_num' => $subtotal,
  3439. 'status_name' => trim((string)($d['status_name'] ?? '')),
  3440. 'is_quoted' => $amountFilled,
  3441. 'quote_label' => $amountFilled ? '已报价' : '未报价',
  3442. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3443. ];
  3444. if (!$quoteVisible) {
  3445. $this->maskSupplierQuoteLineBeforeDeadline($lineRow);
  3446. }
  3447. // 按工序 id 暂存,下面再按上方工序表顺序输出
  3448. $byCompany[$cn]['lines_map'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($lineRow);
  3449. }
  3450. foreach ($byCompany as $cn => $g) {
  3451. $linesMap = is_array($g['lines_map'] ?? null) ? $g['lines_map'] : [];
  3452. $lines = [];
  3453. $usedSids = [];
  3454. foreach ($orderedSids as $sid) {
  3455. if (!isset($linesMap[$sid])) {
  3456. continue;
  3457. }
  3458. $lines[] = $linesMap[$sid];
  3459. $usedSids[$sid] = true;
  3460. }
  3461. foreach ($linesMap as $sid => $ln) {
  3462. if (isset($usedSids[$sid])) {
  3463. continue;
  3464. }
  3465. $lines[] = $ln;
  3466. }
  3467. $total = count($lines);
  3468. $quoted = 0;
  3469. $groupTotal = 0.0;
  3470. $groupHasTotal = false;
  3471. if ($quoteVisible) {
  3472. foreach ($lines as $ln) {
  3473. $am = trim((string)($ln['amount'] ?? ''));
  3474. if ($am !== '' && $am !== '0' && $am !== '0.00') {
  3475. $quoted++;
  3476. }
  3477. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3478. $groupTotal += (float)$ln['subtotal_num'];
  3479. $groupHasTotal = true;
  3480. }
  3481. }
  3482. }
  3483. unset($byCompany[$cn]['lines_map']);
  3484. $byCompany[$cn]['lines'] = $lines;
  3485. $byCompany[$cn]['has_quote'] = $quoteVisible && $total > 0 && $quoted === $total;
  3486. $byCompany[$cn]['line_count'] = $total;
  3487. $byCompany[$cn]['has_total'] = $total > 0;
  3488. $byCompany[$cn]['has_remark'] = $total > 0;
  3489. $this->maskSupplierRemarkBeforeBidOpen($byCompany[$cn], $quoteVisible);
  3490. $byCompany[$cn]['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3491. // 工序行 + 备注行 + 总计行
  3492. $byCompany[$cn]['display_rowspan'] = $total > 0 ? ($total + 2) : 0;
  3493. }
  3494. $groups = array_values($byCompany);
  3495. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3496. return ProcuremenSupplierScore::attachToQuoteGroups($groups, $ccydh, (bool)$quoteVisible);
  3497. }
  3498. /**
  3499. * 采购确认弹窗:按供应商汇总本单各工序报价(含明细 ID 供提交)
  3500. *
  3501. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  3502. * @return array<int, array<string, mixed>>
  3503. */
  3504. protected function loadConfirmSupplierPickGroups(array $bundle): array
  3505. {
  3506. $sids = [];
  3507. $poIdMap = [];
  3508. foreach ($bundle['pos'] ?? [] as $po) {
  3509. if (!is_array($po)) {
  3510. continue;
  3511. }
  3512. $sid = (int)($po['scydgy_id'] ?? 0);
  3513. if ($this->isValidScydgyRowId($sid)) {
  3514. $sids[$sid] = true;
  3515. $poIdMap[$sid] = (int)($po['id'] ?? $po['ID'] ?? 0);
  3516. }
  3517. }
  3518. if ($sids === []) {
  3519. return [];
  3520. }
  3521. $quoteVisible = $this->canViewProcuremenSupplierQuotesForBundle($bundle);
  3522. $gymcMap = [];
  3523. $qtyBySid = [];
  3524. $orderedSids = [];
  3525. foreach ($bundle['merge_rows'] ?? [] as $mr) {
  3526. if (!is_array($mr)) {
  3527. continue;
  3528. }
  3529. $gid = $this->extractScydgyRowId($mr);
  3530. if ($this->isValidScydgyRowId($gid)) {
  3531. $gymcMap[$gid] = trim((string)($mr['CGYMC'] ?? ''));
  3532. $orderedSids[] = $gid;
  3533. $qty = trim((string)($mr['This_quantity'] ?? ''));
  3534. if ($qty === '') {
  3535. $qty = trim((string)($mr['NGZL'] ?? ''));
  3536. }
  3537. $qtyBySid[$gid] = $qty;
  3538. }
  3539. }
  3540. foreach ($bundle['pos'] ?? [] as $po) {
  3541. if (!is_array($po)) {
  3542. continue;
  3543. }
  3544. $gid = (int)($po['scydgy_id'] ?? 0);
  3545. if ($this->isValidScydgyRowId($gid)) {
  3546. $nm = trim((string)($po['CGYMC'] ?? ''));
  3547. if ($nm !== '') {
  3548. $gymcMap[$gid] = $nm;
  3549. }
  3550. }
  3551. }
  3552. try {
  3553. $details = Db::table('purchase_order_detail')
  3554. ->where('scydgy_id', 'in', array_keys($sids))
  3555. ->order('company_name', 'asc')
  3556. ->order('id', 'asc')
  3557. ->select();
  3558. } catch (\Throwable $e) {
  3559. try {
  3560. $details = Db::table('purchase_order_detail')
  3561. ->where('scydgy_id', 'in', array_keys($sids))
  3562. ->order('company_name', 'asc')
  3563. ->order('ID', 'asc')
  3564. ->select();
  3565. } catch (\Throwable $e2) {
  3566. $details = [];
  3567. }
  3568. }
  3569. if (!is_array($details)) {
  3570. $details = [];
  3571. }
  3572. $byCompany = [];
  3573. foreach ($details as $d) {
  3574. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3575. continue;
  3576. }
  3577. $cn = trim((string)($d['company_name'] ?? ''));
  3578. if ($cn === '') {
  3579. continue;
  3580. }
  3581. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  3582. $sid = (int)($d['scydgy_id'] ?? 0);
  3583. if ($detailId <= 0 || !$this->isValidScydgyRowId($sid)) {
  3584. continue;
  3585. }
  3586. if (!isset($byCompany[$cn])) {
  3587. $ph = trim((string)($d['phone'] ?? ''));
  3588. $username = trim((string)($d['username'] ?? ''));
  3589. if ($username === '') {
  3590. $username = $this->resolveCustomerContactName($ph, $cn);
  3591. }
  3592. $byCompany[$cn] = [
  3593. 'name' => $cn,
  3594. 'email' => trim((string)($d['email'] ?? '')),
  3595. 'phone' => $ph,
  3596. 'username' => $username,
  3597. 'remark' => '',
  3598. 'pick_lines' => [],
  3599. 'detail_picks' => [],
  3600. ];
  3601. }
  3602. if ($byCompany[$cn]['remark'] === '') {
  3603. $rm = '';
  3604. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  3605. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  3606. $rm = trim((string)$d[$rk]);
  3607. break;
  3608. }
  3609. }
  3610. if ($rm !== '') {
  3611. $byCompany[$cn]['remark'] = $rm;
  3612. }
  3613. }
  3614. $gymc = $gymcMap[$sid] ?? trim((string)($d['CGYMC'] ?? $d['cgymc'] ?? ''));
  3615. if ($gymc === '') {
  3616. $gymc = '工序';
  3617. }
  3618. $am = trim((string)($d['amount'] ?? ''));
  3619. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  3620. $deliveryRaw = trim((string)($d['delivery'] ?? ''));
  3621. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  3622. if ($deliveryShow === '' && $deliveryRaw !== '') {
  3623. $deliveryShow = $deliveryRaw;
  3624. }
  3625. $deliveryFilled = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow));
  3626. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  3627. $subtotal = null;
  3628. if ($amountNum !== null) {
  3629. $subtotal = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyBySid[$sid] ?? '');
  3630. }
  3631. $unitPriceText = $amountFilled
  3632. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  3633. : '未填写';
  3634. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? $deliveryShow : '');
  3635. $leadFilled = ($leadDays !== null);
  3636. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  3637. $pickLine = [
  3638. 'cgymc' => $gymc,
  3639. 'amount' => $amountFilled ? ($amountNum !== null ? (string)$amountNum : $am) : '',
  3640. 'amount_text' => $amountFilled ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am) : '未填写',
  3641. 'delivery_text' => $deliveryFilled ? $deliveryShow : '未填写',
  3642. 'amount_filled' => $amountFilled,
  3643. 'delivery_filled' => $deliveryFilled,
  3644. 'unit_price_text' => $unitPriceText,
  3645. 'lead_days' => $leadFilled ? $leadDays : '',
  3646. 'lead_days_filled'=> $leadFilled,
  3647. 'lead_days_show' => $leadText,
  3648. 'lead_days_text' => $leadText,
  3649. 'subtotal_text' => $subtotal !== null ? $this->formatProcuremenMoneyDisplay($subtotal) : '',
  3650. 'subtotal_num' => $subtotal,
  3651. 'oper_time_text' => $this->resolveDetailSupplierOperTime($d),
  3652. 'is_quoted' => $amountFilled,
  3653. ];
  3654. if (!$quoteVisible) {
  3655. $this->maskSupplierQuoteLineBeforeDeadline($pickLine);
  3656. }
  3657. $byCompany[$cn]['pick_lines'][$sid] = $this->ensureSupplierQuoteLineDisplayKeys($pickLine);
  3658. $byCompany[$cn]['detail_picks'][$sid] = [
  3659. 'scydgy_id' => $sid,
  3660. 'detail_id' => $detailId,
  3661. 'purchase_order_id' => $poIdMap[$sid] ?? 0,
  3662. 'cgymc' => $gymc,
  3663. ];
  3664. }
  3665. $out = [];
  3666. foreach ($byCompany as $g) {
  3667. $pickLinesMap = $g['pick_lines'] ?? [];
  3668. if (!is_array($pickLinesMap) || $pickLinesMap === []) {
  3669. continue;
  3670. }
  3671. $pickLines = [];
  3672. $usedLineSids = [];
  3673. foreach ($orderedSids as $sid) {
  3674. if (!isset($pickLinesMap[$sid])) {
  3675. continue;
  3676. }
  3677. $pickLines[] = $pickLinesMap[$sid];
  3678. $usedLineSids[$sid] = true;
  3679. }
  3680. foreach ($pickLinesMap as $sid => $ln) {
  3681. if (isset($usedLineSids[$sid])) {
  3682. continue;
  3683. }
  3684. $pickLines[] = $ln;
  3685. }
  3686. $groupTotal = 0.0;
  3687. $groupHasTotal = false;
  3688. if ($quoteVisible) {
  3689. foreach ($pickLines as $ln) {
  3690. if (isset($ln['subtotal_num']) && $ln['subtotal_num'] !== null) {
  3691. $groupTotal += (float)$ln['subtotal_num'];
  3692. $groupHasTotal = true;
  3693. }
  3694. }
  3695. }
  3696. $lineCount = count($pickLines);
  3697. $g['pick_lines'] = $pickLines;
  3698. $g['line_count'] = $lineCount;
  3699. $g['has_total'] = $lineCount > 0;
  3700. $g['has_remark'] = $lineCount > 0;
  3701. $this->maskSupplierRemarkBeforeBidOpen($g, $quoteVisible);
  3702. $g['total_text'] = ($quoteVisible && $groupHasTotal) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '';
  3703. // 工序行 + 备注行 + 总计行
  3704. $g['display_rowspan'] = $lineCount > 0 ? ($lineCount + 2) : 0;
  3705. $detailPicksMap = is_array($g['detail_picks'] ?? null) ? $g['detail_picks'] : [];
  3706. $detailPicks = [];
  3707. $usedPickSids = [];
  3708. foreach ($orderedSids as $sid) {
  3709. if (!isset($detailPicksMap[$sid])) {
  3710. continue;
  3711. }
  3712. $detailPicks[] = $detailPicksMap[$sid];
  3713. $usedPickSids[$sid] = true;
  3714. }
  3715. foreach ($detailPicksMap as $sid => $dp) {
  3716. if (isset($usedPickSids[$sid])) {
  3717. continue;
  3718. }
  3719. $detailPicks[] = $dp;
  3720. }
  3721. $g['detail_picks'] = $detailPicks;
  3722. $g['detail_picks_json'] = json_encode($g['detail_picks'], JSON_UNESCAPED_UNICODE);
  3723. unset($g['detail_picks']);
  3724. $out[] = $g;
  3725. }
  3726. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  3727. return ProcuremenSupplierScore::attachToQuoteGroups($out, $ccydh, (bool)$quoteVisible);
  3728. }
  3729. /**
  3730. * @param array<int, array<string, mixed>> $details purchase_order_detail 行
  3731. * @return array<int, int[]> scydgy_id => detail_id[]
  3732. */
  3733. protected function mapDetailIdsByScydgyId(array $details): array
  3734. {
  3735. $out = [];
  3736. foreach ($details as $d) {
  3737. if (!is_array($d) || !$this->isActivePurchaseOrderDetailRow($d)) {
  3738. continue;
  3739. }
  3740. $sid = (int)($d['scydgy_id'] ?? 0);
  3741. $pk = (int)($d['id'] ?? $d['ID'] ?? 0);
  3742. if (!$this->isValidScydgyRowId($sid) || $pk <= 0) {
  3743. continue;
  3744. }
  3745. if (!isset($out[$sid])) {
  3746. $out[$sid] = [];
  3747. }
  3748. $out[$sid][] = $pk;
  3749. }
  3750. foreach ($out as $sid => $ids) {
  3751. $out[$sid] = array_values(array_unique($ids));
  3752. }
  3753. return $out;
  3754. }
  3755. /**
  3756. * purchase_order 表行 → 列表/弹窗用的工序行(用表内已有字段,不依赖 row_json)
  3757. *
  3758. * @param array<string, mixed> $dbRow
  3759. * @param array<int, mixed> $dStampMap scydgy_id => dStamp
  3760. */
  3761. protected function buildListRowFromPurchaseOrderDbRow(array $dbRow, array $dStampMap = []): array
  3762. {
  3763. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  3764. $r = [
  3765. 'ID' => $sid,
  3766. 'scydgy_id' => $sid,
  3767. 'CCYDH' => $dbRow['CCYDH'] ?? '',
  3768. 'CYJMC' => $dbRow['CYJMC'] ?? '',
  3769. 'CCLBMMC' => $dbRow['CCLBMMC'] ?? '',
  3770. 'CDXMC' => $dbRow['CDXMC'] ?? '',
  3771. 'CGYBH' => $dbRow['CGYBH'] ?? '',
  3772. 'CGYMC' => $dbRow['CGYMC'] ?? '',
  3773. 'CDW' => $dbRow['CDW'] ?? '',
  3774. 'czlyq' => $dbRow['czlyq'] ?? '',
  3775. 'NGZL' => $dbRow['NGZL'] ?? '',
  3776. 'CDF' => $dbRow['CDF'] ?? '',
  3777. 'cGzzxMc' => $dbRow['cGzzxMc'] ?? '',
  3778. 'MBZ' => $dbRow['MBZ'] ?? '',
  3779. 'bwjg' => $dbRow['bwjg'] ?? '',
  3780. 'iStatus' => $dbRow['iStatus'] ?? '',
  3781. 'dputrecord' => $dbRow['dputrecord'] ?? '',
  3782. 'cywyxm' => $dbRow['cywyxm'] ?? '',
  3783. 'This_quantity' => $dbRow['This_quantity'] ?? $dbRow['this_quantity'] ?? '',
  3784. 'ceilingPrice' => $dbRow['ceilingPrice'] ?? $dbRow['ceiling_price'] ?? '',
  3785. 'dStamp' => $dbRow['dStamp'] ?? '',
  3786. 'pick_time' => $dbRow['pick_time'] ?? '',
  3787. ];
  3788. $r['This_quantity'] = $this->resolveProcuremenThisQuantity($r);
  3789. $r['ceilingPrice'] = $this->resolveProcuremenCeilingPrice($r);
  3790. if ($sid > 0 && isset($dStampMap[$sid])) {
  3791. $t = trim((string)$dStampMap[$sid]);
  3792. if ($t !== '' && stripos($t, '0000-00-00') !== 0) {
  3793. $r['dStamp'] = $dStampMap[$sid];
  3794. }
  3795. }
  3796. $dsOut = trim((string)($r['dStamp'] ?? ''));
  3797. if (($dsOut === '' || stripos($dsOut, '0000-00-00') === 0) && !empty($dbRow['createtime'])) {
  3798. $ct = $dbRow['createtime'];
  3799. if (is_numeric($ct) && (int)$ct > 946684800) {
  3800. $r['dStamp'] = date('Y-m-d H:i:s', (int)$ct);
  3801. } elseif (is_string($ct) && trim($ct) !== '' && stripos(trim($ct), '0000-00-00') !== 0) {
  3802. $r['dStamp'] = trim($ct);
  3803. }
  3804. }
  3805. // 列表月份筛选读 dputrecord;手工行无 ERP 提交日时回退 dStamp/createtime
  3806. $dpOut = trim((string)($r['dputrecord'] ?? ''));
  3807. if ($dpOut === '' || stripos($dpOut, '0000-00-00') === 0) {
  3808. $fallback = trim((string)($r['dStamp'] ?? ''));
  3809. if ($fallback !== '' && stripos($fallback, '0000-00-00') !== 0) {
  3810. $r['dputrecord'] = $fallback;
  3811. }
  3812. }
  3813. if (array_key_exists('id', $dbRow)) {
  3814. $r['purchase_order_id'] = (int)$dbRow['id'];
  3815. }
  3816. if ($sid < 0) {
  3817. $r['_is_manual'] = 1;
  3818. }
  3819. $r['createtime'] = $this->formatProcuremenDetailTime($dbRow['createtime'] ?? null);
  3820. $pickOut = trim((string)($r['pick_time'] ?? ''));
  3821. if ($pickOut === '' || stripos($pickOut, '0000-00-00') === 0) {
  3822. foreach (['createtime', 'dputrecord', 'dStamp'] as $pickFallbackKey) {
  3823. $pickFallback = trim((string)($r[$pickFallbackKey] ?? ''));
  3824. if ($pickFallback !== '' && stripos($pickFallback, '0000-00-00') !== 0) {
  3825. $r['pick_time'] = $pickFallback;
  3826. break;
  3827. }
  3828. }
  3829. }
  3830. $pickNm = trim((string)($dbRow['pick_company_name'] ?? ''));
  3831. if ($pickNm !== '') {
  3832. $r['pick_company_name'] = $pickNm;
  3833. $r['picked_supplier_name'] = $pickNm;
  3834. }
  3835. return $r;
  3836. }
  3837. /**
  3838. * 与列表「已下发 / 已选中 / 已完结」同源:将 purchase_order 行还原为工序列表行
  3839. *
  3840. * @return array<int, array<string, mixed>>
  3841. */
  3842. protected function procuremenPoolFromPurchaseOrderDbRows(array $dbRows): array
  3843. {
  3844. $pool = [];
  3845. if (!is_array($dbRows) || $dbRows === []) {
  3846. return $pool;
  3847. }
  3848. $dStampMap = [];
  3849. $sidList = [];
  3850. foreach ($dbRows as $tmpRow) {
  3851. if (is_array($tmpRow) && isset($tmpRow['scydgy_id'])) {
  3852. $sid = (int)$tmpRow['scydgy_id'];
  3853. if ($sid > 0) {
  3854. $ds = trim((string)($tmpRow['dStamp'] ?? ''));
  3855. if ($ds === '' || stripos($ds, '0000-00-00') === 0) {
  3856. $sidList[$sid] = true;
  3857. }
  3858. }
  3859. }
  3860. }
  3861. if ($sidList !== []) {
  3862. try {
  3863. $dStampMap = Db::table('scydgy')->where('ID', 'in', array_keys($sidList))->column('dStamp', 'ID');
  3864. } catch (\Throwable $e) {
  3865. $dStampMap = [];
  3866. }
  3867. }
  3868. foreach ($dbRows as $dbRow) {
  3869. if (!is_array($dbRow)) {
  3870. continue;
  3871. }
  3872. $pool[] = $this->buildListRowFromPurchaseOrderDbRow($dbRow, $dStampMap);
  3873. }
  3874. // 历史单据可能未落库 czlyq:按订单号从 ERP 补齐「类型」
  3875. $needCcydh = [];
  3876. foreach ($pool as $row) {
  3877. if (!is_array($row)) {
  3878. continue;
  3879. }
  3880. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3881. continue;
  3882. }
  3883. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3884. if ($ccydh !== '') {
  3885. $needCcydh[$ccydh] = true;
  3886. }
  3887. }
  3888. if ($needCcydh !== []) {
  3889. $czMap = [];
  3890. try {
  3891. $czMap = Db::table('mcyd')->where('CCYDH', 'in', array_keys($needCcydh))->column('czlyq', 'CCYDH');
  3892. } catch (\Throwable $e) {
  3893. $czMap = [];
  3894. }
  3895. if (is_array($czMap) && $czMap !== []) {
  3896. foreach ($pool as &$row) {
  3897. if (!is_array($row)) {
  3898. continue;
  3899. }
  3900. if (trim((string)($row['czlyq'] ?? '')) !== '') {
  3901. continue;
  3902. }
  3903. $ccydh = trim((string)($row['CCYDH'] ?? ''));
  3904. if ($ccydh !== '' && isset($czMap[$ccydh]) && trim((string)$czMap[$ccydh]) !== '') {
  3905. $row['czlyq'] = trim((string)$czMap[$ccydh]);
  3906. }
  3907. }
  3908. unset($row);
  3909. }
  3910. }
  3911. return $pool;
  3912. }
  3913. /**
  3914. * 批量读取 purchase_order_detail(确认/审批列表统计用)
  3915. *
  3916. * @param int[] $scydgyIds
  3917. * @return array<int, array<string, mixed>>
  3918. */
  3919. protected function loadOrderDetailRowsByScydgyIds(array $scydgyIds): array
  3920. {
  3921. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3922. if ($scydgyIds === []) {
  3923. return [];
  3924. }
  3925. try {
  3926. $list = Db::table('purchase_order_detail')
  3927. ->where('scydgy_id', 'in', $scydgyIds)
  3928. ->field('scydgy_id,company_name,amount,delivery')
  3929. ->select();
  3930. } catch (\Throwable $e) {
  3931. $list = [];
  3932. }
  3933. return is_array($list) ? $list : [];
  3934. }
  3935. /**
  3936. * 合并工序行后按公司去重统计:已下发、已填单价、已填货期
  3937. *
  3938. * @param int[] $scydgyIds
  3939. * @param array<int, array<string, mixed>> $allRows
  3940. * @return array{cnt:int, amt:int, deliv:int}
  3941. */
  3942. protected function summarizeMergedOrderDetails(array $scydgyIds, array $allRows): array
  3943. {
  3944. $out = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  3945. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  3946. if ($scydgyIds === [] || $allRows === []) {
  3947. return $out;
  3948. }
  3949. $idSet = array_flip($scydgyIds);
  3950. $all = [];
  3951. $withAmt = [];
  3952. $withDeliv = [];
  3953. foreach ($allRows as $r) {
  3954. if (!is_array($r)) {
  3955. continue;
  3956. }
  3957. $sid = (int)($r['scydgy_id'] ?? 0);
  3958. if (!isset($idSet[$sid])) {
  3959. continue;
  3960. }
  3961. $cn = trim((string)($r['company_name'] ?? ''));
  3962. if ($cn === '') {
  3963. continue;
  3964. }
  3965. $all[$cn] = true;
  3966. $am = $r['amount'] ?? null;
  3967. if ($am !== null && $am !== '' && !(is_string($am) && trim($am) === '')) {
  3968. $withAmt[$cn] = true;
  3969. }
  3970. $dv = $r['delivery'] ?? null;
  3971. if ($dv !== null && trim((string)$dv) !== '') {
  3972. $withDeliv[$cn] = true;
  3973. }
  3974. }
  3975. return [
  3976. 'cnt' => count($all),
  3977. 'amt' => count($withAmt),
  3978. 'deliv' => count($withDeliv),
  3979. ];
  3980. }
  3981. /**
  3982. * 本次数量:优先 This_quantity,空则回退工作量 NGZL(与下发/确认/审批弹窗一致)
  3983. *
  3984. * @param array<string, mixed> $row
  3985. */
  3986. protected function resolveProcuremenThisQuantity(array $row): string
  3987. {
  3988. $q = trim((string)($row['This_quantity'] ?? $row['this_quantity'] ?? ''));
  3989. if ($q !== '') {
  3990. return $q;
  3991. }
  3992. $ngzl = $row['NGZL'] ?? $row['ngzl'] ?? '';
  3993. if (!is_scalar($ngzl)) {
  3994. return '';
  3995. }
  3996. $s = trim((string)$ngzl);
  3997. if ($s === '') {
  3998. return '';
  3999. }
  4000. if (is_numeric($s) && (float)$s === 0.0) {
  4001. return '';
  4002. }
  4003. return $s;
  4004. }
  4005. /**
  4006. * @param array<string, mixed> $row
  4007. */
  4008. protected function resolveProcuremenCeilingPrice(array $row): string
  4009. {
  4010. return trim((string)($row['ceilingPrice'] ?? $row['ceiling_price'] ?? ''));
  4011. }
  4012. /**
  4013. * 多工序数量/限价拼接:跳过空值,避免出现「、10」「304、」
  4014. *
  4015. * @param array<int, mixed> $parts
  4016. */
  4017. protected function joinProcuremenNonEmpty(array $parts, string $sep = '、'): string
  4018. {
  4019. $out = [];
  4020. foreach ($parts as $p) {
  4021. $s = trim((string)$p);
  4022. if ($s !== '') {
  4023. $out[] = $s;
  4024. }
  4025. }
  4026. return $out === [] ? '' : implode($sep, $out);
  4027. }
  4028. /**
  4029. * 确认/审批列表:合并行按各工序同步本次数量、最高限价(顿号间隔)
  4030. *
  4031. * @param array<int, array<string, mixed>> $rows
  4032. */
  4033. protected function syncCollapsedOrderQtyPriceForList(array &$rows): void
  4034. {
  4035. if ($rows === []) {
  4036. return;
  4037. }
  4038. $idList = [];
  4039. foreach ($rows as $rw) {
  4040. if (!is_array($rw)) {
  4041. continue;
  4042. }
  4043. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4044. foreach ($rw['_order_merge_rows'] as $mr) {
  4045. if (!is_array($mr)) {
  4046. continue;
  4047. }
  4048. $mid = (int)($mr['ID'] ?? 0);
  4049. if ($this->isValidScydgyRowId($mid)) {
  4050. $idList[$mid] = true;
  4051. }
  4052. }
  4053. }
  4054. $id = (int)($rw['ID'] ?? 0);
  4055. if ($this->isValidScydgyRowId($id)) {
  4056. $idList[$id] = true;
  4057. }
  4058. }
  4059. if ($idList === []) {
  4060. return;
  4061. }
  4062. try {
  4063. $list = Db::table('purchase_order')
  4064. ->where('scydgy_id', 'in', array_keys($idList))
  4065. ->field('scydgy_id,This_quantity,ceilingPrice,NGZL,pick_company_name')
  4066. ->select();
  4067. } catch (\Throwable $e) {
  4068. return;
  4069. }
  4070. if (!is_array($list)) {
  4071. return;
  4072. }
  4073. $byId = [];
  4074. foreach ($list as $dbRow) {
  4075. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4076. continue;
  4077. }
  4078. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4079. }
  4080. foreach ($rows as &$rw) {
  4081. if (!is_array($rw)) {
  4082. continue;
  4083. }
  4084. $mergeRows = [];
  4085. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  4086. $mergeRows = $rw['_order_merge_rows'];
  4087. } else {
  4088. $mergeRows = [$rw];
  4089. }
  4090. $qtyList = [];
  4091. $priceList = [];
  4092. $picked = '';
  4093. foreach ($mergeRows as $mr) {
  4094. if (!is_array($mr)) {
  4095. continue;
  4096. }
  4097. $sid = (int)($mr['ID'] ?? 0);
  4098. $db = ($sid !== 0 && isset($byId[$sid])) ? $byId[$sid] : null;
  4099. $src = $mr;
  4100. if (is_array($db)) {
  4101. $qDb = trim((string)($db['This_quantity'] ?? $db['this_quantity'] ?? ''));
  4102. $pDb = trim((string)($db['ceilingPrice'] ?? $db['ceiling_price'] ?? ''));
  4103. $ngzlDb = $db['NGZL'] ?? $db['ngzl'] ?? null;
  4104. if ($qDb !== '') {
  4105. $src['This_quantity'] = $qDb;
  4106. }
  4107. if ($pDb !== '') {
  4108. $src['ceilingPrice'] = $pDb;
  4109. }
  4110. if ($ngzlDb !== null && trim((string)$ngzlDb) !== '') {
  4111. $src['NGZL'] = $ngzlDb;
  4112. }
  4113. if ($picked === '') {
  4114. $picked = trim((string)($db['pick_company_name'] ?? ''));
  4115. }
  4116. }
  4117. if ($picked === '') {
  4118. $picked = trim((string)($mr['pick_company_name'] ?? $mr['picked_supplier_name'] ?? ''));
  4119. }
  4120. $qtyList[] = $this->resolveProcuremenThisQuantity($src);
  4121. $priceList[] = $this->resolveProcuremenCeilingPrice($src);
  4122. }
  4123. $rw['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  4124. $rw['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  4125. if ($picked !== '') {
  4126. $rw['pick_company_name'] = $picked;
  4127. $rw['picked_supplier_name'] = $picked;
  4128. }
  4129. }
  4130. unset($rw);
  4131. }
  4132. /**
  4133. * 已下发列表汇总:按工序行 ID 统计 purchase_order_detail 条数、已填金额条数、已填货期条数
  4134. *
  4135. * @param int[] $scydgyIds
  4136. * @return array<int, array{cnt:int, amt:int, deliv:int}>
  4137. * @deprecated 合并工序展示请用 summarizeMergedOrderDetails
  4138. */
  4139. protected function OrderDetailSummary(array $scydgyIds)
  4140. {
  4141. $out = [];
  4142. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4143. if ($scydgyIds === []) {
  4144. return $out;
  4145. }
  4146. $list = [];
  4147. try {
  4148. $list = Db::table('purchase_order_detail')
  4149. ->where('scydgy_id', 'in', $scydgyIds)
  4150. ->field('id,scydgy_id,amount,delivery')
  4151. ->select();
  4152. } catch (\Throwable $e) {
  4153. $list = [];
  4154. }
  4155. if (!is_array($list)) {
  4156. return $out;
  4157. }
  4158. foreach ($list as $r) {
  4159. if (!is_array($r)) {
  4160. continue;
  4161. }
  4162. $ids = (int)($r['scydgy_id'] ?? 0);
  4163. if (!$this->isValidScydgyRowId($ids)) {
  4164. continue;
  4165. }
  4166. if (!isset($out[$ids])) {
  4167. $out[$ids] = ['cnt' => 0, 'amt' => 0, 'deliv' => 0];
  4168. }
  4169. $out[$ids]['cnt']++;
  4170. $am = $r['amount'] ?? null;
  4171. if ($am !== null && $am !== '') {
  4172. if (!(is_string($am) && trim($am) === '')) {
  4173. $out[$ids]['amt']++;
  4174. }
  4175. }
  4176. $dv = $r['delivery'] ?? null;
  4177. if ($dv !== null && trim((string)$dv) !== '') {
  4178. $out[$ids]['deliv']++;
  4179. }
  4180. }
  4181. return $out;
  4182. }
  4183. /**
  4184. * 列表筛选:月份按 dputrecord(提交日期)、快速搜索、Bootstrap Table filter
  4185. *
  4186. * @return array
  4187. */
  4188. protected function filterProcuremenIndexPool(array $pool, $monthStart, $monthEnd, $applyMonthRange, $search, array $filterArr, array $opArr, string $listTimePrimary = 'dputrecord')
  4189. {
  4190. $strContains = function ($haystack, $needle) {
  4191. if ($needle === '') {
  4192. return false;
  4193. }
  4194. $haystack = (string)$haystack;
  4195. if (function_exists('mb_stripos')) {
  4196. return mb_stripos($haystack, $needle, 0, 'UTF-8') !== false;
  4197. }
  4198. return stripos($haystack, $needle) !== false;
  4199. };
  4200. $stripAlias = function ($f) {
  4201. return preg_replace('/^[ab]\./i', '', (string)$f);
  4202. };
  4203. $searchColNames = [];
  4204. foreach (explode(',', $this->searchFields) as $colRaw) {
  4205. $c = $stripAlias(trim($colRaw));
  4206. if ($c !== '') {
  4207. $searchColNames[] = $c;
  4208. }
  4209. }
  4210. // 等值条件先行(表头下拉),减少后续日期解析量
  4211. $eqFilters = [];
  4212. $otherFilters = [];
  4213. foreach ($filterArr as $fk => $fv) {
  4214. if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', (string)$fk)) {
  4215. continue;
  4216. }
  4217. if (is_array($fv)) {
  4218. continue;
  4219. }
  4220. if ($fv === '' && $fv !== '0' && $fv !== 0) {
  4221. continue;
  4222. }
  4223. $sym = strtoupper(trim((string)($opArr[$fk] ?? '=')));
  4224. $sym = str_replace(['LIKE %...%', 'NOT LIKE %...%'], ['LIKE', 'NOT LIKE'], $sym);
  4225. $field = $stripAlias($fk);
  4226. if ($sym === '=' || $sym === '') {
  4227. $eqFilters[$field] = trim((string)$fv);
  4228. } else {
  4229. $otherFilters[$fk] = ['fv' => $fv, 'sym' => $sym, 'field' => $field];
  4230. }
  4231. }
  4232. $ymTarget = '';
  4233. if ($applyMonthRange && is_string($monthStart) && preg_match('/^(\d{4}-\d{2})/', $monthStart, $ymM)) {
  4234. $ymTarget = $ymM[1];
  4235. }
  4236. $filtered = [];
  4237. foreach ($pool as $r) {
  4238. if (!is_array($r)) {
  4239. continue;
  4240. }
  4241. foreach ($eqFilters as $field => $fv) {
  4242. if (trim((string)($r[$field] ?? '')) !== $fv) {
  4243. continue 2;
  4244. }
  4245. }
  4246. $isManual = !empty($r['_is_manual']) || $this->isManualScydgyRowId((int)($r['ID'] ?? $r['id'] ?? 0));
  4247. // 初选池不应含手工单;若混入则直接剔除
  4248. if ($isManual) {
  4249. continue;
  4250. }
  4251. $listTime = $this->procuremenRowListSortTime($r, $listTimePrimary);
  4252. if ($listTime === '' || stripos($listTime, '0000-00-00') === 0
  4253. || !preg_match('/^([12]\d{3})-(\d{1,2})-(\d{1,2})/', $listTime, $m)) {
  4254. continue;
  4255. }
  4256. if ($applyMonthRange) {
  4257. $mo = (int)$m[2];
  4258. if ($mo < 1 || $mo > 12) {
  4259. continue;
  4260. }
  4261. if ($ymTarget !== '') {
  4262. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4263. if ($ymRow !== $ymTarget) {
  4264. continue;
  4265. }
  4266. } else {
  4267. $ymRow = $m[1] . '-' . str_pad((string)$mo, 2, '0', STR_PAD_LEFT);
  4268. $rowMonthStart = $ymRow . '-01 00:00:00';
  4269. $rowMonthEnd = date('Y-m-t 23:59:59', strtotime($rowMonthStart));
  4270. if (strcmp($rowMonthEnd, $monthStart) < 0 || strcmp($rowMonthStart, $monthEnd) > 0) {
  4271. continue;
  4272. }
  4273. }
  4274. }
  4275. if ($search !== '') {
  4276. $hitSearch = false;
  4277. foreach ($searchColNames as $c) {
  4278. $cell = isset($r[$c]) ? (string)$r[$c] : '';
  4279. if ($cell !== '' && $strContains($cell, $search)) {
  4280. $hitSearch = true;
  4281. break;
  4282. }
  4283. }
  4284. if (!$hitSearch) {
  4285. continue;
  4286. }
  4287. }
  4288. foreach ($otherFilters as $item) {
  4289. $fv = $item['fv'];
  4290. $sym = $item['sym'];
  4291. $field = $item['field'];
  4292. $cell = array_key_exists($field, $r) ? $r[$field] : null;
  4293. $cellStr = trim((string)$cell);
  4294. switch ($sym) {
  4295. case '<>':
  4296. if ((string)$cell === (string)$fv) {
  4297. continue 3;
  4298. }
  4299. break;
  4300. case 'LIKE':
  4301. case 'NOT LIKE':
  4302. $needle = trim((string)$fv);
  4303. $hit = ($needle !== '' && $strContains($cellStr, $needle));
  4304. if ($sym === 'LIKE' && !$hit) {
  4305. continue 3;
  4306. }
  4307. if ($sym === 'NOT LIKE' && $hit) {
  4308. continue 3;
  4309. }
  4310. break;
  4311. case 'BETWEEN':
  4312. case 'RANGE':
  4313. $parts = is_string($fv) ? explode(' - ', $fv) : [];
  4314. if (count($parts) < 2) {
  4315. $parts = is_string($fv) ? explode(',', $fv) : [];
  4316. }
  4317. $begin = isset($parts[0]) ? trim((string)$parts[0]) : '';
  4318. $end = isset($parts[1]) ? trim((string)$parts[1]) : '';
  4319. if ($begin !== '' && strcmp($cellStr, $begin) < 0) {
  4320. continue 3;
  4321. }
  4322. if ($end !== '' && strcmp($cellStr, $end) > 0) {
  4323. continue 3;
  4324. }
  4325. break;
  4326. case '>':
  4327. if (!(strcmp($cellStr, (string)$fv) > 0)) {
  4328. continue 3;
  4329. }
  4330. break;
  4331. case '>=':
  4332. if (!(strcmp($cellStr, (string)$fv) >= 0)) {
  4333. continue 3;
  4334. }
  4335. break;
  4336. case '<':
  4337. if (!(strcmp($cellStr, (string)$fv) < 0)) {
  4338. continue 3;
  4339. }
  4340. break;
  4341. case '<=':
  4342. if (!(strcmp($cellStr, (string)$fv) <= 0)) {
  4343. continue 3;
  4344. }
  4345. break;
  4346. default:
  4347. if ((string)$cell !== (string)$fv) {
  4348. continue 3;
  4349. }
  4350. break;
  4351. }
  4352. }
  4353. $filtered[] = $r;
  4354. }
  4355. return $filtered;
  4356. }
  4357. /**
  4358. * 查询订单 purchase_order 数据查有无记录,无则插、有则改(全部写在本方法内)
  4359. */
  4360. public function snapshotToProcure()
  4361. {
  4362. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4363. $this->error(__('Invalid parameters'));
  4364. }
  4365. $row = json_decode($this->request->post('row_json', ''), true);
  4366. if (!is_array($row)) {
  4367. $this->error(__('Invalid parameters'));
  4368. }
  4369. try {
  4370. $ids = $this->extractScydgyRowId($row);
  4371. if (!$this->isValidScydgyRowId($ids)) {
  4372. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4373. }
  4374. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4375. $data = [
  4376. 'scydgy_id' => $ids,
  4377. 'CCYDH' => $row['CCYDH'] ?? null,
  4378. 'CYJMC' => $row['CYJMC'] ?? null,
  4379. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4380. 'CDXMC' => $row['CDXMC'] ?? null,
  4381. 'CGYBH' => $row['CGYBH'] ?? null,
  4382. 'CGYMC' => $row['CGYMC'] ?? null,
  4383. 'CDW' => $row['CDW'] ?? null,
  4384. 'czlyq' => $row['czlyq'] ?? null,
  4385. 'NGZL' => $row['NGZL'] ?? null,
  4386. 'CDF' => $row['CDF'] ?? null,
  4387. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4388. 'MBZ' => $row['MBZ'] ?? null,
  4389. 'bwjg' => $row['bwjg'] ?? null,
  4390. 'iStatus' => $row['iStatus'] ?? null,
  4391. 'dStamp' => $row['dStamp'] ?? null,
  4392. 'dputrecord' => $row['dputrecord'] ?? null,
  4393. 'cywyxm' => $row['cywyxm'] ?? null,
  4394. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4395. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4396. ];
  4397. $qtySnap = trim((string)($data['This_quantity'] ?? ''));
  4398. $priceSnap = trim((string)($data['ceilingPrice'] ?? ''));
  4399. if (!$exists && $qtySnap === '' && $priceSnap === '') {
  4400. $this->success('操作成功');
  4401. return;
  4402. }
  4403. if ($exists) {
  4404. $upd = $data;
  4405. unset($upd['scydgy_id'], $upd['status']);
  4406. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4407. } else {
  4408. // 新增:不写 status(空/走库默认);仅写创建时间
  4409. $data['createtime'] = date('Y-m-d H:i:s');
  4410. Db::table('purchase_order')->insert($data);
  4411. }
  4412. } catch (\Throwable $e) {
  4413. $this->error($e->getMessage());
  4414. }
  4415. // 操作记录仅在「审核提交」时写入(review POST + addOrderLog),此处同步不写日志,避免与下发记录重复
  4416. $this->success('操作成功');
  4417. }
  4418. /**
  4419. * 未发列表
  4420. * 「完结」或「仅保存本次数量/最高限价」:有则改、无则插
  4421. * POST finish=1(默认):并置 status=1;finish=0:更新时不改 status;新增不写 status。
  4422. */
  4423. public function completeDirectly()
  4424. {
  4425. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4426. $this->error(__('参数错误'));
  4427. }
  4428. if (!$this->procuremenCanComplete()) {
  4429. $this->error(__('You have no permission'));
  4430. }
  4431. $row = json_decode($this->request->post('row_json', ''), true);
  4432. if (!is_array($row)) {
  4433. $this->error(__('Invalid parameters'));
  4434. }
  4435. $finishRaw = $this->request->post('finish', '1');
  4436. $asComplete = ($finishRaw === '1' || $finishRaw === 1 || $finishRaw === true);
  4437. $poIdLog = null;
  4438. try {
  4439. // 获取工序行 ID,对应 purchase_order.scydgy_id;有则改、无则插
  4440. $ids = $this->extractScydgyRowId($row);
  4441. if (!$this->isValidScydgyRowId($ids)) {
  4442. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请刷新列表后重试');
  4443. }
  4444. if ($asComplete) {
  4445. $this->assertPickRowCanComplete($ids, $row);
  4446. }
  4447. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4448. $data = [
  4449. 'scydgy_id' => $ids,
  4450. 'CCYDH' => $row['CCYDH'] ?? null,
  4451. 'CYJMC' => $row['CYJMC'] ?? null,
  4452. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  4453. 'CDXMC' => $row['CDXMC'] ?? null,
  4454. 'CGYBH' => $row['CGYBH'] ?? null,
  4455. 'CGYMC' => $row['CGYMC'] ?? null,
  4456. 'CDW' => $row['CDW'] ?? null,
  4457. 'czlyq' => $row['czlyq'] ?? null,
  4458. 'NGZL' => $row['NGZL'] ?? null,
  4459. 'CDF' => $row['CDF'] ?? null,
  4460. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  4461. 'MBZ' => $row['MBZ'] ?? null,
  4462. 'bwjg' => $row['bwjg'] ?? null,
  4463. 'iStatus' => $row['iStatus'] ?? null,
  4464. 'dStamp' => $row['dStamp'] ?? null,
  4465. 'dputrecord' => $row['dputrecord'] ?? null,
  4466. 'cywyxm' => $row['cywyxm'] ?? null,
  4467. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  4468. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  4469. ];
  4470. if ($asComplete) {
  4471. $data['status'] = ProcuremenStatus::PO_COMPLETED;
  4472. $data['wflow_status'] = ProcuremenStatus::WFLOW_APPROVED;
  4473. }
  4474. $qtyCd = trim((string)($data['This_quantity'] ?? ''));
  4475. $priceCd = trim((string)($data['ceilingPrice'] ?? ''));
  4476. if (!$asComplete && !$exists && $qtyCd === '' && $priceCd === '') {
  4477. $this->success('操作成功');
  4478. return;
  4479. }
  4480. if ($exists) {
  4481. $upd = $data;
  4482. unset($upd['scydgy_id']);
  4483. if (!$asComplete) {
  4484. unset($upd['status']);
  4485. }
  4486. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  4487. } else {
  4488. // 新增:不写 status;完结时 $data 已含 status=1
  4489. $data['createtime'] = date('Y-m-d H:i:s');
  4490. Db::table('purchase_order')->insert($data);
  4491. }
  4492. } catch (\Throwable $e) {
  4493. $this->error($e->getMessage());
  4494. }
  4495. try {
  4496. $rpo = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  4497. if (is_array($rpo)) {
  4498. $tid = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4499. $poIdLog = $tid > 0 ? $tid : null;
  4500. }
  4501. } catch (\Throwable $e) {
  4502. $poIdLog = null;
  4503. }
  4504. $q = isset($data['This_quantity']) ? trim((string)$data['This_quantity']) : '';
  4505. $p = isset($data['ceilingPrice']) ? trim((string)$data['ceilingPrice']) : '';
  4506. if ($asComplete) {
  4507. $this->addOrderLog(
  4508. $ids,
  4509. 'mark_complete',
  4510. '点击「完结」,已标记为已完结',
  4511. $poIdLog
  4512. );
  4513. try {
  4514. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($ids, (int)($poIdLog ?? 0));
  4515. if ($pdfPublicPath === '') {
  4516. Log::write('完结存证PDF/OSS未生成 scydgy_id=' . $ids, 'notice');
  4517. }
  4518. } catch (\Throwable $e) {
  4519. Log::write('完结存证PDF异常 scydgy_id=' . $ids . ' ' . $e->getMessage(), 'error');
  4520. }
  4521. } else {
  4522. $gymc = trim((string)($data['CGYMC'] ?? $row['CGYMC'] ?? ''));
  4523. $qtyPart = '本次数量「' . ($q !== '' ? $q : '') . '」';
  4524. $pricePart = '最高限价「' . ($p !== '' ? $p : '') . '」';
  4525. $detail = ($gymc !== '' ? ($gymc . $qtyPart) : $qtyPart) . ',' . $pricePart;
  4526. $this->addOrderLog(
  4527. $ids,
  4528. 'save_qty_price',
  4529. '保存本次数量、最高限价:' . $detail,
  4530. $poIdLog
  4531. );
  4532. }
  4533. $this->pickHiddenScydgySetCache = null;
  4534. $this->success("操作成功");
  4535. }
  4536. /**
  4537. * 未发列表:从 purchase_order 合并已填的本次数量、最高限价(若表中有对应列)
  4538. *
  4539. * @param array<int, array> $rows 引用传递当前页行
  4540. */
  4541. protected function mergePurchaseOrder(array &$rows)
  4542. {
  4543. if ($rows === []) {
  4544. return;
  4545. }
  4546. $ids = [];
  4547. foreach ($rows as $rw) {
  4548. if (!is_array($rw)) {
  4549. continue;
  4550. }
  4551. $id = (int)($rw['ID'] ?? 0);
  4552. // 含手工新增负数 scydgy_id,避免限价/数量不同步
  4553. if ($this->isValidScydgyRowId($id)) {
  4554. $ids[$id] = true;
  4555. }
  4556. }
  4557. $idList = array_keys($ids);
  4558. if ($idList === []) {
  4559. return;
  4560. }
  4561. try {
  4562. $list = Db::table('purchase_order')
  4563. ->where('scydgy_id', 'in', $idList)
  4564. ->field('scydgy_id,This_quantity,ceilingPrice')
  4565. ->select();
  4566. } catch (\Throwable $e) {
  4567. return;
  4568. }
  4569. if (!is_array($list)) {
  4570. return;
  4571. }
  4572. $byId = [];
  4573. foreach ($list as $dbRow) {
  4574. if (!is_array($dbRow) || !isset($dbRow['scydgy_id'])) {
  4575. continue;
  4576. }
  4577. $byId[(int)$dbRow['scydgy_id']] = $dbRow;
  4578. }
  4579. foreach ($rows as &$rw) {
  4580. if (!is_array($rw)) {
  4581. continue;
  4582. }
  4583. $sid = (int)($rw['ID'] ?? 0);
  4584. if (!$this->isValidScydgyRowId($sid) || !isset($byId[$sid])) {
  4585. continue;
  4586. }
  4587. $db = $byId[$sid];
  4588. // 有 purchase_order 记录时同步数量/限价(含清空后的空串,避免刷新后又冒出来)
  4589. if (array_key_exists('This_quantity', $db)) {
  4590. $rw['This_quantity'] = $db['This_quantity'] === null ? '' : $db['This_quantity'];
  4591. }
  4592. if (array_key_exists('ceilingPrice', $db)) {
  4593. $rw['ceilingPrice'] = $db['ceilingPrice'] === null ? '' : $db['ceilingPrice'];
  4594. } elseif (array_key_exists('ceiling_price', $db)) {
  4595. $rw['ceilingPrice'] = $db['ceiling_price'] === null ? '' : $db['ceiling_price'];
  4596. }
  4597. }
  4598. unset($rw);
  4599. }
  4600. /**
  4601. * 采购确认:明细选中 status=1、未选 status=0;同时将 purchase_order 主表 status 置为 1
  4602. */
  4603. public function purchaseConfirmPick()
  4604. {
  4605. if (!$this->request->isPost() || !$this->request->isAjax()) {
  4606. $this->error(__('Invalid parameters'));
  4607. }
  4608. if (!$this->hasProcuremenPerm(['purchaseconfirmpick', 'purchaseConfirmPick'])) {
  4609. $this->error(__('You have no permission'));
  4610. }
  4611. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  4612. if ($batchRaw !== '') {
  4613. $this->handlePurchaseConfirmOrderBatch($batchRaw);
  4614. return;
  4615. }
  4616. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  4617. $sid = (int)$scydgyId;
  4618. if (!$this->isValidScydgyRowId($sid)) {
  4619. $this->error('参数无效');
  4620. }
  4621. $parseIdList = function ($raw) {
  4622. if (is_array($raw)) {
  4623. $arr = $raw;
  4624. } else {
  4625. $decoded = json_decode((string)$raw, true);
  4626. $arr = is_array($decoded) ? $decoded : [];
  4627. }
  4628. return array_values(array_unique(array_filter(array_map('intval', $arr))));
  4629. };
  4630. $selectedRaw = $this->request->post('selected_ids', null);
  4631. if ($selectedRaw === null || $selectedRaw === '') {
  4632. $legacy = (int)$this->request->post('selected_id', 0);
  4633. $selectedIds = $legacy > 0 ? [$legacy] : [];
  4634. } else {
  4635. $selectedIds = $parseIdList($selectedRaw);
  4636. }
  4637. $unselectedIds = $parseIdList($this->request->post('unselected_ids', '[]'));
  4638. $purchaseOrderId = (int)$this->request->post('purchase_order_id', 0);
  4639. try {
  4640. $result = $this->runPurchaseConfirmPick($sid, $selectedIds, $unselectedIds, $purchaseOrderId);
  4641. } catch (\InvalidArgumentException $e) {
  4642. $this->error($e->getMessage());
  4643. } catch (\Throwable $e) {
  4644. $this->error($e->getMessage());
  4645. }
  4646. $this->pickHiddenScydgySetCache = null;
  4647. $this->success('操作成功', '', $result);
  4648. }
  4649. /**
  4650. * 整单采购确认(多道工序一次提交)
  4651. */
  4652. protected function handlePurchaseConfirmOrderBatch(string $batchRaw): void
  4653. {
  4654. $decoded = json_decode($batchRaw, true);
  4655. if (!is_array($decoded) || $decoded === []) {
  4656. $this->error('提交数据无效');
  4657. }
  4658. $picks = [];
  4659. foreach ($decoded as $item) {
  4660. if (!is_array($item)) {
  4661. continue;
  4662. }
  4663. $sid = (int)($item['scydgy_id'] ?? 0);
  4664. if (!$this->isValidScydgyRowId($sid)) {
  4665. continue;
  4666. }
  4667. $sel = $item['selected_ids'] ?? ($item['selected_id'] ?? []);
  4668. if (!is_array($sel)) {
  4669. $sel = [(int)$sel];
  4670. }
  4671. $unsel = $item['unselected_ids'] ?? [];
  4672. if (!is_array($unsel)) {
  4673. $unsel = json_decode((string)$unsel, true);
  4674. $unsel = is_array($unsel) ? $unsel : [];
  4675. }
  4676. $picks[] = [
  4677. 'scydgy_id' => $sid,
  4678. 'purchase_order_id' => (int)($item['purchase_order_id'] ?? 0),
  4679. 'selected_ids' => array_values(array_unique(array_filter(array_map('intval', $sel)))),
  4680. 'unselected_ids' => array_values(array_unique(array_filter(array_map('intval', $unsel)))),
  4681. ];
  4682. }
  4683. if ($picks === []) {
  4684. $this->error('提交数据无效');
  4685. }
  4686. Db::startTrans();
  4687. $results = [];
  4688. try {
  4689. foreach ($picks as $pick) {
  4690. $results[] = $this->runPurchaseConfirmPick(
  4691. (int)$pick['scydgy_id'],
  4692. $pick['selected_ids'],
  4693. $pick['unselected_ids'],
  4694. (int)$pick['purchase_order_id'],
  4695. false,
  4696. false
  4697. );
  4698. }
  4699. Db::commit();
  4700. } catch (\Throwable $e) {
  4701. Db::rollback();
  4702. $msg = $e->getMessage();
  4703. $this->error($msg !== '' ? $msg : '提交失败');
  4704. }
  4705. try {
  4706. $bundle = $this->loadOrderBundleForConfirmNotify(array_column($picks, 'scydgy_id'));
  4707. $this->dispatchPurchaseConfirmPickNotifications($bundle, $results);
  4708. } catch (\Throwable $e) {
  4709. Log::write('采购确认通知批量发送异常: ' . $e->getMessage(), 'error');
  4710. }
  4711. $this->pickHiddenScydgySetCache = null;
  4712. $this->success('操作成功', '', ['batch' => $results]);
  4713. }
  4714. /**
  4715. * @return array<string, mixed>
  4716. */
  4717. protected function runPurchaseConfirmPick(int $sid, array $selectedIds, array $unselectedIds, int $purchaseOrderId, bool $manageTransaction = true, bool $sendNotifications = true): array
  4718. {
  4719. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid);
  4720. ProcuremenGuard::assertWflowPendingApproval($poRow);
  4721. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法重复审批');
  4722. $scydgyId = (string)$sid;
  4723. if ($selectedIds === []) {
  4724. throw new \InvalidArgumentException('请至少勾选一条明细');
  4725. }
  4726. $inter = array_intersect($selectedIds, $unselectedIds);
  4727. if ($inter !== []) {
  4728. throw new \InvalidArgumentException('选中与未选中 ID 不能重复');
  4729. }
  4730. $allIds = $this->purchaseOrderDetail($sid);
  4731. if ($allIds === []) {
  4732. throw new \InvalidArgumentException('未找到该工序行的下发明细');
  4733. }
  4734. foreach ($selectedIds as $id) {
  4735. if (!in_array($id, $allIds, true)) {
  4736. throw new \InvalidArgumentException('选中 ID 不属于当前工序行');
  4737. }
  4738. }
  4739. foreach ($unselectedIds as $id) {
  4740. if (!in_array($id, $allIds, true)) {
  4741. throw new \InvalidArgumentException('未选中 ID 不属于当前工序行');
  4742. }
  4743. }
  4744. $union = array_values(array_unique(array_merge($selectedIds, $unselectedIds)));
  4745. sort($union, SORT_NUMERIC);
  4746. $expect = $allIds;
  4747. sort($expect, SORT_NUMERIC);
  4748. if ($union !== $expect) {
  4749. throw new \InvalidArgumentException('请提交当前工序下全部明细 ID(选中 + 未选中)');
  4750. }
  4751. if ($manageTransaction) {
  4752. Db::startTrans();
  4753. }
  4754. try {
  4755. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  4756. $aff = 0;
  4757. try {
  4758. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4759. } catch (\Throwable $e) {
  4760. $aff = (int)Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $selectedIds)->update(['status' => ProcuremenStatus::POD_PICKED]);
  4761. }
  4762. if ($aff < 1) {
  4763. throw new \Exception('更新选中状态失败');
  4764. }
  4765. $poPayload = [
  4766. // 审核通过后进入「待入库评分」;合格/不合格后才置已完结
  4767. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  4768. 'wflow_status' => ProcuremenStatus::WFLOW_APPROVED,
  4769. ];
  4770. if ($purchaseOrderId > 0) {
  4771. $poAff = (int)Db::table('purchase_order')
  4772. ->where('id', $purchaseOrderId)
  4773. ->where('scydgy_id', $sid)
  4774. ->update($poPayload);
  4775. if ($poAff < 1) {
  4776. throw new \Exception('主表订单不存在或与工序行不匹配');
  4777. }
  4778. } else {
  4779. $poAff = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->update($poPayload);
  4780. if ($poAff < 1) {
  4781. throw new \Exception('未找到');
  4782. }
  4783. }
  4784. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $selectedIds, '已完成');
  4785. $this->updatePurchaseOrderDetailStatusNameByIds($sid, $unselectedIds, '未通过');
  4786. if ($manageTransaction) {
  4787. Db::commit();
  4788. }
  4789. } catch (\Throwable $e) {
  4790. if ($manageTransaction) {
  4791. Db::rollback();
  4792. }
  4793. throw $e;
  4794. }
  4795. $poIdFinal = $purchaseOrderId;
  4796. if ($poIdFinal <= 0) {
  4797. try {
  4798. $rpo = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  4799. if (is_array($rpo)) {
  4800. $poIdFinal = (int)($rpo['id'] ?? $rpo['ID'] ?? 0);
  4801. }
  4802. } catch (\Throwable $e) {
  4803. $poIdFinal = 0;
  4804. }
  4805. }
  4806. $pickNames = [];
  4807. foreach ($selectedIds as $pid) {
  4808. $dr = $this->purchaseOrderDetai($sid, $pid);
  4809. $nm = trim((string)($dr['company_name'] ?? ''));
  4810. $pickNames[] = $nm !== '' ? $nm : ('明细#' . $pid);
  4811. }
  4812. $this->addOrderLog(
  4813. $sid,
  4814. 'purchase_confirm',
  4815. '审核确认供应商:已选定「' . implode('、', $pickNames) . '」',
  4816. $poIdFinal > 0 ? $poIdFinal : null
  4817. );
  4818. if ($sendNotifications) {
  4819. try {
  4820. $bundle = $this->loadOrderBundleForConfirmNotify([$sid]);
  4821. $this->dispatchPurchaseConfirmPickNotifications($bundle, [[
  4822. 'scydgy_id' => $sid,
  4823. 'selected_ids' => $selectedIds,
  4824. 'unselected_ids' => $unselectedIds,
  4825. 'purchase_order_id' => $purchaseOrderId,
  4826. ]]);
  4827. } catch (\Throwable $e) {
  4828. Log::write('采购确认通知发送异常 scydgy_id=' . $sid . ' ' . $e->getMessage(), 'error');
  4829. }
  4830. }
  4831. Log::write(sprintf(
  4832. 'purchaseConfirmPick scydgy_id=%s purchase_order_id=%d selected_ids=%s unselected_ids=%s',
  4833. $scydgyId,
  4834. $purchaseOrderId,
  4835. json_encode($selectedIds, JSON_UNESCAPED_UNICODE),
  4836. json_encode($unselectedIds, JSON_UNESCAPED_UNICODE)
  4837. ), 'notice');
  4838. $pdfPublicPath = '';
  4839. try {
  4840. $pdfPublicPath = (string)$this->savePurchaseConfirmDetailPdf($sid, $poIdFinal);
  4841. } catch (\Throwable $e) {
  4842. Log::write('采购确认PDF异常: ' . $e->getMessage(), 'error');
  4843. }
  4844. return [
  4845. 'scydgy_id' => $scydgyId,
  4846. 'purchase_order_id' => $purchaseOrderId,
  4847. 'selected_ids' => $selectedIds,
  4848. 'unselected_ids' => $unselectedIds,
  4849. 'purchase_confirm_pdf' => $pdfPublicPath,
  4850. ];
  4851. }
  4852. /**
  4853. * 审批通过短信:按本次涉及的工序汇总 process_lines
  4854. *
  4855. * @param int[]|string[] $scydgyIds
  4856. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  4857. */
  4858. protected function loadOrderBundleForConfirmNotify(array $scydgyIds): array
  4859. {
  4860. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  4861. $scydgyIds = array_values(array_unique(array_filter(array_map('intval', $scydgyIds))));
  4862. if ($scydgyIds === []) {
  4863. return $empty;
  4864. }
  4865. $pos = [];
  4866. try {
  4867. $rows = Db::table('purchase_order')->where('scydgy_id', 'in', $scydgyIds)->order('scydgy_id', 'asc')->select();
  4868. } catch (\Throwable $e) {
  4869. $rows = [];
  4870. }
  4871. if (is_array($rows)) {
  4872. foreach ($rows as $po) {
  4873. if (is_array($po)) {
  4874. $pos[] = $po;
  4875. }
  4876. }
  4877. }
  4878. if ($pos === []) {
  4879. return $empty;
  4880. }
  4881. $ccydh = trim((string)($pos[0]['CCYDH'] ?? ''));
  4882. return [
  4883. 'ccydh' => $ccydh,
  4884. 'pos' => $pos,
  4885. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  4886. ];
  4887. }
  4888. /**
  4889. * 审批通过/未通过:短信 + 邮件(同一供应商只发一条;邮件含平台链接)
  4890. *
  4891. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  4892. * @param array<int, array<string, mixed>> $picks
  4893. */
  4894. protected function dispatchPurchaseConfirmPickNotifications(array $bundle, array $picks): void
  4895. {
  4896. if ($picks === []) {
  4897. return;
  4898. }
  4899. $this->ensureConfirmResultEmailTemplates();
  4900. $fallbackDetailId = 0;
  4901. $winners = [];
  4902. $losers = [];
  4903. foreach ($picks as $pick) {
  4904. if (!is_array($pick)) {
  4905. continue;
  4906. }
  4907. $sid = (int)($pick['scydgy_id'] ?? 0);
  4908. if (!$this->isValidScydgyRowId($sid)) {
  4909. continue;
  4910. }
  4911. $selectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['selected_ids'] ?? [])))));
  4912. $unselectedIds = array_values(array_unique(array_filter(array_map('intval', (array)($pick['unselected_ids'] ?? [])))));
  4913. if ($fallbackDetailId <= 0 && $selectedIds !== []) {
  4914. $fallbackDetailId = (int)$selectedIds[0];
  4915. }
  4916. foreach ($selectedIds as $pid) {
  4917. $dr = $this->purchaseOrderDetai($sid, $pid);
  4918. if (!is_array($dr)) {
  4919. continue;
  4920. }
  4921. $winners[$this->notifySupplierDedupeKey($dr)] = $dr;
  4922. }
  4923. foreach ($unselectedIds as $pid) {
  4924. $dr = $this->purchaseOrderDetai($sid, $pid);
  4925. if (!is_array($dr)) {
  4926. continue;
  4927. }
  4928. $key = $this->notifySupplierDedupeKey($dr);
  4929. if (!isset($winners[$key])) {
  4930. $losers[$key] = $dr;
  4931. }
  4932. }
  4933. }
  4934. if ($winners === [] && $losers === []) {
  4935. return;
  4936. }
  4937. $confirmNotifyVars = $this->buildPurchaseConfirmNotifyVars(0, $fallbackDetailId, $bundle);
  4938. $poIdLog = 0;
  4939. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  4940. if (isset($pos[0]) && is_array($pos[0])) {
  4941. $poIdLog = (int)($pos[0]['id'] ?? 0);
  4942. }
  4943. $sendSmsSafe = function ($phone, $content) {
  4944. $phone = trim((string)$phone);
  4945. if ($phone === '') {
  4946. return;
  4947. }
  4948. try {
  4949. $this->smsbao($phone, $content);
  4950. } catch (\Throwable $e) {
  4951. Log::write('采购确认短信失败 phone=' . $phone . ' ' . $e->getMessage(), 'error');
  4952. }
  4953. };
  4954. $sendConfirmEmailSafe = function (array $dr, string $emailScene) use ($confirmNotifyVars, $poIdLog) {
  4955. $cname = trim((string)($dr['company_name'] ?? ''));
  4956. $ph = trim((string)($dr['phone'] ?? ''));
  4957. $toEmail = trim((string)($dr['email'] ?? ''));
  4958. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  4959. Log::write('采购确认邮件跳过:无有效邮箱 company=' . $cname, 'error');
  4960. return;
  4961. }
  4962. $detailId = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  4963. if ($detailId <= 0) {
  4964. $detailId = (int)($confirmNotifyVars['_fallback_detail_id'] ?? 0);
  4965. }
  4966. try {
  4967. $platformUrl = $this->buildMprocMobileOrderUrl($detailId);
  4968. } catch (\Throwable $e) {
  4969. Log::write('采购确认邮件链接失败: ' . $e->getMessage(), 'error');
  4970. $platformUrl = '';
  4971. }
  4972. $vars = array_merge($confirmNotifyVars, [
  4973. 'company_name' => $cname,
  4974. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  4975. 'phone' => $ph,
  4976. 'email' => $toEmail,
  4977. 'platform_url' => $platformUrl,
  4978. ]);
  4979. unset($vars['_fallback_detail_id']);
  4980. try {
  4981. $mailPlain = $this->renderNotifyTemplate($emailScene, $vars);
  4982. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  4983. $mailSubject = $this->resolveProcuremenEmailSubject($emailScene);
  4984. $mailConfig = $this->loadMailerConfig();
  4985. $this->issueSendSupplierEmail([
  4986. 'company_name' => $cname,
  4987. 'email' => $toEmail,
  4988. 'mail_plain' => $mailPlain,
  4989. 'mail_body' => $mailBody,
  4990. 'notify_vars' => $vars,
  4991. 'sms_content' => '',
  4992. 'detail_links' => $platformUrl !== '' ? [['url' => $platformUrl, 'cgymc' => '']] : [],
  4993. 'email_log_scene' => 'confirm_result',
  4994. 'email_log_scydgy_id' => (int)($dr['scydgy_id'] ?? 0),
  4995. 'email_log_purchase_order_id' => $poIdLog,
  4996. ], $mailConfig, $mailSubject);
  4997. } catch (\Throwable $e) {
  4998. Log::write('采购确认邮件失败 company=' . $cname . ' email=' . $toEmail . ' ' . $e->getMessage(), 'error');
  4999. }
  5000. };
  5001. $confirmNotifyVars['_fallback_detail_id'] = $fallbackDetailId;
  5002. foreach ($winners as $dr) {
  5003. $cname = trim((string)($dr['company_name'] ?? ''));
  5004. $ph = trim((string)($dr['phone'] ?? ''));
  5005. $sms = $this->renderNotifyTemplate('confirm_ok', array_merge($confirmNotifyVars, [
  5006. 'company_name' => $cname,
  5007. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5008. 'phone' => $ph,
  5009. ]));
  5010. $sendSmsSafe($ph, $sms);
  5011. $sendConfirmEmailSafe($dr, 'confirm_ok_email');
  5012. }
  5013. foreach ($losers as $dr) {
  5014. $cname = trim((string)($dr['company_name'] ?? ''));
  5015. $ph = trim((string)($dr['phone'] ?? ''));
  5016. $sms = $this->renderNotifyTemplate('confirm_fail', array_merge($confirmNotifyVars, [
  5017. 'company_name' => $cname,
  5018. 'contact_name' => $this->resolveCustomerContactName($ph, $cname),
  5019. 'phone' => $ph,
  5020. ]));
  5021. $sendSmsSafe($ph, $sms);
  5022. $sendConfirmEmailSafe($dr, 'confirm_fail_email');
  5023. }
  5024. }
  5025. /**
  5026. * 短信去重键:优先手机号,否则公司名
  5027. */
  5028. protected function notifySupplierDedupeKey(array $detailRow): string
  5029. {
  5030. $ph = preg_replace('/\s+/', '', trim((string)($detailRow['phone'] ?? '')));
  5031. if ($ph !== '') {
  5032. return 'p:' . $ph;
  5033. }
  5034. $cn = trim((string)($detailRow['company_name'] ?? ''));
  5035. return 'c:' . $cn;
  5036. }
  5037. /**
  5038. * 批量更新 purchase_order_detail.status_name(兼容 id / ID 列名)
  5039. *
  5040. * @param int[] $detailIds
  5041. */
  5042. protected function updatePurchaseOrderDetailStatusNameByIds(int $sid, array $detailIds, string $statusName): void
  5043. {
  5044. $detailIds = array_values(array_unique(array_filter(array_map('intval', $detailIds))));
  5045. if ($detailIds === []) {
  5046. return;
  5047. }
  5048. $payload = ['status_name' => $statusName];
  5049. try {
  5050. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('id', 'in', $detailIds)->update($payload);
  5051. } catch (\Throwable $e) {
  5052. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->where('ID', 'in', $detailIds)->update($payload);
  5053. }
  5054. }
  5055. /**
  5056. * 审批驳回后按是否已报价恢复 status_name(未提交 / 已提交)
  5057. */
  5058. protected function restorePurchaseOrderDetailStatusNamesAfterReject(int $sid): void
  5059. {
  5060. try {
  5061. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sid)->select();
  5062. } catch (\Throwable $e) {
  5063. return;
  5064. }
  5065. if (!is_array($rows)) {
  5066. return;
  5067. }
  5068. foreach ($rows as $dr) {
  5069. if (!is_array($dr)) {
  5070. continue;
  5071. }
  5072. $id = (int)($dr['id'] ?? $dr['ID'] ?? 0);
  5073. if ($id <= 0) {
  5074. continue;
  5075. }
  5076. $sn = $this->resolvePurchaseOrderDetailQuoteStatusName($dr);
  5077. $pk = isset($dr['id']) ? 'id' : (isset($dr['ID']) ? 'ID' : 'id');
  5078. try {
  5079. Db::table('purchase_order_detail')->where($pk, $id)->update(['status_name' => $sn]);
  5080. } catch (\Throwable $e) {
  5081. }
  5082. }
  5083. }
  5084. /**
  5085. * @param array<string, mixed> $detailRow
  5086. */
  5087. protected function resolvePurchaseOrderDetailQuoteStatusName(array $detailRow): string
  5088. {
  5089. $am = $detailRow['amount'] ?? null;
  5090. $dv = isset($detailRow['delivery']) ? trim((string)$detailRow['delivery']) : '';
  5091. $amountFilled = !($am === null || $am === '' || (is_string($am) && trim($am) === ''));
  5092. $deliveryFilled = ($dv !== '' && !preg_match('/^0000-00-00/i', $dv));
  5093. return ($amountFilled || $deliveryFilled) ? '已提交' : '未提交';
  5094. }
  5095. /**
  5096. * @return int[]
  5097. */
  5098. protected function purchaseOrderDetail(int $scydgyId): array
  5099. {
  5100. if (!$this->isValidScydgyRowId($scydgyId)) {
  5101. return [];
  5102. }
  5103. try {
  5104. $listQuery = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId);
  5105. $this->applyActivePurchaseOrderDetailWhere($listQuery);
  5106. $list = $listQuery->select();
  5107. } catch (\Throwable $e) {
  5108. return [];
  5109. }
  5110. if (!is_array($list)) {
  5111. return [];
  5112. }
  5113. $ids = [];
  5114. foreach ($list as $r) {
  5115. if (!is_array($r)) {
  5116. continue;
  5117. }
  5118. $pk = (int)($r['id'] ?? $r['ID'] ?? 0);
  5119. if ($pk > 0) {
  5120. $ids[] = $pk;
  5121. }
  5122. }
  5123. return array_values(array_unique($ids));
  5124. }
  5125. /**
  5126. * 获取当前登录用户信息 [id, 展示名]
  5127. */
  5128. protected function GetUseName(): array
  5129. {
  5130. $id = 0;
  5131. $name = '';
  5132. try {
  5133. if ($this->auth && $this->auth->isLogin()) {
  5134. $u = $this->auth->getUserInfo();
  5135. if (is_array($u)) {
  5136. $id = (int)($u['id'] ?? 0);
  5137. $name = trim((string)($u['nickname'] ?? ''));
  5138. if ($name === '') {
  5139. $name = trim((string)($u['username'] ?? ''));
  5140. }
  5141. }
  5142. }
  5143. } catch (\Throwable $e) {
  5144. }
  5145. if ($name === '') {
  5146. $name = '未知用户';
  5147. }
  5148. return [$id, $name];
  5149. }
  5150. /**
  5151. * 协助采购操作日志(表未建时仅写 runtime 日志,不中断业务)
  5152. */
  5153. protected function addOrderLog(int $scydgyId, string $action, string $content, ?int $purchaseOrderId = null): void
  5154. {
  5155. ProcuremenOperLog::write($scydgyId, $action, $content, $purchaseOrderId, $this->GetUseName());
  5156. }
  5157. /**
  5158. * 列表页补充:下发 / 确定 / 审批时间(按当前页工序批量读操作日志)
  5159. *
  5160. * @param array<int, array<string, mixed>> $rows
  5161. */
  5162. protected function enrichProcuremenListMilestoneTimes(array &$rows): void
  5163. {
  5164. $sidList = [];
  5165. foreach ($rows as $rw) {
  5166. if (!is_array($rw)) {
  5167. continue;
  5168. }
  5169. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5170. foreach ($rw['_order_merge_rows'] as $mr) {
  5171. $mid = (int)($mr['ID'] ?? 0);
  5172. if ($this->isValidScydgyRowId($mid)) {
  5173. $sidList[$mid] = true;
  5174. }
  5175. }
  5176. }
  5177. $id = (int)($rw['ID'] ?? 0);
  5178. if ($this->isValidScydgyRowId($id)) {
  5179. $sidList[$id] = true;
  5180. }
  5181. }
  5182. $sids = array_keys($sidList);
  5183. $issueBySid = [];
  5184. $confirmBySid = [];
  5185. $approveBySid = [];
  5186. if ($sids !== []) {
  5187. $issueActs = ProcuremenOperLog::expandActionQueryValues('issue_submit');
  5188. $confirmActs = ProcuremenOperLog::expandActionQueryValues(['audit_select', 'audit_confirm']);
  5189. $approveActs = ProcuremenOperLog::expandActionQueryValues('purchase_confirm');
  5190. $allActs = array_values(array_unique(array_merge($issueActs, $confirmActs, $approveActs)));
  5191. try {
  5192. $logs = Db::table('purchase_order_oper_log')
  5193. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $sids)
  5194. ->where(ProcuremenOperLog::COL_ACTION, 'in', $allActs)
  5195. ->field(ProcuremenOperLog::COL_SCYDGY_ID . ',' . ProcuremenOperLog::COL_ACTION . ',' . ProcuremenOperLog::COL_TIME)
  5196. ->order('id', 'asc')
  5197. ->select();
  5198. } catch (\Throwable $e) {
  5199. $logs = [];
  5200. }
  5201. if (is_array($logs)) {
  5202. $issueSet = array_fill_keys($issueActs, true);
  5203. $confirmSet = array_fill_keys($confirmActs, true);
  5204. $approveSet = array_fill_keys($approveActs, true);
  5205. foreach ($logs as $lg) {
  5206. if (!is_array($lg)) {
  5207. continue;
  5208. }
  5209. $lg = ProcuremenOperLog::normalizeRow($lg);
  5210. $sid = (int)($lg[ProcuremenOperLog::COL_SCYDGY_ID] ?? 0);
  5211. if ($sid === 0) {
  5212. continue;
  5213. }
  5214. $action = trim((string)($lg[ProcuremenOperLog::COL_ACTION] ?? ''));
  5215. $t = $this->formatProcuremenDetailTime($lg[ProcuremenOperLog::COL_TIME] ?? null);
  5216. if ($t === '') {
  5217. continue;
  5218. }
  5219. if (isset($issueSet[$action])) {
  5220. if (!isset($issueBySid[$sid]) || strcmp($t, $issueBySid[$sid]) > 0) {
  5221. $issueBySid[$sid] = $t;
  5222. }
  5223. }
  5224. if (isset($confirmSet[$action])) {
  5225. if (!isset($confirmBySid[$sid]) || strcmp($t, $confirmBySid[$sid]) > 0) {
  5226. $confirmBySid[$sid] = $t;
  5227. }
  5228. }
  5229. if (isset($approveSet[$action])) {
  5230. if (!isset($approveBySid[$sid]) || strcmp($t, $approveBySid[$sid]) > 0) {
  5231. $approveBySid[$sid] = $t;
  5232. }
  5233. }
  5234. }
  5235. }
  5236. }
  5237. foreach ($rows as &$rw) {
  5238. if (!is_array($rw)) {
  5239. continue;
  5240. }
  5241. $mergeSids = [];
  5242. if (!empty($rw['_order_merge_rows']) && is_array($rw['_order_merge_rows'])) {
  5243. foreach ($rw['_order_merge_rows'] as $mr) {
  5244. $mid = (int)($mr['ID'] ?? 0);
  5245. if ($this->isValidScydgyRowId($mid)) {
  5246. $mergeSids[] = $mid;
  5247. }
  5248. }
  5249. }
  5250. $rid = (int)($rw['ID'] ?? 0);
  5251. if ($this->isValidScydgyRowId($rid) && !in_array($rid, $mergeSids, true)) {
  5252. $mergeSids[] = $rid;
  5253. }
  5254. $pick = $this->formatProcuremenDetailTime($rw['pick_time'] ?? null);
  5255. $issue = $pick;
  5256. $confirm = '';
  5257. $approve = '';
  5258. foreach ($mergeSids as $sid) {
  5259. if (isset($issueBySid[$sid]) && ($issue === '' || strcmp($issueBySid[$sid], $issue) > 0)) {
  5260. $issue = $issueBySid[$sid];
  5261. }
  5262. if (isset($confirmBySid[$sid]) && ($confirm === '' || strcmp($confirmBySid[$sid], $confirm) > 0)) {
  5263. $confirm = $confirmBySid[$sid];
  5264. }
  5265. if (isset($approveBySid[$sid]) && ($approve === '' || strcmp($approveBySid[$sid], $approve) > 0)) {
  5266. $approve = $approveBySid[$sid];
  5267. }
  5268. }
  5269. if ($issue === '' && $pick !== '') {
  5270. $issue = $pick;
  5271. }
  5272. $rw['issue_time'] = $issue;
  5273. $rw['confirm_time'] = $confirm;
  5274. $rw['approve_time'] = $approve;
  5275. }
  5276. unset($rw);
  5277. }
  5278. /**
  5279. * 按主键取一条
  5280. */
  5281. protected function purchaseOrderDetai(int $scydgyId, int $pk): array
  5282. {
  5283. if (!$this->isValidScydgyRowId($scydgyId) || $pk <= 0) {
  5284. return [];
  5285. }
  5286. try {
  5287. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('id', $pk)->find();
  5288. if (is_array($one)) {
  5289. return $one;
  5290. }
  5291. } catch (\Throwable $e) {
  5292. }
  5293. try {
  5294. $one = Db::table('purchase_order_detail')->where('scydgy_id', $scydgyId)->where('ID', $pk)->find();
  5295. if (is_array($one)) {
  5296. return $one;
  5297. }
  5298. } catch (\Throwable $e) {
  5299. }
  5300. return [];
  5301. }
  5302. /**
  5303. * 主表/明细时间字段统一为可读字符串(用于详情进度)
  5304. */
  5305. protected function formatProcuremenDetailTime($v): string
  5306. {
  5307. if ($v === null || $v === '') {
  5308. return '';
  5309. }
  5310. if (is_numeric($v) && (int)$v > 946684800) {
  5311. return date('Y-m-d H:i:s', (int)$v);
  5312. }
  5313. return ProcuremenTime::formatDisplayDateTime($v);
  5314. }
  5315. /**
  5316. * 交货日期仅展示 YYYY-MM-DD(详情表、列表展示用)
  5317. */
  5318. protected function formatDeliveryYmd($v): string
  5319. {
  5320. if ($v === null || $v === '') {
  5321. return '';
  5322. }
  5323. $s = trim((string)$v);
  5324. if ($s === '' || preg_match('/^0000-00-00/i', $s)) {
  5325. return '';
  5326. }
  5327. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  5328. return $m[1];
  5329. }
  5330. $ts = strtotime($s);
  5331. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : $s;
  5332. }
  5333. /**
  5334. * 供应商是否已在手机端填写单价或交货日期(任一有值即视为已操作)
  5335. */
  5336. protected function detailRowSupplierOperated(array $r): bool
  5337. {
  5338. $am = $r['amount'] ?? null;
  5339. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5340. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5341. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5342. return $okAmt || $okDel;
  5343. }
  5344. /**
  5345. * 详情供应商表「操作时间」:仅手机端填写单价/交期后展示,不用下发明细的 createtime
  5346. */
  5347. protected function resolveDetailSupplierOperTime(array $r): string
  5348. {
  5349. if (!$this->detailRowSupplierOperated($r)) {
  5350. return '';
  5351. }
  5352. $t = $this->formatProcuremenDetailTime($r['updatetime'] ?? null);
  5353. if ($t !== '') {
  5354. return $t;
  5355. }
  5356. foreach (['delivery_createtime', 'deliverycreatetime'] as $col) {
  5357. if (!isset($r[$col]) || $r[$col] === '' || $r[$col] === null) {
  5358. continue;
  5359. }
  5360. $t = $this->formatProcuremenDetailTime($r[$col]);
  5361. if ($t !== '') {
  5362. return $t;
  5363. }
  5364. }
  5365. return '';
  5366. }
  5367. /**
  5368. * 供应商已接单:金额与交货日期均已填写(与列表汇总逻辑一致)
  5369. */
  5370. protected function detailRowSupplierAccepted(array $r): bool
  5371. {
  5372. $am = $r['amount'] ?? null;
  5373. $okAmt = $am !== null && $am !== '' && !(is_string($am) && trim($am) === '');
  5374. $dv = isset($r['delivery']) ? trim((string)$r['delivery']) : '';
  5375. $okDel = $dv !== '' && !preg_match('/^0000-00-00/i', $dv);
  5376. return $okAmt && $okDel;
  5377. }
  5378. /**
  5379. * 是否已协助向供应商下发(有下发明细、已进入审批流或记录下发时间)
  5380. */
  5381. protected function isProcuremenOrderIssued(array $main, int $detailCount): bool
  5382. {
  5383. if ($detailCount > 0) {
  5384. return true;
  5385. }
  5386. if (ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '')) {
  5387. return true;
  5388. }
  5389. $pickTime = trim((string)($main['pick_time'] ?? ''));
  5390. if ($pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0) {
  5391. return true;
  5392. }
  5393. return false;
  5394. }
  5395. /**
  5396. * 下发时间:优先 pick_time,其次首条下发明细时间
  5397. */
  5398. protected function resolveProcuremenIssueTime(array $main, array $details): string
  5399. {
  5400. $issueTime = $this->formatProcuremenDetailTime($main['pick_time'] ?? null);
  5401. if ($issueTime !== '') {
  5402. return $issueTime;
  5403. }
  5404. foreach ($details as $dr) {
  5405. if (!is_array($dr)) {
  5406. continue;
  5407. }
  5408. $t = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5409. if ($t !== '' && ($issueTime === '' || strcmp($t, $issueTime) < 0)) {
  5410. $issueTime = $t;
  5411. }
  5412. }
  5413. if ($issueTime !== '') {
  5414. return $issueTime;
  5415. }
  5416. return $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5417. }
  5418. /**
  5419. * 直接点「完结」时间:优先操作记录 mark_complete
  5420. */
  5421. protected function resolveProcuremenMarkCompleteTime(int $scydgyId): string
  5422. {
  5423. return ProcuremenOperLog::resolveMarkCompleteTime($scydgyId);
  5424. }
  5425. /**
  5426. * 操作记录时间(取指定 action 最近一条)
  5427. *
  5428. * @param string|array<int, string> $actions
  5429. */
  5430. protected function resolveProcuremenOperLogTime(int $scydgyId, $actions): string
  5431. {
  5432. return ProcuremenOperLog::resolveLatestTime($scydgyId, $actions);
  5433. }
  5434. /**
  5435. * 详情弹层:进度步骤 + 订单摘要 + 下发明细(已下发 / 已完结均可用)
  5436. *
  5437. * @param array $main purchase_order 一行
  5438. * @param array $details purchase_order_detail 多行(已预处理 createtime_text)
  5439. * @return array{steps: array, orderSummary: array, orderSummaryGrid: array, detailRows: array}
  5440. */
  5441. protected function buildProcuremenDetailsViewData(array $main, array $details): array
  5442. {
  5443. $issueCnt = count($details);
  5444. $acceptCnt = 0;
  5445. $pickedName = '';
  5446. $pickedTime = '';
  5447. foreach ($details as $dr) {
  5448. if (!is_array($dr)) {
  5449. continue;
  5450. }
  5451. if ($this->detailRowSupplierAccepted($dr)) {
  5452. $acceptCnt++;
  5453. }
  5454. if (ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5455. if ($pickedName === '') {
  5456. $pickedName = trim((string)($dr['company_name'] ?? ''));
  5457. }
  5458. if ($pickedTime === '') {
  5459. $pickedTime = trim((string)($dr['createtime_text'] ?? ''));
  5460. if ($pickedTime === '') {
  5461. $pickedTime = $this->formatProcuremenDetailTime($dr['createtime'] ?? null);
  5462. }
  5463. }
  5464. }
  5465. }
  5466. $hasMain = $main !== [];
  5467. $poTime = $this->formatProcuremenDetailTime($main['createtime'] ?? null);
  5468. if ($poTime === '') {
  5469. $poTime = $this->formatProcuremenDetailTime($main['dStamp'] ?? null);
  5470. }
  5471. $mainCompleted = ProcuremenStatus::isPoCompleted($main['status'] ?? '');
  5472. $wflowPendingApproval = ProcuremenStatus::isWflowPendingApproval($main['wflow_status'] ?? '');
  5473. $wflowAtLeastConfirm = ProcuremenStatus::wflowAtLeastConfirm($main['wflow_status'] ?? '');
  5474. $issued = $this->isProcuremenOrderIssued($main, $issueCnt);
  5475. $issueTime = $issued ? $this->resolveProcuremenIssueTime($main, $details) : '';
  5476. $scydgyId = (int)($main['scydgy_id'] ?? 0);
  5477. $auditSelectTime = $this->resolveProcuremenOperLogTime($scydgyId, ['audit_select', 'audit_confirm']);
  5478. $confirmApproveTime = $this->resolveProcuremenOperLogTime($scydgyId, ['purchase_confirm']);
  5479. $inboundScoreTime = $this->resolveProcuremenOperLogTime($scydgyId, ['inbound_score']);
  5480. $inboundResult = '';
  5481. if ($scydgyId > 0) {
  5482. try {
  5483. $inRow = Db::table('purchase_order_inbound_score')
  5484. ->where('scydgy_id', $scydgyId)
  5485. ->field('result,updatetime,createtime')
  5486. ->find();
  5487. } catch (\Throwable $e) {
  5488. $inRow = null;
  5489. }
  5490. if (is_array($inRow) && $inRow !== []) {
  5491. $inboundResult = trim((string)($inRow['result'] ?? ''));
  5492. if ($inboundScoreTime === '') {
  5493. $inboundScoreTime = $this->formatProcuremenDetailTime($inRow['updatetime'] ?? $inRow['createtime'] ?? null);
  5494. }
  5495. }
  5496. }
  5497. $inboundScored = ($inboundResult === '合格' || $inboundResult === '不合格');
  5498. $supplierTime = '';
  5499. if ($acceptCnt > 0) {
  5500. foreach ($details as $dr) {
  5501. if (!is_array($dr) || !$this->detailRowSupplierAccepted($dr)) {
  5502. continue;
  5503. }
  5504. $t = $this->resolveDetailSupplierOperTime($dr);
  5505. if ($t !== '' && ($supplierTime === '' || strcmp($t, $supplierTime) < 0)) {
  5506. $supplierTime = $t;
  5507. }
  5508. }
  5509. }
  5510. $directComplete = ($mainCompleted && !$issued);
  5511. $doneTime = '';
  5512. if ($mainCompleted) {
  5513. if ($directComplete) {
  5514. $doneTime = $this->resolveProcuremenMarkCompleteTime($scydgyId);
  5515. }
  5516. if ($doneTime === '' && $inboundScoreTime !== '') {
  5517. $doneTime = $inboundScoreTime;
  5518. }
  5519. if ($doneTime === '') {
  5520. $doneTime = $this->formatProcuremenDetailTime($main['updatetime'] ?? null);
  5521. }
  5522. if ($doneTime === '') {
  5523. foreach ($details as $dr) {
  5524. if (!is_array($dr)) {
  5525. continue;
  5526. }
  5527. $t = $this->formatProcuremenDetailTime($dr['updatetime'] ?? $dr['createtime'] ?? null);
  5528. if ($t !== '' && ($doneTime === '' || strcmp($t, $doneTime) > 0)) {
  5529. $doneTime = $t;
  5530. }
  5531. }
  5532. }
  5533. if ($doneTime === '') {
  5534. $doneTime = $poTime;
  5535. }
  5536. // 旧数据:无入库评分时完结时间仍可用审核确认时间兜底
  5537. if ($doneTime === '' && $confirmApproveTime !== '') {
  5538. $doneTime = $confirmApproveTime;
  5539. }
  5540. }
  5541. if ($directComplete) {
  5542. // 未下发直接完结:仅「未发」完成;是否合格/已完结取决于入库评分
  5543. $step1Done = $hasMain;
  5544. $step2Done = false;
  5545. $step3Done = false;
  5546. $step4Done = false;
  5547. $step5Done = false;
  5548. $stepInboundDone = $inboundScored;
  5549. $step6Done = $mainCompleted && $inboundScored;
  5550. } else {
  5551. $step1Done = $issued;
  5552. $step2Done = $issued;
  5553. $step3Done = $acceptCnt > 0;
  5554. $step4Done = $wflowPendingApproval;
  5555. if (!$step4Done) {
  5556. foreach ($details as $dr) {
  5557. if (is_array($dr) && ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  5558. $step4Done = true;
  5559. break;
  5560. }
  5561. }
  5562. }
  5563. $step5Done = $confirmApproveTime !== '' || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') || $mainCompleted;
  5564. $stepInboundDone = $inboundScored;
  5565. // 未确认合格/不合格时,「已完结」保持未点亮(灰色)
  5566. $step6Done = $mainCompleted && $inboundScored;
  5567. // 已走下发流程并完结:中间环节按业务视为已全部完成(不显示灰色「未到达」)
  5568. if ($mainCompleted && $issued) {
  5569. $step3Done = true;
  5570. $step4Done = true;
  5571. $step5Done = true;
  5572. // 是否合格:仅有评分记录才点亮(旧完结单无评分时保持未完成态)
  5573. if ($supplierTime === '') {
  5574. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5575. if ($fillT !== '') {
  5576. $supplierTime = $fillT;
  5577. }
  5578. }
  5579. if ($pickedTime === '') {
  5580. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5581. if ($fillT !== '') {
  5582. $pickedTime = $fillT;
  5583. }
  5584. }
  5585. if ($auditSelectTime === '') {
  5586. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5587. if ($fillT !== '') {
  5588. $auditSelectTime = $fillT;
  5589. }
  5590. }
  5591. if ($confirmApproveTime === '') {
  5592. $fillT = $doneTime !== '' ? $doneTime : $poTime;
  5593. if ($fillT !== '') {
  5594. $confirmApproveTime = $fillT;
  5595. }
  5596. }
  5597. }
  5598. }
  5599. $poTime = ProcuremenTime::formatDisplayDateTime($poTime);
  5600. $issueTime = ProcuremenTime::formatDisplayDateTime($issueTime);
  5601. $supplierTime = ProcuremenTime::formatDisplayDateTime($supplierTime);
  5602. $pickedTime = ProcuremenTime::formatDisplayDateTime($pickedTime);
  5603. $auditSelectTime = ProcuremenTime::formatDisplayDateTime($auditSelectTime);
  5604. $confirmApproveTime = ProcuremenTime::formatDisplayDateTime($confirmApproveTime);
  5605. $inboundScoreTime = ProcuremenTime::formatDisplayDateTime($inboundScoreTime);
  5606. $doneTime = ProcuremenTime::formatDisplayDateTime($doneTime);
  5607. $deadlineLines = [];
  5608. $sysRqRaw = trim((string)($main['sys_rq'] ?? ''));
  5609. if ($sysRqRaw !== '' && stripos($sysRqRaw, '0000-00-00') !== 0) {
  5610. $deadlineDisp = $this->formatProcuremenSysRqForDisplay($sysRqRaw);
  5611. if ($deadlineDisp !== '' && $deadlineDisp !== '—') {
  5612. $deadlineLines[] = '招标截止日期:' . $deadlineDisp;
  5613. }
  5614. }
  5615. $deliveryRaw = trim((string)($main['delivery_deadline'] ?? ''));
  5616. if ($deliveryRaw !== '' && stripos($deliveryRaw, '0000-00-00') !== 0) {
  5617. $deliveryDisp = $this->formatProcuremenDeliveryDeadlineForInput($deliveryRaw);
  5618. if ($deliveryDisp === '') {
  5619. $deliveryDisp = $this->formatDeliveryYmd($deliveryRaw);
  5620. }
  5621. if ($deliveryDisp !== '') {
  5622. $deadlineLines[] = '交货截止日期:' . $deliveryDisp;
  5623. }
  5624. }
  5625. $issueOperTimeRaw = $step2Done ? ($issueTime !== '' ? $issueTime : $poTime) : '';
  5626. $deadlineText = implode("\n", $deadlineLines);
  5627. $prefixOperTime = static function (string $t): string {
  5628. $t = trim($t);
  5629. if ($t === '' || $t === '—') {
  5630. return $t;
  5631. }
  5632. if (strpos($t, '操作时间') === 0) {
  5633. return $t;
  5634. }
  5635. return '操作时间:' . $t;
  5636. };
  5637. $step2Time = ($issueOperTimeRaw !== '' && $issueOperTimeRaw !== '—') ? $issueOperTimeRaw : '';
  5638. $step4Time = $step4Done ? ($auditSelectTime !== '' ? $auditSelectTime : $pickedTime) : '';
  5639. $step5Time = $step5Done ? ($confirmApproveTime !== '' ? $confirmApproveTime : '') : '';
  5640. $stepInboundTime = $stepInboundDone ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5641. $step6Time = $step6Done ? ($inboundScoreTime !== '' ? $inboundScoreTime : $doneTime) : '';
  5642. $steps = [
  5643. [
  5644. 'title' => '未发',
  5645. 'subtitle' => '',
  5646. 'time' => (!$issued && $hasMain) ? $prefixOperTime($poTime) : '',
  5647. 'done' => $step1Done,
  5648. ],
  5649. [
  5650. 'title' => '下发',
  5651. 'subtitle' => $deadlineText,
  5652. 'time' => $prefixOperTime($step2Time),
  5653. 'done' => $step2Done,
  5654. ],
  5655. [
  5656. 'title' => '供应商接单',
  5657. 'subtitle' => '下发 ' . $issueCnt . ' / 接单 ' . $acceptCnt,
  5658. 'time' => '',
  5659. 'done' => $step3Done,
  5660. ],
  5661. [
  5662. 'title' => '待确认',
  5663. 'subtitle' => $step4Done
  5664. ? ($pickedName !== '' ? ('选定:' . $pickedName) : '')
  5665. : ($issued ? '待选供应商' : ''),
  5666. 'time' => $prefixOperTime($step4Time),
  5667. 'done' => $step4Done,
  5668. ],
  5669. [
  5670. 'title' => '待审批',
  5671. 'subtitle' => ($pickedName !== '' && $step4Done) ? ('供应商:' . $pickedName) : '',
  5672. 'time' => $prefixOperTime($step5Time),
  5673. 'done' => $step5Done,
  5674. ],
  5675. [
  5676. 'title' => '是否合格',
  5677. 'subtitle' => $stepInboundDone ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待入库评分' : ''),
  5678. 'time' => $prefixOperTime($stepInboundTime),
  5679. 'done' => $stepInboundDone,
  5680. ],
  5681. [
  5682. 'title' => '已完结',
  5683. 'subtitle' => '',
  5684. 'time' => $prefixOperTime($step6Time),
  5685. 'done' => $step6Done,
  5686. ],
  5687. ];
  5688. $currentIdx = count($steps) - 1;
  5689. if ($directComplete) {
  5690. // 直接完结:中间步骤跳过;未评分时当前停在「是否合格」
  5691. if (!$step6Done) {
  5692. foreach ($steps as $i => $s) {
  5693. if (($s['title'] ?? '') === '是否合格') {
  5694. $currentIdx = $i;
  5695. break;
  5696. }
  5697. }
  5698. }
  5699. } else {
  5700. foreach ($steps as $i => $s) {
  5701. if (!$s['done']) {
  5702. $currentIdx = $i;
  5703. break;
  5704. }
  5705. }
  5706. }
  5707. $nSteps = count($steps);
  5708. foreach ($steps as $idx => &$s) {
  5709. $s['current'] = ($idx === $currentIdx);
  5710. if ($idx === 0) {
  5711. $s['pdf_left_bg'] = '';
  5712. } else {
  5713. $s['pdf_left_bg'] = !empty($steps[$idx - 1]['done']) ? '#1890ff' : '#e0e0e0';
  5714. }
  5715. if ($idx >= $nSteps - 1) {
  5716. $s['pdf_right_bg'] = '';
  5717. } else {
  5718. $s['pdf_right_bg'] = !empty($s['done']) ? '#1890ff' : '#e0e0e0';
  5719. }
  5720. }
  5721. unset($s);
  5722. $labelMap = [
  5723. 'CCYDH' => '订单号',
  5724. 'CYJMC' => '印件名称',
  5725. 'CCLBMMC' => '承揽部门',
  5726. 'CGYMC' => '工序名称',
  5727. 'CDW' => '单位',
  5728. 'czlyq' => '类型',
  5729. 'NGZL' => '工作量',
  5730. 'CDF' => '单价',
  5731. 'cGzzxMc' => '工作中心',
  5732. 'MBZ' => '备注',
  5733. 'This_quantity' => '本次数量',
  5734. 'ceilingPrice' => '最高限价',
  5735. ];
  5736. $orderSummary = [];
  5737. foreach ($labelMap as $key => $lab) {
  5738. if (!array_key_exists($key, $main)) {
  5739. continue;
  5740. }
  5741. $val = $main[$key];
  5742. if ($val === null) {
  5743. $val = '';
  5744. } elseif (!is_scalar($val)) {
  5745. $val = json_encode($val, JSON_UNESCAPED_UNICODE);
  5746. } else {
  5747. $val = (string)$val;
  5748. }
  5749. $orderSummary[] = ['label' => $lab, 'value' => $val];
  5750. }
  5751. $orderSummary[] = [
  5752. 'label' => '是否合格',
  5753. 'value' => $inboundResult !== '' ? $inboundResult : (ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '') ? '待评分' : '—'),
  5754. ];
  5755. $orderSummaryGrid = [];
  5756. $n = count($orderSummary);
  5757. for ($i = 0; $i < $n; $i += 2) {
  5758. $left = $orderSummary[$i];
  5759. $hasRight = ($i + 1) < $n;
  5760. $orderSummaryGrid[] = [
  5761. 'l1' => $left['label'],
  5762. 'v1' => $left['value'],
  5763. 'l2' => $hasRight ? $orderSummary[$i + 1]['label'] : '',
  5764. 'v2' => $hasRight ? $orderSummary[$i + 1]['value'] : '',
  5765. ];
  5766. }
  5767. return [
  5768. 'steps' => $steps,
  5769. 'orderSummary' => $orderSummary,
  5770. 'orderSummaryGrid' => $orderSummaryGrid,
  5771. 'inbound_result' => $inboundResult,
  5772. 'inbound_score_time'=> $inboundScoreTime,
  5773. 'detailRows' => $details,
  5774. ];
  5775. }
  5776. /**
  5777. * 加载并 assign 协助采购「详情」弹窗所需变量(与 {@see details()} 页面一致,供模板 / PDF 共用)。
  5778. *
  5779. * @return array{ok: bool, ccydh: string} ok 表示存在主表或至少一条下发明细(否则 PDF 无可写内容)
  5780. */
  5781. protected function prepareProcuremenDetailsView(string $ids): array
  5782. {
  5783. $main = [];
  5784. try {
  5785. $one = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  5786. $main = is_array($one) ? $one : [];
  5787. } catch (\Throwable $e) {
  5788. $main = [];
  5789. }
  5790. $details = [];
  5791. $mergeRows = $this->loadDetailsMergeRowsByScydgyId($ids);
  5792. if ($mergeRows === []) {
  5793. $mergeRows = $this->scydgyRowsForPurchaseOrders($main !== [] ? [$main] : []);
  5794. if ($mergeRows === [] && $main !== []) {
  5795. $mergeRows = $this->procuremenPoolFromPurchaseOrderDbRows([$main]);
  5796. }
  5797. }
  5798. $detailSidList = [];
  5799. $anchorSid = (int)$ids;
  5800. if ($anchorSid !== 0) {
  5801. $detailSidList[$anchorSid] = true;
  5802. }
  5803. foreach ($mergeRows as $mr) {
  5804. if (!is_array($mr)) {
  5805. continue;
  5806. }
  5807. $sid = $this->extractScydgyRowId($mr);
  5808. if ($sid !== 0) {
  5809. $detailSidList[$sid] = true;
  5810. }
  5811. }
  5812. try {
  5813. if ($detailSidList !== []) {
  5814. $details = Db::table('purchase_order_detail')
  5815. ->where('scydgy_id', 'in', array_keys($detailSidList))
  5816. ->order('id', 'asc')
  5817. ->select();
  5818. }
  5819. } catch (\Throwable $e) {
  5820. $details = [];
  5821. }
  5822. if (!is_array($details)) {
  5823. $details = [];
  5824. }
  5825. foreach ($details as &$r) {
  5826. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  5827. $r['id'] = $r['ID'];
  5828. }
  5829. if (isset($r['createtime'])) {
  5830. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  5831. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  5832. } else {
  5833. $r['createtime_text'] = (string)$r['createtime'];
  5834. }
  5835. } else {
  5836. $r['createtime_text'] = '';
  5837. }
  5838. $r['delivery_ymd'] = $this->formatDeliveryYmd($r['delivery'] ?? null);
  5839. $r['is_void'] = is_array($r) && $this->isPurchaseOrderDetailVoid($r);
  5840. $r['is_picked'] = is_array($r) && ProcuremenStatus::isPodPicked($r['status'] ?? '');
  5841. $r['oper_time_text'] = $this->resolveDetailSupplierOperTime($r);
  5842. if (is_array($r)) {
  5843. $r = $this->maskSupplierContactFields($r);
  5844. }
  5845. }
  5846. unset($r);
  5847. $activeDetails = [];
  5848. foreach ($details as $r) {
  5849. if (is_array($r) && empty($r['is_void'])) {
  5850. $activeDetails[] = $r;
  5851. }
  5852. }
  5853. $operLogs = [];
  5854. try {
  5855. $operSidList = array_keys($detailSidList);
  5856. if ($operSidList === [] && (int)$ids !== 0) {
  5857. $operSidList = [(int)$ids];
  5858. }
  5859. if ($operSidList !== []) {
  5860. $operLogs = Db::table('purchase_order_oper_log')
  5861. ->where(ProcuremenOperLog::COL_SCYDGY_ID, 'in', $operSidList)
  5862. ->order('id', 'asc')
  5863. ->select();
  5864. }
  5865. // 手工单等:主表 scydgy_id 与日志不一致时,再按采购订单ID兜底
  5866. if ((!is_array($operLogs) || $operLogs === []) && $main !== []) {
  5867. $poId = (int)($main['id'] ?? $main['ID'] ?? 0);
  5868. if ($poId > 0) {
  5869. $operLogs = Db::table('purchase_order_oper_log')
  5870. ->where(ProcuremenOperLog::COL_PO_ID, $poId)
  5871. ->order('id', 'asc')
  5872. ->select();
  5873. }
  5874. }
  5875. } catch (\Throwable $e) {
  5876. $operLogs = [];
  5877. }
  5878. if (!is_array($operLogs)) {
  5879. $operLogs = [];
  5880. }
  5881. $operLogsRaw = $operLogs;
  5882. $processNameBySid = [];
  5883. foreach ($mergeRows as $mr) {
  5884. if (!is_array($mr)) {
  5885. continue;
  5886. }
  5887. $psid = (int)($mr['ID'] ?? $mr['scydgy_id'] ?? 0);
  5888. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  5889. if ($psid !== 0 && $gymc !== '') {
  5890. $processNameBySid[$psid] = $gymc;
  5891. }
  5892. }
  5893. $operLogs = ProcuremenOperLog::formatLogRowsForDisplay($operLogs, $processNameBySid);
  5894. $bundle = $this->buildProcuremenDetailsViewData($main, $activeDetails, $operLogsRaw);
  5895. $quoteView = $this->buildProcuremenDetailsQuoteView($mergeRows, $details, $main);
  5896. $ccydh = isset($main['CCYDH']) ? trim((string)$main['CCYDH']) : '';
  5897. if ($ccydh === '') {
  5898. foreach ($details as $r) {
  5899. if (!is_array($r)) {
  5900. continue;
  5901. }
  5902. $ccydh = trim((string)($r['CCYDH'] ?? ''));
  5903. if ($ccydh !== '') {
  5904. break;
  5905. }
  5906. }
  5907. }
  5908. $this->view->assign('ccydh', $ccydh);
  5909. $this->view->assign('steps', $bundle['steps']);
  5910. $this->view->assign('orderSummary', $bundle['orderSummary']);
  5911. $this->view->assign('orderSummaryGrid', $bundle['orderSummaryGrid']);
  5912. $this->view->assign('inboundResult', (string)($bundle['inbound_result'] ?? ''));
  5913. $this->view->assign('inboundScoreTime', (string)($bundle['inbound_score_time'] ?? ''));
  5914. $this->view->assign('processDisplayRows', $quoteView['process_rows']);
  5915. $this->view->assign('processCount', count($mergeRows));
  5916. $this->view->assign('detailRows', $details);
  5917. $this->view->assign('supplierQuoteGroups', $this->maskSupplierContactList($quoteView['supplier_groups']));
  5918. $this->view->assign('orderQuoteTotalText', $quoteView['order_total_text']);
  5919. $this->view->assign('orderQuoteTotalHas', $quoteView['order_total_has']);
  5920. $this->view->assign('selectedQuoteCompany', $quoteView['selected_company']);
  5921. // 未完结前不展示中标/未中标(选定供应商后、审批通过前状态列留空)
  5922. $showSupplierBidResult = ProcuremenStatus::isPoCompleted($main['status'] ?? '')
  5923. || ProcuremenStatus::isWflowApproved($main['wflow_status'] ?? '');
  5924. $this->view->assign('showSupplierBidResult', $showSupplierBidResult ? 1 : 0);
  5925. $this->view->assign('operLogs', $operLogs);
  5926. $sg = $quoteView['supplier_groups'] ?? [];
  5927. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh($ccydh, $main);
  5928. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  5929. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups(is_array($sg) ? $sg : [], $orderScoreRule));
  5930. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore(is_array($sg) ? $sg : [], $orderScoreRule) ? 1 : 0);
  5931. return [
  5932. 'ok' => $main !== [] || $details !== [],
  5933. 'ccydh' => $ccydh,
  5934. ];
  5935. }
  5936. /**
  5937. * 详情弹层:状态进度 + 订单信息 + 下发明细(列表「已下发」「已完结」均可打开)
  5938. */
  5939. public function details()
  5940. {
  5941. $ids = $this->request->param('ids', $this->request->param('id', ''));
  5942. if (is_array($ids)) {
  5943. $ids = isset($ids[0]) ? $ids[0] : '';
  5944. }
  5945. $ids = trim((string)$ids);
  5946. if ($ids === '') {
  5947. $this->error(__('Invalid parameters'));
  5948. }
  5949. $this->assertManualOrderDetailsViewable((int)$ids);
  5950. $this->prepareProcuremenDetailsView($ids);
  5951. /* 弹层内不套 default 布局,避免出现「控制台 / Control panel」整块标题区 */
  5952. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  5953. $this->view->engine->layout(false);
  5954. try {
  5955. return $this->view->fetch('procuremen/details_dialog_shell');
  5956. } finally {
  5957. if ($restoreLayout) {
  5958. $this->view->engine->layout($restoreLayout);
  5959. }
  5960. }
  5961. }
  5962. /**
  5963. * 解析合并审核工序行(订单号须一致,且均未协助)
  5964. *
  5965. * @return array<int, array<string, mixed>>
  5966. */
  5967. protected function parseReviewMergeRows(string $rowJson, string $mergeRowsJson): array
  5968. {
  5969. $primary = json_decode($rowJson, true);
  5970. if (!is_array($primary)) {
  5971. $this->error(__('Invalid parameters'));
  5972. }
  5973. $merge = json_decode($mergeRowsJson, true);
  5974. if (!is_array($merge) || $merge === []) {
  5975. $merge = [$primary];
  5976. }
  5977. $seen = [];
  5978. $out = [];
  5979. foreach ($merge as $r) {
  5980. if (!is_array($r)) {
  5981. continue;
  5982. }
  5983. $id = $this->extractScydgyRowId($r);
  5984. if (!$this->isValidScydgyRowId($id) || isset($seen[$id])) {
  5985. continue;
  5986. }
  5987. $seen[$id] = true;
  5988. $out[] = $r;
  5989. }
  5990. if ($out === []) {
  5991. $this->error('未找到可下发的工序,请关闭弹窗后回到列表重新勾选,再点「下发」');
  5992. }
  5993. $ccydh = null;
  5994. foreach ($out as $r) {
  5995. $dh = trim((string)($r['CCYDH'] ?? ''));
  5996. if ($ccydh === null) {
  5997. $ccydh = $dh;
  5998. } elseif ($dh !== $ccydh) {
  5999. $this->error('合并审核要求所选行的订单号一致');
  6000. }
  6001. }
  6002. $ids = [];
  6003. foreach ($out as $r) {
  6004. $id = $this->extractScydgyRowId($r);
  6005. if ($this->isValidScydgyRowId($id)) {
  6006. $ids[$id] = true;
  6007. }
  6008. }
  6009. $poBySid = [];
  6010. $detCntBySid = [];
  6011. if ($ids !== []) {
  6012. $idList = array_keys($ids);
  6013. try {
  6014. $poList = Db::table('purchase_order')->where('scydgy_id', 'in', $idList)->select();
  6015. if (is_array($poList)) {
  6016. foreach ($poList as $po) {
  6017. if (!is_array($po)) {
  6018. continue;
  6019. }
  6020. $sid = (int)($po['scydgy_id'] ?? 0);
  6021. if ($this->isValidScydgyRowId($sid)) {
  6022. $poBySid[$sid] = $po;
  6023. }
  6024. }
  6025. }
  6026. } catch (\Throwable $e) {
  6027. }
  6028. try {
  6029. $detQuery = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $idList);
  6030. $this->applyActivePurchaseOrderDetailWhere($detQuery);
  6031. $detRows = $detQuery->field('scydgy_id, COUNT(*) AS cnt')->group('scydgy_id')->select();
  6032. if (is_array($detRows)) {
  6033. foreach ($detRows as $dr) {
  6034. if (!is_array($dr)) {
  6035. continue;
  6036. }
  6037. $sid = (int)($dr['scydgy_id'] ?? 0);
  6038. if ($this->isValidScydgyRowId($sid)) {
  6039. $detCntBySid[$sid] = (int)($dr['cnt'] ?? 0);
  6040. }
  6041. }
  6042. }
  6043. } catch (\Throwable $e) {
  6044. }
  6045. }
  6046. foreach ($out as $r) {
  6047. $id = $this->extractScydgyRowId($r);
  6048. if (!$this->isValidScydgyRowId($id)) {
  6049. continue;
  6050. }
  6051. $po = $poBySid[$id] ?? null;
  6052. if (!is_array($po)) {
  6053. continue;
  6054. }
  6055. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '') || ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6056. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6057. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已进入审批流程,不能重复下发');
  6058. }
  6059. $detCnt = (int)($detCntBySid[$id] ?? 0);
  6060. if ($detCnt > 0 && !ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  6061. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6062. $this->error('工序「' . ($gymc !== '' ? $gymc : ('#' . $id)) . '」已存在下发明细,请走采购确认或联系管理员');
  6063. }
  6064. }
  6065. return $out;
  6066. }
  6067. /**
  6068. * 供应商联系信息脱敏(仅用于页面展示 / 只读接口响应)
  6069. */
  6070. protected function maskSupplierContactFields(array $item): array
  6071. {
  6072. if (array_key_exists('email', $item)) {
  6073. $item['email'] = mask_email((string)$item['email']);
  6074. }
  6075. if (array_key_exists('phone', $item)) {
  6076. $item['phone'] = mask_phone((string)$item['phone']);
  6077. }
  6078. return $item;
  6079. }
  6080. /**
  6081. * @param array<int, array<string, mixed>> $list
  6082. * @return array<int, array<string, mixed>>
  6083. */
  6084. protected function maskSupplierContactList(array $list): array
  6085. {
  6086. $out = [];
  6087. foreach ($list as $item) {
  6088. $out[] = is_array($item) ? $this->maskSupplierContactFields($item) : $item;
  6089. }
  6090. return $out;
  6091. }
  6092. /**
  6093. * 从 customer 表行构建下发用供应商联系信息(含明文邮箱/手机,仅服务端使用)
  6094. *
  6095. * @param bool $requireContactChannels true 时须有邮箱或手机才返回;false 仅展示用
  6096. * @return array<string, string>|null
  6097. */
  6098. protected function buildCustomerContactPayloadFromRow($row, bool $requireContactChannels = true): ?array
  6099. {
  6100. if (!is_array($row)) {
  6101. return null;
  6102. }
  6103. $norm = [];
  6104. foreach ($row as $k => $v) {
  6105. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  6106. }
  6107. $row = $norm;
  6108. $st = $row['status'] ?? '';
  6109. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  6110. return null;
  6111. }
  6112. $companyName = '';
  6113. foreach (['company_name', 'name'] as $nk) {
  6114. if (!empty($row[$nk])) {
  6115. $companyName = trim((string)$row[$nk]);
  6116. break;
  6117. }
  6118. }
  6119. if ($companyName === '') {
  6120. return null;
  6121. }
  6122. $username = '';
  6123. foreach (['username', 'contact', 'linkman', 'contacts'] as $uk) {
  6124. if (isset($row[$uk]) && trim((string)$row[$uk]) !== '') {
  6125. $username = trim((string)$row[$uk]);
  6126. break;
  6127. }
  6128. }
  6129. $email = isset($row['email']) ? trim((string)$row['email']) : '';
  6130. $phone = isset($row['phone']) ? trim((string)$row['phone']) : '';
  6131. if ($phone === '' && isset($row['account'])) {
  6132. $phone = trim((string)$row['account']);
  6133. }
  6134. if ($phone === '' && isset($row['mobile'])) {
  6135. $phone = trim((string)$row['mobile']);
  6136. }
  6137. if ($requireContactChannels && $email === '' && $phone === '') {
  6138. return null;
  6139. }
  6140. $category = '';
  6141. foreach (['company_type', 'category', 'type_name'] as $ck) {
  6142. if (isset($row[$ck]) && trim((string)$row[$ck]) !== '') {
  6143. $category = trim((string)$row[$ck]);
  6144. break;
  6145. }
  6146. }
  6147. return [
  6148. 'id' => isset($row['id']) ? (string)$row['id'] : '',
  6149. 'name' => $companyName,
  6150. 'company_name' => $companyName,
  6151. 'username' => $username,
  6152. 'email' => $email,
  6153. 'phone' => $phone,
  6154. 'category' => $category,
  6155. 'company_type' => $category,
  6156. ];
  6157. }
  6158. /**
  6159. * 按 customer.id 解析供应商联系信息(服务端下发/通知用)
  6160. */
  6161. protected function resolveCustomerContactById(string $id): ?array
  6162. {
  6163. $id = trim($id);
  6164. if ($id === '' || !ctype_digit($id)) {
  6165. return null;
  6166. }
  6167. try {
  6168. $row = Db::table('customer')->where('id', (int)$id)->find();
  6169. } catch (\Throwable $e) {
  6170. return null;
  6171. }
  6172. return $this->buildCustomerContactPayloadFromRow($row);
  6173. }
  6174. /**
  6175. * 按供应商名称解析联系信息(兼容旧提交数据)
  6176. *
  6177. * @param bool $requireContactChannels true 时须有邮箱或手机
  6178. */
  6179. protected function resolveCustomerContactByCompanyName(string $name, bool $requireContactChannels = true): ?array
  6180. {
  6181. $name = trim($name);
  6182. if ($name === '') {
  6183. return null;
  6184. }
  6185. try {
  6186. // customer 表仅有 company_name,无 name 列;带 name 条件会导致整查询失败
  6187. $row = Db::table('customer')
  6188. ->where('company_name', $name)
  6189. ->order('id', 'desc')
  6190. ->find();
  6191. } catch (\Throwable $e) {
  6192. return null;
  6193. }
  6194. return $this->buildCustomerContactPayloadFromRow($row, $requireContactChannels);
  6195. }
  6196. /**
  6197. * 规范化下发/确认时勾选的供应商
  6198. *
  6199. * @param array<int, mixed> $companies
  6200. * @return array<int, array<string, string>>
  6201. */
  6202. protected function normalizePickCompanies(array $companies): array
  6203. {
  6204. $out = [];
  6205. foreach ($companies as $c) {
  6206. if (!is_array($c)) {
  6207. continue;
  6208. }
  6209. $resolved = null;
  6210. $cid = trim((string)($c['id'] ?? ''));
  6211. if ($cid !== '') {
  6212. $resolved = $this->resolveCustomerContactById($cid);
  6213. }
  6214. $name = trim((string)($c['name'] ?? $c['company_name'] ?? ''));
  6215. if ($resolved === null && $name !== '') {
  6216. $resolved = $this->resolveCustomerContactByCompanyName($name);
  6217. }
  6218. if ($resolved === null) {
  6219. continue;
  6220. }
  6221. $out[] = $resolved;
  6222. }
  6223. return $out;
  6224. }
  6225. /**
  6226. * 确认供应商列表:按订单号 CCYDH 合并为一行(一单一行,工序汇总)
  6227. *
  6228. * @param array<int, array<string, mixed>> $pool
  6229. * @return array<int, array<string, mixed>>
  6230. */
  6231. protected function collapseProcuremenPoolByOrder(array $pool): array
  6232. {
  6233. if ($pool === []) {
  6234. return [];
  6235. }
  6236. $groups = [];
  6237. foreach ($pool as $row) {
  6238. if (!is_array($row)) {
  6239. continue;
  6240. }
  6241. $dh = trim((string)($row['CCYDH'] ?? ''));
  6242. $key = $dh !== '' ? $dh : ('_id_' . (int)($row['ID'] ?? 0));
  6243. if (!isset($groups[$key])) {
  6244. $groups[$key] = [];
  6245. }
  6246. $groups[$key][] = $row;
  6247. }
  6248. $out = [];
  6249. foreach ($groups as $ccydh => $rows) {
  6250. if ($rows === []) {
  6251. continue;
  6252. }
  6253. usort($rows, function ($a, $b) {
  6254. return ((int)($a['ID'] ?? 0)) <=> ((int)($b['ID'] ?? 0));
  6255. });
  6256. $head = $rows[0];
  6257. $gymcList = [];
  6258. foreach ($rows as $r) {
  6259. $g = trim((string)($r['CGYMC'] ?? ''));
  6260. if ($g !== '' && !in_array($g, $gymcList, true)) {
  6261. $gymcList[] = $g;
  6262. }
  6263. }
  6264. $merged = $head;
  6265. $merged['order_key'] = strpos((string)$ccydh, '_id_') === 0 ? '' : (string)$ccydh;
  6266. $merged['process_count'] = count($rows);
  6267. $merged['_order_merge_rows'] = $rows;
  6268. $qtyList = [];
  6269. $priceList = [];
  6270. foreach ($rows as $r) {
  6271. if (!is_array($r)) {
  6272. continue;
  6273. }
  6274. $qtyList[] = $this->resolveProcuremenThisQuantity($r);
  6275. $priceList[] = $this->resolveProcuremenCeilingPrice($r);
  6276. }
  6277. if (count($rows) > 1) {
  6278. $merged['CGYMC'] = implode('、', $gymcList);
  6279. // 多工序:数量/限价按有值项顿号间隔(空值不占位)
  6280. $merged['This_quantity'] = $this->joinProcuremenNonEmpty($qtyList);
  6281. $merged['ceilingPrice'] = $this->joinProcuremenNonEmpty($priceList);
  6282. } else {
  6283. $merged['This_quantity'] = $qtyList[0] ?? trim((string)($head['This_quantity'] ?? ''));
  6284. $merged['ceilingPrice'] = $priceList[0] ?? trim((string)($head['ceilingPrice'] ?? $head['ceiling_price'] ?? ''));
  6285. }
  6286. // 已选供应商:取合并行中首个非空 pick_company_name
  6287. $pickedName = '';
  6288. foreach ($rows as $r) {
  6289. if (!is_array($r)) {
  6290. continue;
  6291. }
  6292. $pn = trim((string)($r['pick_company_name'] ?? $r['picked_supplier_name'] ?? ''));
  6293. if ($pn !== '') {
  6294. $pickedName = $pn;
  6295. break;
  6296. }
  6297. }
  6298. if ($pickedName !== '') {
  6299. $merged['pick_company_name'] = $pickedName;
  6300. $merged['picked_supplier_name'] = $pickedName;
  6301. }
  6302. $mergedPickTime = '';
  6303. foreach ($rows as $r) {
  6304. $t = $this->procuremenRowListSortTime($r, 'pick_time');
  6305. if ($t !== '' && ($mergedPickTime === '' || strcmp($t, $mergedPickTime) > 0)) {
  6306. $mergedPickTime = $t;
  6307. }
  6308. }
  6309. if ($mergedPickTime !== '') {
  6310. $merged['pick_time'] = $mergedPickTime;
  6311. }
  6312. $out[] = $merged;
  6313. }
  6314. usort($out, function ($a, $b) {
  6315. $ta = $this->procuremenRowListSortTime($a, 'pick_time');
  6316. $tb = $this->procuremenRowListSortTime($b, 'pick_time');
  6317. if ($ta === $tb) {
  6318. $ida = (int)($a['purchase_order_id'] ?? 0);
  6319. $idb = (int)($b['purchase_order_id'] ?? 0);
  6320. if ($ida !== $idb) {
  6321. return $idb <=> $ida;
  6322. }
  6323. return strcmp((string)($b['CCYDH'] ?? ''), (string)($a['CCYDH'] ?? ''));
  6324. }
  6325. if ($ta === '') {
  6326. return 1;
  6327. }
  6328. if ($tb === '') {
  6329. return -1;
  6330. }
  6331. return strcmp($tb, $ta);
  6332. });
  6333. return $out;
  6334. }
  6335. /**
  6336. * 待确认供应商订单下全部工序(同一 CCYDH,wflow_status=1)
  6337. *
  6338. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6339. */
  6340. protected function loadAuditOrderBundleByScydgyId(string $scydgyId): array
  6341. {
  6342. $scydgyId = trim($scydgyId);
  6343. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6344. if ($scydgyId === '') {
  6345. return $empty;
  6346. }
  6347. try {
  6348. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6349. } catch (\Throwable $e) {
  6350. $anchor = null;
  6351. }
  6352. if (!is_array($anchor) || !ProcuremenStatus::isWflowPendingConfirm($anchor['wflow_status'] ?? '')) {
  6353. return $empty;
  6354. }
  6355. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6356. if ($ccydh === '') {
  6357. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  6358. }
  6359. try {
  6360. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->whereIn('wflow_status', ProcuremenStatus::wflowPendingConfirmValues())->order('scydgy_id', 'asc')->select();
  6361. } catch (\Throwable $e) {
  6362. $pos = [$anchor];
  6363. }
  6364. if (!is_array($pos) || $pos === []) {
  6365. $pos = [$anchor];
  6366. }
  6367. return [
  6368. 'ccydh' => $ccydh,
  6369. 'pos' => $pos,
  6370. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6371. ];
  6372. }
  6373. /**
  6374. * 采购确认阶段:purchase_order 是否待确认(status=0 且 wflow_status=2 或已有下发明细)
  6375. */
  6376. protected function purchaseOrderRowInConfirmStage(array $po): bool
  6377. {
  6378. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  6379. return false;
  6380. }
  6381. if (ProcuremenStatus::isWflowApproved($po['wflow_status'] ?? '')) {
  6382. return false;
  6383. }
  6384. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '')) {
  6385. return true;
  6386. }
  6387. if (ProcuremenStatus::isWflowPendingIssue($po['wflow_status'] ?? '')) {
  6388. $sid = (int)($po['scydgy_id'] ?? 0);
  6389. return $this->isValidScydgyRowId($sid) && $this->purchaseOrderDetail($sid) !== [];
  6390. }
  6391. return false;
  6392. }
  6393. /**
  6394. * 采购确认:同一 CCYDH 下全部待确认工序(与列表合并规则一致)
  6395. *
  6396. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  6397. */
  6398. protected function loadConfirmOrderBundleByScydgyId(string $scydgyId): array
  6399. {
  6400. $scydgyId = trim($scydgyId);
  6401. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  6402. if ($scydgyId === '') {
  6403. return $empty;
  6404. }
  6405. try {
  6406. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6407. } catch (\Throwable $e) {
  6408. $anchor = null;
  6409. }
  6410. if (!is_array($anchor) || !$this->purchaseOrderRowInConfirmStage($anchor)) {
  6411. return $empty;
  6412. }
  6413. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6414. if ($ccydh === '') {
  6415. return [
  6416. 'ccydh' => '',
  6417. 'pos' => [$anchor],
  6418. 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor]),
  6419. ];
  6420. }
  6421. try {
  6422. $posQuery = Db::table('purchase_order')->where('CCYDH', $ccydh);
  6423. $this->applyPurchaseOrderConfirmStageWhere($posQuery);
  6424. $pos = $posQuery->order('scydgy_id', 'asc')->select();
  6425. } catch (\Throwable $e) {
  6426. $pos = [$anchor];
  6427. }
  6428. if (!is_array($pos) || $pos === []) {
  6429. $pos = [$anchor];
  6430. }
  6431. $pos = array_values(array_filter($pos, function ($po) {
  6432. return is_array($po) && $this->purchaseOrderRowInConfirmStage($po);
  6433. }));
  6434. if ($pos === []) {
  6435. $pos = [$anchor];
  6436. }
  6437. return [
  6438. 'ccydh' => $ccydh,
  6439. 'pos' => $pos,
  6440. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  6441. ];
  6442. }
  6443. /**
  6444. * @param array<int, array<string, mixed>> $purchaseOrders
  6445. * @return array<int, array<string, mixed>>
  6446. */
  6447. protected function scydgyRowsForPurchaseOrders(array $purchaseOrders): array
  6448. {
  6449. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($purchaseOrders);
  6450. $byId = [];
  6451. foreach ($pool as $r) {
  6452. if (!is_array($r)) {
  6453. continue;
  6454. }
  6455. $sid = (int)($r['ID'] ?? $r['id'] ?? 0);
  6456. if ($this->isValidScydgyRowId($sid)) {
  6457. $byId[$sid] = $r;
  6458. }
  6459. }
  6460. $out = [];
  6461. foreach ($purchaseOrders as $po) {
  6462. if (!is_array($po)) {
  6463. continue;
  6464. }
  6465. $sid = (int)($po['scydgy_id'] ?? 0);
  6466. if ($this->isValidScydgyRowId($sid) && isset($byId[$sid])) {
  6467. $out[] = $byId[$sid];
  6468. }
  6469. }
  6470. return $out;
  6471. }
  6472. /**
  6473. * 详情 / PDF:同一协助批次下的全部工序行(与确认供应商弹窗一致)
  6474. *
  6475. * @return array<int, array<string, mixed>>
  6476. */
  6477. protected function loadDetailsMergeRowsByScydgyId(string $scydgyId): array
  6478. {
  6479. $scydgyId = trim($scydgyId);
  6480. if ($scydgyId === '') {
  6481. return [];
  6482. }
  6483. try {
  6484. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  6485. } catch (\Throwable $e) {
  6486. $anchor = null;
  6487. }
  6488. if (!is_array($anchor)) {
  6489. return [];
  6490. }
  6491. if (!empty($anchor['mod_rq']) && trim((string)$anchor['mod_rq']) !== '' && stripos(trim((string)$anchor['mod_rq']), '0000-00-00') !== 0) {
  6492. return [];
  6493. }
  6494. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  6495. $pickTime = trim((string)($anchor['pick_time'] ?? ''));
  6496. $isValidPick = $pickTime !== '' && stripos($pickTime, '0000-00-00') !== 0;
  6497. try {
  6498. $q = Db::table('purchase_order');
  6499. if ($ccydh !== '') {
  6500. $q->where('CCYDH', $ccydh);
  6501. } else {
  6502. $q->where('scydgy_id', $scydgyId);
  6503. }
  6504. if ($isValidPick) {
  6505. $q->where('pick_time', $pickTime);
  6506. }
  6507. $pos = $q->order('scydgy_id', 'asc')->select();
  6508. } catch (\Throwable $e) {
  6509. $pos = [$anchor];
  6510. }
  6511. if (!is_array($pos) || $pos === []) {
  6512. $pos = [$anchor];
  6513. }
  6514. $pos = array_values(array_filter($pos, function ($po) {
  6515. if (!is_array($po)) {
  6516. return false;
  6517. }
  6518. $mr = $po['mod_rq'] ?? null;
  6519. if ($mr === null || $mr === '') {
  6520. return true;
  6521. }
  6522. $mrs = trim((string)$mr);
  6523. return $mrs === '' || stripos($mrs, '0000-00-00') === 0;
  6524. }));
  6525. if ($pos === []) {
  6526. $pos = [$anchor];
  6527. }
  6528. $rows = $this->scydgyRowsForPurchaseOrders($pos);
  6529. if ($rows === []) {
  6530. $rows = $this->procuremenPoolFromPurchaseOrderDbRows($pos);
  6531. }
  6532. return $rows;
  6533. }
  6534. /**
  6535. * 审核弹窗工序表展示行(与下发弹窗列一致,同订单合并订单号/印件名称单元格)
  6536. *
  6537. * @param array<int, array<string, mixed>> $mergeRows
  6538. * @return array<int, array<string, mixed>>
  6539. */
  6540. protected function buildAuditProcessDisplayRows(array $mergeRows): array
  6541. {
  6542. $list = array_values($mergeRows);
  6543. $n = count($list);
  6544. $orderKey0 = $n > 0 ? trim((string)($list[0]['CCYDH'] ?? '')) : '';
  6545. $nameKey0 = $n > 0 ? trim((string)($list[0]['CYJMC'] ?? '')) : '';
  6546. $mergeSame = $n > 1 && $orderKey0 !== '';
  6547. if ($mergeSame) {
  6548. foreach ($list as $rr) {
  6549. if (!is_array($rr)) {
  6550. $mergeSame = false;
  6551. break;
  6552. }
  6553. if (trim((string)($rr['CCYDH'] ?? '')) !== $orderKey0
  6554. || trim((string)($rr['CYJMC'] ?? '')) !== $nameKey0) {
  6555. $mergeSame = false;
  6556. break;
  6557. }
  6558. }
  6559. }
  6560. $out = [];
  6561. foreach ($list as $idx => $r) {
  6562. if (!is_array($r)) {
  6563. continue;
  6564. }
  6565. $qty = $this->resolveProcuremenThisQuantity($r);
  6566. $price = $this->resolveProcuremenCeilingPrice($r);
  6567. $sid = $this->extractScydgyRowId($r);
  6568. $out[] = [
  6569. 'seq' => $idx + 1,
  6570. 'scydgy_id' => $sid,
  6571. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  6572. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  6573. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  6574. 'CDW' => trim((string)($r['CDW'] ?? '')),
  6575. 'czlyq' => trim((string)($r['czlyq'] ?? '')),
  6576. 'NGZL' => $r['NGZL'] ?? '',
  6577. 'This_quantity' => $qty,
  6578. 'ceilingPrice' => $price,
  6579. 'CDF' => trim((string)($r['CDF'] ?? '')),
  6580. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  6581. 'show_order_cells' => !$mergeSame || $idx === 0,
  6582. 'order_rowspan' => $mergeSame ? $n : 1,
  6583. ];
  6584. }
  6585. return $out;
  6586. }
  6587. /**
  6588. * 解析金额/数量(去千分位等非数字字符)
  6589. */
  6590. protected function parseProcuremenMoneyNumber($value): ?float
  6591. {
  6592. if ($value === null || $value === '') {
  6593. return null;
  6594. }
  6595. if (is_numeric($value)) {
  6596. return (float)$value;
  6597. }
  6598. $v = preg_replace('/[^\d\.\-]/', '', (string)$value);
  6599. return ($v !== '' && is_numeric($v)) ? (float)$v : null;
  6600. }
  6601. protected function formatProcuremenMoneyDisplay(?float $amount): string
  6602. {
  6603. if ($amount === null) {
  6604. return '';
  6605. }
  6606. // 保留小数(最多 5 位),去掉末尾无意义的 0,避免 0.25 被显示成 0
  6607. $s = rtrim(rtrim(sprintf('%.5F', (float)$amount), '0'), '.');
  6608. return $s === '' ? '0' : $s;
  6609. }
  6610. /**
  6611. * 列表/详情展示:工作量为 0 时显示空
  6612. */
  6613. protected function formatProcuremenWorkloadDisplay($value): string
  6614. {
  6615. if ($value === null || $value === '') {
  6616. return '';
  6617. }
  6618. $s = trim((string)$value);
  6619. if ($s === '') {
  6620. return '';
  6621. }
  6622. if (is_numeric($s) && (float)$s == 0) {
  6623. return '';
  6624. }
  6625. return $s;
  6626. }
  6627. /**
  6628. * 详情:已选定供应商名称(明细 status=1 或主表 pick_company_name)
  6629. */
  6630. protected function resolveProcuremenSelectedCompanyName(array $main, array $details): string
  6631. {
  6632. foreach ($details as $d) {
  6633. if (!is_array($d)) {
  6634. continue;
  6635. }
  6636. if (!$this->isPurchaseOrderDetailVoid($d) && ProcuremenStatus::isPodPicked($d['status'] ?? '')) {
  6637. $cn = trim((string)($d['company_name'] ?? ''));
  6638. if ($cn !== '') {
  6639. return $cn;
  6640. }
  6641. }
  6642. }
  6643. return trim((string)($main['pick_company_name'] ?? ''));
  6644. }
  6645. /**
  6646. * 详情报价小计:单价 × 本工序本次数量
  6647. */
  6648. protected function calcProcuremenDetailSubtotal($amountRaw, string $qtyStr): ?float
  6649. {
  6650. $unit = $this->parseProcuremenMoneyNumber($amountRaw);
  6651. if ($unit === null) {
  6652. return null;
  6653. }
  6654. $qty = $this->parseProcuremenMoneyNumber($qtyStr);
  6655. if ($qty === null || $qty <= 0) {
  6656. return null;
  6657. }
  6658. return $unit * $qty;
  6659. }
  6660. /**
  6661. * 详情页:工序小计 + 供应商分组报价与总计
  6662. *
  6663. * @param array<int, array<string, mixed>> $mergeRows
  6664. * @param array<int, array<string, mixed>> $details 含有效与历史明细
  6665. * @return array{
  6666. * process_rows: array,
  6667. * supplier_groups: array,
  6668. * order_total_text: string,
  6669. * order_total_has: bool,
  6670. * selected_company: string
  6671. * }
  6672. */
  6673. protected function buildProcuremenDetailsQuoteView(array $mergeRows, array $details, array $main): array
  6674. {
  6675. $processRows = $this->buildAuditProcessDisplayRows($mergeRows);
  6676. $ccydh = trim((string)($main['CCYDH'] ?? ''));
  6677. $quoteVisible = $this->isProcuremenBidOpenVerified($ccydh)
  6678. || ((int)($main['manual_pick'] ?? 0) === 1);
  6679. $qtyBySid = [];
  6680. $gymcBySid = [];
  6681. $orderedSids = [];
  6682. foreach ($mergeRows as $mr) {
  6683. if (!is_array($mr)) {
  6684. continue;
  6685. }
  6686. $sid = $this->extractScydgyRowId($mr);
  6687. if ($this->isValidScydgyRowId($sid)) {
  6688. $orderedSids[] = $sid;
  6689. }
  6690. $qty = trim((string)($mr['This_quantity'] ?? ''));
  6691. if ($qty === '') {
  6692. $qty = trim((string)($mr['NGZL'] ?? ''));
  6693. }
  6694. $qtyBySid[$sid] = $qty;
  6695. $gymcBySid[$sid] = trim((string)($mr['CGYMC'] ?? ''));
  6696. }
  6697. $selectedCompany = $this->resolveProcuremenSelectedCompanyName($main, $details);
  6698. $detailByCompanySid = [];
  6699. foreach ($details as $d) {
  6700. if (!is_array($d)) {
  6701. continue;
  6702. }
  6703. $cn = trim((string)($d['company_name'] ?? ''));
  6704. $sid = (int)($d['scydgy_id'] ?? 0);
  6705. if ($cn === '' || $sid === 0) {
  6706. continue;
  6707. }
  6708. if (!isset($detailByCompanySid[$cn])) {
  6709. $detailByCompanySid[$cn] = [];
  6710. }
  6711. $detailByCompanySid[$cn][$sid] = $d;
  6712. }
  6713. $supplierGroups = [];
  6714. foreach ($detailByCompanySid as $cn => $bySid) {
  6715. $lines = [];
  6716. $groupTotal = 0.0;
  6717. $groupHas = false;
  6718. $groupVoid = true;
  6719. $usedSids = [];
  6720. $appendLine = function (int $sid, array $d) use (
  6721. &$lines,
  6722. &$groupTotal,
  6723. &$groupHas,
  6724. &$groupVoid,
  6725. $qtyBySid,
  6726. $gymcBySid,
  6727. $quoteVisible
  6728. ) {
  6729. $isVoid = $this->isPurchaseOrderDetailVoid($d);
  6730. if (!$isVoid) {
  6731. $groupVoid = false;
  6732. }
  6733. $qtyStr = $qtyBySid[$sid] ?? '';
  6734. $amountNum = $this->parseProcuremenMoneyNumber($d['amount'] ?? null);
  6735. $am = trim((string)($d['amount'] ?? ''));
  6736. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  6737. $deliveryYmd = $d['delivery_ymd'] ?? $this->formatDeliveryYmd($d['delivery'] ?? null);
  6738. $deliveryFilled = ($deliveryYmd !== '' && !preg_match('/^0000-00-00/i', $deliveryYmd));
  6739. $sub = null;
  6740. if (!$isVoid && $amountNum !== null) {
  6741. $sub = $this->calcProcuremenDetailSubtotal($d['amount'] ?? null, $qtyStr);
  6742. }
  6743. $ct = $this->resolveDetailSupplierOperTime($d);
  6744. $leadDays = $this->resolveProcuremenLeadDays($d, $deliveryFilled ? (string)$deliveryYmd : '');
  6745. $leadFilled = ($leadDays !== null);
  6746. $leadText = $this->formatProcuremenLeadDaysText($leadDays);
  6747. $line = [
  6748. 'cgymc' => $gymcBySid[$sid] ?? trim((string)($d['CGYMC'] ?? '')),
  6749. 'amount' => $am,
  6750. 'unit_price_text' => $amountFilled
  6751. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  6752. : '未填写',
  6753. 'subtotal_text' => $sub !== null ? $this->formatProcuremenMoneyDisplay($sub) : '',
  6754. 'delivery_ymd' => $deliveryYmd,
  6755. 'amount_filled' => $amountFilled,
  6756. 'delivery_filled' => $deliveryFilled,
  6757. 'delivery_show' => $deliveryFilled ? $deliveryYmd : '未填写',
  6758. 'lead_days' => $leadFilled ? $leadDays : '',
  6759. 'lead_days_filled'=> $leadFilled,
  6760. 'lead_days_show' => $leadText,
  6761. 'lead_days_text' => $leadText,
  6762. 'status' => ProcuremenStatus::normalizePodPickStatus($d['status'] ?? ''),
  6763. 'is_picked' => ProcuremenStatus::isPodPicked($d['status'] ?? ''),
  6764. 'is_void' => $isVoid,
  6765. 'oper_time_text' => $ct,
  6766. ];
  6767. if (!$quoteVisible && !$isVoid) {
  6768. $this->maskSupplierQuoteLineBeforeDeadline($line);
  6769. } elseif ($sub !== null) {
  6770. $groupTotal += $sub;
  6771. $groupHas = true;
  6772. }
  6773. $lines[] = $this->ensureSupplierQuoteLineDisplayKeys($line);
  6774. };
  6775. foreach ($orderedSids as $sid) {
  6776. if (!isset($bySid[$sid])) {
  6777. continue;
  6778. }
  6779. $usedSids[$sid] = true;
  6780. $appendLine($sid, $bySid[$sid]);
  6781. }
  6782. foreach ($bySid as $sid => $d) {
  6783. if (isset($usedSids[$sid])) {
  6784. continue;
  6785. }
  6786. $appendLine((int)$sid, $d);
  6787. }
  6788. $firstDetail = null;
  6789. foreach ($bySid as $d) {
  6790. if (is_array($d)) {
  6791. $firstDetail = $d;
  6792. break;
  6793. }
  6794. }
  6795. $ph = is_array($firstDetail) ? trim((string)($firstDetail['phone'] ?? '')) : '';
  6796. $username = is_array($firstDetail) ? trim((string)($firstDetail['username'] ?? '')) : '';
  6797. if ($username === '' && $ph !== '') {
  6798. $username = $this->resolveCustomerContactName($ph, $cn);
  6799. }
  6800. $remark = '';
  6801. foreach ($bySid as $d) {
  6802. if (!is_array($d)) {
  6803. continue;
  6804. }
  6805. $rm = '';
  6806. foreach (['remark', 'Remark', 'REMARK'] as $rk) {
  6807. if (array_key_exists($rk, $d) && $d[$rk] !== null && $d[$rk] !== '') {
  6808. $rm = trim((string)$d[$rk]);
  6809. break;
  6810. }
  6811. }
  6812. if ($rm !== '') {
  6813. $remark = $rm;
  6814. break;
  6815. }
  6816. }
  6817. $lineCount = count($lines);
  6818. $hasRemark = $lineCount > 0;
  6819. $supplierGroup = [
  6820. 'company_name' => $cn,
  6821. 'username' => $username,
  6822. 'email' => is_array($firstDetail) ? trim((string)($firstDetail['email'] ?? '')) : '',
  6823. 'phone' => $ph,
  6824. 'remark' => $remark,
  6825. 'has_remark' => $hasRemark,
  6826. 'is_selected' => ($selectedCompany !== '' && $cn === $selectedCompany),
  6827. 'is_void' => $groupVoid,
  6828. 'lines' => $lines,
  6829. 'line_count' => $lineCount,
  6830. 'display_rowspan'=> $lineCount > 0 ? ($lineCount + 2) : 0,
  6831. 'total_text' => ($quoteVisible && $groupHas) ? $this->formatProcuremenMoneyDisplay($groupTotal) : '',
  6832. 'has_total' => $lineCount > 0,
  6833. ];
  6834. $this->maskSupplierRemarkBeforeBidOpen($supplierGroup, $quoteVisible);
  6835. $supplierGroups[] = $supplierGroup;
  6836. }
  6837. usort($supplierGroups, function ($a, $b) {
  6838. if (($a['is_void'] ?? false) !== ($b['is_void'] ?? false)) {
  6839. return ($a['is_void'] ?? false) ? 1 : -1;
  6840. }
  6841. if (($a['is_selected'] ?? false) !== ($b['is_selected'] ?? false)) {
  6842. return ($a['is_selected'] ?? false) ? -1 : 1;
  6843. }
  6844. return strcmp((string)($a['company_name'] ?? ''), (string)($b['company_name'] ?? ''));
  6845. });
  6846. $supplierGroups = ProcuremenSupplierScore::attachToQuoteGroups($supplierGroups, $ccydh, (bool)$quoteVisible);
  6847. return [
  6848. 'process_rows' => $processRows,
  6849. 'supplier_groups' => $supplierGroups,
  6850. 'order_total_text' => '',
  6851. 'order_total_has' => false,
  6852. 'selected_company' => $selectedCompany,
  6853. ];
  6854. }
  6855. /**
  6856. * 短信用工序明细(仅工序行,订单号/印件名称请在模版里用 {ccydh} {cyjmc} 自行排版)
  6857. */
  6858. protected function buildProcessLinesPlain(array $mergeRows): string
  6859. {
  6860. $lines = [];
  6861. $i = 1;
  6862. foreach ($mergeRows as $r) {
  6863. if (!is_array($r)) {
  6864. continue;
  6865. }
  6866. $gymc = trim((string)($r['CGYMC'] ?? ''));
  6867. $dw = trim((string)($r['CDW'] ?? ''));
  6868. $gzl = trim((string)($r['NGZL'] ?? ''));
  6869. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  6870. $parts = [$i . '.工序名称:' . ($gymc !== '' ? $gymc : '—')];
  6871. if ($dw !== '') {
  6872. $parts[] = '单位:' . $dw;
  6873. }
  6874. if ($gzl !== '') {
  6875. $parts[] = '工作量:' . $gzl;
  6876. }
  6877. if ($qty !== '') {
  6878. $parts[] = '本次数量:' . $qty;
  6879. }
  6880. $lines[] = implode(' ', $parts);
  6881. $i++;
  6882. }
  6883. return implode("\n", $lines);
  6884. }
  6885. /**
  6886. * 采购确认短信/邮件共用变量(含订单号、印件名称、工序明细)
  6887. *
  6888. * @return array<string, string>
  6889. */
  6890. protected function buildPurchaseConfirmNotifyVars(int $sid, int $fallbackDetailId = 0, ?array $bundle = null): array
  6891. {
  6892. if ($bundle === null || !is_array($bundle['merge_rows'] ?? null) || ($bundle['merge_rows'] ?? []) === []) {
  6893. $bundle = $this->loadOrderBundleForConfirmNotify($sid > 0 ? [$sid] : []);
  6894. }
  6895. $mergeRows = is_array($bundle['merge_rows'] ?? null) ? $bundle['merge_rows'] : [];
  6896. $pos = is_array($bundle['pos'] ?? null) ? $bundle['pos'] : [];
  6897. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  6898. $cyjmc = '';
  6899. foreach ($mergeRows as $mr) {
  6900. if (!is_array($mr)) {
  6901. continue;
  6902. }
  6903. if ($ccydh === '') {
  6904. $ccydh = trim((string)($mr['CCYDH'] ?? ''));
  6905. }
  6906. if ($cyjmc === '') {
  6907. $cyjmc = trim((string)($mr['CYJMC'] ?? ''));
  6908. }
  6909. }
  6910. if ($pos !== []) {
  6911. $firstPo = $pos[0];
  6912. if (is_array($firstPo)) {
  6913. if ($ccydh === '') {
  6914. $ccydh = trim((string)($firstPo['CCYDH'] ?? ''));
  6915. }
  6916. if ($cyjmc === '') {
  6917. $cyjmc = trim((string)($firstPo['CYJMC'] ?? ''));
  6918. }
  6919. }
  6920. }
  6921. if (($ccydh === '' || $cyjmc === '') && $fallbackDetailId > 0 && $sid > 0) {
  6922. $any = $this->purchaseOrderDetai($sid, $fallbackDetailId);
  6923. if (is_array($any)) {
  6924. if ($ccydh === '') {
  6925. $ccydh = trim((string)($any['CCYDH'] ?? ''));
  6926. }
  6927. if ($cyjmc === '') {
  6928. $cyjmc = trim((string)($any['CYJMC'] ?? ''));
  6929. }
  6930. }
  6931. }
  6932. $processPlain = $mergeRows !== [] ? $this->buildProcessLinesPlain($mergeRows) : '';
  6933. $processLines = $this->buildPurchaseConfirmProcessLinesText($ccydh, $cyjmc, $processPlain);
  6934. $cgymc = '';
  6935. if (count($mergeRows) === 1 && is_array($mergeRows[0])) {
  6936. $cgymc = trim((string)($mergeRows[0]['CGYMC'] ?? ''));
  6937. }
  6938. return [
  6939. 'ccydh' => $ccydh,
  6940. 'cyjmc' => $cyjmc,
  6941. 'cgymc' => $cgymc,
  6942. 'process_lines' => $processLines,
  6943. 'process_lines_html' => '',
  6944. ];
  6945. }
  6946. /**
  6947. * 采购确认短信中的工序/订单信息块(模版常用 {process_lines})
  6948. */
  6949. protected function buildPurchaseConfirmProcessLinesText(string $ccydh, string $cyjmc, string $processPlain): string
  6950. {
  6951. $lines = [];
  6952. if ($ccydh !== '') {
  6953. $lines[] = '订单号:' . $ccydh;
  6954. }
  6955. if ($cyjmc !== '') {
  6956. $lines[] = '印件名称:' . $cyjmc;
  6957. }
  6958. if ($processPlain !== '') {
  6959. $lines[] = $processPlain;
  6960. }
  6961. return implode("\n", $lines);
  6962. }
  6963. /**
  6964. * 各工序手机端链接(纯文本,供短信模版 {platform_links})
  6965. *
  6966. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6967. */
  6968. protected function buildPlatformLinksPlain(array $detailLinks): string
  6969. {
  6970. $lines = [];
  6971. $i = 1;
  6972. foreach ($detailLinks as $lk) {
  6973. if (!is_array($lk)) {
  6974. continue;
  6975. }
  6976. $url = trim((string)($lk['url'] ?? ''));
  6977. if ($url === '') {
  6978. continue;
  6979. }
  6980. $label = trim((string)($lk['cgymc'] ?? ''));
  6981. if ($label === '') {
  6982. $label = '工序' . $i;
  6983. }
  6984. $lines[] = $label . ':' . $url;
  6985. $i++;
  6986. }
  6987. return implode("\n", $lines);
  6988. }
  6989. /**
  6990. * 各工序手机端链接(HTML,供邮件模版 {platform_links_html})
  6991. *
  6992. * @param array<int, array{cgymc:string,url:string}> $detailLinks
  6993. */
  6994. protected function buildPlatformLinksHtml(array $detailLinks): string
  6995. {
  6996. $parts = [];
  6997. $i = 1;
  6998. foreach ($detailLinks as $lk) {
  6999. if (!is_array($lk)) {
  7000. continue;
  7001. }
  7002. $url = trim((string)($lk['url'] ?? ''));
  7003. if ($url === '') {
  7004. continue;
  7005. }
  7006. $label = trim((string)($lk['cgymc'] ?? ''));
  7007. if ($label === '') {
  7008. $label = '工序' . $i;
  7009. }
  7010. $urlEsc = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
  7011. $parts[] = htmlspecialchars($label, ENT_QUOTES, 'UTF-8')
  7012. . ' — <a href="' . $urlEsc . '">点击查看</a>';
  7013. $i++;
  7014. }
  7015. return implode("<br>\n", $parts);
  7016. }
  7017. /**
  7018. * 发件配置:host/port 等来自 config.php;addr、pass 必须来自 purchase_email 表
  7019. *
  7020. * @return array<string, mixed>
  7021. */
  7022. protected function loadMailerConfig(): array
  7023. {
  7024. try {
  7025. $cfg = \app\admin\model\Purchaseemail::getActiveMailerConfig();
  7026. } catch (\Throwable $e) {
  7027. $cfg = [];
  7028. }
  7029. return is_array($cfg) ? $cfg : [];
  7030. }
  7031. protected function loadNotifyTemplateRow(string $scene): ?array
  7032. {
  7033. try {
  7034. $row = Db::table('purchase_sms_template')
  7035. ->where('scene', $scene)
  7036. ->where(function ($q) {
  7037. $q->where('status', 1)->whereOr('status', '1')->whereOr('status', 'normal');
  7038. })
  7039. ->order('id', 'asc')
  7040. ->find();
  7041. } catch (\Throwable $e) {
  7042. return null;
  7043. }
  7044. if (!is_array($row) || $row === []) {
  7045. return null;
  7046. }
  7047. return [
  7048. 'title' => trim((string)($row['title'] ?? '')),
  7049. 'content' => trim((string)($row['content'] ?? '')),
  7050. ];
  7051. }
  7052. /**
  7053. * 邮件用工序明细 HTML(仅工序块,其它字段请在模版里用 {ccydh} 等变量)
  7054. */
  7055. protected function buildProcessLinesHtml(array $mergeRows): string
  7056. {
  7057. if (count($mergeRows) <= 1) {
  7058. $r = $mergeRows[0] ?? [];
  7059. if (!is_array($r)) {
  7060. return '';
  7061. }
  7062. $gymc = trim((string)($r['CGYMC'] ?? ''));
  7063. $dw = trim((string)($r['CDW'] ?? ''));
  7064. $gzl = trim((string)($r['NGZL'] ?? ''));
  7065. $qty = trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? ''));
  7066. $html = '工序名称:' . htmlspecialchars($gymc !== '' ? $gymc : '—', ENT_QUOTES, 'UTF-8') . '<br>';
  7067. if ($dw !== '') {
  7068. $html .= '单位:' . htmlspecialchars($dw, ENT_QUOTES, 'UTF-8') . '<br>';
  7069. }
  7070. if ($gzl !== '') {
  7071. $html .= '工作量:' . htmlspecialchars($gzl, ENT_QUOTES, 'UTF-8') . '<br>';
  7072. }
  7073. if ($qty !== '') {
  7074. $html .= '本次数量:' . htmlspecialchars($qty, ENT_QUOTES, 'UTF-8') . '<br>';
  7075. }
  7076. return $html;
  7077. }
  7078. $rows = '';
  7079. $i = 1;
  7080. foreach ($mergeRows as $r) {
  7081. if (!is_array($r)) {
  7082. continue;
  7083. }
  7084. $gymc = htmlspecialchars(trim((string)($r['CGYMC'] ?? '')), ENT_QUOTES, 'UTF-8');
  7085. $dw = htmlspecialchars(trim((string)($r['CDW'] ?? '')), ENT_QUOTES, 'UTF-8');
  7086. $gzl = htmlspecialchars(trim((string)($r['NGZL'] ?? '')), ENT_QUOTES, 'UTF-8');
  7087. $qty = htmlspecialchars(trim((string)($r['This_quantity'] ?? $r['this_quantity'] ?? '')), ENT_QUOTES, 'UTF-8');
  7088. $rows .= '<tr><td style="padding:4px 8px;border:1px solid #ddd;text-align:center;">' . $i . '</td>'
  7089. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gymc !== '' ? $gymc : '—') . '</td>'
  7090. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($dw !== '' ? $dw : '—') . '</td>'
  7091. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($gzl !== '' ? $gzl : '—') . '</td>'
  7092. . '<td style="padding:4px 8px;border:1px solid #ddd;">' . ($qty !== '' ? $qty : '—') . '</td></tr>';
  7093. $i++;
  7094. }
  7095. if ($rows === '') {
  7096. return '';
  7097. }
  7098. return '<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;margin:8px 0;font-size:14px;">'
  7099. . '<thead><tr style="background:#f5f5f5;">'
  7100. . '<th style="padding:6px 8px;border:1px solid #ddd;">序号</th>'
  7101. . '<th style="padding:6px 8px;border:1px solid #ddd;">工序名称</th>'
  7102. . '<th style="padding:6px 8px;border:1px solid #ddd;">单位</th>'
  7103. . '<th style="padding:6px 8px;border:1px solid #ddd;">工作量</th>'
  7104. . '<th style="padding:6px 8px;border:1px solid #ddd;">本次数量</th>'
  7105. . '</tr></thead><tbody>' . $rows . '</tbody></table>';
  7106. }
  7107. protected function parseProcuremenSysRqInput(string $sysRq, bool $required = true, bool $allowPast = false): string
  7108. {
  7109. $sysRq = trim($sysRq);
  7110. if ($sysRq === '') {
  7111. if ($required) {
  7112. $this->error('请选择招标截止日期');
  7113. }
  7114. return '';
  7115. }
  7116. $ts = strtotime($sysRq);
  7117. if ($ts === false || $ts <= 0) {
  7118. $this->error('招标截止日期格式无效');
  7119. }
  7120. // 下发询价时须晚于当前;确认供应商等场景截止已过后仍要解析写入,跳过「不能早于今天」
  7121. if (!$allowPast) {
  7122. $ymd = date('Y-m-d', $ts);
  7123. if ($ymd < date('Y-m-d')) {
  7124. $this->error('招标截止日期不能早于今天');
  7125. }
  7126. if ($ts <= time()) {
  7127. $this->error('招标截止时间不能早于当前时间');
  7128. }
  7129. }
  7130. return date('Y-m-d H:i:s', $ts);
  7131. }
  7132. /**
  7133. * 确保 purchase_order.czlyq(类型)存在
  7134. */
  7135. protected function ensurePurchaseOrderCzlyqColumn(): void
  7136. {
  7137. static $done = false;
  7138. if ($done) {
  7139. return;
  7140. }
  7141. $done = true;
  7142. try {
  7143. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'czlyq'");
  7144. if (empty($cols)) {
  7145. Db::execute(
  7146. "ALTER TABLE `purchase_order` ADD COLUMN `czlyq` varchar(64) NOT NULL DEFAULT '' COMMENT '类型' AFTER `CDW`"
  7147. );
  7148. }
  7149. } catch (\Throwable $e) {
  7150. // ignore
  7151. }
  7152. }
  7153. /**
  7154. * 确保 purchase_order.delivery_deadline 存在
  7155. */
  7156. protected function ensurePurchaseOrderDeliveryDeadlineColumn(): void
  7157. {
  7158. static $done = false;
  7159. if ($done) {
  7160. return;
  7161. }
  7162. $done = true;
  7163. try {
  7164. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'delivery_deadline'");
  7165. if (empty($cols)) {
  7166. Db::execute(
  7167. "ALTER TABLE `purchase_order` ADD COLUMN `delivery_deadline` date DEFAULT NULL COMMENT '交货截止日期' AFTER `sys_rq`"
  7168. );
  7169. }
  7170. } catch (\Throwable $e) {
  7171. // ignore
  7172. }
  7173. }
  7174. /**
  7175. * 确保 purchase_order.score_rule_id 及下发时规则权重快照字段存在
  7176. */
  7177. protected function ensurePurchaseOrderScoreRuleIdColumn(): void
  7178. {
  7179. static $done = false;
  7180. if ($done) {
  7181. return;
  7182. }
  7183. $done = true;
  7184. // 不用 AFTER:delivery_deadline 等列可能不存在会导致整句 ALTER 失败
  7185. $adds = [
  7186. 'score_rule_id' => "ADD COLUMN `score_rule_id` int unsigned NOT NULL DEFAULT 0 COMMENT '评分规则ID(订单类型)'",
  7187. 'score_rule_name' => "ADD COLUMN `score_rule_name` varchar(100) NOT NULL DEFAULT '' COMMENT '下发时订单类型名称快照'",
  7188. 'score_quality_weight' => "ADD COLUMN `score_quality_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时质量权重快照%'",
  7189. 'score_price_weight' => "ADD COLUMN `score_price_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时价格权重快照%'",
  7190. 'score_lead_weight' => "ADD COLUMN `score_lead_weight` int unsigned NOT NULL DEFAULT 0 COMMENT '下发时交货权重快照%'",
  7191. ];
  7192. $changed = false;
  7193. foreach ($adds as $col => $ddl) {
  7194. try {
  7195. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE '{$col}'");
  7196. if (!is_array($cols) || $cols === []) {
  7197. Db::execute("ALTER TABLE `purchase_order` {$ddl}");
  7198. $changed = true;
  7199. }
  7200. } catch (\Throwable $e) {
  7201. Log::write('purchase_order.' . $col . ': ' . $e->getMessage(), 'error');
  7202. }
  7203. }
  7204. if ($changed) {
  7205. $this->clearPurchaseOrderTableFieldsCache();
  7206. }
  7207. }
  7208. /**
  7209. * ALTER 后清 ThinkPHP 表字段缓存,避免 fields not exists:[score_rule_id]
  7210. */
  7211. protected function clearPurchaseOrderTableFieldsCache(): void
  7212. {
  7213. try {
  7214. $db = (string)Config::get('database.database');
  7215. $key = $db . '.purchase_order';
  7216. $ref = new \ReflectionProperty(\think\db\Query::class, 'info');
  7217. $ref->setAccessible(true);
  7218. $info = $ref->getValue();
  7219. if (is_array($info) && isset($info[$key])) {
  7220. unset($info[$key]);
  7221. $ref->setValue(null, $info);
  7222. }
  7223. } catch (\Throwable $e) {
  7224. }
  7225. try {
  7226. $db = (string)Config::get('database.database');
  7227. $schemaFile = RUNTIME_PATH . 'schema' . DIRECTORY_SEPARATOR . $db . '.purchase_order.php';
  7228. if (is_file($schemaFile)) {
  7229. @unlink($schemaFile);
  7230. }
  7231. } catch (\Throwable $e) {
  7232. }
  7233. }
  7234. /**
  7235. * @return array<string, bool>
  7236. */
  7237. protected function loadPurchaseOrderColumnSet(): array
  7238. {
  7239. static $set = null;
  7240. if (is_array($set)) {
  7241. return $set;
  7242. }
  7243. $set = [];
  7244. try {
  7245. $cols = Db::query('SHOW COLUMNS FROM `purchase_order`');
  7246. } catch (\Throwable $e) {
  7247. return $set;
  7248. }
  7249. if (!is_array($cols)) {
  7250. return $set;
  7251. }
  7252. foreach ($cols as $c) {
  7253. if (!is_array($c)) {
  7254. continue;
  7255. }
  7256. $f = (string)($c['Field'] ?? $c['field'] ?? '');
  7257. if ($f !== '') {
  7258. $set[$f] = true;
  7259. }
  7260. }
  7261. return $set;
  7262. }
  7263. /**
  7264. * 解析交货截止日期(仅年月日)
  7265. */
  7266. protected function parseProcuremenDeliveryDeadlineInput(string $raw, bool $required = true): string
  7267. {
  7268. $raw = trim($raw);
  7269. if ($raw === '') {
  7270. if ($required) {
  7271. $this->error('请选择交货截止日期');
  7272. }
  7273. return '';
  7274. }
  7275. if (preg_match('/^(\d{4})[\/.\-](\d{1,2})[\/.\-](\d{1,2})/', $raw, $m)) {
  7276. $ymd = sprintf('%04d-%02d-%02d', (int)$m[1], (int)$m[2], (int)$m[3]);
  7277. } else {
  7278. $ts = strtotime(str_replace('/', '-', $raw));
  7279. if ($ts === false || $ts <= 0) {
  7280. $this->error('交货截止日期格式无效');
  7281. }
  7282. $ymd = date('Y-m-d', $ts);
  7283. }
  7284. if ($ymd < date('Y-m-d')) {
  7285. $this->error('交货截止日期不能早于今天');
  7286. }
  7287. return $ymd;
  7288. }
  7289. protected function formatProcuremenDeliveryDeadlineForInput($value): string
  7290. {
  7291. $s = trim((string)$value);
  7292. if ($s === '' || stripos($s, '0000-00-00') === 0) {
  7293. return '';
  7294. }
  7295. if (preg_match('/^(\d{4}-\d{2}-\d{2})/', $s, $m)) {
  7296. return $m[1];
  7297. }
  7298. $ts = strtotime(str_replace('/', '-', $s));
  7299. return ($ts !== false && $ts > 0) ? date('Y-m-d', $ts) : '';
  7300. }
  7301. /**
  7302. * @param array{pos?:array} $bundle
  7303. */
  7304. protected function resolveBundleDeliveryDeadline(array $bundle): string
  7305. {
  7306. foreach ($bundle['pos'] ?? [] as $po) {
  7307. if (!is_array($po)) {
  7308. continue;
  7309. }
  7310. $d = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  7311. if ($d !== '') {
  7312. return $d;
  7313. }
  7314. }
  7315. return '';
  7316. }
  7317. protected function formatProcuremenSysRqForInput($sysRq): string
  7318. {
  7319. $sr = trim((string)$sysRq);
  7320. if ($sr === '' || stripos($sr, '0000-00-00') === 0) {
  7321. return '';
  7322. }
  7323. $ts = strtotime($sr);
  7324. return ($ts !== false && $ts > 0) ? date('Y-m-d H:i:s', $ts) : $sr;
  7325. }
  7326. protected function formatProcuremenSysRqForDisplay($sysRq): string
  7327. {
  7328. $sr = $this->formatProcuremenSysRqForInput($sysRq);
  7329. if ($sr === '') {
  7330. return '—';
  7331. }
  7332. $ts = strtotime($sr);
  7333. return ($ts !== false && $ts > 0) ? date('Y/m/d H:i', $ts) : $sr;
  7334. }
  7335. /**
  7336. * 确认页截止时间已只读:不再根据 POST 覆盖写库,仅沿用订单已有截止时间
  7337. *
  7338. * @param array{ccydh?:string,pos:array,merge_rows:array} $bundle
  7339. * @return array{ccydh?:string,pos:array,merge_rows:array}
  7340. */
  7341. protected function applyAuditSysRqPostToBundle(array $bundle, string $sysRqPost): array
  7342. {
  7343. return $bundle;
  7344. }
  7345. /**
  7346. * 写入/更新 purchase_order(单道工序行)
  7347. *
  7348. * @param array{id?:int,name?:string,quality_weight?:int,price_weight?:int,lead_weight?:int}|null $scoreRule 下发时订单类型快照
  7349. */
  7350. protected function upsertPurchaseOrderFromRow(
  7351. array $row,
  7352. string $sysRqDb,
  7353. $wflowStatus = null,
  7354. ?string $pickTime = null,
  7355. ?array $exists = null,
  7356. ?string $deliveryDeadline = null,
  7357. $scoreRuleId = null
  7358. ): void {
  7359. $ids = $this->extractScydgyRowId($row);
  7360. if (!$this->isValidScydgyRowId($ids)) {
  7361. throw new \Exception($this->formatProcuremenRowLabel($row) . '数据不完整,请关闭弹窗后重新勾选再试');
  7362. }
  7363. if ($exists === null) {
  7364. $exists = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  7365. }
  7366. $this->ensurePurchaseOrderDeliveryDeadlineColumn();
  7367. $this->ensurePurchaseOrderScoreRuleIdColumn();
  7368. $this->ensurePurchaseOrderCzlyqColumn();
  7369. $data = [
  7370. 'scydgy_id' => $ids,
  7371. 'CCYDH' => $row['CCYDH'] ?? null,
  7372. 'CYJMC' => $row['CYJMC'] ?? null,
  7373. 'CCLBMMC' => $row['CCLBMMC'] ?? null,
  7374. 'CDXMC' => $row['CDXMC'] ?? null,
  7375. 'CGYBH' => $row['CGYBH'] ?? null,
  7376. 'CGYMC' => $row['CGYMC'] ?? null,
  7377. 'CDW' => $row['CDW'] ?? null,
  7378. 'czlyq' => $row['czlyq'] ?? null,
  7379. 'NGZL' => $row['NGZL'] ?? null,
  7380. 'CDF' => $row['CDF'] ?? null,
  7381. 'cGzzxMc' => $row['cGzzxMc'] ?? null,
  7382. 'MBZ' => $row['MBZ'] ?? null,
  7383. 'bwjg' => $row['bwjg'] ?? null,
  7384. 'iStatus' => $row['iStatus'] ?? null,
  7385. 'dStamp' => $row['dStamp'] ?? null,
  7386. 'dputrecord' => $row['dputrecord'] ?? null,
  7387. 'cywyxm' => $row['cywyxm'] ?? null,
  7388. 'This_quantity' => $row['This_quantity'] ?? $row['this_quantity'] ?? null,
  7389. 'ceilingPrice' => $row['ceilingPrice'] ?? $row['ceiling_price'] ?? null,
  7390. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  7391. 'sys_rq' => $sysRqDb,
  7392. ];
  7393. // 下发未填本次数量时,用工作量落库,确认/审批列表可直接展示
  7394. $qtyUp = trim((string)($data['This_quantity'] ?? ''));
  7395. if ($qtyUp === '') {
  7396. $qtyFallback = $this->resolveProcuremenThisQuantity([
  7397. 'This_quantity' => '',
  7398. 'NGZL' => $data['NGZL'] ?? ($row['NGZL'] ?? ''),
  7399. ]);
  7400. if ($qtyFallback !== '') {
  7401. $data['This_quantity'] = $qtyFallback;
  7402. }
  7403. }
  7404. if ($deliveryDeadline !== null) {
  7405. $data['delivery_deadline'] = $deliveryDeadline !== '' ? $deliveryDeadline : null;
  7406. }
  7407. // 兼容:旧调用传 int 规则ID;新调用传完整规则数组(含权重快照)
  7408. $scoreRule = null;
  7409. if (is_array($scoreRuleId)) {
  7410. $scoreRule = $scoreRuleId;
  7411. $scoreRuleId = (int)($scoreRule['id'] ?? 0);
  7412. } else {
  7413. $scoreRuleId = $scoreRuleId !== null ? (int)$scoreRuleId : null;
  7414. }
  7415. if ($scoreRuleId !== null && $scoreRuleId > 0) {
  7416. $poCols = $this->loadPurchaseOrderColumnSet();
  7417. if (!empty($poCols['score_rule_id'])) {
  7418. $data['score_rule_id'] = $scoreRuleId;
  7419. if (is_array($scoreRule)) {
  7420. if (!empty($poCols['score_rule_name'])) {
  7421. $data['score_rule_name'] = trim((string)($scoreRule['name'] ?? ''));
  7422. }
  7423. if (!empty($poCols['score_quality_weight'])) {
  7424. $data['score_quality_weight'] = max(0, (int)($scoreRule['quality_weight'] ?? 0));
  7425. }
  7426. if (!empty($poCols['score_price_weight'])) {
  7427. $data['score_price_weight'] = max(0, (int)($scoreRule['price_weight'] ?? 0));
  7428. }
  7429. if (!empty($poCols['score_lead_weight'])) {
  7430. $data['score_lead_weight'] = max(0, (int)($scoreRule['lead_weight'] ?? 0));
  7431. }
  7432. }
  7433. }
  7434. }
  7435. if ($wflowStatus !== null && $wflowStatus !== '') {
  7436. $data['wflow_status'] = ProcuremenStatus::normalizeWflowStatus($wflowStatus);
  7437. }
  7438. if ($pickTime !== null && $pickTime !== '') {
  7439. $data['pick_time'] = $pickTime;
  7440. $data['pick_company_name'] = '';
  7441. }
  7442. if ($exists) {
  7443. $upd = $data;
  7444. unset($upd['scydgy_id']);
  7445. Db::table('purchase_order')->where('scydgy_id', $ids)->update($upd);
  7446. } else {
  7447. $data['createtime'] = date('Y-m-d H:i:s');
  7448. Db::table('purchase_order')->insert($data);
  7449. }
  7450. }
  7451. /**
  7452. * 协助下发 — 仅写入 purchase_order_detail(第一步不发通知)
  7453. *
  7454. * @return array<int, array{detail_id:int, cgymc:string, url:string}>
  7455. */
  7456. protected function issuePersistSupplierDetails(array $c, array $mergeRows, bool $buildMobileLinks = true, bool $skipExisting = false, bool $requirePhone = true): array
  7457. {
  7458. $toDb = function ($value) {
  7459. if ($value === null) {
  7460. return null;
  7461. }
  7462. if (is_scalar($value)) {
  7463. return $value;
  7464. }
  7465. return json_encode($value, JSON_UNESCAPED_UNICODE);
  7466. };
  7467. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7468. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7469. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7470. $username = isset($c['username']) ? trim((string)$c['username']) : '';
  7471. if ($username === '') {
  7472. $username = $this->resolveCustomerContactName($phone, $companyName);
  7473. }
  7474. if ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
  7475. throw new \Exception($companyName . ' 未填写有效邮箱,无法保存下发记录');
  7476. }
  7477. if ($requirePhone && $phone === '') {
  7478. throw new \Exception(($companyName !== '' ? $companyName : '外协单位') . ' 未填写手机号,无法保存下发记录');
  7479. }
  7480. $detailLinks = [];
  7481. foreach ($mergeRows as $row) {
  7482. if (!is_array($row)) {
  7483. continue;
  7484. }
  7485. $sid = $this->extractScydgyRowId($row);
  7486. $detailId = 0;
  7487. if ($skipExisting) {
  7488. try {
  7489. $existsQuery = Db::table('purchase_order_detail')
  7490. ->where('scydgy_id', $sid)
  7491. ->where('company_name', $companyName);
  7492. $this->applyActivePurchaseOrderDetailWhere($existsQuery);
  7493. $exists = $existsQuery->find();
  7494. } catch (\Throwable $e) {
  7495. $exists = null;
  7496. }
  7497. if (is_array($exists)) {
  7498. $detailId = (int)($exists['id'] ?? $exists['ID'] ?? 0);
  7499. }
  7500. }
  7501. if ($detailId <= 0) {
  7502. $one = [
  7503. 'scydgy_id' => $toDb($sid),
  7504. 'CCYDH' => $toDb($row['CCYDH'] ?? null),
  7505. 'CYJMC' => $toDb($row['CYJMC'] ?? null),
  7506. 'company_name' => isset($c['name']) ? (string)$c['name'] : null,
  7507. 'username' => $username !== '' ? $username : null,
  7508. 'email' => isset($c['email']) ? (string)$c['email'] : null,
  7509. 'phone' => isset($c['phone']) ? (string)$c['phone'] : null,
  7510. 'createtime' => date('Y-m-d H:i:s'),
  7511. 'status' => ProcuremenStatus::POD_UNPICKED,
  7512. 'status_name' => '未提交',
  7513. ];
  7514. Db::table('purchase_order_detail')->insert($one);
  7515. $detailId = (int)Db::getLastInsID();
  7516. }
  7517. $mprocUrl = '';
  7518. if ($buildMobileLinks && $detailId > 0) {
  7519. $mprocUrl = $this->buildMprocMobileOrderUrl($detailId);
  7520. }
  7521. $detailLinks[] = [
  7522. 'detail_id' => $detailId,
  7523. 'cgymc' => trim((string)($row['CGYMC'] ?? '')),
  7524. 'url' => $mprocUrl,
  7525. ];
  7526. }
  7527. $this->invalidatePickHiddenScydgyCache();
  7528. return $detailLinks;
  7529. }
  7530. /**
  7531. * @param array<int, array{detail_id:int, cgymc:string, url:string}> $detailLinks
  7532. * @return array<string, mixed>
  7533. */
  7534. protected function composeSupplierNotifyBundle(array $c, array $ctx, array $detailLinks, string $emailTplScene = 'review_email'): array
  7535. {
  7536. $toEmail = isset($c['email']) ? trim((string)$c['email']) : '';
  7537. $companyName = isset($c['name']) ? trim((string)$c['name']) : '外协单位';
  7538. $phone = isset($c['phone']) ? trim((string)$c['phone']) : '';
  7539. $platformUrl = isset($detailLinks[0]['url']) ? trim((string)$detailLinks[0]['url']) : '';
  7540. $platformLinksPlain = $this->buildPlatformLinksPlain($detailLinks);
  7541. $platformLinksHtml = $this->buildPlatformLinksHtml($detailLinks);
  7542. $isMerge = !empty($ctx['is_merge']);
  7543. $contactName = trim((string)($c['username'] ?? ''));
  7544. if ($contactName === '') {
  7545. $contactName = $this->resolveCustomerContactName($phone, $companyName);
  7546. }
  7547. $notifyVars = [
  7548. 'company_name' => $companyName,
  7549. 'contact_name' => $contactName,
  7550. 'phone' => $phone,
  7551. 'email' => $toEmail,
  7552. 'ccydh' => (string)($ctx['ccydh'] ?? ''),
  7553. 'cyjmc' => (string)($ctx['cyjmc'] ?? ''),
  7554. 'cgymc' => $isMerge ? '' : (string)($ctx['cgymc_single'] ?? ''),
  7555. 'category' => trim((string)($c['category'] ?? $c['company_type'] ?? '')),
  7556. 'deadline' => (string)($ctx['deadline'] ?? ''),
  7557. 'process_lines' => (string)($ctx['process_plain'] ?? ''),
  7558. 'process_lines_html' => (string)($ctx['process_html'] ?? ''),
  7559. 'order_type' => (string)($ctx['order_type'] ?? ''),
  7560. 'score_weights' => (string)($ctx['score_weights'] ?? ''),
  7561. 'platform_url' => $platformUrl,
  7562. 'platform_links' => $platformLinksPlain,
  7563. 'platform_links_html' => $platformLinksHtml,
  7564. ];
  7565. $smsContent = $this->renderNotifyTemplate('review_sms', $notifyVars);
  7566. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  7567. $mailPlain = $this->renderNotifyTemplate($emailTplScene, $notifyVars);
  7568. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  7569. return [
  7570. 'company_name' => $companyName,
  7571. 'phone' => $phone,
  7572. 'email' => $toEmail,
  7573. 'sms_content' => $smsContent,
  7574. 'mail_plain' => $mailPlain,
  7575. 'mail_body' => $mailBody,
  7576. 'notify_vars' => $notifyVars,
  7577. 'detail_links' => $detailLinks,
  7578. ];
  7579. }
  7580. /**
  7581. * @param array<string, mixed> $chosen
  7582. * @param array<int, array<string, mixed>> $mergeRows
  7583. * @param array{ccydh:string, pos:array} $bundle
  7584. */
  7585. protected function sendAuditSupplierNotifyChannels(array $chosen, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $emailLogScene = 'pick_issue', string $emailTplScene = 'review_email'): void
  7586. {
  7587. if (!$sendSms && !$sendEmail) {
  7588. return;
  7589. }
  7590. $companyName = trim((string)($chosen['name'] ?? ''));
  7591. $phone = trim((string)($chosen['phone'] ?? ''));
  7592. $toEmail = trim((string)($chosen['email'] ?? ''));
  7593. if ($companyName === '') {
  7594. throw new \Exception('供应商名称无效');
  7595. }
  7596. if ($sendEmail && ($toEmail === '' || !filter_var($toEmail, FILTER_VALIDATE_EMAIL))) {
  7597. throw new \Exception($companyName . ' 未填写有效邮箱,无法发送邮件');
  7598. }
  7599. if ($sendSms && $phone === '') {
  7600. throw new \Exception($companyName . ' 未填写手机号,无法发送短信');
  7601. }
  7602. $sids = [];
  7603. foreach ($mergeRows as $mr) {
  7604. if (!is_array($mr)) {
  7605. continue;
  7606. }
  7607. $sid = $this->extractScydgyRowId($mr);
  7608. if ($this->isValidScydgyRowId($sid)) {
  7609. $sids[$sid] = true;
  7610. }
  7611. }
  7612. if ($sids === []) {
  7613. throw new \Exception('未找到工序行,无法发送通知');
  7614. }
  7615. $sysRqNotify = '';
  7616. $pos = $bundle['pos'] ?? [];
  7617. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7618. $sr = trim((string)($pos[0]['sys_rq'] ?? ''));
  7619. if ($sr !== '' && stripos($sr, '0000-00-00') !== 0) {
  7620. $ts = strtotime($sr);
  7621. $sysRqNotify = ($ts !== false && $ts > 0) ? date('Y-m-d H:i', $ts) : $sr;
  7622. }
  7623. }
  7624. try {
  7625. $detailsQuery = Db::table('purchase_order_detail')
  7626. ->where('scydgy_id', 'in', array_keys($sids))
  7627. ->where('company_name', $companyName);
  7628. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7629. $details = $detailsQuery->order('id', 'asc')->select();
  7630. } catch (\Throwable $e) {
  7631. $details = [];
  7632. }
  7633. if (!is_array($details) || $details === []) {
  7634. $this->issuePersistSupplierDetails($chosen, $mergeRows, true, true);
  7635. try {
  7636. $detailsQuery = Db::table('purchase_order_detail')
  7637. ->where('scydgy_id', 'in', array_keys($sids))
  7638. ->where('company_name', $companyName);
  7639. $this->applyActivePurchaseOrderDetailWhere($detailsQuery);
  7640. $details = $detailsQuery->order('id', 'asc')->select();
  7641. } catch (\Throwable $e) {
  7642. $details = [];
  7643. }
  7644. }
  7645. if (!is_array($details) || $details === []) {
  7646. throw new \Exception('未能生成该供应商的下发明细,无法发送通知');
  7647. }
  7648. $detailLinks = [];
  7649. foreach ($details as $d) {
  7650. if (!is_array($d)) {
  7651. continue;
  7652. }
  7653. $detailId = (int)($d['id'] ?? $d['ID'] ?? 0);
  7654. if ($detailId <= 0) {
  7655. continue;
  7656. }
  7657. $sid = (int)($d['scydgy_id'] ?? 0);
  7658. $gymc = '';
  7659. foreach ($mergeRows as $mr) {
  7660. if (is_array($mr) && $this->extractScydgyRowId($mr) === $sid) {
  7661. $gymc = trim((string)($mr['CGYMC'] ?? ''));
  7662. break;
  7663. }
  7664. }
  7665. $detailLinks[] = [
  7666. 'detail_id' => $detailId,
  7667. 'cgymc' => $gymc,
  7668. 'url' => $this->buildMprocMobileOrderUrl($detailId),
  7669. ];
  7670. }
  7671. if ($detailLinks === []) {
  7672. throw new \Exception('未找到有效的手机端链接,无法发送通知');
  7673. }
  7674. $emailTplScene = trim($emailTplScene) !== '' ? trim($emailTplScene) : 'review_email';
  7675. $ctx = $this->buildIssueNotifyContext($mergeRows, $sysRqNotify);
  7676. $orderTypeCtx = $this->resolveIssueNotifyOrderTypeFromBundle($bundle);
  7677. $ctx['order_type'] = (string)($orderTypeCtx['order_type'] ?? '');
  7678. $ctx['score_weights'] = (string)($orderTypeCtx['score_weights'] ?? '');
  7679. $notifyBundle = $this->composeSupplierNotifyBundle($chosen, $ctx, $detailLinks, $emailTplScene);
  7680. $notifyBundle['email_log_scene'] = $emailLogScene;
  7681. $notifyBundle['email_log_scydgy_id'] = (int)array_key_first($sids);
  7682. $poIdLog = 0;
  7683. $pos = $bundle['pos'] ?? [];
  7684. if (is_array($pos) && isset($pos[0]) && is_array($pos[0])) {
  7685. $poIdLog = (int)($pos[0]['id'] ?? 0);
  7686. }
  7687. $notifyBundle['email_log_purchase_order_id'] = $poIdLog;
  7688. if ($sendEmail) {
  7689. $mailTplRow = $this->loadNotifyTemplateRow($emailTplScene);
  7690. if ($mailTplRow === null || trim((string)($mailTplRow['content'] ?? '')) === '') {
  7691. throw new \Exception($this->notifyTemplateMissingMessage($emailTplScene));
  7692. }
  7693. $mailSubject = $this->resolveProcuremenEmailSubject($emailTplScene);
  7694. $mailConfig = $this->loadMailerConfig();
  7695. if (!$this->isProcuremenNotifyDryRun()) {
  7696. if (empty($mailConfig['host'])) {
  7697. throw new \Exception('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  7698. }
  7699. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  7700. throw new \Exception('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  7701. }
  7702. }
  7703. $this->issueSendSupplierEmail($notifyBundle, $mailConfig, $mailSubject);
  7704. }
  7705. if ($sendSms) {
  7706. $this->issueSendSupplierSms($notifyBundle);
  7707. }
  7708. }
  7709. /**
  7710. * @param array<int, array<string, mixed>> $quoteGroups
  7711. * @return array<int, array<string, mixed>>
  7712. */
  7713. protected function resolveAuditResendTargets(array $quoteGroups, string $selectedCompany = '', $companiesJson = ''): array
  7714. {
  7715. $names = [];
  7716. if (is_string($companiesJson) && $companiesJson !== '') {
  7717. $decoded = json_decode($companiesJson, true);
  7718. if (is_array($decoded)) {
  7719. foreach ($decoded as $nm) {
  7720. $nm = trim((string)$nm);
  7721. if ($nm !== '') {
  7722. $names[] = $nm;
  7723. }
  7724. }
  7725. }
  7726. }
  7727. $names = array_values(array_unique($names));
  7728. if ($names === [] && $selectedCompany !== '') {
  7729. $names = [$selectedCompany];
  7730. }
  7731. if ($names === []) {
  7732. return $quoteGroups;
  7733. }
  7734. $targets = [];
  7735. foreach ($quoteGroups as $g) {
  7736. if (!is_array($g)) {
  7737. continue;
  7738. }
  7739. $cn = trim((string)($g['name'] ?? ''));
  7740. if ($cn !== '' && in_array($cn, $names, true)) {
  7741. $targets[] = $g;
  7742. }
  7743. }
  7744. return $targets;
  7745. }
  7746. /**
  7747. * @return array{pos:array, merge_rows:array, bundle:array}
  7748. */
  7749. protected function loadAuditResendBundle(string $scydgyId): array
  7750. {
  7751. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  7752. $pos = $bundle['pos'];
  7753. $mergeRows = $bundle['merge_rows'];
  7754. if ($pos === [] || $mergeRows === []) {
  7755. $this->error('该订单不在待确认供应商状态');
  7756. }
  7757. $sysRqDb = '';
  7758. if (isset($pos[0]) && is_array($pos[0])) {
  7759. $sysRqDb = trim((string)($pos[0]['sys_rq'] ?? ''));
  7760. }
  7761. foreach ($pos as $i => $poRow) {
  7762. if (is_array($pos[$i]) && $sysRqDb !== '') {
  7763. $pos[$i]['sys_rq'] = $sysRqDb;
  7764. }
  7765. }
  7766. $bundle['pos'] = $pos;
  7767. return ['pos' => $pos, 'merge_rows' => $mergeRows, 'bundle' => $bundle];
  7768. }
  7769. /**
  7770. * @param array<int, array<string, mixed>> $targets
  7771. */
  7772. protected function auditResendNotifyToTargets(array $targets, array $mergeRows, array $bundle, bool $sendSms, bool $sendEmail, string $successVerb): void
  7773. {
  7774. if ($targets === []) {
  7775. $this->error('未找到可通知的供应商');
  7776. }
  7777. $notifyErrors = [];
  7778. try {
  7779. $this->notifyDryRunPreview = [];
  7780. foreach ($targets as $g) {
  7781. if (!is_array($g)) {
  7782. continue;
  7783. }
  7784. $cname = trim((string)($g['name'] ?? ''));
  7785. if ($cname === '') {
  7786. continue;
  7787. }
  7788. $chosen = [
  7789. 'name' => $cname,
  7790. 'company_name' => $cname,
  7791. 'email' => trim((string)($g['email'] ?? '')),
  7792. 'phone' => trim((string)($g['phone'] ?? '')),
  7793. 'username' => trim((string)($g['username'] ?? '')),
  7794. ];
  7795. try {
  7796. $this->sendAuditSupplierNotifyChannels($chosen, $mergeRows, $bundle, $sendSms, $sendEmail, 'audit_resend');
  7797. } catch (\Throwable $e) {
  7798. $notifyErrors[] = $cname . ':' . $e->getMessage();
  7799. }
  7800. }
  7801. } catch (\Throwable $e) {
  7802. $this->error('通知发送失败:' . $e->getMessage());
  7803. }
  7804. if ($notifyErrors !== []) {
  7805. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  7806. }
  7807. if ($this->isProcuremenNotifyDryRun()) {
  7808. $this->success('【演练模式】已生成二次' . $successVerb . '预览', '', [
  7809. 'notify_dry_run' => true,
  7810. 'notify_preview' => $this->notifyDryRunPreview,
  7811. ]);
  7812. }
  7813. $nameLabels = [];
  7814. foreach ($targets as $g) {
  7815. if (!is_array($g)) {
  7816. continue;
  7817. }
  7818. $n = trim((string)($g['name'] ?? ''));
  7819. if ($n !== '') {
  7820. $nameLabels[] = $n;
  7821. }
  7822. }
  7823. $logAction = $sendSms ? 'audit_resend_sms' : 'audit_resend_email';
  7824. $logMsg = '确认页重新发送' . $successVerb . '(' . count($nameLabels) . ' 家)'
  7825. . ($nameLabels !== [] ? (':' . implode('、', $nameLabels)) : '');
  7826. $seenLogSid = [];
  7827. foreach ($bundle['pos'] ?? [] as $poRow) {
  7828. if (!is_array($poRow)) {
  7829. continue;
  7830. }
  7831. $sid = (int)($poRow['scydgy_id'] ?? 0);
  7832. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  7833. continue;
  7834. }
  7835. $seenLogSid[$sid] = true;
  7836. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  7837. $this->addOrderLog($sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  7838. }
  7839. if ($seenLogSid === []) {
  7840. foreach ($mergeRows as $mr) {
  7841. if (!is_array($mr)) {
  7842. continue;
  7843. }
  7844. $sid = $this->extractScydgyRowId($mr);
  7845. if ($this->isValidScydgyRowId($sid)) {
  7846. $this->addOrderLog($sid, $logAction, $logMsg, null);
  7847. break;
  7848. }
  7849. }
  7850. }
  7851. $this->success('已向 ' . count($targets) . ' 家供应商重新发送' . $successVerb);
  7852. }
  7853. /**
  7854. * 协助下发 — 发送短信(一家供应商)
  7855. *
  7856. * @param array<string, mixed> $bundle composeSupplierNotifyBundle 返回值
  7857. */
  7858. protected function issueSendSupplierSms(array $bundle): void
  7859. {
  7860. $companyName = (string)($bundle['company_name'] ?? '');
  7861. $phone = (string)($bundle['phone'] ?? '');
  7862. $smsContent = (string)($bundle['sms_content'] ?? '');
  7863. $this->logIssueNotifyDebug('短信', [
  7864. 'company' => $companyName,
  7865. 'phone' => $phone,
  7866. 'sms_content' => $smsContent,
  7867. ]);
  7868. if ($this->isProcuremenNotifyDryRun()) {
  7869. $this->recordNotifyDryRunPreview([
  7870. 'scene' => 'issue_sms',
  7871. 'company_name' => $companyName,
  7872. 'phone' => $phone,
  7873. 'sms_content' => $smsContent,
  7874. ]);
  7875. return;
  7876. }
  7877. $this->smsbao($phone, $smsContent);
  7878. }
  7879. /**
  7880. * 协助下发 — 发送邮件(一家供应商)
  7881. *
  7882. * @param array<string, mixed> $bundle
  7883. * @param array<string, mixed> $mailConfig
  7884. */
  7885. protected function issueSendSupplierEmail(array $bundle, array $mailConfig, string $mailSubject): void
  7886. {
  7887. $companyName = (string)($bundle['company_name'] ?? '');
  7888. $toEmail = (string)($bundle['email'] ?? '');
  7889. $mailPlain = (string)($bundle['mail_plain'] ?? '');
  7890. $mailBody = (string)($bundle['mail_body'] ?? '');
  7891. $this->logIssueNotifyDebug('邮件', [
  7892. 'company' => $companyName,
  7893. 'email' => $toEmail,
  7894. 'mail_subject' => $mailSubject,
  7895. 'mail_body' => $mailPlain,
  7896. ]);
  7897. if ($this->isProcuremenNotifyDryRun()) {
  7898. $this->recordNotifyDryRunPreview([
  7899. 'scene' => 'issue_email',
  7900. 'company_name' => $companyName,
  7901. 'email' => $toEmail,
  7902. 'mail_subject' => $mailSubject,
  7903. 'mail_body' => $mailPlain,
  7904. 'sms_content' => (string)($bundle['sms_content'] ?? ''),
  7905. 'notify_vars' => $bundle['notify_vars'] ?? [],
  7906. 'detail_links' => $bundle['detail_links'] ?? [],
  7907. ]);
  7908. return;
  7909. }
  7910. $mail = new PHPMailer(true);
  7911. $mail->isSMTP();
  7912. $mail->Host = $mailConfig['host'];
  7913. $mail->SMTPAuth = true;
  7914. $mail->Username = $mailConfig['addr'];
  7915. $mail->Password = $mailConfig['pass'];
  7916. $mail->SMTPSecure = $mailConfig['security'];
  7917. $mail->Port = $mailConfig['port'];
  7918. $mail->CharSet = $mailConfig['charset'];
  7919. $mail->setFrom($mailConfig['addr'], $mailConfig['name']);
  7920. $mail->addAddress($toEmail, $companyName);
  7921. $mail->isHTML(true);
  7922. $mail->Subject = $mailSubject;
  7923. $mail->Body = $mailBody;
  7924. $fromEmail = trim((string)($mailConfig['addr'] ?? ''));
  7925. $sendOk = true;
  7926. $failReason = '';
  7927. try {
  7928. $mail->send();
  7929. } catch (\Throwable $e) {
  7930. $sendOk = false;
  7931. $failReason = $e->getMessage();
  7932. $this->persistEmailSendLog([
  7933. 'from_email' => $fromEmail,
  7934. 'to_email' => $toEmail,
  7935. 'send_time' => date('Y-m-d H:i:s'),
  7936. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7937. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7938. 'company_name' => $companyName,
  7939. 'mail_subject' => $mailSubject,
  7940. 'status' => 0,
  7941. 'fail_reason' => $failReason,
  7942. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7943. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7944. ]);
  7945. throw $e;
  7946. }
  7947. $this->persistEmailSendLog([
  7948. 'from_email' => $fromEmail,
  7949. 'to_email' => $toEmail,
  7950. 'send_time' => date('Y-m-d H:i:s'),
  7951. 'scene' => (string)($bundle['email_log_scene'] ?? 'pick_issue'),
  7952. 'ccydh' => trim((string)(($bundle['notify_vars']['ccydh'] ?? '') ?: ($bundle['ccydh'] ?? ''))),
  7953. 'company_name' => $companyName,
  7954. 'mail_subject' => $mailSubject,
  7955. 'status' => 1,
  7956. 'fail_reason' => '',
  7957. 'scydgy_id' => (int)($bundle['email_log_scydgy_id'] ?? 0),
  7958. 'purchase_order_id' => (int)($bundle['email_log_purchase_order_id'] ?? 0),
  7959. ]);
  7960. }
  7961. /**
  7962. * 下发通知:解析订单类型名称与评分比例文案
  7963. *
  7964. * @param array<string, mixed> $bundle
  7965. * @return array{order_type:string,score_weights:string}
  7966. */
  7967. protected function resolveIssueNotifyOrderTypeFromBundle(array $bundle): array
  7968. {
  7969. $orderType = '';
  7970. $scoreWeights = '';
  7971. $rule = null;
  7972. if (!empty($bundle['score_rule']) && is_array($bundle['score_rule'])) {
  7973. $rule = $bundle['score_rule'];
  7974. }
  7975. $pos = $bundle['pos'] ?? [];
  7976. $po0 = (is_array($pos) && isset($pos[0]) && is_array($pos[0])) ? $pos[0] : null;
  7977. if ($rule === null && is_array($po0)) {
  7978. $ruleId = (int)($po0['score_rule_id'] ?? 0);
  7979. if ($ruleId > 0) {
  7980. try {
  7981. $rule = ProcuremenSupplierScore::getRuleById($ruleId);
  7982. } catch (\Throwable $e) {
  7983. $rule = null;
  7984. }
  7985. }
  7986. if (!is_array($rule) || (int)($rule['id'] ?? 0) <= 0) {
  7987. $qw = (int)($po0['score_quality_weight'] ?? 0);
  7988. $pw = (int)($po0['score_price_weight'] ?? 0);
  7989. $lw = (int)($po0['score_lead_weight'] ?? 0);
  7990. if ($qw > 0 || $pw > 0 || $lw > 0) {
  7991. $rule = [
  7992. 'name' => trim((string)($po0['score_rule_name'] ?? '')),
  7993. 'quality_weight' => $qw,
  7994. 'price_weight' => $pw,
  7995. 'lead_weight' => $lw,
  7996. ];
  7997. }
  7998. }
  7999. }
  8000. if (is_array($rule)) {
  8001. $orderType = trim((string)($rule['name'] ?? ''));
  8002. $scoreWeights = $this->formatScoreRuleWeightsText($rule);
  8003. }
  8004. if ($orderType === '' && is_array($po0)) {
  8005. $orderType = trim((string)($po0['score_rule_name'] ?? ''));
  8006. }
  8007. return [
  8008. 'order_type' => $orderType,
  8009. 'score_weights' => $scoreWeights,
  8010. ];
  8011. }
  8012. /**
  8013. * 评分比例文案:质量30%、价格50%、交货20%
  8014. *
  8015. * @param array{quality_weight?:mixed,price_weight?:mixed,lead_weight?:mixed} $rule
  8016. */
  8017. protected function formatScoreRuleWeightsText(array $rule): string
  8018. {
  8019. $parts = [];
  8020. $qw = max(0, (float)($rule['quality_weight'] ?? 0));
  8021. $pw = max(0, (float)($rule['price_weight'] ?? 0));
  8022. $lw = max(0, (float)($rule['lead_weight'] ?? 0));
  8023. $fmt = static function ($n) {
  8024. $s = rtrim(rtrim(sprintf('%.2F', (float)$n), '0'), '.');
  8025. return $s === '' ? '0' : $s;
  8026. };
  8027. if ($qw > 0) {
  8028. $parts[] = '质量' . $fmt($qw) . '%';
  8029. }
  8030. if ($pw > 0) {
  8031. $parts[] = '价格' . $fmt($pw) . '%';
  8032. }
  8033. if ($lw > 0) {
  8034. $parts[] = '交货' . $fmt($lw) . '%';
  8035. }
  8036. return implode('、', $parts);
  8037. }
  8038. /**
  8039. * 协助下发通知上下文(订单号、工序明细等,供短信/邮件共用)
  8040. *
  8041. * @param array<int, array<string, mixed>> $mergeRows
  8042. * @return array<string, mixed>
  8043. */
  8044. protected function buildIssueNotifyContext(array $mergeRows, string $sysRqNotify): array
  8045. {
  8046. $head = $mergeRows[0] ?? [];
  8047. $isMerge = count($mergeRows) > 1;
  8048. return [
  8049. 'ccydh' => isset($head['CCYDH']) ? (string)$head['CCYDH'] : '',
  8050. 'cyjmc' => isset($head['CYJMC']) ? (string)$head['CYJMC'] : '',
  8051. 'cgymc_single' => trim((string)($head['CGYMC'] ?? '')),
  8052. 'is_merge' => $isMerge,
  8053. 'process_plain' => $this->buildProcessLinesPlain($mergeRows),
  8054. 'process_html' => $this->buildProcessLinesHtml($mergeRows),
  8055. 'deadline' => $sysRqNotify,
  8056. 'order_type' => '',
  8057. 'score_weights' => '',
  8058. ];
  8059. }
  8060. /**
  8061. * 调试:app_debug 或 notify_dry_run 时把短信/邮件内容写入 runtime/log
  8062. *
  8063. * @param array<string, mixed> $data
  8064. */
  8065. protected function logIssueNotifyDebug(string $type, array $data): void
  8066. {
  8067. if (!Config::get('app_debug') && !$this->isProcuremenNotifyDryRun()) {
  8068. return;
  8069. }
  8070. Log::write('[协助下发-' . $type . '] ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  8071. }
  8072. protected function ensurePurchaseEmailSendLogTableOnce(): void
  8073. {
  8074. try {
  8075. Db::query('SELECT 1 FROM `purchase_email_send_log` LIMIT 1');
  8076. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  8077. return;
  8078. } catch (\Throwable $e) {
  8079. }
  8080. $sqlFile = APP_PATH . 'extra' . DS . 'purchase_email_send_log_install.sql';
  8081. if (is_file($sqlFile)) {
  8082. $sql = file_get_contents($sqlFile);
  8083. if (is_string($sql) && $sql !== '') {
  8084. foreach (preg_split('/;\s*[\r\n]+/', $sql) as $stmt) {
  8085. $stmt = trim($stmt);
  8086. if ($stmt === '' || stripos($stmt, 'CREATE TABLE') === false) {
  8087. continue;
  8088. }
  8089. try {
  8090. Db::execute($stmt);
  8091. } catch (\Throwable $ignore) {
  8092. }
  8093. }
  8094. }
  8095. }
  8096. Cache::set(self::EMAIL_SEND_LOG_SCHEMA_CACHE_KEY, 1);
  8097. }
  8098. /**
  8099. * @param array<string, mixed> $row
  8100. */
  8101. protected function persistEmailSendLog(array $row): void
  8102. {
  8103. try {
  8104. $this->ensurePurchaseEmailSendLogTableOnce();
  8105. } catch (\Throwable $e) {
  8106. return;
  8107. }
  8108. list($adminId, $adminName) = $this->GetUseName();
  8109. $cut = function ($s, $max) {
  8110. $s = (string)$s;
  8111. if (function_exists('mb_substr')) {
  8112. return mb_substr($s, 0, $max, 'UTF-8');
  8113. }
  8114. return strlen($s) <= $max ? $s : substr($s, 0, $max);
  8115. };
  8116. $data = [
  8117. 'from_email' => $cut($row['from_email'] ?? '', 128),
  8118. 'to_email' => $cut($row['to_email'] ?? '', 128),
  8119. 'send_time' => $row['send_time'] ?? date('Y-m-d H:i:s'),
  8120. 'scene' => $cut($row['scene'] ?? 'pick_issue', 32),
  8121. 'ccydh' => $cut($row['ccydh'] ?? '', 64),
  8122. 'company_name' => $cut($row['company_name'] ?? '', 128),
  8123. 'mail_subject' => $cut($row['mail_subject'] ?? '', 255),
  8124. 'status' => !empty($row['status']) ? 1 : 0,
  8125. 'fail_reason' => $cut($row['fail_reason'] ?? '', 500),
  8126. 'admin_id' => (int)$adminId,
  8127. 'admin_name' => $cut($adminName, 64),
  8128. 'scydgy_id' => (int)($row['scydgy_id'] ?? 0),
  8129. 'purchase_order_id' => (int)($row['purchase_order_id'] ?? 0),
  8130. 'createtime' => date('Y-m-d H:i:s'),
  8131. ];
  8132. try {
  8133. Db::table('purchase_email_send_log')->insert($data);
  8134. } catch (\Throwable $e) {
  8135. Log::write('persistEmailSendLog: ' . $e->getMessage(), 'error');
  8136. }
  8137. }
  8138. protected function formatEmailLogSceneText(string $scene): string
  8139. {
  8140. $map = [
  8141. 'pick_issue' => '初选下发',
  8142. 'audit_resend' => '确认页重发',
  8143. 'rfq_salesman' => '询价通知业务员',
  8144. 'rfq_supplier' => '供应商询价通知',
  8145. ];
  8146. return $map[$scene] ?? $scene;
  8147. }
  8148. /**
  8149. * 邮件发送日志列表
  8150. */
  8151. public function emailLog()
  8152. {
  8153. $this->relationSearch = false;
  8154. $this->searchFields = 'from_email,to_email,ccydh,company_name,admin_name,mail_subject';
  8155. $this->request->filter(['strip_tags', 'trim']);
  8156. $bakModel = $this->model;
  8157. $this->model = new \app\admin\model\Purchaseemailsendlog;
  8158. if ($this->request->isAjax()) {
  8159. $this->ensurePurchaseEmailSendLogTableOnce();
  8160. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  8161. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  8162. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  8163. $list = $this->model
  8164. ->where($where)
  8165. ->order($sortField, $orderDir)
  8166. ->paginate($limit);
  8167. $rows = [];
  8168. foreach ($list->items() as $item) {
  8169. $row = is_array($item) ? $item : $item->toArray();
  8170. $scene = trim((string)($row['scene'] ?? ''));
  8171. $row['scene_text'] = $this->formatEmailLogSceneText($scene);
  8172. $row['status_text'] = !empty($row['status']) ? '成功' : '失败';
  8173. $row['to_email_masked'] = mask_email((string)($row['to_email'] ?? ''));
  8174. $row['from_email_masked'] = mask_email((string)($row['from_email'] ?? ''));
  8175. $rows[] = $row;
  8176. }
  8177. $this->model = $bakModel;
  8178. return json(['total' => $list->total(), 'rows' => $rows]);
  8179. }
  8180. $this->model = $bakModel;
  8181. return $this->view->fetch('procuremen/emaillog');
  8182. }
  8183. /**
  8184. * 协助下发弹窗(选多家供应商并通知)
  8185. */
  8186. public function pickReview()
  8187. {
  8188. if (!$this->hasProcuremenPerm(['pickreview', 'picksubmit', 'review'])) {
  8189. $this->error(__('You have no permission'));
  8190. }
  8191. if ($this->request->isPost()) {
  8192. $this->error('请使用弹窗内「确认下发」提交');
  8193. }
  8194. $this->view->assign('pickMode', 1);
  8195. $this->view->assign('scoreRuleOptions', ProcuremenSupplierScore::listRulesForSelect());
  8196. return $this->fetchProcuremenDialogLite('procuremen/review', '初选供应商');
  8197. }
  8198. /**
  8199. * 确保 purchase_order.notify_salesman(通知业务员,可多选拼接)存在
  8200. */
  8201. protected function ensurePurchaseOrderNotifySalesmanColumn(): void
  8202. {
  8203. static $done = false;
  8204. if ($done) {
  8205. return;
  8206. }
  8207. $done = true;
  8208. try {
  8209. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'notify_salesman'");
  8210. if (empty($cols)) {
  8211. Db::execute(
  8212. "ALTER TABLE `purchase_order` ADD COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)' AFTER `cywyxm`"
  8213. );
  8214. } else {
  8215. $type = strtolower((string)($cols[0]['Type'] ?? $cols[0]['type'] ?? ''));
  8216. if (preg_match('/varchar\((\d+)\)/', $type, $m) && (int)$m[1] < 255) {
  8217. Db::execute(
  8218. "ALTER TABLE `purchase_order` MODIFY COLUMN `notify_salesman` varchar(255) NOT NULL DEFAULT '' COMMENT '通知业务员(可多选)'"
  8219. );
  8220. }
  8221. }
  8222. } catch (\Throwable $e) {
  8223. // ignore
  8224. }
  8225. }
  8226. /**
  8227. * 确保 purchase_order.rfq_salesman_notified / rfq_salesman_notify_time
  8228. */
  8229. protected function ensurePurchaseOrderRfqSalesmanNotifiedColumn(): void
  8230. {
  8231. static $done = false;
  8232. if ($done) {
  8233. return;
  8234. }
  8235. $done = true;
  8236. try {
  8237. $cols = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notified'");
  8238. if (empty($cols)) {
  8239. Db::execute(
  8240. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notified` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '手工询价已通知业务员0否1是' AFTER `notify_salesman`"
  8241. );
  8242. }
  8243. } catch (\Throwable $e) {
  8244. // ignore
  8245. }
  8246. try {
  8247. $cols2 = Db::query("SHOW COLUMNS FROM `purchase_order` LIKE 'rfq_salesman_notify_time'");
  8248. if (empty($cols2)) {
  8249. Db::execute(
  8250. "ALTER TABLE `purchase_order` ADD COLUMN `rfq_salesman_notify_time` datetime NULL DEFAULT NULL COMMENT '手工询价通知业务员时间' AFTER `rfq_salesman_notified`"
  8251. );
  8252. }
  8253. } catch (\Throwable $e) {
  8254. // ignore
  8255. }
  8256. }
  8257. /**
  8258. * 确保「采购确认通过/未通过」邮箱模版存在(正文同短信,末尾加平台链接)
  8259. */
  8260. protected function ensureConfirmResultEmailTemplates(): void
  8261. {
  8262. static $done = false;
  8263. if ($done) {
  8264. return;
  8265. }
  8266. $done = true;
  8267. $now = date('Y-m-d H:i:s');
  8268. $seeds = [
  8269. 'confirm_ok_email' => [
  8270. 'title' => '采购确认结果:已通过',
  8271. 'content' => "【可集达】您好,{company_name}:\n\n您参与的外发加工订单采购确认结果:已通过。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  8272. 'remark' => '审批通过-中标供应商邮箱通知;模版名称作邮件主题',
  8273. ],
  8274. 'confirm_fail_email' => [
  8275. 'title' => '采购确认结果:未通过',
  8276. 'content' => "【可集达】您好,{company_name}:\n\n您参与的外发加工订单采购确认结果:未通过。\n{process_lines}\n\n请前往平台查看:{platform_url}\n",
  8277. 'remark' => '审批通过-未中标供应商邮箱通知;模版名称作邮件主题',
  8278. ],
  8279. ];
  8280. try {
  8281. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8282. } catch (\Throwable $e) {
  8283. return;
  8284. }
  8285. $colNames = [];
  8286. foreach ($cols as $c) {
  8287. if (!is_array($c)) {
  8288. continue;
  8289. }
  8290. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8291. if ($n !== '') {
  8292. $colNames[$n] = true;
  8293. }
  8294. }
  8295. foreach ($seeds as $scene => $seed) {
  8296. try {
  8297. $row = Db::table('purchase_sms_template')->where('scene', $scene)->find();
  8298. } catch (\Throwable $e) {
  8299. continue;
  8300. }
  8301. if (is_array($row) && $row !== []) {
  8302. continue;
  8303. }
  8304. $data = [
  8305. 'scene' => $scene,
  8306. 'title' => $seed['title'],
  8307. 'content' => $seed['content'],
  8308. 'remark' => $seed['remark'],
  8309. 'status' => 1,
  8310. ];
  8311. if (isset($colNames['updatetime'])) {
  8312. $data['updatetime'] = $now;
  8313. }
  8314. if (isset($colNames['createtime'])) {
  8315. $data['createtime'] = $now;
  8316. }
  8317. try {
  8318. Db::table('purchase_sms_template')->insert($data);
  8319. } catch (\Throwable $e) {
  8320. // ignore
  8321. }
  8322. }
  8323. }
  8324. /**
  8325. * 确保「供应商询价通知」邮箱模版存在(查询询价-询价/发邮件;可在短信模版配置中修改)
  8326. */
  8327. protected function ensureRfqSupplierEmailTemplate(): void
  8328. {
  8329. static $done = false;
  8330. if ($done) {
  8331. return;
  8332. }
  8333. $done = true;
  8334. $content = "您好,{company_name}:\n\n"
  8335. . "您有新的协助采购询价需求,请登录平台查看并处理。\n\n"
  8336. . "需求编号:{ccydh}\n"
  8337. . "印件名称:{cyjmc}\n"
  8338. . "{process_lines}\n\n"
  8339. . "请在 {deadline} 前完成回复。\n\n"
  8340. . "平台链接:{platform_url}\n";
  8341. try {
  8342. $row = Db::table('purchase_sms_template')
  8343. ->where('scene', 'rfq_supplier_email')
  8344. ->find();
  8345. } catch (\Throwable $e) {
  8346. return;
  8347. }
  8348. $now = date('Y-m-d H:i:s');
  8349. if (is_array($row) && $row !== []) {
  8350. return;
  8351. }
  8352. try {
  8353. $data = [
  8354. 'scene' => 'rfq_supplier_email',
  8355. 'title' => '供应商询价通知',
  8356. 'content' => $content,
  8357. 'remark' => '查询询价-询价/发邮件通知供应商;模版名称作邮件主题',
  8358. 'status' => 1,
  8359. ];
  8360. try {
  8361. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8362. } catch (\Throwable $e) {
  8363. $cols = [];
  8364. }
  8365. $colNames = [];
  8366. foreach ($cols as $c) {
  8367. if (!is_array($c)) {
  8368. continue;
  8369. }
  8370. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8371. if ($n !== '') {
  8372. $colNames[$n] = true;
  8373. }
  8374. }
  8375. if (isset($colNames['updatetime'])) {
  8376. $data['updatetime'] = $now;
  8377. }
  8378. if (isset($colNames['createtime'])) {
  8379. $data['createtime'] = $now;
  8380. }
  8381. Db::table('purchase_sms_template')->insert($data);
  8382. } catch (\Throwable $e) {
  8383. // ignore
  8384. }
  8385. }
  8386. /**
  8387. * 确保「询价通知业务员-邮箱」模版存在(可在后台短信模版配置中修改)
  8388. */
  8389. protected function ensureRfqSalesmanEmailTemplate(): void
  8390. {
  8391. static $done = false;
  8392. if ($done) {
  8393. return;
  8394. }
  8395. $done = true;
  8396. $content = "您好,{contact_name}:\n\n"
  8397. . "有新的协助采购询价需求,请知悉。\n"
  8398. . "印件名称:{cyjmc}\n"
  8399. . "工序名称:{cgymc}\n"
  8400. . "本次数量:{this_quantity}\n"
  8401. . "供应商报价:\n{supplier_quotes}\n"
  8402. . "需求发起人:{cywyxm}\n";
  8403. try {
  8404. $row = Db::table('purchase_sms_template')
  8405. ->where('scene', 'rfq_salesman_email')
  8406. ->find();
  8407. } catch (\Throwable $e) {
  8408. return;
  8409. }
  8410. $now = date('Y-m-d H:i:s');
  8411. if (is_array($row) && $row !== []) {
  8412. $old = (string)($row['content'] ?? '');
  8413. // 仍用旧的「供应商:{supplier_name}」或没有报价占位符时,补上单价表格
  8414. $needMigrate = (strpos($old, '{supplier_quotes}') === false)
  8415. || (strpos($old, '供应商:{supplier_name}') !== false);
  8416. if ($needMigrate) {
  8417. $data = ['content' => $content];
  8418. if (trim((string)($row['title'] ?? '')) === '' || trim((string)($row['title'] ?? '')) === '询价通知') {
  8419. $data['title'] = '业务员询价通知';
  8420. }
  8421. try {
  8422. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template` LIKE 'updatetime'");
  8423. if (!empty($cols)) {
  8424. $data['updatetime'] = $now;
  8425. }
  8426. } catch (\Throwable $e) {
  8427. }
  8428. try {
  8429. Db::table('purchase_sms_template')
  8430. ->where('id', (int)($row['id'] ?? 0))
  8431. ->update($data);
  8432. } catch (\Throwable $e) {
  8433. }
  8434. }
  8435. return;
  8436. }
  8437. try {
  8438. $data = [
  8439. 'scene' => 'rfq_salesman_email',
  8440. 'title' => '业务员询价通知',
  8441. 'content' => $content,
  8442. 'remark' => '查询询价-通知业务员邮箱;模版名称作邮件主题',
  8443. 'status' => 1,
  8444. ];
  8445. try {
  8446. $cols = Db::query("SHOW COLUMNS FROM `purchase_sms_template`");
  8447. } catch (\Throwable $e) {
  8448. $cols = [];
  8449. }
  8450. $colNames = [];
  8451. foreach ($cols as $c) {
  8452. if (!is_array($c)) {
  8453. continue;
  8454. }
  8455. $n = (string)($c['Field'] ?? $c['field'] ?? '');
  8456. if ($n !== '') {
  8457. $colNames[$n] = true;
  8458. }
  8459. }
  8460. if (isset($colNames['updatetime'])) {
  8461. $data['updatetime'] = $now;
  8462. }
  8463. if (isset($colNames['createtime'])) {
  8464. $data['createtime'] = $now;
  8465. }
  8466. Db::table('purchase_sms_template')->insert($data);
  8467. } catch (\Throwable $e) {
  8468. // ignore
  8469. }
  8470. }
  8471. /**
  8472. * 通知业务员邮件:供应商报价明细行(仅名称+单价)
  8473. *
  8474. * @return array<int, array{name:string,amount:string}>
  8475. */
  8476. protected function loadRfqSalesmanSupplierQuoteRows(int $sid, string $supplierRaw = ''): array
  8477. {
  8478. $list = [];
  8479. $seen = [];
  8480. try {
  8481. $rows = Db::table('purchase_order_detail')
  8482. ->where('scydgy_id', $sid)
  8483. ->field('company_name,amount')
  8484. ->order('id', 'asc')
  8485. ->select();
  8486. if (is_array($rows)) {
  8487. foreach ($rows as $r) {
  8488. if (!is_array($r)) {
  8489. continue;
  8490. }
  8491. $cn = trim((string)($r['company_name'] ?? ''));
  8492. if ($cn === '' || isset($seen[$cn])) {
  8493. continue;
  8494. }
  8495. $seen[$cn] = true;
  8496. $amount = trim((string)($r['amount'] ?? ''));
  8497. $list[] = [
  8498. 'name' => $cn,
  8499. 'amount' => $amount !== '' ? $amount : '未报价',
  8500. ];
  8501. }
  8502. }
  8503. } catch (\Throwable $e) {
  8504. }
  8505. if ($list === [] && $supplierRaw !== '') {
  8506. foreach ($this->splitRfqSalesmanNames($supplierRaw) as $cn) {
  8507. if ($cn === '' || isset($seen[$cn])) {
  8508. continue;
  8509. }
  8510. $seen[$cn] = true;
  8511. $list[] = [
  8512. 'name' => $cn,
  8513. 'amount' => '未报价',
  8514. ];
  8515. }
  8516. }
  8517. return $list;
  8518. }
  8519. /**
  8520. * 通知业务员邮件:供应商报价 HTML 表格(名称+单价,不含时间)
  8521. */
  8522. protected function buildRfqSalesmanSupplierQuotesHtml(int $sid, string $supplierRaw = ''): string
  8523. {
  8524. $rows = $this->loadRfqSalesmanSupplierQuoteRows($sid, $supplierRaw);
  8525. if ($rows === []) {
  8526. return '<p style="margin:8px 0;color:#888;">暂无报价</p>';
  8527. }
  8528. $html = '<table cellpadding="0" cellspacing="0" border="1" '
  8529. . 'style="border-collapse:collapse;border-color:#ddd;width:100%;max-width:560px;font-size:14px;margin:8px 0;">'
  8530. . '<thead><tr style="background:#f5f5f5;">'
  8531. . '<th style="padding:8px 10px;text-align:center;width:56px;">序号</th>'
  8532. . '<th style="padding:8px 10px;text-align:left;">供应商名称</th>'
  8533. . '<th style="padding:8px 10px;text-align:center;width:100px;">单价</th>'
  8534. . '</tr></thead><tbody>';
  8535. foreach ($rows as $i => $row) {
  8536. $html .= '<tr>'
  8537. . '<td style="padding:8px 10px;text-align:center;">' . ($i + 1) . '</td>'
  8538. . '<td style="padding:8px 10px;">' . htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8') . '</td>'
  8539. . '<td style="padding:8px 10px;text-align:center;">' . htmlspecialchars($row['amount'], ENT_QUOTES, 'UTF-8') . '</td>'
  8540. . '</tr>';
  8541. }
  8542. $html .= '</tbody></table>';
  8543. return $html;
  8544. }
  8545. /**
  8546. * 询价多选字段:数组或字符串统一为顿号拼接
  8547. *
  8548. * @param mixed $raw
  8549. */
  8550. protected function joinRfqMultiSelectValues($raw): string
  8551. {
  8552. $parts = [];
  8553. if (is_array($raw)) {
  8554. foreach ($raw as $item) {
  8555. if (is_array($item)) {
  8556. continue;
  8557. }
  8558. $v = trim((string)$item);
  8559. if ($v !== '') {
  8560. $parts[] = $v;
  8561. }
  8562. }
  8563. } else {
  8564. $s = trim((string)$raw);
  8565. if ($s !== '') {
  8566. foreach (preg_split('/[,,、;;]+/u', $s) as $piece) {
  8567. $v = trim((string)$piece);
  8568. if ($v !== '') {
  8569. $parts[] = $v;
  8570. }
  8571. }
  8572. }
  8573. }
  8574. $parts = array_values(array_unique($parts));
  8575. return implode('、', $parts);
  8576. }
  8577. /**
  8578. * 新增询价:可选供应商名称(仅落库记录,不发通知)
  8579. *
  8580. * @return string[]
  8581. */
  8582. protected function loadRfqSupplierNameOptions(): array
  8583. {
  8584. $out = [];
  8585. try {
  8586. $rows = Db::table('customer')
  8587. ->where(function ($q) {
  8588. $q->where('status', 1)
  8589. ->whereOr('status', '1')
  8590. ->whereOr('status', '')
  8591. ->whereNull('status');
  8592. })
  8593. ->order('id', 'desc')
  8594. ->column('company_name');
  8595. } catch (\Throwable $e) {
  8596. return [];
  8597. }
  8598. if (!is_array($rows)) {
  8599. return [];
  8600. }
  8601. foreach ($rows as $name) {
  8602. $name = trim((string)$name);
  8603. if ($name === '' || isset($out[$name])) {
  8604. continue;
  8605. }
  8606. $out[$name] = $name;
  8607. }
  8608. return array_values($out);
  8609. }
  8610. /**
  8611. * 新增询价「通知业务员」角色组 id(auth_group,默认「业务员」)
  8612. */
  8613. protected function rfqNotifySalesmanAuthGroupId(): int
  8614. {
  8615. $id = (int)Config::get('mproc.rfq_notify_salesman_group_id');
  8616. if ($id > 0) {
  8617. return $id;
  8618. }
  8619. try {
  8620. $found = Db::name('auth_group')
  8621. ->where('name', '业务员')
  8622. ->where('status', 'normal')
  8623. ->order('id', 'asc')
  8624. ->value('id');
  8625. $id = (int)$found;
  8626. } catch (\Throwable $e) {
  8627. $id = 0;
  8628. }
  8629. return $id > 0 ? $id : 12;
  8630. }
  8631. /**
  8632. * 新增询价:通知业务员下拉(仅「业务员」角色组下的正常管理员)
  8633. *
  8634. * @return string[]
  8635. */
  8636. protected function loadRfqSalesmanNameOptions(): array
  8637. {
  8638. $out = [];
  8639. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  8640. $name = trim((string)($row['name'] ?? ''));
  8641. if ($name !== '') {
  8642. $out[] = $name;
  8643. }
  8644. }
  8645. return $out;
  8646. }
  8647. /**
  8648. * 业务员角色组下管理员:姓名、邮箱、手机
  8649. *
  8650. * @return array<int, array{name:string,email:string,mobile:string}>
  8651. */
  8652. protected function loadRfqSalesmanContactOptions(): array
  8653. {
  8654. $out = [];
  8655. $seen = [];
  8656. $groupId = $this->rfqNotifySalesmanAuthGroupId();
  8657. if ($groupId <= 0) {
  8658. return [];
  8659. }
  8660. try {
  8661. $adminIds = Db::name('auth_group_access')
  8662. ->where('group_id', $groupId)
  8663. ->column('uid');
  8664. } catch (\Throwable $e) {
  8665. return [];
  8666. }
  8667. $adminIds = is_array($adminIds)
  8668. ? array_values(array_unique(array_filter(array_map('intval', $adminIds))))
  8669. : [];
  8670. if ($adminIds === []) {
  8671. return [];
  8672. }
  8673. try {
  8674. $rows = Db::name('admin')
  8675. ->where('status', 'normal')
  8676. ->where('id', 'in', $adminIds)
  8677. ->order('id', 'asc')
  8678. ->field('id,nickname,username,email,mobile')
  8679. ->select();
  8680. } catch (\Throwable $e) {
  8681. return [];
  8682. }
  8683. if (!is_array($rows)) {
  8684. return [];
  8685. }
  8686. foreach ($rows as $row) {
  8687. if (!is_array($row)) {
  8688. continue;
  8689. }
  8690. $name = trim((string)($row['nickname'] ?? ''));
  8691. if ($name === '') {
  8692. $name = trim((string)($row['username'] ?? ''));
  8693. }
  8694. if ($name === '' || isset($seen[$name])) {
  8695. continue;
  8696. }
  8697. $seen[$name] = true;
  8698. $out[] = [
  8699. 'name' => $name,
  8700. 'email' => trim((string)($row['email'] ?? '')),
  8701. 'mobile' => preg_replace('/\s+/', '', trim((string)($row['mobile'] ?? ''))),
  8702. ];
  8703. }
  8704. return $out;
  8705. }
  8706. /**
  8707. * 新增询价:需求部门可选列表(来自 ERP mcyd + 历史单,仍可手输)
  8708. *
  8709. * @return string[]
  8710. */
  8711. protected function loadRfqDeptNameOptions(): array
  8712. {
  8713. $out = [];
  8714. // ERP 承揽部门(主来源)
  8715. try {
  8716. $vals = Db::table('mcyd')
  8717. ->where('CCLBMMC', '<>', '')
  8718. ->whereNotNull('CCLBMMC')
  8719. ->distinct(true)
  8720. ->limit(300)
  8721. ->column('CCLBMMC');
  8722. } catch (\Throwable $e) {
  8723. $vals = [];
  8724. }
  8725. if (is_array($vals)) {
  8726. foreach ($vals as $v) {
  8727. $v = trim((string)$v);
  8728. if ($v === '' || isset($out[$v])) {
  8729. continue;
  8730. }
  8731. $out[$v] = $v;
  8732. }
  8733. }
  8734. // 手工询价历史部门补全
  8735. try {
  8736. $poVals = Db::table('purchase_order')
  8737. ->where('CCLBMMC', '<>', '')
  8738. ->whereNotNull('CCLBMMC')
  8739. ->distinct(true)
  8740. ->limit(200)
  8741. ->column('CCLBMMC');
  8742. } catch (\Throwable $e) {
  8743. $poVals = [];
  8744. }
  8745. if (is_array($poVals)) {
  8746. foreach ($poVals as $v) {
  8747. $v = trim((string)$v);
  8748. if ($v === '' || isset($out[$v])) {
  8749. continue;
  8750. }
  8751. $out[$v] = $v;
  8752. }
  8753. }
  8754. foreach (['营销中心', '业务部', '市场部', '外贸部', '新华技术业务部', '新华广告', '数字印刷中心'] as $preset) {
  8755. if (!isset($out[$preset])) {
  8756. $out[$preset] = $preset;
  8757. }
  8758. }
  8759. $list = array_values($out);
  8760. // 常用部门靠前
  8761. usort($list, static function ($a, $b) {
  8762. $weight = [
  8763. '营销中心' => 1,
  8764. '业务部' => 2,
  8765. '市场部' => 3,
  8766. '外贸部' => 4,
  8767. '新华技术业务部' => 5,
  8768. ];
  8769. $wa = $weight[$a] ?? 100;
  8770. $wb = $weight[$b] ?? 100;
  8771. if ($wa !== $wb) {
  8772. return $wa <=> $wb;
  8773. }
  8774. return strcmp((string)$a, (string)$b);
  8775. });
  8776. return $list;
  8777. }
  8778. /**
  8779. * 业务员新增询价(独立页面,与下发弹窗 pickAdd 分离)
  8780. */
  8781. public function add()
  8782. {
  8783. if ($this->request->isPost()) {
  8784. $params = $this->request->post('row/a');
  8785. if (!is_array($params)) {
  8786. $this->error(__('Parameter %s can not be empty', ''));
  8787. }
  8788. [, $adminName] = $this->GetUseName();
  8789. $params['cywyxm'] = $adminName;
  8790. try {
  8791. $sid = $this->saveManualPickOrder($params);
  8792. } catch (\InvalidArgumentException $e) {
  8793. $this->error($e->getMessage());
  8794. } catch (\Throwable $e) {
  8795. $this->error($e->getMessage());
  8796. }
  8797. $this->success('新增成功', '', [
  8798. 'scydgy_id' => $sid,
  8799. 'nextOrderCcydh' => $this->allocateManualOrderCcydh(),
  8800. ]);
  8801. }
  8802. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8803. [, $adminName] = $this->GetUseName();
  8804. $this->view->assign('adminNickname', $adminName);
  8805. $this->view->assign('nextOrderCcydh', $this->allocateManualOrderCcydh());
  8806. $this->view->assign('defaultCclbmmc', '营销中心');
  8807. $this->view->assign('rfqDeptOptions', $this->loadRfqDeptNameOptions());
  8808. $this->view->assign('rfqSupplierOptions', $this->loadRfqSupplierNameOptions());
  8809. $this->view->assign('rfqSalesmanOptions', $this->loadRfqSalesmanNameOptions());
  8810. return $this->view->fetch();
  8811. }
  8812. /**
  8813. * 业务员新增进度查询(手工询价;有查询权限看全部,含手机端新增且未通知业务员的)
  8814. */
  8815. public function rfqlist()
  8816. {
  8817. $this->relationSearch = false;
  8818. $this->searchFields = 'CCYDH,CYJMC,CGYMC,CCLBMMC,cywyxm,notify_salesman,pick_company_name,cGzzxMc,MBZ';
  8819. $this->request->filter(['strip_tags', 'trim']);
  8820. $this->ensurePurchaseOrderNotifySalesmanColumn();
  8821. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  8822. $this->ensureRfqSalesmanEmailTemplate();
  8823. $this->ensureRfqSupplierEmailTemplate();
  8824. if ($this->request->isAjax()) {
  8825. try {
  8826. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  8827. $limit = max(10, min(500, (int)$limit));
  8828. $filterYm = trim((string)$this->request->param('filter_ym', ''));
  8829. if (!preg_match('/^\d{4}-\d{2}$/', $filterYm)) {
  8830. $filterYm = date('Y-m');
  8831. }
  8832. $applyFilters = function ($query) use ($where, $filterYm) {
  8833. $query->where('scydgy_id', '<', 0);
  8834. $this->applyPurchaseOrderNotDeletedWhere($query);
  8835. // 查询询价:有菜单权限即可看全部手工单(含手机端新增、尚未通知业务员的)
  8836. $this->applyRfqListMonthFilter($query, $filterYm);
  8837. if (!empty($where)) {
  8838. // 计算字段不能直接 where,避免 SQL 异常被吞成「暂无数据」
  8839. $safeWhere = [];
  8840. $skipFields = [
  8841. 'supplier_name' => true,
  8842. 'progress_text' => true,
  8843. 'createtime_text' => true,
  8844. 'notify_time_text' => true,
  8845. 'can_notify_salesman' => true,
  8846. 'has_issued' => true,
  8847. 'has_quoted' => true,
  8848. ];
  8849. foreach ((array)$where as $cond) {
  8850. if (!is_array($cond) || !isset($cond[0])) {
  8851. continue;
  8852. }
  8853. $field = (string)$cond[0];
  8854. $fieldBase = (string)preg_replace('/\|.*$/', '', $field);
  8855. $fieldBase = (string)preg_replace('/^.*\./', '', $fieldBase);
  8856. if (isset($skipFields[$fieldBase])) {
  8857. continue;
  8858. }
  8859. if ($fieldBase === 'supplier_name') {
  8860. continue;
  8861. }
  8862. $safeWhere[] = $cond;
  8863. }
  8864. if ($safeWhere !== []) {
  8865. $query->where($safeWhere);
  8866. }
  8867. }
  8868. };
  8869. $countQuery = Db::table('purchase_order');
  8870. $applyFilters($countQuery);
  8871. $total = (int)$countQuery->count();
  8872. $sortField = preg_match('/^[a-zA-Z0-9_]+$/', (string)$sort) ? $sort : 'id';
  8873. $orderDir = strtoupper((string)$order) === 'ASC' ? 'ASC' : 'DESC';
  8874. $listQuery = Db::table('purchase_order');
  8875. $applyFilters($listQuery);
  8876. $rows = $listQuery
  8877. ->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')
  8878. ->order($sortField, $orderDir)
  8879. ->limit($offset, $limit)
  8880. ->select();
  8881. if (!is_array($rows)) {
  8882. $rows = [];
  8883. }
  8884. $sidList = [];
  8885. foreach ($rows as $r) {
  8886. if (!is_array($r)) {
  8887. continue;
  8888. }
  8889. $sid = (int)($r['scydgy_id'] ?? 0);
  8890. if ($sid < 0) {
  8891. $sidList[$sid] = true;
  8892. }
  8893. }
  8894. $issuedSidSet = $this->loadRfqIssuedScydgyIdSet(array_keys($sidList));
  8895. $quotedSidSet = $this->loadRfqQuotedScydgyIdSet(array_keys($sidList));
  8896. $out = [];
  8897. foreach ($rows as $r) {
  8898. if (!is_array($r)) {
  8899. continue;
  8900. }
  8901. $sid = (int)($r['scydgy_id'] ?? 0);
  8902. if ($sid >= 0) {
  8903. continue;
  8904. }
  8905. $createdText = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  8906. if ($createdText === '') {
  8907. $createdText = trim((string)($r['dStamp'] ?? ''));
  8908. }
  8909. $notifyTimeText = $this->formatProcuremenDetailTime($r['rfq_salesman_notify_time'] ?? null);
  8910. $supplier = trim((string)($r['cGzzxMc'] ?? ''));
  8911. if ($supplier === '') {
  8912. $supplier = trim((string)($r['pick_company_name'] ?? ''));
  8913. }
  8914. $hasIssued = ProcuremenStatus::wflowAtLeastConfirm($r['wflow_status'] ?? '')
  8915. || isset($issuedSidSet[$sid]);
  8916. $hasQuoted = isset($quotedSidSet[$sid]);
  8917. $salesmanNotified = (int)($r['rfq_salesman_notified'] ?? 0) === 1;
  8918. $canNotifySalesman = ($hasIssued && $hasQuoted && !$salesmanNotified) ? 1 : 0;
  8919. $out[] = [
  8920. 'id' => (int)($r['id'] ?? 0),
  8921. 'scydgy_id' => $sid,
  8922. 'CCYDH' => trim((string)($r['CCYDH'] ?? '')),
  8923. 'CYJMC' => trim((string)($r['CYJMC'] ?? '')),
  8924. 'CCLBMMC' => trim((string)($r['CCLBMMC'] ?? '')),
  8925. 'CGYMC' => trim((string)($r['CGYMC'] ?? '')),
  8926. 'CDW' => trim((string)($r['CDW'] ?? '')),
  8927. 'This_quantity' => trim((string)($r['This_quantity'] ?? '')),
  8928. 'ceilingPrice' => trim((string)($r['ceilingPrice'] ?? '')),
  8929. 'CDF' => trim((string)($r['CDF'] ?? '')),
  8930. 'supplier_name' => $supplier,
  8931. 'cywyxm' => trim((string)($r['cywyxm'] ?? '')),
  8932. 'notify_salesman' => trim((string)($r['notify_salesman'] ?? '')),
  8933. 'rfq_salesman_notified' => $salesmanNotified ? 1 : 0,
  8934. 'rfq_salesman_notify_time' => $r['rfq_salesman_notify_time'] ?? null,
  8935. 'notify_time_text' => $notifyTimeText,
  8936. 'MBZ' => trim((string)($r['MBZ'] ?? '')),
  8937. 'progress_text' => $this->formatProcuremenRfqProgressText($r, $hasIssued, $hasQuoted),
  8938. 'has_issued' => $hasIssued ? 1 : 0,
  8939. 'has_quoted' => $hasQuoted ? 1 : 0,
  8940. 'can_notify_salesman' => $canNotifySalesman,
  8941. 'createtime' => $r['createtime'] ?? null,
  8942. 'createtime_text' => $createdText,
  8943. ];
  8944. }
  8945. return json(['total' => $total, 'rows' => $out]);
  8946. } catch (\Throwable $e) {
  8947. Log::write('查询询价列表失败:' . $e->getMessage() . "\n" . $e->getTraceAsString(), 'error');
  8948. return json(['total' => 0, 'rows' => [], 'msg' => '列表加载失败:' . $e->getMessage()]);
  8949. }
  8950. }
  8951. $sidebar = $this->loadRfqSidebarYearMonths();
  8952. $defaultYm = $this->resolveRfqListDefaultYm($sidebar);
  8953. $sidebar = $this->ensureProcuremenSidebarHasYm($sidebar, $defaultYm);
  8954. [, $adminName] = $this->GetUseName();
  8955. $this->view->assign('isSuperAdmin', $this->auth->isSuperAdmin());
  8956. $this->view->assign('adminNickname', $adminName);
  8957. $this->view->assign('defaultYm', $defaultYm);
  8958. $this->view->assign('sidebarYearMonths', $sidebar);
  8959. return $this->view->fetch('procuremen/rfqlist');
  8960. }
  8961. /**
  8962. * 列表默认月份:当月有数据用当月,否则取最近有数据的月份
  8963. *
  8964. * @param array<int, array{year:string, months:array}> $sidebar
  8965. */
  8966. protected function resolveRfqListDefaultYm(array $sidebar): string
  8967. {
  8968. $current = date('Y-m');
  8969. $yms = $this->flattenProcuremenSidebarYms($sidebar);
  8970. if (in_array($current, $yms, true)) {
  8971. return $current;
  8972. }
  8973. if ($yms !== []) {
  8974. rsort($yms, SORT_STRING);
  8975. return (string)$yms[0];
  8976. }
  8977. return $current;
  8978. }
  8979. /**
  8980. * 手工询价列表左侧月份(按 createtime / dStamp)
  8981. *
  8982. * @return array<int, array{year:string, months:array}>
  8983. */
  8984. protected function loadRfqSidebarYearMonths(): array
  8985. {
  8986. $ymSet = [];
  8987. try {
  8988. $q = Db::table('purchase_order')->where('scydgy_id', '<', 0);
  8989. $this->applyPurchaseOrderNotDeletedWhere($q);
  8990. $rows = $q->field('createtime,dStamp')->limit(5000)->select();
  8991. } catch (\Throwable $e) {
  8992. $rows = [];
  8993. }
  8994. if (!is_array($rows)) {
  8995. $rows = [];
  8996. }
  8997. foreach ($rows as $r) {
  8998. if (!is_array($r)) {
  8999. continue;
  9000. }
  9001. $t = $this->formatProcuremenDetailTime($r['createtime'] ?? null);
  9002. if ($t === '') {
  9003. $t = $this->formatProcuremenDetailTime($r['dStamp'] ?? null);
  9004. }
  9005. if ($t !== '' && preg_match('/^([12]\d{3})-(\d{2})/', $t, $m)) {
  9006. $ymSet[$m[1] . '-' . $m[2]] = true;
  9007. }
  9008. }
  9009. return $this->buildYearMonthSidebar(array_keys($ymSet));
  9010. }
  9011. /**
  9012. * 手工询价可见范围(用于详情/操作校验):
  9013. * 超管、具备「查询询价」权限、需求发起人、通知业务员 → 可见
  9014. * 列表页本身不再按发起人/通知过滤,避免手机端新增后后台看不到。
  9015. */
  9016. protected function applyManualRfqViewerWhere($query): void
  9017. {
  9018. if ($this->auth->isSuperAdmin() || $this->hasProcuremenPerm(['rfqlist'])) {
  9019. return;
  9020. }
  9021. [, $adminName] = $this->GetUseName();
  9022. $adminName = trim((string)$adminName);
  9023. if ($adminName === '') {
  9024. $query->whereRaw('1 = 0');
  9025. return;
  9026. }
  9027. // 不用 whereRaw 绑定,避免与软删除条件混用触发 HY093
  9028. $query->where(function ($q) use ($adminName) {
  9029. $q->where('cywyxm', $adminName)
  9030. ->whereOr('notify_salesman', $adminName)
  9031. ->whereOr('notify_salesman', 'like', '%、' . $adminName . '、%')
  9032. ->whereOr('notify_salesman', 'like', $adminName . '、%')
  9033. ->whereOr('notify_salesman', 'like', '%、' . $adminName)
  9034. ->whereOr('notify_salesman', 'like', '%,' . $adminName . ',%')
  9035. ->whereOr('notify_salesman', 'like', $adminName . ',%')
  9036. ->whereOr('notify_salesman', 'like', '%,' . $adminName);
  9037. });
  9038. }
  9039. /**
  9040. * 当前用户是否可查看/操作该手工询价单
  9041. */
  9042. protected function canViewManualRfqOrder(array $po): bool
  9043. {
  9044. if ($this->auth->isSuperAdmin()) {
  9045. return true;
  9046. }
  9047. // 有查询询价权限则可操作全部手工询价(询价/查看报价/通知业务员等)
  9048. if ($this->hasProcuremenPerm(['rfqlist'])) {
  9049. return true;
  9050. }
  9051. [, $adminName] = $this->GetUseName();
  9052. $adminName = trim((string)$adminName);
  9053. if ($adminName !== '' && trim((string)($po['cywyxm'] ?? '')) === $adminName) {
  9054. return true;
  9055. }
  9056. if ($adminName !== '') {
  9057. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  9058. if ($n === $adminName) {
  9059. return true;
  9060. }
  9061. }
  9062. }
  9063. return false;
  9064. }
  9065. /**
  9066. * 手工询价列表按月份过滤(优先 createtime,空则 dStamp;不用 ? 绑定,避免与其它 whereRaw 混用触发 HY093)
  9067. */
  9068. protected function applyRfqListMonthFilter($query, string $ym): void
  9069. {
  9070. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  9071. $ym = date('Y-m');
  9072. }
  9073. $ymEsc = str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $ym);
  9074. // 兼容 createtime 为 unix 秒级时间戳或 datetime 字符串
  9075. $query->whereRaw(
  9076. "("
  9077. . "CASE "
  9078. . "WHEN createtime IS NOT NULL AND CAST(createtime AS CHAR(32)) REGEXP '^[0-9]{10,}$' "
  9079. . "THEN FROM_UNIXTIME(CAST(createtime AS UNSIGNED)) "
  9080. . "WHEN createtime IS NOT NULL AND TRIM(CAST(createtime AS CHAR(32))) <> '' "
  9081. . "AND TRIM(CAST(createtime AS CHAR(32))) NOT LIKE '0000-00-00%' "
  9082. . "THEN TRIM(CAST(createtime AS CHAR(32))) "
  9083. . "ELSE TRIM(CAST(IFNULL(dStamp, '') AS CHAR(32))) "
  9084. . "END"
  9085. . ") LIKE '{$ymEsc}-%'"
  9086. );
  9087. }
  9088. /**
  9089. * 业务员进度详情(与 procuremen/details 同一弹层,保留兼容旧链接)
  9090. */
  9091. public function rfqlistDetails()
  9092. {
  9093. return $this->details();
  9094. }
  9095. /**
  9096. * 查询询价 — 弹窗:可选通知业务员名单(勾选后确认通知)
  9097. */
  9098. public function rfqnotifysalesmen()
  9099. {
  9100. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman'])) {
  9101. $this->error(__('You have no permission'));
  9102. }
  9103. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9104. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  9105. $sid = (int)$this->request->param('scydgy_id', 0);
  9106. if ($sid >= 0) {
  9107. $this->error('仅支持手工新增询价单');
  9108. }
  9109. $po = $this->loadManualRfqOrderForNotify($sid);
  9110. $selectedMap = [];
  9111. foreach ($this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? ''))) as $n) {
  9112. $selectedMap[$n] = true;
  9113. }
  9114. $list = [];
  9115. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  9116. $name = trim((string)($row['name'] ?? ''));
  9117. if ($name === '') {
  9118. continue;
  9119. }
  9120. $email = trim((string)($row['email'] ?? ''));
  9121. $mobile = trim((string)($row['mobile'] ?? ''));
  9122. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  9123. $list[] = [
  9124. 'name' => $name,
  9125. 'email' => $email,
  9126. 'mobile' => $mobile,
  9127. 'can_select' => $hasEmail ? 1 : 0,
  9128. 'checked' => (!empty($selectedMap[$name]) && $hasEmail) ? 1 : 0,
  9129. ];
  9130. }
  9131. $canNotify = $this->canRfqNotifySalesman($po);
  9132. $this->success('', null, [
  9133. 'scydgy_id' => $sid,
  9134. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9135. 'notify_salesman' => trim((string)($po['notify_salesman'] ?? '')),
  9136. 'rfq_salesman_notified' => (int)($po['rfq_salesman_notified'] ?? 0),
  9137. 'can_notify_salesman' => $canNotify ? 1 : 0,
  9138. 'list' => $list,
  9139. ]);
  9140. }
  9141. /**
  9142. * 查询询价 — 补加通知业务员可选名单
  9143. */
  9144. public function rfqsalesmanoptions()
  9145. {
  9146. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqsalesmanoptions', 'rfqappendsalesmen'])) {
  9147. $this->error(__('You have no permission'));
  9148. }
  9149. $out = [];
  9150. foreach ($this->loadRfqSalesmanContactOptions() as $row) {
  9151. $email = trim((string)($row['email'] ?? ''));
  9152. $mobile = trim((string)($row['mobile'] ?? ''));
  9153. $hasEmail = $email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
  9154. $out[] = [
  9155. 'name' => (string)($row['name'] ?? ''),
  9156. 'email' => $email,
  9157. 'mobile' => $mobile,
  9158. 'can_select' => $hasEmail ? 1 : 0,
  9159. ];
  9160. }
  9161. $this->success('', null, ['list' => $out]);
  9162. }
  9163. /**
  9164. * 查询询价 — 补加通知业务员(合并更新 notify_salesman)
  9165. */
  9166. public function rfqappendsalesmen()
  9167. {
  9168. if (!$this->request->isPost()) {
  9169. $this->error(__('Invalid parameters'));
  9170. }
  9171. if (!$this->hasProcuremenPerm(['rfqnotifysalesmen', 'rfqnotifysalesman', 'rfqappendsalesmen'])) {
  9172. $this->error(__('You have no permission'));
  9173. }
  9174. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9175. $sid = (int)$this->request->post('scydgy_id', 0);
  9176. if ($sid >= 0) {
  9177. $this->error('仅支持手工新增询价单');
  9178. }
  9179. $po = $this->loadManualRfqOrderForNotify($sid);
  9180. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9181. $this->error('订单已完结,无法添加业务员');
  9182. }
  9183. $raw = $this->request->post('salesmen/a', []);
  9184. if (!is_array($raw) || $raw === []) {
  9185. $salesmenJson = $this->request->post('salesmen_json', '');
  9186. if (is_string($salesmenJson) && $salesmenJson !== '') {
  9187. $decoded = json_decode($salesmenJson, true);
  9188. $raw = is_array($decoded) ? $decoded : [];
  9189. }
  9190. }
  9191. $addNames = [];
  9192. foreach ((array)$raw as $item) {
  9193. if (is_array($item)) {
  9194. $n = trim((string)($item['name'] ?? ''));
  9195. } else {
  9196. $n = trim((string)$item);
  9197. }
  9198. if ($n !== '') {
  9199. $addNames[] = $n;
  9200. }
  9201. }
  9202. $addNames = array_values(array_unique($addNames));
  9203. if ($addNames === []) {
  9204. $this->error('请选择要添加的业务员');
  9205. }
  9206. $allowedOptions = $this->loadRfqSalesmanContactOptions();
  9207. $allowedMap = [];
  9208. foreach ($allowedOptions as $opt) {
  9209. $n = trim((string)($opt['name'] ?? ''));
  9210. if ($n === '') {
  9211. continue;
  9212. }
  9213. $email = trim((string)($opt['email'] ?? ''));
  9214. $allowedMap[$n] = ($email !== '' && (bool)filter_var($email, FILTER_VALIDATE_EMAIL));
  9215. }
  9216. foreach ($addNames as $n) {
  9217. if (!array_key_exists($n, $allowedMap)) {
  9218. $this->error('业务员不在可选名单中:' . $n);
  9219. }
  9220. if (!$allowedMap[$n]) {
  9221. $this->error('业务员未填写有效邮箱,无法添加:' . $n);
  9222. }
  9223. }
  9224. $existingRaw = trim((string)($po['notify_salesman'] ?? ''));
  9225. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9226. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9227. try {
  9228. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['notify_salesman' => $mergedStr]);
  9229. } catch (\Throwable $e) {
  9230. $this->error('保存失败:' . $e->getMessage());
  9231. }
  9232. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9233. $this->addOrderLog($sid, 'rfq_append_salesman', '添加通知业务员:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9234. $this->success('已添加业务员', null, [
  9235. 'scydgy_id' => $sid,
  9236. 'notify_salesman' => $mergedStr,
  9237. 'added_count' => count($addNames),
  9238. ]);
  9239. }
  9240. /**
  9241. * 查询询价 — 勾选业务员后邮箱通知(salesmen_json)
  9242. */
  9243. public function rfqnotifysalesman()
  9244. {
  9245. if (!$this->request->isPost()) {
  9246. $this->error(__('Invalid parameters'));
  9247. }
  9248. if (!$this->hasProcuremenPerm(['rfqnotifysalesman', 'rfqnotifysalesmen'])) {
  9249. $this->error(__('You have no permission'));
  9250. }
  9251. $this->ensurePurchaseOrderNotifySalesmanColumn();
  9252. $this->ensurePurchaseOrderRfqSalesmanNotifiedColumn();
  9253. $sid = (int)$this->request->post('scydgy_id', 0);
  9254. if ($sid >= 0) {
  9255. $this->error('仅支持手工新增询价单');
  9256. }
  9257. $po = $this->loadManualRfqOrderForNotify($sid);
  9258. $this->assertRfqCanNotifySalesman($po);
  9259. $raw = $this->request->post('salesmen/a', []);
  9260. if (!is_array($raw) || $raw === []) {
  9261. $salesmenJson = $this->request->post('salesmen_json', '');
  9262. if (is_string($salesmenJson) && $salesmenJson !== '') {
  9263. $decoded = json_decode($salesmenJson, true);
  9264. $raw = is_array($decoded) ? $decoded : [];
  9265. }
  9266. }
  9267. // 兼容旧参数:notify_all / 单人 name
  9268. if ((!is_array($raw) || $raw === []) && (int)$this->request->post('notify_all', 0) === 1) {
  9269. $raw = $this->splitRfqSalesmanNames(trim((string)($po['notify_salesman'] ?? '')));
  9270. }
  9271. if ((!is_array($raw) || $raw === [])) {
  9272. $oneName = trim((string)$this->request->post('name', ''));
  9273. if ($oneName !== '') {
  9274. $raw = [$oneName];
  9275. }
  9276. }
  9277. $selectedNames = [];
  9278. foreach ((array)$raw as $item) {
  9279. if (is_array($item)) {
  9280. $n = trim((string)($item['name'] ?? ''));
  9281. } else {
  9282. $n = trim((string)$item);
  9283. }
  9284. if ($n !== '') {
  9285. $selectedNames[] = $n;
  9286. }
  9287. }
  9288. $selectedNames = array_values(array_unique($selectedNames));
  9289. if ($selectedNames === []) {
  9290. $this->error('请选择要通知的业务员');
  9291. }
  9292. $optionMap = [];
  9293. foreach ($this->loadRfqSalesmanContactOptions() as $opt) {
  9294. $n = trim((string)($opt['name'] ?? ''));
  9295. if ($n === '') {
  9296. continue;
  9297. }
  9298. $optionMap[$n] = $opt;
  9299. }
  9300. $targets = [];
  9301. foreach ($selectedNames as $n) {
  9302. if (!isset($optionMap[$n])) {
  9303. $this->error('业务员不在可选名单中:' . $n);
  9304. }
  9305. $email = trim((string)($optionMap[$n]['email'] ?? ''));
  9306. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9307. $this->error('业务员未填写有效邮箱,无法通知:' . $n);
  9308. }
  9309. $resolved = $this->resolveRfqSalesmanContactRows([$n]);
  9310. $targets[] = $resolved[0] ?? [
  9311. 'admin_id' => 0,
  9312. 'name' => $n,
  9313. 'email' => $email,
  9314. ];
  9315. }
  9316. $mergedStr = $this->joinRfqMultiSelectValues($selectedNames);
  9317. try {
  9318. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  9319. 'notify_salesman' => $mergedStr,
  9320. ]);
  9321. } catch (\Throwable $e) {
  9322. $this->error('保存通知业务员失败:' . $e->getMessage());
  9323. }
  9324. $po['notify_salesman'] = $mergedStr;
  9325. $mailConfig = $this->loadMailerConfig();
  9326. if (empty($mailConfig['host'])) {
  9327. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9328. }
  9329. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9330. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9331. }
  9332. $this->ensureRfqSalesmanEmailTemplate();
  9333. $ccydh = trim((string)($po['CCYDH'] ?? ''));
  9334. $cyjmc = trim((string)($po['CYJMC'] ?? ''));
  9335. $cgymc = trim((string)($po['CGYMC'] ?? ''));
  9336. $cdw = trim((string)($po['CDW'] ?? ''));
  9337. $qty = trim((string)$this->resolveProcuremenThisQuantity($po));
  9338. $ceiling = trim((string)$this->resolveProcuremenCeilingPrice($po));
  9339. $mbz = trim((string)($po['MBZ'] ?? ''));
  9340. $cywyxm = trim((string)($po['cywyxm'] ?? ''));
  9341. $supplier = trim((string)($po['cGzzxMc'] ?? ''));
  9342. if ($supplier === '') {
  9343. $supplier = trim((string)($po['pick_company_name'] ?? ''));
  9344. }
  9345. $supplierQuotesHtml = $this->buildRfqSalesmanSupplierQuotesHtml($sid, $supplier);
  9346. try {
  9347. $mailSubjectTpl = $this->resolveProcuremenEmailSubject('rfq_salesman_email');
  9348. } catch (\Throwable $e) {
  9349. $this->error($e->getMessage());
  9350. }
  9351. $okNames = [];
  9352. $failMsgs = [];
  9353. foreach ($targets as $contact) {
  9354. $toEmail = trim((string)($contact['email'] ?? ''));
  9355. $toName = trim((string)($contact['name'] ?? ''));
  9356. $notifyVars = [
  9357. 'contact_name' => $toName,
  9358. 'salesman_name' => $toName,
  9359. 'company_name' => $toName,
  9360. 'email' => $toEmail,
  9361. 'ccydh' => $ccydh,
  9362. 'cyjmc' => $cyjmc,
  9363. 'cgymc' => $cgymc,
  9364. 'cdw' => $cdw,
  9365. 'this_quantity' => $qty,
  9366. 'ceilingPrice' => $ceiling,
  9367. 'MBZ' => $mbz,
  9368. 'supplier_name' => $supplier,
  9369. // 占位符,转 HTML 后再替换成表格,避免被 htmlspecialchars 转义
  9370. 'supplier_quotes' => '__RFQ_SUPPLIER_QUOTES_TABLE__',
  9371. 'cywyxm' => $cywyxm,
  9372. ];
  9373. try {
  9374. $mailPlain = $this->renderNotifyTemplate('rfq_salesman_email', $notifyVars);
  9375. $mailSubject = $mailSubjectTpl;
  9376. foreach ($notifyVars as $k => $v) {
  9377. if ($k === 'supplier_quotes') {
  9378. continue;
  9379. }
  9380. $mailSubject = str_replace('{' . $k . '}', (string)$v, $mailSubject);
  9381. }
  9382. $mailSubject = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $mailSubject);
  9383. $mailSubject = trim((string)$mailSubject);
  9384. if ($mailSubject === '') {
  9385. $mailSubject = '协助采购询价通知' . ($ccydh !== '' ? ' - ' . $ccydh : '');
  9386. }
  9387. $mailBody = $this->plainTextToHtmlEmailBody($mailPlain);
  9388. $mailBody = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', $supplierQuotesHtml, $mailBody);
  9389. $mailPlainForLog = str_replace('__RFQ_SUPPLIER_QUOTES_TABLE__', strip_tags(str_replace(['</tr>', '</p>'], "\n", $supplierQuotesHtml)), $mailPlain);
  9390. $bundle = [
  9391. 'company_name' => $toName,
  9392. 'email' => $toEmail,
  9393. 'mail_plain' => $mailPlainForLog,
  9394. 'mail_body' => $mailBody,
  9395. 'ccydh' => $ccydh,
  9396. 'email_log_scene' => 'rfq_salesman',
  9397. 'email_log_scydgy_id' => $sid,
  9398. 'email_log_purchase_order_id' => (int)($po['id'] ?? 0),
  9399. 'notify_vars' => $notifyVars,
  9400. ];
  9401. $this->issueSendSupplierEmail($bundle, $mailConfig, $mailSubject);
  9402. $okNames[] = $toName . '(' . $toEmail . ')';
  9403. } catch (\Throwable $e) {
  9404. $failMsgs[] = ($toName !== '' ? $toName : $toEmail) . ':' . $e->getMessage();
  9405. }
  9406. }
  9407. if ($okNames === []) {
  9408. $this->error('邮件发送失败:' . ($failMsgs !== [] ? implode(';', $failMsgs) : '未知错误'));
  9409. }
  9410. $now = date('Y-m-d H:i:s');
  9411. try {
  9412. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  9413. 'rfq_salesman_notified' => 1,
  9414. 'rfq_salesman_notify_time' => $now,
  9415. ]);
  9416. } catch (\Throwable $e) {
  9417. // ignore
  9418. }
  9419. $this->addOrderLog(
  9420. $sid,
  9421. 'rfq_notify_salesman',
  9422. '邮箱通知业务员:' . implode('、', $okNames),
  9423. (int)($po['id'] ?? 0)
  9424. );
  9425. $msg = '已通知 ' . count($okNames) . ' 人';
  9426. if ($failMsgs !== []) {
  9427. $msg .= ';部分失败:' . implode(';', $failMsgs);
  9428. }
  9429. $this->success($msg, null, [
  9430. 'scydgy_id' => $sid,
  9431. 'notify_salesman' => $mergedStr,
  9432. 'rfq_salesman_notified' => 1,
  9433. 'rfq_salesman_notify_time' => $now,
  9434. 'notify_time_text' => $now,
  9435. 'ok_count' => count($okNames),
  9436. 'fail_count' => count($failMsgs),
  9437. ]);
  9438. }
  9439. /**
  9440. * 查询询价 — 下发前:返回将通知的供应商表格数据
  9441. */
  9442. public function rfqissuesuppliers()
  9443. {
  9444. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesuppliers'])) {
  9445. $this->error(__('You have no permission'));
  9446. }
  9447. $sid = (int)$this->request->param('scydgy_id', 0);
  9448. if ($sid >= 0) {
  9449. $this->error('仅支持手工新增询价单');
  9450. }
  9451. $po = $this->loadManualRfqOrderForNotify($sid);
  9452. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9453. if ($supplierRaw === '') {
  9454. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9455. }
  9456. $names = $this->splitRfqSalesmanNames($supplierRaw);
  9457. // 已成功发过询价邮件的供应商(含历史 pick_issue 场景)
  9458. $notifiedMap = [];
  9459. try {
  9460. $this->ensurePurchaseEmailSendLogTableOnce();
  9461. $logRows = Db::table('purchase_email_send_log')
  9462. ->where('scydgy_id', $sid)
  9463. ->where('status', 1)
  9464. ->where('scene', 'in', ['rfq_supplier', 'pick_issue'])
  9465. ->field('company_name')
  9466. ->select();
  9467. if (is_array($logRows)) {
  9468. foreach ($logRows as $lr) {
  9469. if (!is_array($lr)) {
  9470. continue;
  9471. }
  9472. $cn = trim((string)($lr['company_name'] ?? ''));
  9473. if ($cn !== '') {
  9474. $notifiedMap[$cn] = true;
  9475. }
  9476. }
  9477. }
  9478. } catch (\Throwable $e) {
  9479. }
  9480. // 兼容:明细已生成(曾下发)也视为已通知
  9481. try {
  9482. $detRows = Db::table('purchase_order_detail')
  9483. ->where('scydgy_id', $sid)
  9484. ->field('company_name')
  9485. ->select();
  9486. if (is_array($detRows)) {
  9487. foreach ($detRows as $dr) {
  9488. if (!is_array($dr)) {
  9489. continue;
  9490. }
  9491. $cn = trim((string)($dr['company_name'] ?? ''));
  9492. if ($cn !== '') {
  9493. $notifiedMap[$cn] = true;
  9494. }
  9495. }
  9496. }
  9497. } catch (\Throwable $e) {
  9498. }
  9499. $list = [];
  9500. foreach ($names as $name) {
  9501. // 展示用:无邮箱/手机也返回档案信息(与供应商分组一致)
  9502. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9503. $email = is_array($contact) ? trim((string)($contact['email'] ?? '')) : '';
  9504. $phone = is_array($contact) ? trim((string)($contact['phone'] ?? '')) : '';
  9505. $username = is_array($contact) ? trim((string)($contact['username'] ?? '')) : '';
  9506. $okEmail = ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL));
  9507. $notified = !empty($notifiedMap[$name]) ? 1 : 0;
  9508. $list[] = [
  9509. 'name' => $name,
  9510. 'username' => $username,
  9511. 'email' => $email,
  9512. 'phone' => $phone,
  9513. 'can_notify' => $okEmail ? 1 : 0,
  9514. 'found' => is_array($contact) ? 1 : 0,
  9515. 'notified' => $notified,
  9516. 'notify_status_text' => $notified ? '已通知' : '未通知',
  9517. ];
  9518. }
  9519. $this->success('', null, [
  9520. 'scydgy_id' => $sid,
  9521. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9522. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9523. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9524. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9525. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9526. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9527. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9528. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9529. 'list' => $list,
  9530. ]);
  9531. }
  9532. /**
  9533. * 查询询价 — 补加供应商可选名单
  9534. */
  9535. public function rfqsupplieroptions()
  9536. {
  9537. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers', 'rfqsupplieroptions'])) {
  9538. $this->error(__('You have no permission'));
  9539. }
  9540. $names = array_values($this->loadRfqSupplierNameOptions());
  9541. $out = [];
  9542. foreach ($names as $name) {
  9543. $out[] = ['name' => $name];
  9544. }
  9545. $this->success('', null, ['list' => $out]);
  9546. }
  9547. /**
  9548. * 查询询价 — 补加供应商(仅合并更新主表 cGzzxMc,不写明细、不发邮件)
  9549. */
  9550. public function rfqappendsuppliers()
  9551. {
  9552. if (!$this->request->isPost()) {
  9553. $this->error(__('Invalid parameters'));
  9554. }
  9555. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqappendsuppliers'])) {
  9556. $this->error(__('You have no permission'));
  9557. }
  9558. $sid = (int)$this->request->post('scydgy_id', 0);
  9559. if ($sid >= 0) {
  9560. $this->error('仅支持手工新增询价单');
  9561. }
  9562. $po = $this->loadManualRfqOrderForNotify($sid);
  9563. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9564. $this->error('订单已完结,无法补加供应商');
  9565. }
  9566. $raw = $this->request->post('suppliers/a', []);
  9567. if (!is_array($raw) || $raw === []) {
  9568. $suppliersJson = $this->request->post('suppliers_json', '');
  9569. if (is_string($suppliersJson) && $suppliersJson !== '') {
  9570. $decoded = json_decode($suppliersJson, true);
  9571. $raw = is_array($decoded) ? $decoded : [];
  9572. }
  9573. }
  9574. $addNames = [];
  9575. foreach ((array)$raw as $item) {
  9576. if (is_array($item)) {
  9577. $n = trim((string)($item['name'] ?? $item['company_name'] ?? ''));
  9578. } else {
  9579. $n = trim((string)$item);
  9580. }
  9581. if ($n !== '') {
  9582. $addNames[] = $n;
  9583. }
  9584. }
  9585. $addNames = array_values(array_unique($addNames));
  9586. if ($addNames === []) {
  9587. $this->error('请选择要补加的供应商');
  9588. }
  9589. $existingRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9590. if ($existingRaw === '') {
  9591. $existingRaw = trim((string)($po['pick_company_name'] ?? ''));
  9592. }
  9593. $merged = array_merge($this->splitRfqSalesmanNames($existingRaw), $addNames);
  9594. $mergedStr = $this->joinRfqMultiSelectValues($merged);
  9595. try {
  9596. Db::table('purchase_order')->where('scydgy_id', $sid)->update(['cGzzxMc' => $mergedStr]);
  9597. } catch (\Throwable $e) {
  9598. $this->error('保存失败:' . $e->getMessage());
  9599. }
  9600. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9601. $this->addOrderLog($sid, 'rfq_append_supplier', '补加供应商:' . implode('、', $addNames), $poId > 0 ? $poId : null);
  9602. $this->success('已补加供应商', null, [
  9603. 'scydgy_id' => $sid,
  9604. 'cGzzxMc' => $mergedStr,
  9605. 'added_count' => count($addNames),
  9606. ]);
  9607. }
  9608. /**
  9609. * 查询询价 — 下发:按「选择供应商」写入明细并用邮箱通知询价
  9610. */
  9611. public function rfqissue()
  9612. {
  9613. if (!$this->request->isPost()) {
  9614. $this->error(__('Invalid parameters'));
  9615. }
  9616. if (!$this->hasProcuremenPerm(['rfqissue'])) {
  9617. $this->error(__('You have no permission'));
  9618. }
  9619. $this->ensureRfqSupplierEmailTemplate();
  9620. $sid = (int)$this->request->post('scydgy_id', 0);
  9621. if ($sid >= 0) {
  9622. $this->error('仅支持手工新增询价单');
  9623. }
  9624. $po = $this->loadManualRfqOrderForNotify($sid);
  9625. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9626. $this->error('订单已完结,无法下发');
  9627. }
  9628. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9629. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9630. $this->error('订单已进入后续流程,无法再下发');
  9631. }
  9632. $supplierRaw = trim((string)($po['cGzzxMc'] ?? ''));
  9633. if ($supplierRaw === '') {
  9634. $supplierRaw = trim((string)($po['pick_company_name'] ?? ''));
  9635. }
  9636. $supplierNames = $this->splitRfqSalesmanNames($supplierRaw);
  9637. if ($supplierNames === []) {
  9638. $this->error('请先在新增询价时选择供应商');
  9639. }
  9640. $companies = [];
  9641. $missing = [];
  9642. $noEmail = [];
  9643. foreach ($supplierNames as $name) {
  9644. $contact = $this->resolveCustomerContactByCompanyName($name, false);
  9645. if ($contact === null) {
  9646. $missing[] = $name;
  9647. continue;
  9648. }
  9649. $em = trim((string)($contact['email'] ?? ''));
  9650. if ($em === '' || !filter_var($em, FILTER_VALIDATE_EMAIL)) {
  9651. $noEmail[] = $name;
  9652. continue;
  9653. }
  9654. $companies[] = $contact;
  9655. }
  9656. if ($missing !== []) {
  9657. $this->error('未找到供应商档案:' . implode('、', $missing));
  9658. }
  9659. if ($noEmail !== []) {
  9660. $this->error('以下供应商未填写有效邮箱:' . implode('、', $noEmail));
  9661. }
  9662. if ($companies === []) {
  9663. $this->error('没有可通知的供应商');
  9664. }
  9665. $mailConfig = $this->loadMailerConfig();
  9666. if (empty($mailConfig['host'])) {
  9667. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9668. }
  9669. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9670. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9671. }
  9672. $mergeRow = $po;
  9673. $mergeRow['ID'] = $sid;
  9674. $mergeRow['id'] = $sid;
  9675. $mergeRows = [$mergeRow];
  9676. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9677. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9678. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9679. }
  9680. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9681. $issueTime = date('Y-m-d H:i:s');
  9682. $nameLabels = [];
  9683. foreach ($companies as $c) {
  9684. $nameLabels[] = trim((string)($c['name'] ?? ''));
  9685. }
  9686. $logMsg = '询价下发通知供应商(' . count($companies) . ' 家):' . implode('、', $nameLabels);
  9687. Db::startTrans();
  9688. try {
  9689. $this->upsertPurchaseOrderFromRow(
  9690. $mergeRow,
  9691. $sysRqDb,
  9692. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9693. $issueTime,
  9694. $po,
  9695. null,
  9696. $scoreRule
  9697. );
  9698. foreach ($companies as $c) {
  9699. $this->issuePersistSupplierDetails($c, $mergeRows, true, true, false);
  9700. }
  9701. Db::commit();
  9702. } catch (\Throwable $e) {
  9703. Db::rollback();
  9704. $this->error($e->getMessage());
  9705. }
  9706. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9707. if ($poId <= 0) {
  9708. try {
  9709. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9710. } catch (\Throwable $e) {
  9711. $poId = 0;
  9712. }
  9713. }
  9714. $this->addOrderLog($sid, 'issue_submit', $logMsg, $poId > 0 ? $poId : null);
  9715. $posNotify = [];
  9716. try {
  9717. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9718. if (is_array($fresh)) {
  9719. $fresh['sys_rq'] = $sysRqDb;
  9720. $posNotify = [$fresh];
  9721. }
  9722. } catch (\Throwable $e) {
  9723. $posNotify = [$po];
  9724. $posNotify[0]['sys_rq'] = $sysRqDb;
  9725. }
  9726. $notifyBundle = [
  9727. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9728. 'pos' => $posNotify,
  9729. 'merge_rows' => $mergeRows,
  9730. ];
  9731. $notifyErrors = [];
  9732. foreach ($companies as $c) {
  9733. $cname = trim((string)($c['name'] ?? ''));
  9734. try {
  9735. // 询价下发:仅邮箱通知供应商
  9736. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  9737. } catch (\Throwable $e) {
  9738. $notifyErrors[] = ($cname !== '' ? $cname : '供应商') . ':' . $e->getMessage();
  9739. }
  9740. }
  9741. if ($notifyErrors !== []) {
  9742. $this->error('下发已保存,但邮件通知失败:' . implode(';', $notifyErrors));
  9743. }
  9744. $this->success('已询价并邮件通知供应商', null, [
  9745. 'scydgy_id' => $sid,
  9746. 'progress_text' => '待报价',
  9747. 'supplier_count' => count($companies),
  9748. ]);
  9749. }
  9750. /**
  9751. * 查询询价 — 弹窗内向单个供应商发送询价邮件
  9752. */
  9753. public function rfqissuesendmail()
  9754. {
  9755. if (!$this->request->isPost()) {
  9756. $this->error(__('Invalid parameters'));
  9757. }
  9758. if (!$this->hasProcuremenPerm(['rfqissue', 'rfqissuesendmail'])) {
  9759. $this->error(__('You have no permission'));
  9760. }
  9761. $this->ensureRfqSupplierEmailTemplate();
  9762. $sid = (int)$this->request->post('scydgy_id', 0);
  9763. $companyName = trim((string)$this->request->post('company_name', ''));
  9764. if ($sid >= 0) {
  9765. $this->error('仅支持手工新增询价单');
  9766. }
  9767. if ($companyName === '') {
  9768. $this->error('请选择供应商');
  9769. }
  9770. $po = $this->loadManualRfqOrderForNotify($sid);
  9771. if (ProcuremenStatus::isPoCompleted($po['status'] ?? '')) {
  9772. $this->error('订单已完结,无法发送');
  9773. }
  9774. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')
  9775. && !ProcuremenStatus::isWflowPendingConfirm($po['wflow_status'] ?? '')) {
  9776. $this->error('订单已进入后续流程,无法再发送');
  9777. }
  9778. $contact = $this->resolveCustomerContactByCompanyName($companyName, false);
  9779. if ($contact === null) {
  9780. $this->error('未找到供应商档案:' . $companyName);
  9781. }
  9782. $email = trim((string)($contact['email'] ?? ''));
  9783. if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  9784. $this->error('该供应商未填写有效邮箱');
  9785. }
  9786. $mailConfig = $this->loadMailerConfig();
  9787. if (empty($mailConfig['host'])) {
  9788. $this->error('邮件 SMTP 未配置,请检查 config.php 中 Mailer.host');
  9789. }
  9790. if (empty($mailConfig['addr']) || empty($mailConfig['pass'])) {
  9791. $this->error('发件邮箱或授权码未配置,请至后台「邮箱配置」填写');
  9792. }
  9793. $mergeRow = $po;
  9794. $mergeRow['ID'] = $sid;
  9795. $mergeRow['id'] = $sid;
  9796. $mergeRows = [$mergeRow];
  9797. $sysRqDb = trim((string)($po['sys_rq'] ?? ''));
  9798. if ($sysRqDb === '' || stripos($sysRqDb, '0000-00-00') === 0) {
  9799. $sysRqDb = date('Y-m-d 18:00:00', strtotime('+3 days'));
  9800. }
  9801. $scoreRule = ProcuremenSupplierScore::getDefaultRule();
  9802. $issueTime = date('Y-m-d H:i:s');
  9803. Db::startTrans();
  9804. try {
  9805. $this->upsertPurchaseOrderFromRow(
  9806. $mergeRow,
  9807. $sysRqDb,
  9808. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  9809. $issueTime,
  9810. $po,
  9811. null,
  9812. $scoreRule
  9813. );
  9814. $this->issuePersistSupplierDetails($contact, $mergeRows, true, true, false);
  9815. Db::commit();
  9816. } catch (\Throwable $e) {
  9817. Db::rollback();
  9818. $this->error($e->getMessage());
  9819. }
  9820. $posNotify = [];
  9821. try {
  9822. $fresh = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  9823. if (is_array($fresh)) {
  9824. $fresh['sys_rq'] = $sysRqDb;
  9825. $posNotify = [$fresh];
  9826. }
  9827. } catch (\Throwable $e) {
  9828. $posNotify = [$po];
  9829. $posNotify[0]['sys_rq'] = $sysRqDb;
  9830. }
  9831. $notifyBundle = [
  9832. 'ccydh' => trim((string)($po['CCYDH'] ?? '')),
  9833. 'pos' => $posNotify,
  9834. 'merge_rows' => $mergeRows,
  9835. ];
  9836. try {
  9837. $this->sendAuditSupplierNotifyChannels($contact, $mergeRows, $notifyBundle, false, true, 'rfq_supplier', 'rfq_supplier_email');
  9838. } catch (\Throwable $e) {
  9839. $this->error('明细已保存,但邮件发送失败:' . $e->getMessage());
  9840. }
  9841. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  9842. if ($poId <= 0) {
  9843. try {
  9844. $poId = (int)Db::table('purchase_order')->where('scydgy_id', $sid)->value('id');
  9845. } catch (\Throwable $e) {
  9846. $poId = 0;
  9847. }
  9848. }
  9849. $this->addOrderLog($sid, 'issue_submit', '询价邮件通知供应商:' . $companyName, $poId > 0 ? $poId : null);
  9850. $this->success('已向「' . $companyName . '」发送询价邮件', null, [
  9851. 'scydgy_id' => $sid,
  9852. 'company_name' => $companyName,
  9853. ]);
  9854. }
  9855. /**
  9856. * 查询询价 — 查看各供应商报价(单价)
  9857. */
  9858. public function rfqquotes()
  9859. {
  9860. if (!$this->hasProcuremenPerm(['rfqquotes', 'rfqissue'])) {
  9861. $this->error(__('You have no permission'));
  9862. }
  9863. $sid = (int)$this->request->param('scydgy_id', 0);
  9864. if ($sid >= 0) {
  9865. $this->error('仅支持手工新增询价单');
  9866. }
  9867. $po = $this->loadManualRfqOrderForNotify($sid);
  9868. $rows = [];
  9869. try {
  9870. // 表无 updatetime,勿写入 field,否则 Unknown column 被吞掉后弹窗空白
  9871. $q = Db::table('purchase_order_detail')
  9872. ->where('scydgy_id', $sid)
  9873. ->field('id,company_name,amount,status_name,createtime,delivery_createtime,delivery,lead_days')
  9874. ->order('id', 'asc');
  9875. $this->applyActivePurchaseOrderDetailWhere($q);
  9876. $rows = $q->select();
  9877. } catch (\Throwable $e) {
  9878. try {
  9879. $q = Db::table('purchase_order_detail')
  9880. ->where('scydgy_id', $sid)
  9881. ->order('id', 'asc');
  9882. $this->applyActivePurchaseOrderDetailWhere($q);
  9883. $rows = $q->select();
  9884. } catch (\Throwable $e2) {
  9885. $rows = [];
  9886. }
  9887. }
  9888. if (!is_array($rows)) {
  9889. $rows = [];
  9890. }
  9891. $list = [];
  9892. foreach ($rows as $row) {
  9893. if (!is_array($row)) {
  9894. continue;
  9895. }
  9896. $amount = trim((string)($row['amount'] ?? ''));
  9897. $isQuoted = ($amount !== '' && $amount !== '0' && $amount !== '0.00') ? 1 : 0;
  9898. // 未报价不显示时间(createtime 是下发时间,不是报价时间)
  9899. $oper = '';
  9900. if ($isQuoted) {
  9901. $oper = $this->formatProcuremenDetailTime($row['delivery_createtime'] ?? null);
  9902. if ($oper === '') {
  9903. $oper = $this->formatProcuremenDetailTime($row['createtime'] ?? null);
  9904. }
  9905. }
  9906. $list[] = [
  9907. 'id' => (int)($row['id'] ?? 0),
  9908. 'company_name' => trim((string)($row['company_name'] ?? '')),
  9909. 'amount' => $amount,
  9910. 'amount_text' => $isQuoted ? $amount : '',
  9911. 'is_quoted' => $isQuoted,
  9912. 'quote_label' => $isQuoted ? '已报价' : '未报价',
  9913. 'status_name' => trim((string)($row['status_name'] ?? '')),
  9914. 'oper_time' => $oper,
  9915. ];
  9916. }
  9917. $this->success('', null, [
  9918. 'scydgy_id' => $sid,
  9919. 'CCYDH' => trim((string)($po['CCYDH'] ?? '')),
  9920. 'CYJMC' => trim((string)($po['CYJMC'] ?? '')),
  9921. 'CGYMC' => trim((string)($po['CGYMC'] ?? '')),
  9922. 'CDW' => trim((string)($po['CDW'] ?? '')),
  9923. 'This_quantity' => $this->resolveProcuremenThisQuantity($po),
  9924. 'ceilingPrice' => $this->resolveProcuremenCeilingPrice($po),
  9925. 'CDF' => trim((string)($po['CDF'] ?? '')),
  9926. 'MBZ' => trim((string)($po['MBZ'] ?? '')),
  9927. 'list' => $list,
  9928. ]);
  9929. }
  9930. /**
  9931. * 手工询价是否已下发(有下发明细或已进入待确认及之后)
  9932. */
  9933. protected function isRfqOrderIssued(array $po): bool
  9934. {
  9935. if (ProcuremenStatus::wflowAtLeastConfirm($po['wflow_status'] ?? '')) {
  9936. return true;
  9937. }
  9938. $sid = (int)($po['scydgy_id'] ?? 0);
  9939. if ($sid >= 0) {
  9940. return false;
  9941. }
  9942. try {
  9943. $q = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  9944. $this->applyActivePurchaseOrderDetailWhere($q);
  9945. return (int)$q->count() > 0;
  9946. } catch (\Throwable $e) {
  9947. return false;
  9948. }
  9949. }
  9950. /**
  9951. * 批量:已有下发明细的手工询价 scydgy_id
  9952. *
  9953. * @param int[] $scydgyIds
  9954. * @return array<int, bool>
  9955. */
  9956. protected function loadRfqIssuedScydgyIdSet(array $scydgyIds): array
  9957. {
  9958. $set = [];
  9959. $ids = [];
  9960. foreach ($scydgyIds as $sid) {
  9961. $sid = (int)$sid;
  9962. if ($sid < 0) {
  9963. $ids[$sid] = true;
  9964. }
  9965. }
  9966. if ($ids === []) {
  9967. return $set;
  9968. }
  9969. try {
  9970. $q = Db::table('purchase_order_detail')
  9971. ->where('scydgy_id', 'in', array_keys($ids))
  9972. ->field('scydgy_id');
  9973. $this->applyActivePurchaseOrderDetailWhere($q);
  9974. $rows = $q->select();
  9975. } catch (\Throwable $e) {
  9976. return $set;
  9977. }
  9978. if (!is_array($rows)) {
  9979. return $set;
  9980. }
  9981. foreach ($rows as $row) {
  9982. if (!is_array($row)) {
  9983. continue;
  9984. }
  9985. $sid = (int)($row['scydgy_id'] ?? 0);
  9986. if ($sid < 0) {
  9987. $set[$sid] = true;
  9988. }
  9989. }
  9990. return $set;
  9991. }
  9992. /**
  9993. * 批量:已填单价(已报价)的手工询价 scydgy_id
  9994. *
  9995. * @param int[] $scydgyIds
  9996. * @return array<int, bool>
  9997. */
  9998. protected function loadRfqQuotedScydgyIdSet(array $scydgyIds): array
  9999. {
  10000. $set = [];
  10001. $ids = [];
  10002. foreach ($scydgyIds as $sid) {
  10003. $sid = (int)$sid;
  10004. if ($sid < 0) {
  10005. $ids[$sid] = true;
  10006. }
  10007. }
  10008. if ($ids === []) {
  10009. return $set;
  10010. }
  10011. try {
  10012. $q = Db::table('purchase_order_detail')
  10013. ->where('scydgy_id', 'in', array_keys($ids))
  10014. ->field('scydgy_id,amount');
  10015. $this->applyActivePurchaseOrderDetailWhere($q);
  10016. $rows = $q->select();
  10017. } catch (\Throwable $e) {
  10018. return $set;
  10019. }
  10020. if (!is_array($rows)) {
  10021. return $set;
  10022. }
  10023. foreach ($rows as $row) {
  10024. if (!is_array($row)) {
  10025. continue;
  10026. }
  10027. $amount = trim((string)($row['amount'] ?? ''));
  10028. if ($amount === '' || $amount === '0' || $amount === '0.00') {
  10029. continue;
  10030. }
  10031. $sid = (int)($row['scydgy_id'] ?? 0);
  10032. if ($sid < 0) {
  10033. $set[$sid] = true;
  10034. }
  10035. }
  10036. return $set;
  10037. }
  10038. /**
  10039. * 已下发且至少一家供应商已报价,才允许通知业务员
  10040. */
  10041. protected function canRfqNotifySalesman(array $po): bool
  10042. {
  10043. if (!$this->isRfqOrderIssued($po)) {
  10044. return false;
  10045. }
  10046. $sid = (int)($po['scydgy_id'] ?? 0);
  10047. if ($sid >= 0) {
  10048. return false;
  10049. }
  10050. $quoted = $this->loadRfqQuotedScydgyIdSet([$sid]);
  10051. return isset($quoted[$sid]);
  10052. }
  10053. protected function assertRfqCanNotifySalesman(array $po): void
  10054. {
  10055. if (!$this->isRfqOrderIssued($po)) {
  10056. $this->error('请先询价并等待供应商报价后再通知业务员');
  10057. }
  10058. if (!$this->canRfqNotifySalesman($po)) {
  10059. $this->error('供应商尚未报价,暂不能通知业务员');
  10060. }
  10061. }
  10062. /**
  10063. * 加载手工询价单(含可见性校验)
  10064. *
  10065. * @return array<string, mixed>
  10066. */
  10067. protected function loadManualRfqOrderForNotify(int $scydgyId): array
  10068. {
  10069. try {
  10070. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10071. } catch (\Throwable $e) {
  10072. $po = null;
  10073. }
  10074. if (!is_array($po)) {
  10075. $this->error('订单不存在');
  10076. }
  10077. $modRq = trim((string)($po['mod_rq'] ?? ''));
  10078. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  10079. $this->error('订单不存在');
  10080. }
  10081. if ($this->auth->isSuperAdmin()) {
  10082. return $po;
  10083. }
  10084. if ($this->canViewManualRfqOrder($po)) {
  10085. return $po;
  10086. }
  10087. $this->error('无权操作该订单');
  10088. }
  10089. /**
  10090. * @return string[]
  10091. */
  10092. protected function splitRfqSalesmanNames(string $raw): array
  10093. {
  10094. $parts = [];
  10095. $raw = trim($raw);
  10096. if ($raw === '') {
  10097. return [];
  10098. }
  10099. foreach (preg_split('/[\n\r、;;,,]+/u', $raw) as $piece) {
  10100. $v = trim((string)$piece);
  10101. if ($v !== '' && !in_array($v, $parts, true)) {
  10102. $parts[] = $v;
  10103. }
  10104. }
  10105. return $parts;
  10106. }
  10107. /**
  10108. * 按姓名匹配 fa_admin 邮箱
  10109. *
  10110. * @param string[] $names
  10111. * @return array<int, array{admin_id:int,name:string,email:string}>
  10112. */
  10113. protected function resolveRfqSalesmanContactRows(array $names): array
  10114. {
  10115. $out = [];
  10116. foreach ($names as $name) {
  10117. $name = trim((string)$name);
  10118. if ($name === '') {
  10119. continue;
  10120. }
  10121. $adminId = 0;
  10122. $email = '';
  10123. try {
  10124. $row = Db::name('admin')
  10125. ->where(function ($q) use ($name) {
  10126. $q->where('nickname', $name)->whereOr('username', $name);
  10127. })
  10128. ->where('status', 'normal')
  10129. ->order('id', 'asc')
  10130. ->field('id,nickname,username,email')
  10131. ->find();
  10132. } catch (\Throwable $e) {
  10133. $row = null;
  10134. }
  10135. if (is_array($row)) {
  10136. $adminId = (int)($row['id'] ?? 0);
  10137. $email = trim((string)($row['email'] ?? ''));
  10138. $disp = trim((string)($row['nickname'] ?? ''));
  10139. if ($disp === '') {
  10140. $disp = trim((string)($row['username'] ?? ''));
  10141. }
  10142. if ($disp !== '') {
  10143. $name = $disp;
  10144. }
  10145. }
  10146. $out[] = [
  10147. 'admin_id' => $adminId,
  10148. 'name' => $name,
  10149. 'email' => $email,
  10150. ];
  10151. }
  10152. return $out;
  10153. }
  10154. /**
  10155. * 手工新增工序详情:业务员只看本人;超管及协助流程岗位可看全部
  10156. */
  10157. protected function assertManualOrderDetailsViewable(int $scydgyId): void
  10158. {
  10159. if ($scydgyId >= 0) {
  10160. return;
  10161. }
  10162. try {
  10163. $po = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  10164. } catch (\Throwable $e) {
  10165. $po = null;
  10166. }
  10167. if (!is_array($po)) {
  10168. $this->error('订单不存在');
  10169. }
  10170. $modRq = trim((string)($po['mod_rq'] ?? ''));
  10171. if ($modRq !== '' && stripos($modRq, '0000-00-00') !== 0) {
  10172. $this->error('订单不存在');
  10173. }
  10174. if ($this->auth->isSuperAdmin()) {
  10175. return;
  10176. }
  10177. [, $adminName] = $this->GetUseName();
  10178. $cywy = trim((string)($po['cywyxm'] ?? ''));
  10179. if ($cywy !== '' && $cywy === $adminName) {
  10180. return;
  10181. }
  10182. foreach (['procuremen/pick', 'procuremen/audit', 'procuremen/confirm', 'procuremen/index'] as $rule) {
  10183. try {
  10184. if ($this->auth->check($rule)) {
  10185. return;
  10186. }
  10187. } catch (\Throwable $e) {
  10188. }
  10189. }
  10190. $this->error('无权查看该订单');
  10191. }
  10192. /**
  10193. * 手工询价进度:待询价 → 待报价(已发邮件)→ 供应商已报价 → 已通知业务员
  10194. */
  10195. protected function formatProcuremenRfqProgressText(array $row, bool $hasIssued = false, bool $hasQuoted = false): string
  10196. {
  10197. if (ProcuremenStatus::isPoCompleted($row['status'] ?? '')) {
  10198. return ProcuremenStatus::PO_COMPLETED;
  10199. }
  10200. $sid = (int)($row['scydgy_id'] ?? 0);
  10201. if ($sid < 0) {
  10202. if ((int)($row['rfq_salesman_notified'] ?? 0) === 1) {
  10203. return '已通知业务员';
  10204. }
  10205. if ($hasQuoted) {
  10206. return '供应商已报价';
  10207. }
  10208. if ($hasIssued
  10209. || ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')
  10210. || ProcuremenStatus::wflowAtLeastConfirm($row['wflow_status'] ?? '')) {
  10211. return '待报价';
  10212. }
  10213. try {
  10214. $detCntQuery = Db::table('purchase_order_detail')->where('scydgy_id', $sid);
  10215. $this->applyActivePurchaseOrderDetailWhere($detCntQuery);
  10216. if ((int)$detCntQuery->count() > 0) {
  10217. return '待报价';
  10218. }
  10219. } catch (\Throwable $e) {
  10220. }
  10221. return '待询价';
  10222. }
  10223. if (ProcuremenStatus::isWflowApproved($row['wflow_status'] ?? '')) {
  10224. return '待入库评分';
  10225. }
  10226. if (ProcuremenStatus::isWflowPendingApproval($row['wflow_status'] ?? '')) {
  10227. return '待采购确认';
  10228. }
  10229. if (ProcuremenStatus::isWflowPendingConfirm($row['wflow_status'] ?? '')) {
  10230. return '待确认供应商';
  10231. }
  10232. return '待协助下发';
  10233. }
  10234. /**
  10235. * 协助初选列表 — 批量软删除
  10236. */
  10237. public function pickDelete()
  10238. {
  10239. if (!$this->request->isPost() || !$this->request->isAjax()) {
  10240. $this->error(__('Invalid parameters'));
  10241. }
  10242. if (!$this->procuremenCanPickDelete()) {
  10243. $this->error(__('You have no permission'));
  10244. }
  10245. $rowsRaw = $this->request->post('rows_json', '[]');
  10246. $rows = json_decode(is_string($rowsRaw) ? $rowsRaw : '', true);
  10247. if (!is_array($rows) || $rows === []) {
  10248. $this->error('请至少勾选一条工序');
  10249. }
  10250. $done = 0;
  10251. Db::startTrans();
  10252. try {
  10253. foreach ($rows as $row) {
  10254. if (!is_array($row)) {
  10255. continue;
  10256. }
  10257. $this->softDeleteProcuremenPickRow($row);
  10258. $done++;
  10259. }
  10260. if ($done < 1) {
  10261. throw new \Exception('没有可删除的工序');
  10262. }
  10263. Db::commit();
  10264. } catch (\InvalidArgumentException $e) {
  10265. Db::rollback();
  10266. $this->error($e->getMessage());
  10267. } catch (\Throwable $e) {
  10268. Db::rollback();
  10269. $this->error($e->getMessage());
  10270. }
  10271. $this->pickHiddenScydgySetCache = null;
  10272. $this->success('已删除 ' . $done . ' 条工序');
  10273. }
  10274. /**
  10275. * 下发 — 手工新增工序(弹窗)
  10276. */
  10277. public function pickAdd()
  10278. {
  10279. if ($this->request->isPost()) {
  10280. $params = $this->request->post('row/a');
  10281. if (!is_array($params)) {
  10282. $this->error(__('Parameter %s can not be empty', ''));
  10283. }
  10284. try {
  10285. $sid = $this->saveManualPickOrder($params);
  10286. } catch (\InvalidArgumentException $e) {
  10287. $this->error($e->getMessage());
  10288. } catch (\Throwable $e) {
  10289. $this->error($e->getMessage());
  10290. }
  10291. $this->success('新增成功', '', ['scydgy_id' => $sid]);
  10292. }
  10293. return $this->view->fetch('procuremen/pick_add');
  10294. }
  10295. /**
  10296. * 下发提交 — 通知供应商 → POST procuremen/picksubmit
  10297. */
  10298. public function pickSubmit()
  10299. {
  10300. if (!$this->request->isPost()) {
  10301. $this->error(__('Invalid parameters'));
  10302. }
  10303. // ---------- 接口订单数据 ----------
  10304. $rowJson = $this->request->post('row_json', '');
  10305. $mergeRowsJson = $this->request->post('merge_rows_json', '');
  10306. $companiesJson = $this->request->post('companies_json', '[]');
  10307. $mergeRows = $this->parseReviewMergeRows($rowJson, $mergeRowsJson);
  10308. $companies = json_decode($companiesJson, true);
  10309. if (!is_array($companies)) {
  10310. $this->error('供应商数据无效');
  10311. }
  10312. $issueCompanies = $this->normalizePickCompanies($companies);
  10313. if ($issueCompanies === []) {
  10314. $this->error('请至少选择一家合作供应商');
  10315. }
  10316. $issueNameLabels = [];
  10317. foreach ($issueCompanies as $pc) {
  10318. $issueNameLabels[] = $pc['name'];
  10319. }
  10320. $issueNamesSummary = implode('、', $issueNameLabels);
  10321. $sysRq = trim((string)$this->request->post('sys_rq', ''));
  10322. if ($sysRq === '') {
  10323. $this->error('请选择招标截止日期');
  10324. }
  10325. $sysRqDb = $this->parseProcuremenSysRqInput($sysRq, true);
  10326. $deliveryDeadlineDb = $this->parseProcuremenDeliveryDeadlineInput(
  10327. (string)$this->request->post('delivery_deadline', ''),
  10328. true
  10329. );
  10330. $scoreRuleId = (int)$this->request->post('score_rule_id', 0);
  10331. if ($scoreRuleId <= 0) {
  10332. $this->error('请选择订单类型');
  10333. }
  10334. $scoreRule = ProcuremenSupplierScore::getRuleById($scoreRuleId);
  10335. if ((int)($scoreRule['id'] ?? 0) <= 0) {
  10336. $this->error('订单类型无效,请刷新后重选');
  10337. }
  10338. $scoreRuleId = (int)$scoreRule['id'];
  10339. $this->ensurePurchaseOrderScoreRuleIdColumn();
  10340. $isMerge = count($mergeRows) > 1;
  10341. $procPart = $isMerge ? '(' . count($mergeRows) . ' 道工序)' : '';
  10342. $logMsg = '下发' . $procPart
  10343. . '通知供应商(' . count($issueCompanies) . ' 家):' . $issueNamesSummary;
  10344. $issueTime = date('Y-m-d H:i:s');
  10345. $logSidList = [];
  10346. foreach ($mergeRows as $row) {
  10347. if (!is_array($row)) {
  10348. continue;
  10349. }
  10350. $sid = $this->extractScydgyRowId($row);
  10351. if ($this->isValidScydgyRowId($sid)) {
  10352. $logSidList[$sid] = true;
  10353. }
  10354. }
  10355. $existingBySid = [];
  10356. if ($logSidList !== []) {
  10357. try {
  10358. $existingRows = Db::table('purchase_order')
  10359. ->where('scydgy_id', 'in', array_keys($logSidList))
  10360. ->select();
  10361. if (is_array($existingRows)) {
  10362. foreach ($existingRows as $poRow) {
  10363. if (!is_array($poRow)) {
  10364. continue;
  10365. }
  10366. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10367. if ($this->isValidScydgyRowId($sid)) {
  10368. $existingBySid[$sid] = $poRow;
  10369. }
  10370. }
  10371. }
  10372. } catch (\Throwable $e) {
  10373. $existingBySid = [];
  10374. }
  10375. }
  10376. Db::startTrans();
  10377. try {
  10378. // ---------- 主表 wflow_status=待确认;明细写入 purchase_order_detail,随后向供应商发短信/邮件 ----------
  10379. foreach ($mergeRows as $row) {
  10380. if (!is_array($row)) {
  10381. continue;
  10382. }
  10383. $sid = $this->extractScydgyRowId($row);
  10384. $this->upsertPurchaseOrderFromRow(
  10385. $row,
  10386. $sysRqDb,
  10387. ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  10388. $issueTime,
  10389. $this->isValidScydgyRowId($sid) ? ($existingBySid[$sid] ?? null) : null,
  10390. $deliveryDeadlineDb,
  10391. $scoreRule
  10392. );
  10393. }
  10394. foreach ($issueCompanies as $c) {
  10395. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10396. }
  10397. Db::commit();
  10398. } catch (\Throwable $e) {
  10399. Db::rollback();
  10400. $this->error($e->getMessage());
  10401. }
  10402. $poIdBySid = [];
  10403. if ($logSidList !== []) {
  10404. try {
  10405. $poIdBySid = Db::table('purchase_order')
  10406. ->where('scydgy_id', 'in', array_keys($logSidList))
  10407. ->column('id', 'scydgy_id');
  10408. } catch (\Throwable $e) {
  10409. $poIdBySid = [];
  10410. }
  10411. }
  10412. // ---------- 操作日志记录(批量写入,减少提交等待) ----------
  10413. if ($logSidList !== []) {
  10414. list($adminId, $adminName) = $this->GetUseName();
  10415. $logRows = [];
  10416. $seenLogSid = [];
  10417. foreach ($mergeRows as $row) {
  10418. if (!is_array($row)) {
  10419. continue;
  10420. }
  10421. $ids = $this->extractScydgyRowId($row);
  10422. if (!$this->isValidScydgyRowId($ids) || isset($seenLogSid[$ids])) {
  10423. continue;
  10424. }
  10425. $seenLogSid[$ids] = true;
  10426. $poIdLog = null;
  10427. if (isset($poIdBySid[$ids])) {
  10428. $tid = (int)$poIdBySid[$ids];
  10429. $poIdLog = $tid > 0 ? $tid : null;
  10430. }
  10431. $logRows[] = ProcuremenOperLog::buildInsertRow(
  10432. $ids,
  10433. 'issue_submit',
  10434. $logMsg,
  10435. $poIdLog,
  10436. (int)$adminId,
  10437. (string)$adminName
  10438. );
  10439. }
  10440. if ($logRows !== []) {
  10441. try {
  10442. Db::table('purchase_order_oper_log')->insertAll($logRows);
  10443. } catch (\Throwable $e) {
  10444. Log::write('procuremen pickSubmit batch log: ' . $e->getMessage(), 'error');
  10445. }
  10446. }
  10447. }
  10448. $notifyErrors = [];
  10449. $posNotify = [];
  10450. if ($logSidList !== []) {
  10451. try {
  10452. $posNotify = Db::table('purchase_order')->where('scydgy_id', 'in', array_keys($logSidList))->select();
  10453. } catch (\Throwable $e) {
  10454. $posNotify = [];
  10455. }
  10456. }
  10457. if (!is_array($posNotify)) {
  10458. $posNotify = [];
  10459. }
  10460. foreach ($posNotify as $i => $prow) {
  10461. if (is_array($posNotify[$i])) {
  10462. $posNotify[$i]['sys_rq'] = $sysRqDb;
  10463. }
  10464. }
  10465. $ccydhPick = '';
  10466. foreach ($mergeRows as $row) {
  10467. if (!is_array($row)) {
  10468. continue;
  10469. }
  10470. $ccydhPick = trim((string)($row['CCYDH'] ?? ''));
  10471. if ($ccydhPick !== '') {
  10472. break;
  10473. }
  10474. }
  10475. $notifyBundleBase = [
  10476. 'ccydh' => $ccydhPick,
  10477. 'pos' => $posNotify,
  10478. 'merge_rows' => $mergeRows,
  10479. 'score_rule' => is_array($scoreRule) ? $scoreRule : null,
  10480. ];
  10481. try {
  10482. $this->notifyDryRunPreview = [];
  10483. foreach ($issueCompanies as $c) {
  10484. if (!is_array($c)) {
  10485. continue;
  10486. }
  10487. $cname = trim((string)($c['name'] ?? ''));
  10488. if ($cname === '') {
  10489. continue;
  10490. }
  10491. try {
  10492. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true);
  10493. } catch (\Throwable $e) {
  10494. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10495. }
  10496. }
  10497. } catch (\Throwable $e) {
  10498. $this->error('通知发送失败:' . $e->getMessage());
  10499. }
  10500. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10501. $this->error('部分供应商通知失败:' . implode(';', $notifyErrors));
  10502. }
  10503. if ($this->isProcuremenNotifyDryRun()) {
  10504. $this->success('【演练模式】已保存并生成通知预览', '', [
  10505. 'notify_dry_run' => true,
  10506. 'notify_preview' => $this->notifyDryRunPreview,
  10507. ]);
  10508. }
  10509. $this->success('已向 ' . count($issueCompanies) . ' 家供应商发送短信与邮件,请至「协助审批下发」确认供应商');
  10510. }
  10511. /**
  10512. * 确认供应商弹窗
  10513. */
  10514. public function auditIssue()
  10515. {
  10516. $ids = $this->request->param('ids', $this->request->param('id', ''));
  10517. if (is_array($ids)) {
  10518. $ids = isset($ids[0]) ? $ids[0] : '';
  10519. }
  10520. $ids = trim((string)$ids);
  10521. if ($ids === '') {
  10522. $this->error(__('Invalid parameters'));
  10523. }
  10524. if ($this->request->isPost()) {
  10525. $this->error('请使用弹窗内「确认」提交');
  10526. }
  10527. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10528. $pos = $bundle['pos'];
  10529. if ($pos === []) {
  10530. $this->error('该订单不在待确认供应商状态');
  10531. }
  10532. $po = $pos[0];
  10533. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10534. if ($quoteGroups === []) {
  10535. $this->error('暂无下发明细,请确认该订单已在「协助初选」完成下发');
  10536. }
  10537. $pickedName = '';
  10538. foreach ($pos as $poRow) {
  10539. if (!is_array($poRow)) {
  10540. continue;
  10541. }
  10542. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  10543. if ($pn !== '') {
  10544. $pickedName = $pn;
  10545. break;
  10546. }
  10547. }
  10548. $this->view->assign('po', $po);
  10549. $this->view->assign('scydgyId', $ids);
  10550. $this->view->assign('orderCcydh', $bundle['ccydh']);
  10551. $mergeRows = $bundle['merge_rows'];
  10552. $this->view->assign('processRows', $mergeRows);
  10553. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows($mergeRows));
  10554. $this->view->assign('processCount', count($mergeRows));
  10555. $this->view->assign('quoteGroups', $this->maskSupplierContactList($quoteGroups));
  10556. $this->view->assign('quoteGroupsJson', json_encode($this->maskSupplierContactList($quoteGroups), JSON_UNESCAPED_UNICODE));
  10557. $this->view->assign('pickedCompanyName', $pickedName);
  10558. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10559. if ($sysRqForView === '') {
  10560. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10561. }
  10562. $this->view->assign('sysRq', $sysRqForView);
  10563. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? null);
  10564. if ($deliveryDeadlineForView === '') {
  10565. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10566. }
  10567. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10568. $this->ensurePurchaseOrderManualPickColumns();
  10569. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($bundle) ? 1 : 0;
  10570. $manualPickInfo = $this->resolveProcuremenManualPickInfo($bundle);
  10571. $manualPicked = $this->isProcuremenManualPickedForBundle($bundle) ? 1 : 0;
  10572. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  10573. if ($manualPicked && $pickedName === '' && $manualPickInfo['company'] !== '') {
  10574. $pickedName = $manualPickInfo['company'];
  10575. $this->view->assign('pickedCompanyName', $pickedName);
  10576. }
  10577. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  10578. $this->view->assign('manualPicked', $manualPicked);
  10579. $this->view->assign('manualPickReason', $manualPickInfo['reason']);
  10580. $this->view->assign('quoteVisible', $quoteVisible);
  10581. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($bundle['ccydh'] ?? ''));
  10582. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  10583. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($quoteGroups, $orderScoreRule));
  10584. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($quoteGroups, $orderScoreRule) ? 1 : 0);
  10585. $quoteDeadlineReached = $this->isProcuremenQuoteDeadlineReached($this->resolveBundleSysRq($bundle)) ? 1 : 0;
  10586. $this->view->assign('quoteDeadlineReached', $quoteDeadlineReached);
  10587. $this->view->assign('canAppendSupplier', $this->canProcuremenAppendSupplierForBundle($bundle) ? 1 : 0);
  10588. $this->view->assign('appendSupplierDeadlinePassed', $this->canProcuremenAppendSupplierActionForBundle($bundle) ? 0 : 1);
  10589. return $this->view->fetch('procuremen/audit_issue');
  10590. }
  10591. /**
  10592. * 确认页是否显示补加供应商按钮:未开标即可显示(超截止点击时再提示)
  10593. *
  10594. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10595. */
  10596. protected function canProcuremenAppendSupplierForBundle(array $bundle): bool
  10597. {
  10598. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10599. return false;
  10600. }
  10601. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10602. return false;
  10603. }
  10604. return true;
  10605. }
  10606. /**
  10607. * 是否允许实际执行补加:未开标且未过招标截止(无截止时间时允许)
  10608. *
  10609. * @param array{ccydh?:string,pos?:array,merge_rows?:array} $bundle
  10610. */
  10611. protected function canProcuremenAppendSupplierActionForBundle(array $bundle): bool
  10612. {
  10613. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10614. return false;
  10615. }
  10616. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10617. return false;
  10618. }
  10619. $sysRq = trim((string)$this->resolveBundleSysRq($bundle));
  10620. if ($sysRq === '' || preg_match('/^0000-00-00/i', $sysRq)) {
  10621. return true;
  10622. }
  10623. return !$this->isProcuremenQuoteDeadlineReached($sysRq);
  10624. }
  10625. /**
  10626. * 确认页 — 补加供应商弹窗
  10627. */
  10628. public function auditAppend()
  10629. {
  10630. if (!$this->hasProcuremenPermStrict(['auditappend'])) {
  10631. $this->error(__('You have no permission'));
  10632. }
  10633. $ids = $this->request->param('scydgy_id', $this->request->param('ids', $this->request->param('id', '')));
  10634. if (is_array($ids)) {
  10635. $ids = isset($ids[0]) ? $ids[0] : '';
  10636. }
  10637. $ids = trim((string)$ids);
  10638. if ($ids === '') {
  10639. $this->error(__('Invalid parameters'));
  10640. }
  10641. if ($this->request->isPost()) {
  10642. $this->error('请使用弹窗内「确认」提交');
  10643. }
  10644. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10645. if (($bundle['pos'] ?? []) === []) {
  10646. $this->error('该订单不在待确认供应商状态');
  10647. }
  10648. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10649. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10650. $this->error('已开标验证,不能再补加供应商');
  10651. }
  10652. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10653. $this->error('已指定供应商,不能再补加供应商');
  10654. }
  10655. $this->error('已经超过了招标截止日期,不可操作');
  10656. }
  10657. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10658. $existingNames = [];
  10659. foreach ($quoteGroups as $g) {
  10660. if (!is_array($g)) {
  10661. continue;
  10662. }
  10663. $n = trim((string)($g['company_name'] ?? $g['name'] ?? ''));
  10664. if ($n !== '') {
  10665. $existingNames[$n] = true;
  10666. }
  10667. }
  10668. $po = is_array($bundle['pos'][0] ?? null) ? $bundle['pos'][0] : [];
  10669. $mergeRows = $bundle['merge_rows'] ?? [];
  10670. $this->view->assign('scydgyId', $ids);
  10671. $this->view->assign('orderCcydh', $bundle['ccydh'] ?? '');
  10672. $this->view->assign('po', $po);
  10673. $this->view->assign('processDisplayRows', $this->buildAuditProcessDisplayRows(is_array($mergeRows) ? $mergeRows : []));
  10674. $this->view->assign('existingCompanyNames', array_keys($existingNames));
  10675. $this->view->assign('existingCompanyNamesJson', json_encode(array_keys($existingNames), JSON_UNESCAPED_UNICODE));
  10676. $sysRqForView = $this->formatProcuremenSysRqForInput($po['sys_rq'] ?? null);
  10677. if ($sysRqForView === '') {
  10678. $sysRqForView = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  10679. }
  10680. $this->view->assign('sysRq', $sysRqForView);
  10681. $deliveryDeadlineForView = $this->formatProcuremenDeliveryDeadlineForInput($po['delivery_deadline'] ?? '');
  10682. if ($deliveryDeadlineForView === '') {
  10683. $deliveryDeadlineForView = $this->resolveBundleDeliveryDeadline($bundle);
  10684. }
  10685. $this->view->assign('deliveryDeadline', $deliveryDeadlineForView);
  10686. return $this->fetchProcuremenDialogLite('procuremen/audit_append', '补加供应商');
  10687. }
  10688. /**
  10689. * 确认页 — 补加供应商提交
  10690. */
  10691. public function auditAppendSubmit()
  10692. {
  10693. if (!$this->request->isPost()) {
  10694. $this->error(__('Invalid parameters'));
  10695. }
  10696. if (!$this->hasProcuremenPermStrict(['auditappendsubmit', 'auditappend'])) {
  10697. $this->error(__('You have no permission'));
  10698. }
  10699. $ids = trim((string)$this->request->post('scydgy_id', $this->request->post('ids', '')));
  10700. if ($ids === '') {
  10701. $this->error(__('Invalid parameters'));
  10702. }
  10703. $bundle = $this->loadAuditOrderBundleByScydgyId($ids);
  10704. if (($bundle['pos'] ?? []) === []) {
  10705. $this->error('该订单不在待确认供应商状态');
  10706. }
  10707. if (!$this->canProcuremenAppendSupplierActionForBundle($bundle)) {
  10708. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10709. $this->error('已开标验证,不能再补加供应商');
  10710. }
  10711. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10712. $this->error('已指定供应商,不能再补加供应商');
  10713. }
  10714. $this->error('已经超过了招标截止日期,不可操作');
  10715. }
  10716. $companiesJson = $this->request->post('companies_json', '[]');
  10717. $companies = json_decode((string)$companiesJson, true);
  10718. if (!is_array($companies)) {
  10719. $this->error('供应商数据无效');
  10720. }
  10721. $issueCompanies = $this->normalizePickCompanies($companies);
  10722. if ($issueCompanies === []) {
  10723. $this->error('请至少选择一家合作供应商');
  10724. }
  10725. $mergeRows = $bundle['merge_rows'] ?? [];
  10726. if (!is_array($mergeRows) || $mergeRows === []) {
  10727. $this->error('未找到工序行,无法补加');
  10728. }
  10729. $existingNames = [];
  10730. foreach ($this->loadAuditSupplierQuoteGroups($bundle) as $g) {
  10731. if (!is_array($g)) {
  10732. continue;
  10733. }
  10734. $n = trim((string)($g['company_name'] ?? ''));
  10735. if ($n !== '') {
  10736. $existingNames[$n] = true;
  10737. }
  10738. }
  10739. $toAdd = [];
  10740. foreach ($issueCompanies as $c) {
  10741. if (!is_array($c)) {
  10742. continue;
  10743. }
  10744. $n = trim((string)($c['name'] ?? ''));
  10745. if ($n === '' || isset($existingNames[$n])) {
  10746. continue;
  10747. }
  10748. $toAdd[] = $c;
  10749. }
  10750. if ($toAdd === []) {
  10751. $this->error('所选供应商均已在本单中,请选择新的供应商');
  10752. }
  10753. $addedNames = [];
  10754. Db::startTrans();
  10755. try {
  10756. foreach ($toAdd as $c) {
  10757. $this->issuePersistSupplierDetails($c, $mergeRows, false, true);
  10758. $addedNames[] = trim((string)($c['name'] ?? ''));
  10759. }
  10760. Db::commit();
  10761. } catch (\Throwable $e) {
  10762. Db::rollback();
  10763. $this->error($e->getMessage());
  10764. }
  10765. $notifyErrors = [];
  10766. $notifyBundleBase = [
  10767. 'ccydh' => $bundle['ccydh'] ?? '',
  10768. 'pos' => $bundle['pos'] ?? [],
  10769. 'merge_rows' => $mergeRows,
  10770. ];
  10771. foreach ($toAdd as $c) {
  10772. if (!is_array($c)) {
  10773. continue;
  10774. }
  10775. $cname = trim((string)($c['name'] ?? ''));
  10776. if ($cname === '') {
  10777. continue;
  10778. }
  10779. try {
  10780. $this->sendAuditSupplierNotifyChannels($c, $mergeRows, $notifyBundleBase, true, true, 'audit_append');
  10781. } catch (\Throwable $e) {
  10782. $notifyErrors[] = $cname . ':' . $e->getMessage();
  10783. }
  10784. }
  10785. $logMsg = '补加供应商(' . count($toAdd) . ' 家):' . implode('、', array_filter($addedNames));
  10786. $seenLogSid = [];
  10787. foreach ($bundle['pos'] ?? [] as $poRow) {
  10788. if (!is_array($poRow)) {
  10789. continue;
  10790. }
  10791. $sid = (int)($poRow['scydgy_id'] ?? 0);
  10792. if (!$this->isValidScydgyRowId($sid) || isset($seenLogSid[$sid])) {
  10793. continue;
  10794. }
  10795. $seenLogSid[$sid] = true;
  10796. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  10797. $this->addOrderLog($sid, 'audit_append_supplier', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  10798. }
  10799. if ($seenLogSid === []) {
  10800. $logSid = $this->extractScydgyRowId(is_array($mergeRows[0] ?? null) ? $mergeRows[0] : []);
  10801. if ($this->isValidScydgyRowId($logSid)) {
  10802. $this->addOrderLog($logSid, 'audit_append_supplier', $logMsg, null);
  10803. }
  10804. }
  10805. if ($notifyErrors !== [] && !$this->isProcuremenNotifyDryRun()) {
  10806. $this->error('已写入明细,但部分通知失败:' . implode(';', $notifyErrors));
  10807. }
  10808. $this->success('已补加 ' . count($toAdd) . ' 家供应商并发送通知');
  10809. }
  10810. /**
  10811. * 开标双重验证 — 可选验证人列表
  10812. */
  10813. public function bidOpenUsers()
  10814. {
  10815. if (!$this->hasProcuremenPerm(['bidopenusers', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10816. $this->error('无权限');
  10817. }
  10818. $scydgyId = trim((string)$this->request->param('scydgy_id', $this->request->param('ids', '')));
  10819. if ($scydgyId !== '') {
  10820. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10821. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10822. $this->success('已完成开标验证', null, [
  10823. 'verified' => 1,
  10824. 'users' => [],
  10825. ]);
  10826. }
  10827. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10828. $this->error('本单已指定供应商,无需再开标');
  10829. }
  10830. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10831. }
  10832. $this->success('', null, [
  10833. 'verified' => 0,
  10834. 'users' => $this->listBidOpenVerifierCandidates(),
  10835. ]);
  10836. }
  10837. /**
  10838. * 开标双重验证 — 向指定管理员发送短信验证码
  10839. */
  10840. public function bidOpenSendCode()
  10841. {
  10842. if (!$this->request->isPost()) {
  10843. $this->error(__('Invalid parameters'));
  10844. }
  10845. if (!$this->hasProcuremenPerm(['bidopensendcode', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10846. $this->error('无权限');
  10847. }
  10848. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10849. $adminId = (int)$this->request->post('admin_id', 0);
  10850. if ($scydgyId === '' || $adminId <= 0) {
  10851. $this->error('参数无效');
  10852. }
  10853. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10854. if ($bundle['pos'] === []) {
  10855. $this->error('该订单不在待确认供应商状态');
  10856. }
  10857. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10858. $this->success('已完成开标验证,无需重复发送');
  10859. }
  10860. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10861. $this->error('本单已指定供应商,无需再开标');
  10862. }
  10863. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10864. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10865. if ($ccydh === '') {
  10866. $this->error('订单号无效');
  10867. }
  10868. $admin = $this->loadBidOpenAdminUser($adminId);
  10869. if ($admin === null) {
  10870. $this->error('验证人无效或未绑定手机号');
  10871. }
  10872. $cd = (int)(Config::get('mproc.sms_resend_cd') ?: 55);
  10873. $cd = max(30, min(120, $cd));
  10874. if (Cache::get($this->bidOpenSmsWaitCacheKey($adminId))) {
  10875. $this->error('发送过于频繁,请稍后再试');
  10876. }
  10877. $code = (string)random_int(100000, 999999);
  10878. $ttl = (int)(Config::get('mproc.sms_code_ttl') ?: 300);
  10879. $ttl = max(60, min(600, $ttl));
  10880. Cache::set($this->bidOpenSmsCacheKey($adminId, $ccydh), $code, $ttl);
  10881. Cache::set($this->bidOpenSmsWaitCacheKey($adminId), 1, $cd);
  10882. try {
  10883. $this->sendBidOpenVerifySms($admin['mobile'], $code);
  10884. } catch (\Throwable $e) {
  10885. Cache::rm($this->bidOpenSmsCacheKey($adminId, $ccydh));
  10886. Cache::rm($this->bidOpenSmsWaitCacheKey($adminId));
  10887. $this->error($e->getMessage());
  10888. }
  10889. $this->success('验证码已发送至「' . ($admin['nickname'] !== '' ? $admin['nickname'] : $admin['username']) . '」');
  10890. }
  10891. /**
  10892. * 开标双重验证 — 两人验证码校验并记录
  10893. */
  10894. public function bidOpenVerify()
  10895. {
  10896. if (!$this->request->isPost()) {
  10897. $this->error(__('Invalid parameters'));
  10898. }
  10899. if (!$this->hasProcuremenPerm(['bidopenverify', 'bidopen', 'auditissue', 'auditsubmit'])) {
  10900. $this->error('无权限');
  10901. }
  10902. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10903. $verifier1Id = (int)$this->request->post('verifier1_id', 0);
  10904. $verifier2Id = (int)$this->request->post('verifier2_id', 0);
  10905. $code1 = trim((string)$this->request->post('code1', ''));
  10906. $code2 = trim((string)$this->request->post('code2', ''));
  10907. if ($scydgyId === '') {
  10908. $this->error('参数无效');
  10909. }
  10910. if ($verifier1Id <= 0 || $verifier2Id <= 0) {
  10911. $this->error('请选择两位验证人');
  10912. }
  10913. if ($verifier1Id === $verifier2Id) {
  10914. $this->error('两位验证人不能相同');
  10915. }
  10916. if (!preg_match('/^\d{6}$/', $code1) || !preg_match('/^\d{6}$/', $code2)) {
  10917. $this->error('请输入6位短信验证码');
  10918. }
  10919. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10920. if ($bundle['pos'] === []) {
  10921. $this->error('该订单不在待确认供应商状态');
  10922. }
  10923. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  10924. if ($ccydh === '') {
  10925. $this->error('订单号无效');
  10926. }
  10927. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10928. $this->success('已完成开标验证');
  10929. }
  10930. if ($this->isProcuremenManualPickedForBundle($bundle)) {
  10931. $this->error('本单已指定供应商,无需再开标');
  10932. }
  10933. $this->assertProcuremenBidOpenAfterDeadline($bundle);
  10934. $verifier1 = $this->loadBidOpenAdminUser($verifier1Id);
  10935. $verifier2 = $this->loadBidOpenAdminUser($verifier2Id);
  10936. if ($verifier1 === null || $verifier2 === null) {
  10937. $this->error('验证人无效或未绑定手机号');
  10938. }
  10939. if (!$this->verifyBidOpenSmsCode($verifier1Id, $ccydh, $code1)) {
  10940. $this->error('验证人「' . ($verifier1['nickname'] !== '' ? $verifier1['nickname'] : $verifier1['username']) . '」验证码不正确或已过期');
  10941. }
  10942. if (!$this->verifyBidOpenSmsCode($verifier2Id, $ccydh, $code2)) {
  10943. $this->error('验证人「' . ($verifier2['nickname'] !== '' ? $verifier2['nickname'] : $verifier2['username']) . '」验证码不正确或已过期');
  10944. }
  10945. try {
  10946. $this->recordProcuremenBidOpenVerification($bundle, $verifier1, $verifier2);
  10947. } catch (\Throwable $e) {
  10948. $this->error($e->getMessage());
  10949. }
  10950. $this->success('开标验证成功,可查看供应商报价与交货日期');
  10951. }
  10952. /**
  10953. * 确认页 — 自选供应商(免开标验证:选定供应商 + 选择说明,并显示报价)
  10954. */
  10955. public function auditManualPick()
  10956. {
  10957. if (!$this->request->isPost()) {
  10958. $this->error(__('Invalid parameters'));
  10959. }
  10960. if (!$this->hasProcuremenPerm(['auditmanualpick', 'auditsubmit', 'auditissue'])) {
  10961. $this->error('无权限');
  10962. }
  10963. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  10964. if ($scydgyId === '') {
  10965. $this->error('参数无效');
  10966. }
  10967. $companyName = trim((string)$this->request->post('selected_company', ''));
  10968. $reason = trim((string)$this->request->post('pick_reason', ''));
  10969. if ($companyName === '') {
  10970. $this->error('请选择一家供应商');
  10971. }
  10972. if ($reason === '') {
  10973. $this->error('请填写选择说明');
  10974. }
  10975. if (mb_strlen($reason) > 500) {
  10976. $this->error('选择说明不能超过500字');
  10977. }
  10978. $this->ensurePurchaseOrderManualPickColumns();
  10979. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  10980. $pos = $bundle['pos'];
  10981. if ($pos === []) {
  10982. $this->error('该订单不在待确认供应商状态');
  10983. }
  10984. if ($this->isProcuremenBidOpenVerifiedForBundle($bundle)) {
  10985. $this->error('本单已开标验证,请直接在列表中选定供应商后确认');
  10986. }
  10987. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  10988. if ($quoteGroups === []) {
  10989. $this->error('暂无供应商,请确认已完成协助初选通知');
  10990. }
  10991. $matched = null;
  10992. foreach ($quoteGroups as $g) {
  10993. if (!is_array($g)) {
  10994. continue;
  10995. }
  10996. if (trim((string)($g['name'] ?? '')) === $companyName) {
  10997. $matched = $g;
  10998. break;
  10999. }
  11000. }
  11001. if ($matched === null) {
  11002. $this->error('所选供应商不在本单报价列表中');
  11003. }
  11004. $logMsg = '指定供应商:已选定「' . $companyName . '」;说明:' . $reason;
  11005. Db::startTrans();
  11006. try {
  11007. foreach ($pos as $poRow) {
  11008. if (!is_array($poRow)) {
  11009. continue;
  11010. }
  11011. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11012. if (!$this->isValidScydgyRowId($sid)) {
  11013. continue;
  11014. }
  11015. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11016. 'pick_company_name' => $companyName,
  11017. 'manual_pick' => 1,
  11018. 'manual_pick_reason' => $reason,
  11019. ]);
  11020. }
  11021. Db::commit();
  11022. } catch (\Throwable $e) {
  11023. Db::rollback();
  11024. $this->error($e->getMessage());
  11025. }
  11026. foreach ($pos as $poRow) {
  11027. if (!is_array($poRow)) {
  11028. continue;
  11029. }
  11030. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11031. if (!$this->isValidScydgyRowId($sid)) {
  11032. continue;
  11033. }
  11034. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11035. $this->addOrderLog($sid, 'manual_pick', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11036. }
  11037. // 自选后可见报价:按本单规则计算评分(与开标后一致)
  11038. try {
  11039. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11040. if ($ccydh !== '') {
  11041. // 重新加载以拿到未掩码报价参与计分
  11042. $bundleFresh = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11043. $groupsFresh = $this->loadAuditSupplierQuoteGroups($bundleFresh);
  11044. ProcuremenSupplierScore::saveForOrder($ccydh, $groupsFresh, date('Y-m'));
  11045. }
  11046. } catch (\Throwable $e) {
  11047. Log::write('manual pick supplier score: ' . $e->getMessage(), 'error');
  11048. }
  11049. $this->success('已指定供应商「' . $companyName . '」,报价已显示,请核对后点击确认');
  11050. }
  11051. /**
  11052. * 确认供应商提交(选定唯一供应商,进入采购终审;默认不发短信)
  11053. */
  11054. public function auditSubmit()
  11055. {
  11056. if (!$this->request->isPost()) {
  11057. $this->error(__('Invalid parameters'));
  11058. }
  11059. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11060. if ($scydgyId === '') {
  11061. $this->error('参数无效');
  11062. }
  11063. $bundle = $this->loadAuditOrderBundleByScydgyId($scydgyId);
  11064. $pos = $bundle['pos'];
  11065. $mergeRows = $bundle['merge_rows'];
  11066. if ($pos === [] || $mergeRows === []) {
  11067. $this->error('该订单不在待确认供应商状态');
  11068. }
  11069. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11070. if ($quoteGroups === []) {
  11071. $this->error('暂无供应商报价,请确认已完成协助初选通知');
  11072. }
  11073. $companyName = trim((string)$this->request->post('selected_company', ''));
  11074. if ($companyName === '') {
  11075. $this->error('请选择一家供应商');
  11076. }
  11077. $matched = null;
  11078. foreach ($quoteGroups as $g) {
  11079. if (!is_array($g)) {
  11080. continue;
  11081. }
  11082. if (trim((string)($g['name'] ?? '')) === $companyName) {
  11083. $matched = $g;
  11084. break;
  11085. }
  11086. }
  11087. if ($matched === null) {
  11088. $this->error('所选供应商不在本单报价列表中');
  11089. }
  11090. $sysRqDb = $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq($bundle));
  11091. if ($sysRqDb === '') {
  11092. $sysRqDb = $this->parseProcuremenSysRqInput(trim((string)$this->request->post('sys_rq', '')), true, true);
  11093. } else {
  11094. // 确认供应商须已过招标截止,允许解析已过期的截止时间
  11095. $sysRqDb = $this->parseProcuremenSysRqInput($sysRqDb, true, true);
  11096. }
  11097. if (!$this->isProcuremenQuoteDeadlineReached($sysRqDb)) {
  11098. $this->error('未到招标截止日期,暂不可确认');
  11099. }
  11100. if (!$this->isProcuremenBidOpenVerifiedForBundle($bundle)
  11101. && !$this->isProcuremenManualPickedForBundle($bundle)
  11102. ) {
  11103. $this->error('请先完成开标双重验证或指定供应商后再确认');
  11104. }
  11105. $procCnt = count($mergeRows);
  11106. $procPart = $procCnt > 1 ? '(' . $procCnt . ' 道工序)' : '';
  11107. $logMsg = '确认供应商' . $procPart . ':已选定「' . $companyName . '」';
  11108. Db::startTrans();
  11109. try {
  11110. foreach ($pos as $poRow) {
  11111. if (!is_array($poRow)) {
  11112. continue;
  11113. }
  11114. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11115. if (!$this->isValidScydgyRowId($sid)) {
  11116. continue;
  11117. }
  11118. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11119. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_APPROVAL,
  11120. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11121. 'pick_company_name' => $companyName,
  11122. 'sys_rq' => $sysRqDb,
  11123. ]);
  11124. }
  11125. Db::commit();
  11126. } catch (\Throwable $e) {
  11127. Db::rollback();
  11128. $this->error($e->getMessage());
  11129. }
  11130. foreach ($pos as $poRow) {
  11131. if (!is_array($poRow)) {
  11132. continue;
  11133. }
  11134. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11135. if (!$this->isValidScydgyRowId($sid)) {
  11136. continue;
  11137. }
  11138. $poIdLog = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11139. $this->addOrderLog($sid, 'audit_select', $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11140. }
  11141. $this->success('已确认供应商「' . $companyName . '」,请至「采购终审确认」审批');
  11142. }
  11143. /**
  11144. * 确认供应商 — 二次发送短信(可选单家/批量/全部)
  11145. */
  11146. public function auditResendSms()
  11147. {
  11148. if (!$this->request->isPost()) {
  11149. $this->error(__('Invalid parameters'));
  11150. }
  11151. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11152. if ($scydgyId === '') {
  11153. $this->error('参数无效');
  11154. }
  11155. $loaded = $this->loadAuditResendBundle($scydgyId);
  11156. $mergeRows = $loaded['merge_rows'];
  11157. $bundle = $loaded['bundle'];
  11158. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  11159. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11160. if ($quoteGroups === []) {
  11161. $this->error('暂无可通知的供应商');
  11162. }
  11163. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  11164. $companiesJson = (string)$this->request->post('companies_json', '');
  11165. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  11166. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, true, false, '短信');
  11167. }
  11168. /**
  11169. * 确认供应商 — 二次发送邮件(可选单家/批量)
  11170. */
  11171. public function auditResendEmail()
  11172. {
  11173. if (!$this->request->isPost()) {
  11174. $this->error(__('Invalid parameters'));
  11175. }
  11176. $scydgyId = trim((string)$this->request->post('scydgy_id', ''));
  11177. if ($scydgyId === '') {
  11178. $this->error('参数无效');
  11179. }
  11180. $loaded = $this->loadAuditResendBundle($scydgyId);
  11181. $mergeRows = $loaded['merge_rows'];
  11182. $bundle = $loaded['bundle'];
  11183. $bundle = $this->applyAuditSysRqPostToBundle($bundle, (string)$this->request->post('sys_rq', ''));
  11184. $quoteGroups = $this->loadAuditSupplierQuoteGroups($bundle);
  11185. if ($quoteGroups === []) {
  11186. $this->error('暂无可通知的供应商');
  11187. }
  11188. $companiesJson = (string)$this->request->post('companies_json', '');
  11189. $selectedCompany = trim((string)$this->request->post('selected_company', ''));
  11190. $targets = $this->resolveAuditResendTargets($quoteGroups, $selectedCompany, $companiesJson);
  11191. if ($companiesJson === '' && $selectedCompany === '') {
  11192. $this->error('请勾选要发送邮件的供应商,或点击行内「发邮件」');
  11193. }
  11194. $this->auditResendNotifyToTargets($targets, $mergeRows, $bundle, false, true, '邮件');
  11195. }
  11196. /**
  11197. * 废弃单个订单 bundle(退回协助初选,明细归档留痕)
  11198. *
  11199. * @param array{ccydh:string, pos:array, merge_rows:array} $bundle
  11200. * @return array<int, true> 已处理的 scydgy_id 集合
  11201. */
  11202. protected function abandonOrderBundleToPick(array $bundle, string $logAction, string $logSuffix = ',退回协助初选'): array
  11203. {
  11204. $pos = $bundle['pos'] ?? [];
  11205. if (!is_array($pos) || $pos === []) {
  11206. return [];
  11207. }
  11208. $sids = [];
  11209. $poIdBySid = [];
  11210. foreach ($pos as $poRow) {
  11211. if (!is_array($poRow)) {
  11212. continue;
  11213. }
  11214. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11215. if ($this->isValidScydgyRowId($sid)) {
  11216. $sids[$sid] = true;
  11217. $poId = (int)($poRow['id'] ?? $poRow['ID'] ?? 0);
  11218. if ($poId > 0) {
  11219. $poIdBySid[$sid] = $poId;
  11220. }
  11221. }
  11222. }
  11223. if ($sids === []) {
  11224. return [];
  11225. }
  11226. $logMsg = '重新下发';
  11227. $suffix = trim((string)$logSuffix, ',, ');
  11228. if ($suffix !== '' && mb_strpos($suffix, '历史存证', 0, 'UTF-8') !== false) {
  11229. $logMsg .= ':从历史存证退回协助初选';
  11230. } else {
  11231. $logMsg .= ':退回协助初选';
  11232. }
  11233. Db::table('purchase_order')
  11234. ->where('scydgy_id', 'in', array_keys($sids))
  11235. ->update([
  11236. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_ISSUE,
  11237. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11238. 'pick_company_name' => '',
  11239. 'pick_time' => null,
  11240. 'sys_rq' => null,
  11241. 'mod_rq' => null,
  11242. ]);
  11243. $this->voidPurchaseOrderDetailsForScydgyIds(array_keys($sids));
  11244. foreach (array_keys($sids) as $sid) {
  11245. $poIdLog = (int)($poIdBySid[$sid] ?? 0);
  11246. $this->addOrderLog((int)$sid, $logAction, $logMsg, $poIdLog > 0 ? $poIdLog : null);
  11247. }
  11248. return $sids;
  11249. }
  11250. /**
  11251. * 历史存证 — 已完结订单 bundle(同一 CCYDH 下 status=1 的全部工序)
  11252. *
  11253. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  11254. */
  11255. protected function loadArchiveOrderBundleByScydgyId(string $scydgyId): array
  11256. {
  11257. $scydgyId = trim($scydgyId);
  11258. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11259. if ($scydgyId === '') {
  11260. return $empty;
  11261. }
  11262. try {
  11263. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  11264. } catch (\Throwable $e) {
  11265. $anchor = null;
  11266. }
  11267. if (!is_array($anchor) || !$this->purchaseOrderRowIsCompleted($anchor)) {
  11268. return $empty;
  11269. }
  11270. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  11271. if ($ccydh === '') {
  11272. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  11273. }
  11274. try {
  11275. $query = Db::table('purchase_order')->where('CCYDH', $ccydh);
  11276. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  11277. $pos = $query->order('scydgy_id', 'asc')->select();
  11278. } catch (\Throwable $e) {
  11279. $pos = [$anchor];
  11280. }
  11281. if (!is_array($pos) || $pos === []) {
  11282. $pos = [$anchor];
  11283. }
  11284. return [
  11285. 'ccydh' => $ccydh,
  11286. 'pos' => $pos,
  11287. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  11288. ];
  11289. }
  11290. protected function purchaseOrderRowIsCompleted(array $po): bool
  11291. {
  11292. return ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11293. }
  11294. /**
  11295. * 重新下发 — 按工序 ID 加载同单全部主单(不限状态;点了重新下发即可退回)
  11296. *
  11297. * @return array{ccydh:string, pos:array<int,array>, merge_rows:array<int,array>}
  11298. */
  11299. protected function loadAnyOrderBundleByScydgyId(string $scydgyId): array
  11300. {
  11301. $scydgyId = trim($scydgyId);
  11302. $empty = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11303. if ($scydgyId === '') {
  11304. return $empty;
  11305. }
  11306. try {
  11307. $anchor = Db::table('purchase_order')->where('scydgy_id', $scydgyId)->find();
  11308. } catch (\Throwable $e) {
  11309. $anchor = null;
  11310. }
  11311. if (!is_array($anchor)) {
  11312. return $empty;
  11313. }
  11314. $ccydh = trim((string)($anchor['CCYDH'] ?? ''));
  11315. if ($ccydh === '') {
  11316. return ['ccydh' => '', 'pos' => [$anchor], 'merge_rows' => $this->scydgyRowsForPurchaseOrders([$anchor])];
  11317. }
  11318. try {
  11319. $pos = Db::table('purchase_order')->where('CCYDH', $ccydh)->order('scydgy_id', 'asc')->select();
  11320. } catch (\Throwable $e) {
  11321. $pos = [$anchor];
  11322. }
  11323. if (!is_array($pos) || $pos === []) {
  11324. $pos = [$anchor];
  11325. }
  11326. return [
  11327. 'ccydh' => $ccydh,
  11328. 'pos' => $pos,
  11329. 'merge_rows' => $this->scydgyRowsForPurchaseOrders($pos),
  11330. ];
  11331. }
  11332. /**
  11333. * 废弃订单 — 退回协助初选重新询价(支持单条或批量)
  11334. * 统一入口:待确认 / 已完结 / 其它状态均可重新下发
  11335. */
  11336. public function auditAbandon()
  11337. {
  11338. if (!$this->request->isPost()) {
  11339. $this->error(__('Invalid parameters'));
  11340. }
  11341. $anchorIds = [];
  11342. $batchRaw = trim((string)$this->request->post('scydgy_ids_json', ''));
  11343. if ($batchRaw !== '') {
  11344. $decoded = json_decode($batchRaw, true);
  11345. if (is_array($decoded)) {
  11346. foreach ($decoded as $id) {
  11347. $s = trim((string)$id);
  11348. if ($s !== '') {
  11349. $anchorIds[] = $s;
  11350. }
  11351. }
  11352. }
  11353. }
  11354. if ($anchorIds === []) {
  11355. $single = trim((string)$this->request->post('scydgy_id', ''));
  11356. if ($single !== '') {
  11357. $anchorIds[] = $single;
  11358. }
  11359. }
  11360. if ($anchorIds === []) {
  11361. $this->error('请至少选择一条订单');
  11362. }
  11363. $processedCcydh = [];
  11364. $doneOrders = 0;
  11365. $allSids = [];
  11366. Db::startTrans();
  11367. try {
  11368. foreach ($anchorIds as $anchorId) {
  11369. $fromArchive = false;
  11370. $bundle = $this->loadAuditOrderBundleByScydgyId($anchorId);
  11371. if (($bundle['pos'] ?? []) === []) {
  11372. $bundle = $this->loadArchiveOrderBundleByScydgyId($anchorId);
  11373. $fromArchive = ($bundle['pos'] ?? []) !== [];
  11374. }
  11375. if (($bundle['pos'] ?? []) === []) {
  11376. $bundle = $this->loadAnyOrderBundleByScydgyId($anchorId);
  11377. $fromArchive = ($bundle['pos'] ?? []) !== [];
  11378. }
  11379. if (($bundle['pos'] ?? []) === []) {
  11380. continue;
  11381. }
  11382. $ccydh = trim((string)($bundle['ccydh'] ?? ''));
  11383. $dedupeKey = $ccydh !== '' ? $ccydh : ('sid:' . $anchorId);
  11384. if (isset($processedCcydh[$dedupeKey])) {
  11385. continue;
  11386. }
  11387. $processedCcydh[$dedupeKey] = true;
  11388. $sids = $fromArchive
  11389. ? $this->abandonOrderBundleToPick($bundle, 'audit_abandon', ',从历史存证退回协助初选')
  11390. : $this->abandonOrderBundleToPick($bundle, 'audit_abandon');
  11391. if ($sids === []) {
  11392. continue;
  11393. }
  11394. $doneOrders++;
  11395. foreach (array_keys($sids) as $sid) {
  11396. $allSids[(int)$sid] = true;
  11397. }
  11398. }
  11399. if ($doneOrders < 1) {
  11400. throw new \Exception('未找到可重新下发的订单,请刷新后重试');
  11401. }
  11402. Db::commit();
  11403. } catch (\Throwable $e) {
  11404. Db::rollback();
  11405. $this->error($e->getMessage());
  11406. }
  11407. $this->pickHiddenScydgySetCache = null;
  11408. $msg = $doneOrders > 1
  11409. ? ('已重新下发 ' . $doneOrders . ' 个订单并退回协助初选,历史下发与操作记录已保留')
  11410. : '已退回协助初选,请重新选择供应商下发(历史记录已保留)';
  11411. $this->success($msg);
  11412. }
  11413. /**
  11414. * @deprecated 请统一使用 auditAbandon(procuremen/auditabandon)
  11415. */
  11416. public function archiveAbandon()
  11417. {
  11418. return $this->auditAbandon();
  11419. }
  11420. /**
  11421. * 采购终审 — 审批驳回(退回协助审批下发,不发送短信)
  11422. */
  11423. public function purchaseApprovalReject()
  11424. {
  11425. if (!$this->request->isPost() || !$this->request->isAjax()) {
  11426. $this->error(__('Invalid parameters'));
  11427. }
  11428. if (!$this->hasProcuremenPerm(['purchaseapprovalreject', 'purchaseApprovalReject'])) {
  11429. $this->error(__('You have no permission'));
  11430. }
  11431. $batchRaw = trim((string)$this->request->post('order_picks_json', ''));
  11432. $decoded = json_decode($batchRaw, true);
  11433. if (!is_array($decoded) || $decoded === []) {
  11434. $this->error('提交数据无效');
  11435. }
  11436. $done = 0;
  11437. Db::startTrans();
  11438. try {
  11439. foreach ($decoded as $item) {
  11440. if (!is_array($item)) {
  11441. continue;
  11442. }
  11443. $sid = (int)($item['scydgy_id'] ?? 0);
  11444. if (!$this->isValidScydgyRowId($sid)) {
  11445. continue;
  11446. }
  11447. $this->runPurchaseApprovalRejectForSid($sid);
  11448. $done++;
  11449. }
  11450. if ($done < 1) {
  11451. throw new \Exception('所选订单均不在待审批状态');
  11452. }
  11453. Db::commit();
  11454. } catch (\Throwable $e) {
  11455. Db::rollback();
  11456. $this->error($e->getMessage() !== '' ? $e->getMessage() : '驳回失败');
  11457. }
  11458. $this->pickHiddenScydgySetCache = null;
  11459. $this->success('已驳回并退回「协助审批下发」');
  11460. }
  11461. /**
  11462. * @throws \Exception
  11463. */
  11464. protected function runPurchaseApprovalRejectForSid(int $sid): void
  11465. {
  11466. $poRow = ProcuremenGuard::loadPurchaseOrderOrFail($sid, '未找到订单');
  11467. ProcuremenGuard::assertWflowPendingApproval($poRow, '该订单不在待审批状态,无法驳回');
  11468. ProcuremenGuard::assertNotCompleted($poRow, '订单已完结,无法驳回');
  11469. $allIds = $this->purchaseOrderDetail($sid);
  11470. if ($allIds === []) {
  11471. throw new \Exception('未找到下发明细');
  11472. }
  11473. Db::table('purchase_order')->where('scydgy_id', $sid)->update([
  11474. 'wflow_status' => ProcuremenStatus::WFLOW_PENDING_CONFIRM,
  11475. 'status' => ProcuremenStatus::PO_IN_PROGRESS,
  11476. 'pick_company_name' => '',
  11477. ]);
  11478. Db::table('purchase_order_detail')->where('scydgy_id', $sid)->update(['status' => ProcuremenStatus::POD_UNPICKED]);
  11479. $this->restorePurchaseOrderDetailStatusNamesAfterReject($sid);
  11480. $poId = 0;
  11481. try {
  11482. $po = Db::table('purchase_order')->where('scydgy_id', $sid)->find();
  11483. if (is_array($po)) {
  11484. $poId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11485. }
  11486. } catch (\Throwable $e) {
  11487. }
  11488. $this->addOrderLog($sid, 'purchase_reject', '审核驳回:退回确认供应商', $poId > 0 ? $poId : null);
  11489. }
  11490. /**
  11491. * 审核弹窗(旧入口,POST 已关闭)
  11492. */
  11493. public function review()
  11494. {
  11495. if (!$this->hasProcuremenPerm(['review', 'picksubmit', 'pickreview'])) {
  11496. $this->error(__('You have no permission'));
  11497. }
  11498. if ($this->request->isPost()) {
  11499. $this->error('请使用第一步「协助下发」通知供应商,再在「确认供应商」中选定一家');
  11500. }
  11501. $this->view->assign('pickMode', 0);
  11502. return $this->fetchProcuremenDialogLite('procuremen/review', '选商');
  11503. }
  11504. /**
  11505. * 审核弹窗获取公司列表
  11506. */
  11507. public function reviewCompanies()
  11508. {
  11509. if (!$this->hasProcuremenPerm(['reviewcompanies', 'pickreview', 'picksubmit', 'review', 'auditissue', 'auditappend', 'auditappendsubmit'])) {
  11510. $this->error(__('You have no permission'));
  11511. }
  11512. if (!$this->request->isAjax()) {
  11513. $this->error(__('Invalid parameters'));
  11514. }
  11515. $list = [];
  11516. try {
  11517. // 仅「正常」外协(customer.status=1);0=禁止登录,与手机端 mprocCustomerUserActive 一致
  11518. $rows = Db::table('customer')
  11519. ->where(function ($q) {
  11520. $q->where('status', 1)
  11521. ->whereOr('status', '1')
  11522. ->whereOr('status', '')
  11523. ->whereNull('status');
  11524. })
  11525. ->order('id', 'desc')
  11526. ->select();
  11527. } catch (\Throwable $e) {
  11528. $this->success('', '', []);
  11529. return;
  11530. }
  11531. if (!is_array($rows)) {
  11532. $this->success('', '', []);
  11533. return;
  11534. }
  11535. $detailColCandidates = [
  11536. 'detail', 'mingxi', 'remark', 'memo', 'notes', 'description',
  11537. 'company_detail', 'company_desc', 'address',
  11538. ];
  11539. foreach ($rows as $row) {
  11540. if (!is_array($row)) {
  11541. continue;
  11542. }
  11543. $norm = [];
  11544. foreach ($row as $k => $v) {
  11545. $norm[is_string($k) ? strtolower($k) : $k] = $v;
  11546. }
  11547. $row = $norm;
  11548. $st = $row['status'] ?? '';
  11549. if ($st !== '' && $st !== null && $st !== 1 && $st !== '1') {
  11550. continue;
  11551. }
  11552. $payload = $this->buildCustomerContactPayloadFromRow($row);
  11553. if ($payload === null) {
  11554. continue;
  11555. }
  11556. $detail = '';
  11557. foreach ($detailColCandidates as $dk) {
  11558. if (!isset($row[$dk])) {
  11559. continue;
  11560. }
  11561. $dv = trim((string)$row[$dk]);
  11562. if ($dv !== '') {
  11563. $detail = $dv;
  11564. break;
  11565. }
  11566. }
  11567. $payload['detail'] = $detail;
  11568. $list[] = $this->maskSupplierContactFields($payload);
  11569. }
  11570. $this->success('', '', $list);
  11571. }
  11572. /**
  11573. * 采购确认-下发明细弹窗:
  11574. * 查 purchase_order_detail;ids 为工序行 scydgy.ID,对应明细 scydgy_id
  11575. */
  11576. public function outward_detail()
  11577. {
  11578. $ids = $this->request->param('ids', $this->request->param('id', ''));
  11579. if (is_array($ids)) {
  11580. $ids = isset($ids[0]) ? $ids[0] : '';
  11581. }
  11582. $ids = trim((string)$ids);
  11583. if ($ids === '') {
  11584. $this->error(__('Invalid parameters'));
  11585. }
  11586. $wffTab = trim((string)$this->request->param('wff_tab', 'all'));
  11587. if (!in_array($wffTab, ['all', 'pending', 'picked', 'done', 'confirm'], true)) {
  11588. $wffTab = 'all';
  11589. }
  11590. $isPurchaseConfirm = ($wffTab === 'pending' || $wffTab === 'confirm');
  11591. $purchaseOrderId = 0;
  11592. $po = null;
  11593. try {
  11594. $po = Db::table('purchase_order')->where('scydgy_id', $ids)->find();
  11595. if (is_array($po)) {
  11596. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11597. }
  11598. } catch (\Throwable $e) {
  11599. $purchaseOrderId = 0;
  11600. $po = null;
  11601. }
  11602. if (!$isPurchaseConfirm && is_array($po)) {
  11603. $isDone = ProcuremenStatus::isPoCompleted($po['status'] ?? '');
  11604. if (ProcuremenStatus::isWflowPendingApproval($po['wflow_status'] ?? '') && !$isDone) {
  11605. $isPurchaseConfirm = true;
  11606. }
  11607. }
  11608. $headTitle = $isPurchaseConfirm ? '采购确认' : '下发明细';
  11609. $confirmBundle = ['ccydh' => '', 'pos' => [], 'merge_rows' => []];
  11610. $confirmProcessCount = 1;
  11611. $confirmPickGroups = [];
  11612. $processDisplayRows = [];
  11613. $allDetailsBySid = [];
  11614. $requiredSidList = [];
  11615. $sidList = [$ids];
  11616. if ($isPurchaseConfirm) {
  11617. $confirmBundle = $this->loadConfirmOrderBundleByScydgyId($ids);
  11618. $mergeRows = $confirmBundle['merge_rows'] ?? [];
  11619. if ($mergeRows !== []) {
  11620. $processDisplayRows = $this->buildAuditProcessDisplayRows($mergeRows);
  11621. }
  11622. $confirmPickGroups = $this->loadConfirmSupplierPickGroups($confirmBundle);
  11623. if ($confirmBundle['pos'] !== []) {
  11624. $sidList = [];
  11625. foreach ($confirmBundle['pos'] as $poRow) {
  11626. if (!is_array($poRow)) {
  11627. continue;
  11628. }
  11629. $sid = (int)($poRow['scydgy_id'] ?? 0);
  11630. if (!$this->isValidScydgyRowId($sid)) {
  11631. continue;
  11632. }
  11633. $sidList[] = (string)$sid;
  11634. $requiredSidList[] = $sid;
  11635. }
  11636. }
  11637. if ($sidList === []) {
  11638. $sidList = [$ids];
  11639. $requiredSidList = [(int)$ids];
  11640. }
  11641. $confirmProcessCount = max(1, count($requiredSidList));
  11642. if (is_array($po) && $purchaseOrderId <= 0) {
  11643. $purchaseOrderId = (int)($po['id'] ?? $po['ID'] ?? 0);
  11644. }
  11645. }
  11646. $rows = [];
  11647. try {
  11648. if (count($sidList) === 1) {
  11649. $rows = Db::table('purchase_order_detail')->where('scydgy_id', $sidList[0])->order('id', 'desc')->select();
  11650. } else {
  11651. $rows = Db::table('purchase_order_detail')->where('scydgy_id', 'in', $sidList)->order('scydgy_id', 'asc')->order('id', 'desc')->select();
  11652. }
  11653. } catch (\Throwable $e) {
  11654. $rows = [];
  11655. }
  11656. if ($isPurchaseConfirm) {
  11657. $allDetailsBySid = $this->mapDetailIdsByScydgyId(is_array($rows) ? $rows : []);
  11658. }
  11659. foreach ($rows as &$r) {
  11660. if (is_array($r) && isset($r['ID']) && !isset($r['id'])) {
  11661. $r['id'] = $r['ID'];
  11662. }
  11663. if (isset($r['createtime'])) {
  11664. if (is_numeric($r['createtime']) && (int)$r['createtime'] > 946684800) {
  11665. $r['createtime_text'] = date('Y-m-d H:i:s', (int)$r['createtime']);
  11666. } else {
  11667. $r['createtime_text'] = (string)$r['createtime'];
  11668. }
  11669. } else {
  11670. $r['createtime_text'] = '';
  11671. }
  11672. if (is_array($r)) {
  11673. $r = $this->maskSupplierContactFields($r);
  11674. }
  11675. }
  11676. unset($r);
  11677. $pickedCompanyName = '';
  11678. $manualPicked = 0;
  11679. $manualPickReason = '';
  11680. $quoteVisible = 0;
  11681. $bidOpenVerified = 0;
  11682. if ($isPurchaseConfirm) {
  11683. // 确认包为空时,用当前主单兜底,避免指定说明读不到
  11684. if (($confirmBundle['ccydh'] ?? '') === '' && is_array($po)) {
  11685. $confirmBundle['ccydh'] = trim((string)($po['CCYDH'] ?? ''));
  11686. }
  11687. if (($confirmBundle['pos'] ?? []) === [] && is_array($po)) {
  11688. $confirmBundle['pos'] = [$po];
  11689. }
  11690. $manualPickInfo = $this->resolveProcuremenManualPickInfo($confirmBundle);
  11691. $manualPicked = $this->isProcuremenManualPickedForBundle($confirmBundle) ? 1 : 0;
  11692. $manualPickReason = (string)($manualPickInfo['reason'] ?? '');
  11693. if ($manualPickInfo['company'] !== '') {
  11694. $pickedCompanyName = $manualPickInfo['company'];
  11695. }
  11696. if ($pickedCompanyName === '') {
  11697. foreach ($confirmBundle['pos'] ?? [] as $poRow) {
  11698. if (!is_array($poRow)) {
  11699. continue;
  11700. }
  11701. $pn = trim((string)($poRow['pick_company_name'] ?? ''));
  11702. if ($pn !== '') {
  11703. $pickedCompanyName = $pn;
  11704. break;
  11705. }
  11706. }
  11707. }
  11708. // 再兜底:直接读当前主单字段
  11709. if (is_array($po) && (int)($po['manual_pick'] ?? 0) === 1) {
  11710. $manualPicked = 1;
  11711. if ($manualPickReason === '') {
  11712. $manualPickReason = trim((string)($po['manual_pick_reason'] ?? ''));
  11713. }
  11714. if ($pickedCompanyName === '') {
  11715. $pickedCompanyName = trim((string)($po['pick_company_name'] ?? ''));
  11716. }
  11717. }
  11718. $bidOpenVerified = $this->isProcuremenBidOpenVerifiedForBundle($confirmBundle) ? 1 : 0;
  11719. $quoteVisible = ($bidOpenVerified || $manualPicked) ? 1 : 0;
  11720. }
  11721. $this->view->assign('rows', $rows ?: []);
  11722. $this->view->assign('rowCount', count($rows ?: []));
  11723. $this->view->assign('scydgyId', $ids);
  11724. $this->view->assign('purchaseOrderId', $purchaseOrderId);
  11725. $this->view->assign('headTitle', $headTitle);
  11726. $this->view->assign('showPurchaseConfirm', $isPurchaseConfirm ? 1 : 0);
  11727. $this->view->assign('detailColspan', $isPurchaseConfirm ? 7 : 9);
  11728. $this->view->assign('confirmProcessCount', $confirmProcessCount);
  11729. $this->view->assign('orderCcydh', $confirmBundle['ccydh'] ?? '');
  11730. $this->view->assign('processDisplayRows', $processDisplayRows);
  11731. $this->view->assign('confirmPickGroups', $this->maskSupplierContactList($confirmPickGroups));
  11732. $this->view->assign('confirmPickCount', count($confirmPickGroups));
  11733. $this->view->assign('pickedCompanyName', $pickedCompanyName);
  11734. $this->view->assign('manualPicked', $manualPicked);
  11735. $this->view->assign('manualPickReason', $manualPickReason);
  11736. $this->view->assign('bidOpenVerified', $bidOpenVerified);
  11737. $this->view->assign('quoteVisible', $quoteVisible);
  11738. $orderScoreRule = ProcuremenSupplierScore::resolveRuleForCcydh((string)($confirmBundle['ccydh'] ?? ''));
  11739. $this->view->assign('orderScoreRuleName', (string)($orderScoreRule['name'] ?? ''));
  11740. $this->view->assign('supplierScoreRuleText', ProcuremenSupplierScore::formatRuleFormulaTextForGroups($confirmPickGroups, $orderScoreRule));
  11741. $this->view->assign('showServiceLeadScore', ProcuremenSupplierScore::detectShowLeadScore($confirmPickGroups, $orderScoreRule) ? 1 : 0);
  11742. $sysRqDisplay = '—';
  11743. if ($isPurchaseConfirm) {
  11744. $sysRqDisplay = $this->formatProcuremenSysRqForDisplay(
  11745. $this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []])
  11746. );
  11747. }
  11748. $this->view->assign('sysRqDisplay', $sysRqDisplay);
  11749. $this->view->assign('sysRq', $isPurchaseConfirm
  11750. ? $this->formatProcuremenSysRqForInput($this->resolveBundleSysRq(['pos' => $confirmBundle['pos'] ?? []]))
  11751. : '');
  11752. $this->view->assign('deliveryDeadline', $isPurchaseConfirm
  11753. ? $this->resolveBundleDeliveryDeadline(['pos' => $confirmBundle['pos'] ?? []])
  11754. : '');
  11755. $this->view->assign('requiredSidListJson', json_encode(array_values($requiredSidList), JSON_UNESCAPED_UNICODE));
  11756. $this->view->assign('allDetailsBySidJson', json_encode($allDetailsBySid, JSON_UNESCAPED_UNICODE));
  11757. /* 采购确认需在 iframe 内加载 require-backend,以便勾选与提交 */
  11758. if ($isPurchaseConfirm) {
  11759. return $this->view->fetch();
  11760. }
  11761. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  11762. $this->view->engine->layout(false);
  11763. try {
  11764. $bodyHtml = $this->view->fetch('procuremen/outward_detail');
  11765. $this->view->assign('dialogBody', $bodyHtml);
  11766. return $this->view->fetch('procuremen/outward_detail_lite_shell');
  11767. } finally {
  11768. if ($restoreLayout) {
  11769. $this->view->engine->layout($restoreLayout);
  11770. }
  11771. }
  11772. }
  11773. /**
  11774. * 月度导出记录表(不存在时自动创建)
  11775. */
  11776. protected function ensurePurchaseMonthExportLogTable(): void
  11777. {
  11778. try {
  11779. Db::query('SELECT 1 FROM `purchase_month_export_log` LIMIT 1');
  11780. } catch (\Throwable $e) {
  11781. Db::execute(
  11782. "CREATE TABLE IF NOT EXISTS `purchase_month_export_log` (
  11783. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  11784. `ym` char(7) NOT NULL COMMENT 'YYYY-MM',
  11785. `admin_id` int(10) unsigned NOT NULL DEFAULT 0,
  11786. `admin_name` varchar(64) NOT NULL DEFAULT '',
  11787. `row_count` int(10) unsigned NOT NULL DEFAULT 0,
  11788. `total_amount` decimal(14,2) NOT NULL DEFAULT 0.00,
  11789. `createtime` int(10) unsigned DEFAULT NULL,
  11790. PRIMARY KEY (`id`),
  11791. KEY `idx_ym` (`ym`),
  11792. KEY `idx_ct` (`createtime`)
  11793. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='月度协助明细导出记录'"
  11794. );
  11795. }
  11796. }
  11797. /**
  11798. * 月度导出:按列表搜索条件过滤 purchase_order 行(与 procuremenexport 列表一致)
  11799. *
  11800. * @param array<int, mixed> $dbRows
  11801. * @return array<int, array<string, mixed>>
  11802. */
  11803. protected function filterMonthOutwardExportDbRowsBySearch(array $dbRows): array
  11804. {
  11805. $keyword = trim((string)$this->request->get('search', ''));
  11806. if ($keyword === '') {
  11807. $keyword = trim((string)$this->request->request('search', ''));
  11808. }
  11809. $filter = $this->request->get('filter', '');
  11810. $op = $this->request->get('op', '');
  11811. if (is_string($filter) && $filter !== '') {
  11812. $filterArr = (array)json_decode($filter, true);
  11813. } else {
  11814. $filterArr = is_array($filter) ? $filter : [];
  11815. }
  11816. if (is_string($op) && $op !== '') {
  11817. $opArr = (array)json_decode($op, true);
  11818. } else {
  11819. $opArr = is_array($op) ? $op : [];
  11820. }
  11821. if ($keyword === '' && $filterArr === []) {
  11822. return array_values(array_filter($dbRows, 'is_array'));
  11823. }
  11824. $searchFields = ['CCYDH', 'CYJMC', 'CGYMC'];
  11825. $out = [];
  11826. foreach ($dbRows as $row) {
  11827. if (!is_array($row)) {
  11828. continue;
  11829. }
  11830. if ($keyword !== '') {
  11831. $hit = false;
  11832. foreach ($searchFields as $f) {
  11833. if (mb_stripos((string)($row[$f] ?? ''), $keyword) !== false) {
  11834. $hit = true;
  11835. break;
  11836. }
  11837. }
  11838. if (!$hit) {
  11839. continue;
  11840. }
  11841. }
  11842. $passFilter = true;
  11843. foreach ($filterArr as $field => $val) {
  11844. $field = (string)$field;
  11845. $val = trim((string)$val);
  11846. if ($field === '' || $val === '') {
  11847. continue;
  11848. }
  11849. if (!array_key_exists($field, $row) && !in_array($field, $searchFields, true)) {
  11850. continue;
  11851. }
  11852. $cell = (string)($row[$field] ?? '');
  11853. $mode = strtoupper((string)($opArr[$field] ?? 'LIKE'));
  11854. if ($mode === '=' || $mode === 'EQUAL') {
  11855. if (strcasecmp($cell, $val) !== 0) {
  11856. $passFilter = false;
  11857. break;
  11858. }
  11859. } elseif (mb_stripos($cell, $val) === false) {
  11860. $passFilter = false;
  11861. break;
  11862. }
  11863. }
  11864. if (!$passFilter) {
  11865. continue;
  11866. }
  11867. $out[] = $row;
  11868. }
  11869. return $out;
  11870. }
  11871. /**
  11872. * 按月份导出:已完结订单(与历史存证、月度列表一致),按完结月份筛选。
  11873. * 表头固定 8 列(与历史「协助明细」模板一致):序号、传票号、传票名称、外加工单位、订法、客户名称、工序、加工金额。
  11874. */
  11875. public function export_month_outward()
  11876. {
  11877. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward'])) {
  11878. $this->error(__('You have no permission'));
  11879. }
  11880. $bundle = $this->prepareMonthOutwardExportBundle();
  11881. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  11882. $exportLines = is_array($bundle['exportLines'] ?? null) ? $bundle['exportLines'] : [];
  11883. $groups = is_array($bundle['groups'] ?? null) ? $bundle['groups'] : [];
  11884. $spreadsheet = new Spreadsheet();
  11885. $sheet = $spreadsheet->getActiveSheet();
  11886. $sheet->setTitle('外协加工明细');
  11887. $mon = (int)substr($ym, 5, 2);
  11888. $sheet->mergeCells('A1:H1');
  11889. $sheet->setCellValue('A1', $mon . '月份外协加工明细');
  11890. $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
  11891. $sheet->getStyle('A1')->getAlignment()
  11892. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  11893. ->setVertical(Alignment::VERTICAL_CENTER);
  11894. $headers = ['序号', '传票号', '传票名称', '外加工单位', '订法', '客户名称', '工序', '加工金额'];
  11895. $col = 'A';
  11896. foreach ($headers as $h) {
  11897. $sheet->setCellValue($col . '2', $h);
  11898. $col++;
  11899. }
  11900. $sheet->getStyle('A2:H2')->getFont()->setBold(true);
  11901. $sheet->getStyle('A2:H2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11902. $rowNum = 3;
  11903. $sumSubtotalCounts = 0;
  11904. $grandAmount = 0.0;
  11905. $globalSeq = 0;
  11906. if ($groups === []) {
  11907. $sheet->mergeCells('A3:H3');
  11908. $sheet->setCellValue('A3', '(当月暂无符合条件的协助明细)');
  11909. $sheet->getStyle('A3')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  11910. $rowNum = 4;
  11911. } else {
  11912. foreach ($groups as $items) {
  11913. if ($items === []) {
  11914. continue;
  11915. }
  11916. $groupLineCount = count($items);
  11917. $subAmount = 0.0;
  11918. foreach ($items as $line) {
  11919. $globalSeq++;
  11920. $dr = $line['detail'];
  11921. $amt = $this->procuremenExportAmount($dr);
  11922. $subAmount += $amt;
  11923. $sheet->setCellValue('A' . $rowNum, $globalSeq);
  11924. $sheet->setCellValue('B' . $rowNum, $line['CCYDH']);
  11925. $sheet->setCellValue('C' . $rowNum, $line['CYJMC']);
  11926. $sheet->setCellValue('D' . $rowNum, $line['company_name']);
  11927. $sheet->setCellValue('E' . $rowNum, $line['CDF']);
  11928. $sheet->setCellValue('F' . $rowNum, $line['cGzzxMc']);
  11929. $sheet->setCellValue('G' . $rowNum, $line['gx']);
  11930. $sheet->setCellValue('H' . $rowNum, $amt);
  11931. $sheet->getStyle('H' . $rowNum)->getNumberFormat()->setFormatCode('"¥"#,##0.00');
  11932. $rowNum++;
  11933. }
  11934. $sumSubtotalCounts += $groupLineCount;
  11935. $grandAmount += $subAmount;
  11936. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11937. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($subAmount, 2, '.', ','));
  11938. $sheet->getStyle('G' . $rowNum)->getAlignment()
  11939. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  11940. ->setVertical(Alignment::VERTICAL_CENTER);
  11941. $rowNum++;
  11942. }
  11943. }
  11944. $sheet->setCellValue('A' . $rowNum, '总计');
  11945. $sheet->setCellValue('B' . $rowNum, $sumSubtotalCounts);
  11946. $sheet->mergeCells('G' . $rowNum . ':H' . $rowNum);
  11947. $sheet->setCellValue('G' . $rowNum, '¥ ' . number_format($grandAmount, 2, '.', ','));
  11948. $sheet->getStyle('A' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  11949. $sheet->getStyle('G' . $rowNum)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
  11950. $lastRow = $rowNum;
  11951. $sheet->getStyle('A1:H' . $lastRow)->applyFromArray([
  11952. 'borders' => [
  11953. 'allBorders' => [
  11954. 'borderStyle' => Border::BORDER_THIN,
  11955. 'color' => ['rgb' => '000000'],
  11956. ],
  11957. ],
  11958. ]);
  11959. $sheet->getStyle('A3:H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  11960. if ($lastRow >= 3) {
  11961. $sheet->getStyle('C3:C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11962. $sheet->getStyle('D3:D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11963. $sheet->getStyle('F3:F' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11964. $sheet->getStyle('G3:G' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  11965. }
  11966. $this->applyMonthExportTableAlignment($sheet, 2, 3, $lastRow, 'H');
  11967. $sheet->getColumnDimension('A')->setWidth(7);
  11968. $sheet->getColumnDimension('B')->setWidth(16);
  11969. $sheet->getColumnDimension('C')->setWidth(52);
  11970. $sheet->getColumnDimension('D')->setWidth(32);
  11971. $sheet->getColumnDimension('E')->setWidth(12);
  11972. $sheet->getColumnDimension('F')->setWidth(44);
  11973. $sheet->getColumnDimension('G')->setWidth(26);
  11974. $sheet->getColumnDimension('H')->setWidth(13);
  11975. $sheet->getRowDimension(1)->setRowHeight(28);
  11976. $ymCompact = str_replace('-', '', $ym);
  11977. $fileBase = $mon . '月份外协加工明细_' . $ymCompact;
  11978. $filename = $fileBase . '.xlsx';
  11979. try {
  11980. $this->ensurePurchaseMonthExportLogTable();
  11981. list($adminId, $adminName) = $this->GetUseName();
  11982. Db::table('purchase_month_export_log')->insert([
  11983. 'ym' => $ym,
  11984. 'admin_id' => (int)$adminId,
  11985. 'admin_name' => mb_substr((string)$adminName, 0, 64, 'UTF-8'),
  11986. 'row_count' => count($exportLines),
  11987. 'total_amount' => round($grandAmount, 2),
  11988. 'createtime' => time(),
  11989. ]);
  11990. } catch (\Throwable $e) {
  11991. Log::write('month export log: ' . $e->getMessage(), 'error');
  11992. }
  11993. if (ob_get_length()) {
  11994. ob_end_clean();
  11995. }
  11996. $asciiName = 'wxjgmx_' . $ymCompact . '.xlsx';
  11997. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  11998. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  11999. header('Cache-Control: max-age=0');
  12000. $writer = new Xlsx($spreadsheet);
  12001. $writer->save('php://output');
  12002. $spreadsheet->disconnectWorksheets();
  12003. unset($spreadsheet);
  12004. exit;
  12005. }
  12006. /**
  12007. * 按月份单独导出:供应商报价明细(含未中标),与加工明细分开文件
  12008. */
  12009. public function export_month_quote()
  12010. {
  12011. if (!$this->hasProcuremenPerm(['export_month_outward', 'exportMonthOutward', 'export_month_quote', 'exportMonthQuote'])) {
  12012. $this->error(__('You have no permission'));
  12013. }
  12014. $bundle = $this->prepareMonthOutwardExportBundle();
  12015. $ym = (string)($bundle['ym'] ?? date('Y-m'));
  12016. $detailRows = is_array($bundle['detailRows'] ?? null) ? $bundle['detailRows'] : [];
  12017. $mainBySid = is_array($bundle['mainBySid'] ?? null) ? $bundle['mainBySid'] : [];
  12018. $quoteLines = $this->buildMonthExportQuoteLines($detailRows, $mainBySid);
  12019. $spreadsheet = new Spreadsheet();
  12020. $sheet = $spreadsheet->getActiveSheet();
  12021. $sheet->setTitle('供应商报价明细');
  12022. $mon = (int)substr($ym, 5, 2);
  12023. $quoteLastRow = $this->appendMonthExportQuoteBlock($sheet, $quoteLines, $ym, 1);
  12024. $sheet->getColumnDimension('A')->setWidth(7);
  12025. $sheet->getColumnDimension('B')->setWidth(16);
  12026. $sheet->getColumnDimension('C')->setWidth(52);
  12027. $sheet->getColumnDimension('D')->setWidth(26);
  12028. $sheet->getColumnDimension('E')->setWidth(32);
  12029. $sheet->getColumnDimension('F')->setWidth(12);
  12030. $sheet->getColumnDimension('G')->setWidth(14);
  12031. $sheet->getColumnDimension('H')->setWidth(12);
  12032. if ($quoteLastRow < 1) {
  12033. $quoteLastRow = 3;
  12034. }
  12035. $ymCompact = str_replace('-', '', $ym);
  12036. $filename = $mon . '月供应商报价明细_' . $ymCompact . '.xlsx';
  12037. if (ob_get_length()) {
  12038. ob_end_clean();
  12039. }
  12040. $asciiName = 'gysbjmx_' . $ymCompact . '.xlsx';
  12041. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  12042. header('Content-Disposition: attachment;filename="' . $asciiName . '"; filename*=UTF-8\'\'' . rawurlencode($filename));
  12043. header('Cache-Control: max-age=0');
  12044. $writer = new Xlsx($spreadsheet);
  12045. $writer->save('php://output');
  12046. $spreadsheet->disconnectWorksheets();
  12047. unset($spreadsheet);
  12048. exit;
  12049. }
  12050. /**
  12051. * 月度导出公共数据:已完结订单按月份/搜索筛选后的主表与明细
  12052. *
  12053. * @return array{ym:string,mainBySid:array,detailRows:array,exportLines:array,groups:array}
  12054. */
  12055. protected function prepareMonthOutwardExportBundle(): array
  12056. {
  12057. $this->request->filter(['strip_tags', 'trim']);
  12058. $ym = trim((string)$this->request->get('ym', date('Y-m')));
  12059. if (!preg_match('/^\d{4}-\d{2}$/', $ym)) {
  12060. $ym = date('Y-m');
  12061. }
  12062. $dbRows = [];
  12063. try {
  12064. $query = Db::table('purchase_order');
  12065. $query->whereRaw(ProcuremenStatus::sqlPoCompleted('status'));
  12066. $dbRows = $query->select();
  12067. } catch (\Throwable $e) {
  12068. $dbRows = [];
  12069. }
  12070. if (!is_array($dbRows)) {
  12071. $dbRows = [];
  12072. }
  12073. $completeTsMap = [];
  12074. $sidList = [];
  12075. foreach ($dbRows as $dbRow) {
  12076. if (!is_array($dbRow)) {
  12077. continue;
  12078. }
  12079. $sid = (int)($dbRow['scydgy_id'] ?? 0);
  12080. if ($sid > 0) {
  12081. $sidList[$sid] = true;
  12082. }
  12083. }
  12084. if ($sidList !== []) {
  12085. $completeTsMap = ProcuremenTime::loadOperLogTimestampMap(array_keys($sidList), ['purchase_confirm', 'mark_complete']);
  12086. }
  12087. // 导出始终按「查看月份」取当月完结单;搜索只在当月内再缩小(勿跨月,否则会与列表不一致)
  12088. $dbRows = array_values(array_filter($dbRows, function ($dbRow) use ($ym, $completeTsMap) {
  12089. if (!is_array($dbRow)) {
  12090. return false;
  12091. }
  12092. $done = ProcuremenTime::resolveCompletedDone($dbRow, $completeTsMap);
  12093. if ($done['ts'] <= 0) {
  12094. return false;
  12095. }
  12096. return date('Y-m', $done['ts']) === $ym;
  12097. }));
  12098. $dbRows = $this->filterMonthOutwardExportDbRowsBySearch($dbRows);
  12099. $pool = $this->procuremenPoolFromPurchaseOrderDbRows($dbRows);
  12100. $mainBySid = [];
  12101. foreach ($pool as $rw) {
  12102. if (!is_array($rw)) {
  12103. continue;
  12104. }
  12105. $rid = (int)($rw['ID'] ?? 0);
  12106. if ($rid > 0) {
  12107. $mainBySid[$rid] = $rw;
  12108. }
  12109. }
  12110. if ($mainBySid === []) {
  12111. $detailRows = [];
  12112. } else {
  12113. try {
  12114. $detailRows = Db::table('purchase_order_detail')
  12115. ->where('scydgy_id', 'in', array_keys($mainBySid))
  12116. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  12117. ->order('status', 'desc')
  12118. ->order('CCYDH', 'asc')
  12119. ->order('company_name', 'asc')
  12120. ->order('id', 'asc')
  12121. ->select();
  12122. } catch (\Throwable $e) {
  12123. try {
  12124. $detailRows = Db::table('purchase_order_detail')
  12125. ->where('scydgy_id', 'in', array_keys($mainBySid))
  12126. ->whereRaw(ProcuremenStatus::sqlPodNotVoid('status'))
  12127. ->order('status', 'desc')
  12128. ->order('CCYDH', 'asc')
  12129. ->order('company_name', 'asc')
  12130. ->order('ID', 'asc')
  12131. ->select();
  12132. } catch (\Throwable $e2) {
  12133. $detailRows = [];
  12134. }
  12135. }
  12136. }
  12137. if (!is_array($detailRows)) {
  12138. $detailRows = [];
  12139. }
  12140. $exportLines = [];
  12141. $detailSidSeen = [];
  12142. foreach ($detailRows as $dr) {
  12143. if (!is_array($dr)) {
  12144. continue;
  12145. }
  12146. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12147. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  12148. continue;
  12149. }
  12150. if (isset($detailSidSeen[$sid])) {
  12151. continue;
  12152. }
  12153. if (!ProcuremenStatus::isPodPicked($dr['status'] ?? '')) {
  12154. continue;
  12155. }
  12156. $detailSidSeen[$sid] = true;
  12157. $m = $mainBySid[$sid];
  12158. $exportLines[] = [
  12159. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12160. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12161. 'company_name' => (string)($dr['company_name'] ?? ''),
  12162. 'CDF' => (string)($m['CDF'] ?? ''),
  12163. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12164. 'gx' => $this->procuremenExportGxText($m),
  12165. 'detail' => $dr,
  12166. ];
  12167. }
  12168. foreach ($detailRows as $dr) {
  12169. if (!is_array($dr)) {
  12170. continue;
  12171. }
  12172. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12173. if ($sid <= 0 || !isset($mainBySid[$sid]) || isset($detailSidSeen[$sid])) {
  12174. continue;
  12175. }
  12176. $detailSidSeen[$sid] = true;
  12177. $m = $mainBySid[$sid];
  12178. $exportLines[] = [
  12179. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12180. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12181. 'company_name' => (string)($dr['company_name'] ?? ''),
  12182. 'CDF' => (string)($m['CDF'] ?? ''),
  12183. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12184. 'gx' => $this->procuremenExportGxText($m),
  12185. 'detail' => $dr,
  12186. ];
  12187. }
  12188. foreach ($mainBySid as $sid => $m) {
  12189. if (isset($detailSidSeen[$sid])) {
  12190. continue;
  12191. }
  12192. $company = trim((string)($m['pick_company_name'] ?? ''));
  12193. $exportLines[] = [
  12194. 'CCYDH' => (string)($m['CCYDH'] ?? ''),
  12195. 'CYJMC' => (string)($m['CYJMC'] ?? ''),
  12196. 'company_name' => $company,
  12197. 'CDF' => (string)($m['CDF'] ?? ''),
  12198. 'cGzzxMc' => (string)($m['cGzzxMc'] ?? ''),
  12199. 'gx' => $this->procuremenExportGxText($m),
  12200. 'detail' => [],
  12201. ];
  12202. }
  12203. $groups = [];
  12204. foreach ($exportLines as $line) {
  12205. $k = $line['CCYDH'] . "\x1f" . $line['company_name'];
  12206. if (!isset($groups[$k])) {
  12207. $groups[$k] = [];
  12208. }
  12209. $groups[$k][] = $line;
  12210. }
  12211. ksort($groups, SORT_STRING);
  12212. return [
  12213. 'ym' => $ym,
  12214. 'mainBySid' => $mainBySid,
  12215. 'detailRows' => $detailRows,
  12216. 'exportLines' => $exportLines,
  12217. 'groups' => $groups,
  12218. ];
  12219. }
  12220. /**
  12221. * 导出用:工序列文案
  12222. */
  12223. protected function procuremenExportGxText(array $r)
  12224. {
  12225. $a = trim((string)($r['CDXMC'] ?? ''));
  12226. $b = trim((string)($r['CGYMC'] ?? ''));
  12227. if ($a !== '' && $b !== '') {
  12228. return $a . ':' . $b;
  12229. }
  12230. return $a !== '' ? $a : $b;
  12231. }
  12232. /**
  12233. * 导出用:加工金额(表中有 amount/jje/jgje 等则读取,否则 0)
  12234. */
  12235. protected function procuremenExportAmount(array $r)
  12236. {
  12237. foreach (['amount', 'jje', 'jgje', 'processing_amount'] as $k) {
  12238. if (!array_key_exists($k, $r)) {
  12239. continue;
  12240. }
  12241. $v = $r[$k];
  12242. if ($v === null || $v === '') {
  12243. continue;
  12244. }
  12245. if (is_numeric($v)) {
  12246. return (float)$v;
  12247. }
  12248. $v = preg_replace('/[^\d\.\-]/', '', (string)$v);
  12249. if ($v !== '' && is_numeric($v)) {
  12250. return (float)$v;
  12251. }
  12252. }
  12253. return 0.0;
  12254. }
  12255. /**
  12256. * 月度导出:各工序下所有下发供应商的报价明细(含未中标)
  12257. *
  12258. * @param array<int, array<string, mixed>> $detailRows
  12259. * @param array<int, array<string, mixed>> $mainBySid
  12260. * @return array<int, array<string, mixed>>
  12261. */
  12262. protected function buildMonthExportQuoteLines(array $detailRows, array $mainBySid): array
  12263. {
  12264. $lines = [];
  12265. foreach ($detailRows as $dr) {
  12266. if (!is_array($dr)) {
  12267. continue;
  12268. }
  12269. $sid = (int)($dr['scydgy_id'] ?? $dr['SCYDGY_ID'] ?? 0);
  12270. if ($sid <= 0 || !isset($mainBySid[$sid])) {
  12271. continue;
  12272. }
  12273. if (ProcuremenStatus::isPodVoid($dr['status'] ?? '')) {
  12274. continue;
  12275. }
  12276. $cn = trim((string)($dr['company_name'] ?? ''));
  12277. if ($cn === '') {
  12278. continue;
  12279. }
  12280. $m = $mainBySid[$sid];
  12281. $am = trim((string)($dr['amount'] ?? ''));
  12282. $amountFilled = ($am !== '' && $am !== '0' && $am !== '0.00');
  12283. $amountNum = $this->parseProcuremenMoneyNumber($dr['amount'] ?? null);
  12284. $amountText = $amountFilled
  12285. ? ($amountNum !== null ? $this->formatProcuremenMoneyDisplay($amountNum) : $am)
  12286. : '未填写';
  12287. $deliveryRaw = trim((string)($dr['delivery'] ?? ''));
  12288. $deliveryShow = $this->formatDeliveryYmd($deliveryRaw);
  12289. if ($deliveryShow === '' && $deliveryRaw !== '') {
  12290. $deliveryShow = $deliveryRaw;
  12291. }
  12292. $deliveryText = ($deliveryShow !== '' && !preg_match('/^0000-00-00/i', $deliveryShow))
  12293. ? $deliveryShow
  12294. : '未填写';
  12295. $picked = ProcuremenStatus::isPodPicked($dr['status'] ?? '');
  12296. $lines[] = [
  12297. 'CCYDH' => (string)($dr['CCYDH'] ?? $m['CCYDH'] ?? ''),
  12298. 'CYJMC' => (string)($dr['CYJMC'] ?? $m['CYJMC'] ?? ''),
  12299. 'gx' => $this->procuremenExportGxText($m),
  12300. 'company_name' => $cn,
  12301. 'amount_text' => $amountText,
  12302. 'amount_num' => $amountFilled ? $amountNum : null,
  12303. 'delivery_text' => $deliveryText,
  12304. 'picked_text' => $picked ? '中标' : '未中标',
  12305. 'picked' => $picked,
  12306. ];
  12307. }
  12308. $winnerSupplierByOrder = [];
  12309. foreach ($lines as $line) {
  12310. $dh = trim((string)($line['CCYDH'] ?? ''));
  12311. $cn = trim((string)($line['company_name'] ?? ''));
  12312. if ($dh !== '' && $cn !== '' && !empty($line['picked'])) {
  12313. $winnerSupplierByOrder[$dh][$cn] = true;
  12314. }
  12315. }
  12316. usort($lines, function ($a, $b) use ($winnerSupplierByOrder) {
  12317. $c = strcmp((string)($a['CCYDH'] ?? ''), (string)($b['CCYDH'] ?? ''));
  12318. if ($c !== 0) {
  12319. return $c;
  12320. }
  12321. $dh = trim((string)($a['CCYDH'] ?? ''));
  12322. $aCn = trim((string)($a['company_name'] ?? ''));
  12323. $bCn = trim((string)($b['company_name'] ?? ''));
  12324. $aSupplierWin = ($dh !== '' && $aCn !== '' && !empty($winnerSupplierByOrder[$dh][$aCn]));
  12325. $bSupplierWin = ($dh !== '' && $bCn !== '' && !empty($winnerSupplierByOrder[$dh][$bCn]));
  12326. if ($aSupplierWin !== $bSupplierWin) {
  12327. return $aSupplierWin ? -1 : 1;
  12328. }
  12329. $c = strcmp($aCn, $bCn);
  12330. if ($c !== 0) {
  12331. return $c;
  12332. }
  12333. if (!empty($a['picked']) !== !empty($b['picked'])) {
  12334. return !empty($a['picked']) ? -1 : 1;
  12335. }
  12336. $c = strcmp((string)($a['gx'] ?? ''), (string)($b['gx'] ?? ''));
  12337. if ($c !== 0) {
  12338. return $c;
  12339. }
  12340. return 0;
  12341. });
  12342. return $lines;
  12343. }
  12344. /**
  12345. * 月度导出:在同一工作表指定行起写入供应商报价明细(含未中标)
  12346. *
  12347. * @param array<int, array<string, mixed>> $quoteLines
  12348. */
  12349. protected function appendMonthExportQuoteBlock(Worksheet $sheet, array $quoteLines, string $ym, int $startRow): int
  12350. {
  12351. $mon = (int)substr($ym, 5, 2);
  12352. $titleRow = $startRow;
  12353. $headerRow = $startRow + 1;
  12354. $dataStartRow = $startRow + 2;
  12355. $sheet->mergeCells('A' . $titleRow . ':H' . $titleRow);
  12356. $sheet->setCellValue('A' . $titleRow, $mon . '月供应商报价明细');
  12357. $sheet->getStyle('A' . $titleRow)->getFont()->setBold(true)->setSize(14);
  12358. $sheet->getStyle('A' . $titleRow)->getAlignment()
  12359. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12360. ->setVertical(Alignment::VERTICAL_CENTER);
  12361. $headers = ['序号', '传票号', '传票名称', '工序', '供应商', '单价', '交货期', '是否中标'];
  12362. $col = 'A';
  12363. foreach ($headers as $h) {
  12364. $sheet->setCellValue($col . $headerRow, $h);
  12365. $col++;
  12366. }
  12367. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getFont()->setBold(true);
  12368. $sheet->getStyle('A' . $headerRow . ':H' . $headerRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12369. $rowNum = $dataStartRow;
  12370. if ($quoteLines === []) {
  12371. $sheet->mergeCells('A' . $dataStartRow . ':H' . $dataStartRow);
  12372. $sheet->setCellValue('A' . $dataStartRow, '(当月暂无供应商报价明细)');
  12373. $sheet->getStyle('A' . $dataStartRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  12374. $rowNum = $dataStartRow + 1;
  12375. } else {
  12376. $i = 0;
  12377. foreach ($quoteLines as $line) {
  12378. $i++;
  12379. $sheet->setCellValue('A' . $rowNum, $i);
  12380. $sheet->setCellValue('B' . $rowNum, (string)($line['CCYDH'] ?? ''));
  12381. $sheet->setCellValue('C' . $rowNum, (string)($line['CYJMC'] ?? ''));
  12382. $sheet->setCellValue('D' . $rowNum, (string)($line['gx'] ?? ''));
  12383. $sheet->setCellValue('E' . $rowNum, (string)($line['company_name'] ?? ''));
  12384. if ($line['amount_num'] !== null) {
  12385. $sheet->setCellValue('F' . $rowNum, (float)$line['amount_num']);
  12386. $sheet->getStyle('F' . $rowNum)->getNumberFormat()->setFormatCode('#,##0.00');
  12387. } else {
  12388. $sheet->setCellValue('F' . $rowNum, (string)($line['amount_text'] ?? '未填写'));
  12389. }
  12390. $sheet->setCellValue('G' . $rowNum, (string)($line['delivery_text'] ?? ''));
  12391. $sheet->setCellValue('H' . $rowNum, (string)($line['picked_text'] ?? ''));
  12392. if (!empty($line['picked'])) {
  12393. $sheet->getStyle('E' . $rowNum . ':H' . $rowNum)->getFont()->setBold(true);
  12394. }
  12395. $rowNum++;
  12396. }
  12397. }
  12398. $lastRow = $rowNum - 1;
  12399. if ($lastRow >= $headerRow) {
  12400. $sheet->getStyle('A' . $titleRow . ':H' . $lastRow)->applyFromArray([
  12401. 'borders' => [
  12402. 'allBorders' => [
  12403. 'borderStyle' => Border::BORDER_THIN,
  12404. 'color' => ['rgb' => '000000'],
  12405. ],
  12406. ],
  12407. ]);
  12408. $sheet->getStyle('A' . $dataStartRow . ':H' . $lastRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
  12409. $sheet->getStyle('C' . $dataStartRow . ':C' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12410. $sheet->getStyle('D' . $dataStartRow . ':D' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12411. $sheet->getStyle('E' . $dataStartRow . ':E' . $lastRow)->getAlignment()->setWrapText(true)->setVertical(Alignment::VERTICAL_TOP);
  12412. $sheet->getRowDimension($titleRow)->setRowHeight(28);
  12413. if ($lastRow >= $dataStartRow) {
  12414. $this->applyMonthExportTableAlignment($sheet, $headerRow, $dataStartRow, $lastRow, 'H');
  12415. }
  12416. }
  12417. return $lastRow;
  12418. }
  12419. /**
  12420. * 月度导出表格对齐:表头居中、序号列居中、其余列居左
  12421. */
  12422. protected function applyMonthExportTableAlignment(Worksheet $sheet, int $headerRow, int $dataStartRow, int $lastRow, string $lastCol = 'H'): void
  12423. {
  12424. if ($lastRow < $dataStartRow || $headerRow < 1) {
  12425. return;
  12426. }
  12427. $sheet->getStyle('A' . $headerRow . ':' . $lastCol . $headerRow)->getAlignment()
  12428. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12429. ->setVertical(Alignment::VERTICAL_CENTER);
  12430. $sheet->getStyle('A' . $dataStartRow . ':A' . $lastRow)->getAlignment()
  12431. ->setHorizontal(Alignment::HORIZONTAL_CENTER)
  12432. ->setVertical(Alignment::VERTICAL_CENTER);
  12433. if ($lastCol > 'B') {
  12434. $sheet->getStyle('B' . $dataStartRow . ':' . $lastCol . $lastRow)->getAlignment()
  12435. ->setHorizontal(Alignment::HORIZONTAL_LEFT)
  12436. ->setVertical(Alignment::VERTICAL_CENTER);
  12437. }
  12438. }
  12439. /**
  12440. * 订单号等用于 PDF 文件名片段(去掉路径非法字符)
  12441. */
  12442. protected function sanitizePurchaseConfirmPdfOrderKey(string $ccydh): string
  12443. {
  12444. $s = trim($ccydh);
  12445. if ($s === '') {
  12446. return 'ORDER';
  12447. }
  12448. $s = preg_replace('@[\\\\/:*?"<>|\\s]+@u', '_', $s);
  12449. $s = trim($s, '._-');
  12450. if ($s === '') {
  12451. return 'ORDER';
  12452. }
  12453. if (function_exists('mb_substr')) {
  12454. return mb_substr($s, 0, 80, 'UTF-8');
  12455. }
  12456. return strlen($s) <= 80 ? $s : substr($s, 0, 80);
  12457. }
  12458. /**
  12459. * 采购确认 PDF 相对路径(与 OSS 对象键一致,无前导斜杠):
  12460. * xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf
  12461. *
  12462. * @return array{objectKey: string, webPath: string}
  12463. */
  12464. protected function buildPurchaseConfirmPdfPaths(int $scydgyId, string $ccydhRaw): array
  12465. {
  12466. $sid = (int)$scydgyId;
  12467. $safeOrder = $this->sanitizePurchaseConfirmPdfOrderKey($ccydhRaw);
  12468. $y = date('Y');
  12469. $m = date('m');
  12470. $d = date('d');
  12471. $basename = $safeOrder . '_' . $sid . '.pdf';
  12472. $objectKey = 'xinhua/' . $y . '/' . $m . '/' . $d . '/' . $sid . '/' . $basename;
  12473. return [
  12474. 'objectKey' => $objectKey,
  12475. 'webPath' => '/' . $objectKey,
  12476. ];
  12477. }
  12478. /**
  12479. * 采购确认成功后:用与「详情」弹窗相同的模板片段渲染 HTML,再存为 PDF(改 details_fragment 后 PDF 同步变化)。
  12480. * 优先上传至阿里云 OSS(application/config.php 的 oss 节点);失败或未配置时回退到 public 下与 objectKey 相同目录结构。
  12481. * 成功后将相对路径写入 purchase_order.pdf_url(形如 /xinhua/年/月/日/scydgy_id/订单号_scydgy_id.pdf)。
  12482. *
  12483. * @return string OSS 返回 https 完整 URL;本地回退为以 / 开头的 Web 路径;失败返回空串
  12484. */
  12485. protected function savePurchaseConfirmDetailPdf(int $scydgyId, int $purchaseOrderId): string
  12486. {
  12487. if (!$this->isValidScydgyRowId($scydgyId)) {
  12488. return '';
  12489. }
  12490. $ids = trim((string)$scydgyId);
  12491. $prep = $this->prepareProcuremenDetailsView($ids);
  12492. if (!$prep['ok']) {
  12493. return '';
  12494. }
  12495. $ccydh = $prep['ccydh'];
  12496. $paths = $this->buildPurchaseConfirmPdfPaths((int)$scydgyId, $ccydh);
  12497. $objectKey = $paths['objectKey'];
  12498. $webPath = $paths['webPath'];
  12499. $meta = sprintf('工序行ID %s | 主表订单ID %d | PDF生成时间 %s', $ids, (int)$purchaseOrderId, date('Y-m-d H:i:s'));
  12500. $this->view->assign([
  12501. 'pdf_export' => 1,
  12502. 'pdfMetaLine' => $meta,
  12503. ]);
  12504. // 关闭后台 layout,避免 default 布局里的「控制台」面包屑等被打进 PDF
  12505. $restoreLayout = !empty($this->layout) ? ('layout/' . $this->layout) : false;
  12506. $this->view->engine->layout(false);
  12507. try {
  12508. $html = $this->view->fetch('procuremen/details_pdf_shell');
  12509. } catch (\Throwable $e) {
  12510. if ($restoreLayout) {
  12511. $this->view->engine->layout($restoreLayout);
  12512. }
  12513. Log::write('采购确认PDF模板渲染失败: ' . $e->getMessage(), 'error');
  12514. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12515. return '';
  12516. }
  12517. if ($restoreLayout) {
  12518. $this->view->engine->layout($restoreLayout);
  12519. }
  12520. $this->view->assign(['pdf_export' => '', 'pdfMetaLine' => '']);
  12521. $tempDir = ROOT_PATH . 'runtime' . DIRECTORY_SEPARATOR . 'mpdf_tmp';
  12522. if (!is_dir($tempDir)) {
  12523. @mkdir($tempDir, 0755, true);
  12524. }
  12525. $tempPdf = $tempDir . DIRECTORY_SEPARATOR . uniqid('pc_pdf_', true) . '.pdf';
  12526. try {
  12527. $mpdf = new \Mpdf\Mpdf([
  12528. 'mode' => 'utf-8',
  12529. 'format' => 'A4',
  12530. 'margin_left' => 12,
  12531. 'margin_right' => 12,
  12532. 'margin_top' => 14,
  12533. 'margin_bottom' => 14,
  12534. 'tempDir' => $tempDir,
  12535. 'autoScriptToLang' => true,
  12536. 'autoLangToFont' => true,
  12537. ]);
  12538. // 与当前站点 HTTP_HOST 不同的占位 base,使 basepathIsLocal=false,避免 mPDF CssManager
  12539. // 在 parse_url 得到有 scheme 无 host 时对 $tr['host'] 触发「Undefined index: host」(日志已复现)。
  12540. $mpdf->SetBasePath('http://127.0.0.1/');
  12541. $mpdf->WriteHTML($html);
  12542. $mpdf->Output($tempPdf, \Mpdf\Output\Destination::FILE);
  12543. } catch (\Throwable $e) {
  12544. Log::write('采购确认PDF写入失败: ' . $e->getMessage(), 'error');
  12545. if (is_file($tempPdf)) {
  12546. @unlink($tempPdf);
  12547. }
  12548. return '';
  12549. }
  12550. $ossUrl = AliyunOss::uploadLocalFile($tempPdf, $objectKey);
  12551. if ($ossUrl !== '') {
  12552. @unlink($tempPdf);
  12553. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12554. return $ossUrl;
  12555. }
  12556. $pi = pathinfo($objectKey);
  12557. $dirRel = isset($pi['dirname']) ? (string)$pi['dirname'] : 'xinhua';
  12558. $baseFile = isset($pi['basename']) ? (string)$pi['basename'] : '';
  12559. if ($baseFile === '') {
  12560. @unlink($tempPdf);
  12561. return '';
  12562. }
  12563. $dir = ROOT_PATH . 'public' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dirRel);
  12564. if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
  12565. Log::write('采购确认PDF目录创建失败: ' . $dir, 'error');
  12566. @unlink($tempPdf);
  12567. return '';
  12568. }
  12569. $fullPath = $dir . DIRECTORY_SEPARATOR . $baseFile;
  12570. if (!@copy($tempPdf, $fullPath)) {
  12571. Log::write('采购确认PDF复制到本地失败: ' . $fullPath, 'error');
  12572. @unlink($tempPdf);
  12573. return '';
  12574. }
  12575. @unlink($tempPdf);
  12576. $this->persistPurchaseOrderPdfUrl((int)$scydgyId, $webPath);
  12577. return $webPath;
  12578. }
  12579. /**
  12580. * 采购确认 PDF 生成成功后写入 purchase_order.pdf_url(列不存在时仅记日志)
  12581. */
  12582. protected function persistPurchaseOrderPdfUrl(int $scydgyId, string $webPath): void
  12583. {
  12584. if ($scydgyId <= 0 || $webPath === '') {
  12585. return;
  12586. }
  12587. try {
  12588. Db::table('purchase_order')->where('scydgy_id', $scydgyId)->update(['pdf_url' => $webPath]);
  12589. } catch (\Throwable $e) {
  12590. Log::write('purchase_order.pdf_url 更新失败 scydgy_id=' . $scydgyId . ' ' . $e->getMessage(), 'notice');
  12591. }
  12592. }
  12593. /**
  12594. * 整理短信变量:去空格;联系人姓名为空时用公司名称
  12595. *
  12596. * @param array<string, string> $vars
  12597. * @return array<string, string>
  12598. */
  12599. protected function normalizeSmsTemplateVars(array $vars): array
  12600. {
  12601. $out = [];
  12602. foreach ($vars as $k => $v) {
  12603. $out[(string)$k] = trim((string)$v);
  12604. }
  12605. if (($out['contact_name'] ?? '') === '' && ($out['company_name'] ?? '') !== '') {
  12606. $out['contact_name'] = $out['company_name'];
  12607. }
  12608. return $out;
  12609. }
  12610. /**
  12611. * 按手机号或公司名称查 customer 表联系人姓名
  12612. */
  12613. protected function resolveCustomerContactName(string $phone, string $companyName): string
  12614. {
  12615. $phone = trim($phone);
  12616. $companyName = trim($companyName);
  12617. try {
  12618. if ($phone !== '' && preg_match('/^1\d{10}$/', $phone)) {
  12619. $row = Db::table('customer')
  12620. ->where(function ($q) use ($phone) {
  12621. $q->where('phone', $phone)->whereOr('account', $phone);
  12622. })
  12623. ->order('id', 'asc')
  12624. ->find();
  12625. if (is_array($row)) {
  12626. $nm = trim((string)($row['username'] ?? ''));
  12627. if ($nm !== '') {
  12628. return $nm;
  12629. }
  12630. }
  12631. }
  12632. if ($companyName !== '') {
  12633. $row = Db::table('customer')->where('company_name', $companyName)->order('id', 'asc')->find();
  12634. if (is_array($row)) {
  12635. return trim((string)($row['username'] ?? ''));
  12636. }
  12637. }
  12638. } catch (\Throwable $e) {
  12639. }
  12640. return '';
  12641. }
  12642. /**
  12643. * 模版纯文本转邮件 HTML:换行转 &lt;br&gt;;http(s) 链接做成可点的 &lt;a&gt;(微信 QQ 邮箱提醒纯文本 URL 常不可点)
  12644. */
  12645. protected function plainTextToHtmlEmailBody(string $text): string
  12646. {
  12647. $text = str_replace(["\r\n", "\r"], "\n", (string)$text);
  12648. $parts = explode("\n", $text);
  12649. $out = [];
  12650. foreach ($parts as $line) {
  12651. if (preg_match('/<a\s+[^>]*href=/i', $line)) {
  12652. $out[] = $line;
  12653. } else {
  12654. $esc = htmlspecialchars($line, ENT_QUOTES, 'UTF-8');
  12655. $esc = preg_replace(
  12656. '#(https?://[^\s<>"\']+)#iu',
  12657. '<a href="$1" style="color:#1565c0;text-decoration:underline;word-break:break-all;">$1</a>',
  12658. $esc
  12659. );
  12660. $out[] = $esc;
  12661. }
  12662. }
  12663. return implode("<br>\n", $out);
  12664. }
  12665. /**
  12666. * 短信场景:去掉链接类变量,避免误填 URL
  12667. *
  12668. * @param array<string, string> $vars
  12669. * @return array<string, string>
  12670. */
  12671. protected function stripLinkVarsForSmsScene(string $scene, array $vars): array
  12672. {
  12673. if (!in_array($scene, ['review_sms', 'confirm_ok', 'confirm_fail'], true)) {
  12674. return $vars;
  12675. }
  12676. foreach (['platform_url', 'platform_links', 'platform_links_html', 'process_lines_html'] as $k) {
  12677. $vars[$k] = '';
  12678. }
  12679. return $vars;
  12680. }
  12681. /**
  12682. * 读取通知模版并替换变量;无模版、正文为空或 status≠1 时抛异常(不使用代码内兜底文案)
  12683. *
  12684. * @param array<string, string> $vars
  12685. */
  12686. protected function renderNotifyTemplate(string $scene, array $vars): string
  12687. {
  12688. $vars = $this->normalizeSmsTemplateVars($vars);
  12689. $vars = $this->stripLinkVarsForSmsScene($scene, $vars);
  12690. $row = $this->loadNotifyTemplateRow($scene);
  12691. if ($row === null) {
  12692. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12693. }
  12694. $tpl = trim((string)($row['content'] ?? ''));
  12695. if ($tpl === '') {
  12696. throw new \Exception($this->notifyTemplateMissingMessage($scene));
  12697. }
  12698. foreach ($vars as $k => $v) {
  12699. $tpl = str_replace('{' . $k . '}', (string)$v, $tpl);
  12700. }
  12701. // 未传入的占位符置空,避免短信出现 {process_lines} 等原文
  12702. $tpl = preg_replace('/\{[a-zA-Z0-9_]+\}/', '', $tpl);
  12703. return $tpl;
  12704. }
  12705. protected function resolveProcuremenEmailSubject(string $scene): string
  12706. {
  12707. // 询价 / 采购确认结果邮箱:模版名称即邮件主题
  12708. if (in_array($scene, ['rfq_salesman_email', 'rfq_supplier_email', 'confirm_ok_email', 'confirm_fail_email'], true)) {
  12709. $row = $this->loadNotifyTemplateRow($scene);
  12710. $title = is_array($row) ? trim((string)($row['title'] ?? '')) : '';
  12711. if ($title !== '') {
  12712. return $title;
  12713. }
  12714. $fallback = [
  12715. 'rfq_supplier_email' => '供应商询价通知',
  12716. 'rfq_salesman_email' => '协助采购询价通知',
  12717. 'confirm_ok_email' => '采购确认结果:已通过',
  12718. 'confirm_fail_email' => '采购确认结果:未通过',
  12719. ];
  12720. return $fallback[$scene] ?? '协助采购通知';
  12721. }
  12722. $map = [
  12723. 'review_email' => '您有新的协助加工订单',
  12724. ];
  12725. $subject = trim((string)($map[$scene] ?? ''));
  12726. if ($subject === '') {
  12727. $this->error('未配置邮件主题:' . $scene);
  12728. }
  12729. return $subject;
  12730. }
  12731. protected function notifyTemplateMissingMessage(string $scene, bool $titleRequired = false): string
  12732. {
  12733. $map = [
  12734. 'review_email' => '协助下发-邮箱',
  12735. 'review_sms' => '协助下发-短信',
  12736. 'confirm_ok' => '采购确认-通过',
  12737. 'confirm_fail' => '采购确认-未通过',
  12738. 'confirm_ok_email' => '采购确认通过-邮箱',
  12739. 'confirm_fail_email' => '采购确认未通过-邮箱',
  12740. 'bid_open' => '开标双重验证',
  12741. 'rfq_salesman_email' => '询价通知业务员-邮箱',
  12742. 'rfq_supplier_email' => '供应商询价通知',
  12743. ];
  12744. $label = $map[$scene] ?? $scene;
  12745. if ($titleRequired) {
  12746. return "通知模版「{$label}」({$scene})未配置、已禁用或缺少邮件标题,请在后台「短信模版配置」维护后再操作";
  12747. }
  12748. return "通知模版「{$label}」({$scene})未配置、已禁用或正文为空,请在后台「短信模版配置」维护后再操作";
  12749. }
  12750. /**
  12751. * 是否开启协助通知演练(不发真实短信/邮件)
  12752. */
  12753. protected function isProcuremenNotifyDryRun(): bool
  12754. {
  12755. return (bool)Config::get('procuremen_notify_dry_run');
  12756. }
  12757. /**
  12758. * @param array<string, mixed> $payload
  12759. */
  12760. protected function recordNotifyDryRunPreview(array $payload): void
  12761. {
  12762. $this->notifyDryRunPreview[] = $payload;
  12763. Log::write('[协助通知演练] ' . json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'notice');
  12764. }
  12765. /**
  12766. * 短信宝发送;失败抛异常(供事务回滚,避免「已入库但未通知」与「通知失败仍入库」)
  12767. * @throws \Exception
  12768. */
  12769. protected function smsbao($phone, $content)
  12770. {
  12771. if ($this->isProcuremenNotifyDryRun()) {
  12772. $this->recordNotifyDryRunPreview([
  12773. 'scene' => 'sms_only',
  12774. 'phone' => $phone,
  12775. 'sms_content' => $content,
  12776. ]);
  12777. return;
  12778. }
  12779. $statusStr = [
  12780. '0' => '短信发送成功',
  12781. '-1' => '参数不全',
  12782. '-2' => '服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!',
  12783. '30' => '密码错误',
  12784. '40' => '账号不存在',
  12785. '41' => '余额不足',
  12786. '42' => '帐户已过期',
  12787. '43' => 'IP地址限制',
  12788. '50' => '内容含有敏感词',
  12789. ];
  12790. $smsapi = 'http://api.smsbao.com/';
  12791. $user = 'zhuwei123';
  12792. $pass = md5('1d1e605c101e4c1f8a156c6d7b19f126');
  12793. $sendurl = $smsapi . 'sms?u=' . $user . '&p=' . $pass . '&m=' . $phone . '&c=' . urlencode($content);
  12794. $result = @file_get_contents($sendurl);
  12795. if ($result === false) {
  12796. \think\Log::record('smsbao 请求失败 phone=' . $phone, 'error');
  12797. throw new \Exception('短信接口请求失败,请检查网络或稍后再试(未写入数据)');
  12798. }
  12799. $result = trim((string)$result);
  12800. if ($result !== '0') {
  12801. $msg = isset($statusStr[$result]) ? $statusStr[$result] : ('返回码 ' . $result);
  12802. \think\Log::record('smsbao 发送失败 phone=' . $phone . ' code=' . $result . ' ' . $msg, 'error');
  12803. throw new \Exception('短信发送失败:' . $msg . '(' . $phone . '),未写入数据');
  12804. }
  12805. }
  12806. }